@abstractframework/observer 0.7.1 → 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-MpJXfwrX.css → index-C0KSkRrQ.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/index-KdTDT-qO.js +0 -162
- package/dist/assets/index-KdTDT-qO.js.map +0 -1
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
var sS=Object.defineProperty;var rS=(e,t,n)=>t in e?sS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var es=(e,t,n)=>rS(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(a){if(a.ep)return;a.ep=!0;const l=n(a);fetch(a.href,l)}})();function Jg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Q_={exports:{}},Qd={},ep={exports:{}},Jt={};/**
|
|
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 sw;function iS(){if(sw)return Jt;sw=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),c=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),g=Symbol.iterator;function y(O){return O===null||typeof O!="object"?null:(O=g&&O[g]||O["@@iterator"],typeof O=="function"?O:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,b={};function S(O,V,J){this.props=O,this.context=V,this.refs=b,this.updater=J||w}S.prototype.isReactComponent={},S.prototype.setState=function(O,V){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,V,"setState")},S.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function N(){}N.prototype=S.prototype;function R(O,V,J){this.props=O,this.context=V,this.refs=b,this.updater=J||w}var $=R.prototype=new N;$.constructor=R,k($,S.prototype),$.isPureReactComponent=!0;var A=Array.isArray,W=Object.prototype.hasOwnProperty,z={current:null},H={key:!0,ref:!0,__self:!0,__source:!0};function G(O,V,J){var le,ie={},_e=null,pe=null;if(V!=null)for(le in V.ref!==void 0&&(pe=V.ref),V.key!==void 0&&(_e=""+V.key),V)W.call(V,le)&&!H.hasOwnProperty(le)&&(ie[le]=V[le]);var ye=arguments.length-2;if(ye===1)ie.children=J;else if(1<ye){for(var Ne=Array(ye),Be=0;Be<ye;Be++)Ne[Be]=arguments[Be+2];ie.children=Ne}if(O&&O.defaultProps)for(le in ye=O.defaultProps,ye)ie[le]===void 0&&(ie[le]=ye[le]);return{$$typeof:e,type:O,key:_e,ref:pe,props:ie,_owner:z.current}}function re(O,V){return{$$typeof:e,type:O.type,key:V,ref:O.ref,props:O.props,_owner:O._owner}}function te(O){return typeof O=="object"&&O!==null&&O.$$typeof===e}function Q(O){var V={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(J){return V[J]})}var D=/\/+/g;function T(O,V){return typeof O=="object"&&O!==null&&O.key!=null?Q(""+O.key):V.toString(36)}function E(O,V,J,le,ie){var _e=typeof O;(_e==="undefined"||_e==="boolean")&&(O=null);var pe=!1;if(O===null)pe=!0;else switch(_e){case"string":case"number":pe=!0;break;case"object":switch(O.$$typeof){case e:case t:pe=!0}}if(pe)return pe=O,ie=ie(pe),O=le===""?"."+T(pe,0):le,A(ie)?(J="",O!=null&&(J=O.replace(D,"$&/")+"/"),E(ie,V,J,"",function(Be){return Be})):ie!=null&&(te(ie)&&(ie=re(ie,J+(!ie.key||pe&&pe.key===ie.key?"":(""+ie.key).replace(D,"$&/")+"/")+O)),V.push(ie)),1;if(pe=0,le=le===""?".":le+":",A(O))for(var ye=0;ye<O.length;ye++){_e=O[ye];var Ne=le+T(_e,ye);pe+=E(_e,V,J,Ne,ie)}else if(Ne=y(O),typeof Ne=="function")for(O=Ne.call(O),ye=0;!(_e=O.next()).done;)_e=_e.value,Ne=le+T(_e,ye++),pe+=E(_e,V,J,Ne,ie);else if(_e==="object")throw V=String(O),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(O).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.");return pe}function L(O,V,J){if(O==null)return O;var le=[],ie=0;return E(O,le,"","",function(_e){return V.call(J,_e,ie++)}),le}function M(O){if(O._status===-1){var V=O._result;V=V(),V.then(function(J){(O._status===0||O._status===-1)&&(O._status=1,O._result=J)},function(J){(O._status===0||O._status===-1)&&(O._status=2,O._result=J)}),O._status===-1&&(O._status=0,O._result=V)}if(O._status===1)return O._result.default;throw O._result}var ee={current:null},F={transition:null},U={ReactCurrentDispatcher:ee,ReactCurrentBatchConfig:F,ReactCurrentOwner:z};function K(){throw Error("act(...) is not supported in production builds of React.")}return Jt.Children={map:L,forEach:function(O,V,J){L(O,function(){V.apply(this,arguments)},J)},count:function(O){var V=0;return L(O,function(){V++}),V},toArray:function(O){return L(O,function(V){return V})||[]},only:function(O){if(!te(O))throw Error("React.Children.only expected to receive a single React element child.");return O}},Jt.Component=S,Jt.Fragment=n,Jt.Profiler=a,Jt.PureComponent=R,Jt.StrictMode=r,Jt.Suspense=f,Jt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=U,Jt.act=K,Jt.cloneElement=function(O,V,J){if(O==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+O+".");var le=k({},O.props),ie=O.key,_e=O.ref,pe=O._owner;if(V!=null){if(V.ref!==void 0&&(_e=V.ref,pe=z.current),V.key!==void 0&&(ie=""+V.key),O.type&&O.type.defaultProps)var ye=O.type.defaultProps;for(Ne in V)W.call(V,Ne)&&!H.hasOwnProperty(Ne)&&(le[Ne]=V[Ne]===void 0&&ye!==void 0?ye[Ne]:V[Ne])}var Ne=arguments.length-2;if(Ne===1)le.children=J;else if(1<Ne){ye=Array(Ne);for(var Be=0;Be<Ne;Be++)ye[Be]=arguments[Be+2];le.children=ye}return{$$typeof:e,type:O.type,key:ie,ref:_e,props:le,_owner:pe}},Jt.createContext=function(O){return O={$$typeof:c,_currentValue:O,_currentValue2:O,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},O.Provider={$$typeof:l,_context:O},O.Consumer=O},Jt.createElement=G,Jt.createFactory=function(O){var V=G.bind(null,O);return V.type=O,V},Jt.createRef=function(){return{current:null}},Jt.forwardRef=function(O){return{$$typeof:u,render:O}},Jt.isValidElement=te,Jt.lazy=function(O){return{$$typeof:m,_payload:{_status:-1,_result:O},_init:M}},Jt.memo=function(O,V){return{$$typeof:h,type:O,compare:V===void 0?null:V}},Jt.startTransition=function(O){var V=F.transition;F.transition={};try{O()}finally{F.transition=V}},Jt.unstable_act=K,Jt.useCallback=function(O,V){return ee.current.useCallback(O,V)},Jt.useContext=function(O){return ee.current.useContext(O)},Jt.useDebugValue=function(){},Jt.useDeferredValue=function(O){return ee.current.useDeferredValue(O)},Jt.useEffect=function(O,V){return ee.current.useEffect(O,V)},Jt.useId=function(){return ee.current.useId()},Jt.useImperativeHandle=function(O,V,J){return ee.current.useImperativeHandle(O,V,J)},Jt.useInsertionEffect=function(O,V){return ee.current.useInsertionEffect(O,V)},Jt.useLayoutEffect=function(O,V){return ee.current.useLayoutEffect(O,V)},Jt.useMemo=function(O,V){return ee.current.useMemo(O,V)},Jt.useReducer=function(O,V,J){return ee.current.useReducer(O,V,J)},Jt.useRef=function(O){return ee.current.useRef(O)},Jt.useState=function(O){return ee.current.useState(O)},Jt.useSyncExternalStore=function(O,V,J){return ee.current.useSyncExternalStore(O,V,J)},Jt.useTransition=function(){return ee.current.useTransition()},Jt.version="18.3.1",Jt}var rw;function Xf(){return rw||(rw=1,ep.exports=iS()),ep.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 iw;function aS(){if(iw)return Qd;iw=1;var e=Xf(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,a=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function c(u,f,h){var m,g={},y=null,w=null;h!==void 0&&(y=""+h),f.key!==void 0&&(y=""+f.key),f.ref!==void 0&&(w=f.ref);for(m in f)r.call(f,m)&&!l.hasOwnProperty(m)&&(g[m]=f[m]);if(u&&u.defaultProps)for(m in f=u.defaultProps,f)g[m]===void 0&&(g[m]=f[m]);return{$$typeof:t,type:u,key:y,ref:w,props:g,_owner:a.current}}return Qd.Fragment=n,Qd.jsx=c,Qd.jsxs=c,Qd}var aw;function oS(){return aw||(aw=1,Q_.exports=aS()),Q_.exports}var s=oS(),_=Xf();const xe=Jg(_);var om={},tp={exports:{}},zr={},np={exports:{}},sp={};/**
|
|
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 ow;function lS(){return ow||(ow=1,(function(e){function t(F,U){var K=F.length;F.push(U);e:for(;0<K;){var O=K-1>>>1,V=F[O];if(0<a(V,U))F[O]=U,F[K]=V,K=O;else break e}}function n(F){return F.length===0?null:F[0]}function r(F){if(F.length===0)return null;var U=F[0],K=F.pop();if(K!==U){F[0]=K;e:for(var O=0,V=F.length,J=V>>>1;O<J;){var le=2*(O+1)-1,ie=F[le],_e=le+1,pe=F[_e];if(0>a(ie,K))_e<V&&0>a(pe,ie)?(F[O]=pe,F[_e]=K,O=_e):(F[O]=ie,F[le]=K,O=le);else if(_e<V&&0>a(pe,K))F[O]=pe,F[_e]=K,O=_e;else break e}}return U}function a(F,U){var K=F.sortIndex-U.sortIndex;return K!==0?K:F.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var c=Date,u=c.now();e.unstable_now=function(){return c.now()-u}}var f=[],h=[],m=1,g=null,y=3,w=!1,k=!1,b=!1,S=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function $(F){for(var U=n(h);U!==null;){if(U.callback===null)r(h);else if(U.startTime<=F)r(h),U.sortIndex=U.expirationTime,t(f,U);else break;U=n(h)}}function A(F){if(b=!1,$(F),!k)if(n(f)!==null)k=!0,M(W);else{var U=n(h);U!==null&&ee(A,U.startTime-F)}}function W(F,U){k=!1,b&&(b=!1,N(G),G=-1),w=!0;var K=y;try{for($(U),g=n(f);g!==null&&(!(g.expirationTime>U)||F&&!Q());){var O=g.callback;if(typeof O=="function"){g.callback=null,y=g.priorityLevel;var V=O(g.expirationTime<=U);U=e.unstable_now(),typeof V=="function"?g.callback=V:g===n(f)&&r(f),$(U)}else r(f);g=n(f)}if(g!==null)var J=!0;else{var le=n(h);le!==null&&ee(A,le.startTime-U),J=!1}return J}finally{g=null,y=K,w=!1}}var z=!1,H=null,G=-1,re=5,te=-1;function Q(){return!(e.unstable_now()-te<re)}function D(){if(H!==null){var F=e.unstable_now();te=F;var U=!0;try{U=H(!0,F)}finally{U?T():(z=!1,H=null)}}else z=!1}var T;if(typeof R=="function")T=function(){R(D)};else if(typeof MessageChannel<"u"){var E=new MessageChannel,L=E.port2;E.port1.onmessage=D,T=function(){L.postMessage(null)}}else T=function(){S(D,0)};function M(F){H=F,z||(z=!0,T())}function ee(F,U){G=S(function(){F(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(F){F.callback=null},e.unstable_continueExecution=function(){k||w||(k=!0,M(W))},e.unstable_forceFrameRate=function(F){0>F||125<F?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):re=0<F?Math.floor(1e3/F):5},e.unstable_getCurrentPriorityLevel=function(){return y},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(F){switch(y){case 1:case 2:case 3:var U=3;break;default:U=y}var K=y;y=U;try{return F()}finally{y=K}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(F,U){switch(F){case 1:case 2:case 3:case 4:case 5:break;default:F=3}var K=y;y=F;try{return U()}finally{y=K}},e.unstable_scheduleCallback=function(F,U,K){var O=e.unstable_now();switch(typeof K=="object"&&K!==null?(K=K.delay,K=typeof K=="number"&&0<K?O+K:O):K=O,F){case 1:var V=-1;break;case 2:V=250;break;case 5:V=1073741823;break;case 4:V=1e4;break;default:V=5e3}return V=K+V,F={id:m++,callback:U,priorityLevel:F,startTime:K,expirationTime:V,sortIndex:-1},K>O?(F.sortIndex=K,t(h,F),n(f)===null&&F===n(h)&&(b?(N(G),G=-1):b=!0,ee(A,K-O))):(F.sortIndex=V,t(f,F),k||w||(k=!0,M(W))),F},e.unstable_shouldYield=Q,e.unstable_wrapCallback=function(F){var U=y;return function(){var K=y;y=U;try{return F.apply(this,arguments)}finally{y=K}}}})(sp)),sp}var lw;function cS(){return lw||(lw=1,np.exports=lS()),np.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 cw;function uS(){if(cw)return zr;cw=1;var e=Xf(),t=cS();function n(i){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+i,d=1;d<arguments.length;d++)o+="&args[]="+encodeURIComponent(arguments[d]);return"Minified React error #"+i+"; visit "+o+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,a={};function l(i,o){c(i,o),c(i+"Capture",o)}function c(i,o){for(a[i]=o,i=0;i<o.length;i++)r.add(o[i])}var u=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=Object.prototype.hasOwnProperty,h=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,m={},g={};function y(i){return f.call(g,i)?!0:f.call(m,i)?!1:h.test(i)?g[i]=!0:(m[i]=!0,!1)}function w(i,o,d,p){if(d!==null&&d.type===0)return!1;switch(typeof o){case"function":case"symbol":return!0;case"boolean":return p?!1:d!==null?!d.acceptsBooleans:(i=i.toLowerCase().slice(0,5),i!=="data-"&&i!=="aria-");default:return!1}}function k(i,o,d,p){if(o===null||typeof o>"u"||w(i,o,d,p))return!0;if(p)return!1;if(d!==null)switch(d.type){case 3:return!o;case 4:return o===!1;case 5:return isNaN(o);case 6:return isNaN(o)||1>o}return!1}function b(i,o,d,p,x,j,P){this.acceptsBooleans=o===2||o===3||o===4,this.attributeName=p,this.attributeNamespace=x,this.mustUseProperty=d,this.propertyName=i,this.type=o,this.sanitizeURL=j,this.removeEmptyString=P}var S={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(i){S[i]=new b(i,0,!1,i,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(i){var o=i[0];S[o]=new b(o,1,!1,i[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(i){S[i]=new b(i,2,!1,i.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(i){S[i]=new b(i,2,!1,i,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(i){S[i]=new b(i,3,!1,i.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(i){S[i]=new b(i,3,!0,i,null,!1,!1)}),["capture","download"].forEach(function(i){S[i]=new b(i,4,!1,i,null,!1,!1)}),["cols","rows","size","span"].forEach(function(i){S[i]=new b(i,6,!1,i,null,!1,!1)}),["rowSpan","start"].forEach(function(i){S[i]=new b(i,5,!1,i.toLowerCase(),null,!1,!1)});var N=/[\-:]([a-z])/g;function R(i){return i[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(i){var o=i.replace(N,R);S[o]=new b(o,1,!1,i,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(i){var o=i.replace(N,R);S[o]=new b(o,1,!1,i,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(i){var o=i.replace(N,R);S[o]=new b(o,1,!1,i,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(i){S[i]=new b(i,1,!1,i.toLowerCase(),null,!1,!1)}),S.xlinkHref=new b("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(i){S[i]=new b(i,1,!1,i.toLowerCase(),null,!0,!0)});function $(i,o,d,p){var x=S.hasOwnProperty(o)?S[o]:null;(x!==null?x.type!==0:p||!(2<o.length)||o[0]!=="o"&&o[0]!=="O"||o[1]!=="n"&&o[1]!=="N")&&(k(o,d,x,p)&&(d=null),p||x===null?y(o)&&(d===null?i.removeAttribute(o):i.setAttribute(o,""+d)):x.mustUseProperty?i[x.propertyName]=d===null?x.type===3?!1:"":d:(o=x.attributeName,p=x.attributeNamespace,d===null?i.removeAttribute(o):(x=x.type,d=x===3||x===4&&d===!0?"":""+d,p?i.setAttributeNS(p,o,d):i.setAttribute(o,d))))}var A=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,W=Symbol.for("react.element"),z=Symbol.for("react.portal"),H=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),te=Symbol.for("react.provider"),Q=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),T=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),M=Symbol.for("react.lazy"),ee=Symbol.for("react.offscreen"),F=Symbol.iterator;function U(i){return i===null||typeof i!="object"?null:(i=F&&i[F]||i["@@iterator"],typeof i=="function"?i:null)}var K=Object.assign,O;function V(i){if(O===void 0)try{throw Error()}catch(d){var o=d.stack.trim().match(/\n( *(at )?)/);O=o&&o[1]||""}return`
|
|
34
|
-
`+O+i}var J=!1;function le(i,o){if(!i||J)return"";J=!0;var d=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(o)if(o=function(){throw Error()},Object.defineProperty(o.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(o,[])}catch(ve){var p=ve}Reflect.construct(i,[],o)}else{try{o.call()}catch(ve){p=ve}i.call(o.prototype)}else{try{throw Error()}catch(ve){p=ve}i()}}catch(ve){if(ve&&p&&typeof ve.stack=="string"){for(var x=ve.stack.split(`
|
|
35
|
-
`),j=p.stack.split(`
|
|
36
|
-
`),P=x.length-1,ne=j.length-1;1<=P&&0<=ne&&x[P]!==j[ne];)ne--;for(;1<=P&&0<=ne;P--,ne--)if(x[P]!==j[ne]){if(P!==1||ne!==1)do if(P--,ne--,0>ne||x[P]!==j[ne]){var ae=`
|
|
37
|
-
`+x[P].replace(" at new "," at ");return i.displayName&&ae.includes("<anonymous>")&&(ae=ae.replace("<anonymous>",i.displayName)),ae}while(1<=P&&0<=ne);break}}}finally{J=!1,Error.prepareStackTrace=d}return(i=i?i.displayName||i.name:"")?V(i):""}function ie(i){switch(i.tag){case 5:return V(i.type);case 16:return V("Lazy");case 13:return V("Suspense");case 19:return V("SuspenseList");case 0:case 2:case 15:return i=le(i.type,!1),i;case 11:return i=le(i.type.render,!1),i;case 1:return i=le(i.type,!0),i;default:return""}}function _e(i){if(i==null)return null;if(typeof i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i;switch(i){case H:return"Fragment";case z:return"Portal";case re:return"Profiler";case G:return"StrictMode";case T:return"Suspense";case E:return"SuspenseList"}if(typeof i=="object")switch(i.$$typeof){case Q:return(i.displayName||"Context")+".Consumer";case te:return(i._context.displayName||"Context")+".Provider";case D:var o=i.render;return i=i.displayName,i||(i=o.displayName||o.name||"",i=i!==""?"ForwardRef("+i+")":"ForwardRef"),i;case L:return o=i.displayName||null,o!==null?o:_e(i.type)||"Memo";case M:o=i._payload,i=i._init;try{return _e(i(o))}catch{}}return null}function pe(i){var o=i.type;switch(i.tag){case 24:return"Cache";case 9:return(o.displayName||"Context")+".Consumer";case 10:return(o._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return i=o.render,i=i.displayName||i.name||"",o.displayName||(i!==""?"ForwardRef("+i+")":"ForwardRef");case 7:return"Fragment";case 5:return o;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return _e(o);case 8:return o===G?"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 o=="function")return o.displayName||o.name||null;if(typeof o=="string")return o}return null}function ye(i){switch(typeof i){case"boolean":case"number":case"string":case"undefined":return i;case"object":return i;default:return""}}function Ne(i){var o=i.type;return(i=i.nodeName)&&i.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function Be(i){var o=Ne(i)?"checked":"value",d=Object.getOwnPropertyDescriptor(i.constructor.prototype,o),p=""+i[o];if(!i.hasOwnProperty(o)&&typeof d<"u"&&typeof d.get=="function"&&typeof d.set=="function"){var x=d.get,j=d.set;return Object.defineProperty(i,o,{configurable:!0,get:function(){return x.call(this)},set:function(P){p=""+P,j.call(this,P)}}),Object.defineProperty(i,o,{enumerable:d.enumerable}),{getValue:function(){return p},setValue:function(P){p=""+P},stopTracking:function(){i._valueTracker=null,delete i[o]}}}}function Ue(i){i._valueTracker||(i._valueTracker=Be(i))}function ut(i){if(!i)return!1;var o=i._valueTracker;if(!o)return!0;var d=o.getValue(),p="";return i&&(p=Ne(i)?i.checked?"true":"false":i.value),i=p,i!==d?(o.setValue(i),!0):!1}function De(i){if(i=i||(typeof document<"u"?document:void 0),typeof i>"u")return null;try{return i.activeElement||i.body}catch{return i.body}}function Qe(i,o){var d=o.checked;return K({},o,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:d??i._wrapperState.initialChecked})}function at(i,o){var d=o.defaultValue==null?"":o.defaultValue,p=o.checked!=null?o.checked:o.defaultChecked;d=ye(o.value!=null?o.value:d),i._wrapperState={initialChecked:p,initialValue:d,controlled:o.type==="checkbox"||o.type==="radio"?o.checked!=null:o.value!=null}}function Ke(i,o){o=o.checked,o!=null&&$(i,"checked",o,!1)}function ce(i,o){Ke(i,o);var d=ye(o.value),p=o.type;if(d!=null)p==="number"?(d===0&&i.value===""||i.value!=d)&&(i.value=""+d):i.value!==""+d&&(i.value=""+d);else if(p==="submit"||p==="reset"){i.removeAttribute("value");return}o.hasOwnProperty("value")?Ae(i,o.type,d):o.hasOwnProperty("defaultValue")&&Ae(i,o.type,ye(o.defaultValue)),o.checked==null&&o.defaultChecked!=null&&(i.defaultChecked=!!o.defaultChecked)}function oe(i,o,d){if(o.hasOwnProperty("value")||o.hasOwnProperty("defaultValue")){var p=o.type;if(!(p!=="submit"&&p!=="reset"||o.value!==void 0&&o.value!==null))return;o=""+i._wrapperState.initialValue,d||o===i.value||(i.value=o),i.defaultValue=o}d=i.name,d!==""&&(i.name=""),i.defaultChecked=!!i._wrapperState.initialChecked,d!==""&&(i.name=d)}function Ae(i,o,d){(o!=="number"||De(i.ownerDocument)!==i)&&(d==null?i.defaultValue=""+i._wrapperState.initialValue:i.defaultValue!==""+d&&(i.defaultValue=""+d))}var he=Array.isArray;function Ce(i,o,d,p){if(i=i.options,o){o={};for(var x=0;x<d.length;x++)o["$"+d[x]]=!0;for(d=0;d<i.length;d++)x=o.hasOwnProperty("$"+i[d].value),i[d].selected!==x&&(i[d].selected=x),x&&p&&(i[d].defaultSelected=!0)}else{for(d=""+ye(d),o=null,x=0;x<i.length;x++){if(i[x].value===d){i[x].selected=!0,p&&(i[x].defaultSelected=!0);return}o!==null||i[x].disabled||(o=i[x])}o!==null&&(o.selected=!0)}}function Te(i,o){if(o.dangerouslySetInnerHTML!=null)throw Error(n(91));return K({},o,{value:void 0,defaultValue:void 0,children:""+i._wrapperState.initialValue})}function Ye(i,o){var d=o.value;if(d==null){if(d=o.children,o=o.defaultValue,d!=null){if(o!=null)throw Error(n(92));if(he(d)){if(1<d.length)throw Error(n(93));d=d[0]}o=d}o==null&&(o=""),d=o}i._wrapperState={initialValue:ye(d)}}function rt(i,o){var d=ye(o.value),p=ye(o.defaultValue);d!=null&&(d=""+d,d!==i.value&&(i.value=d),o.defaultValue==null&&i.defaultValue!==d&&(i.defaultValue=d)),p!=null&&(i.defaultValue=""+p)}function ht(i){var o=i.textContent;o===i._wrapperState.initialValue&&o!==""&&o!==null&&(i.value=o)}function lt(i){switch(i){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function St(i,o){return i==null||i==="http://www.w3.org/1999/xhtml"?lt(o):i==="http://www.w3.org/2000/svg"&&o==="foreignObject"?"http://www.w3.org/1999/xhtml":i}var Zt,On=(function(i){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(o,d,p,x){MSApp.execUnsafeLocalFunction(function(){return i(o,d,p,x)})}:i})(function(i,o){if(i.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in i)i.innerHTML=o;else{for(Zt=Zt||document.createElement("div"),Zt.innerHTML="<svg>"+o.valueOf().toString()+"</svg>",o=Zt.firstChild;i.firstChild;)i.removeChild(i.firstChild);for(;o.firstChild;)i.appendChild(o.firstChild)}});function Bt(i,o){if(o){var d=i.firstChild;if(d&&d===i.lastChild&&d.nodeType===3){d.nodeValue=o;return}}i.textContent=o}var yn={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},zn=["Webkit","ms","Moz","O"];Object.keys(yn).forEach(function(i){zn.forEach(function(o){o=o+i.charAt(0).toUpperCase()+i.substring(1),yn[o]=yn[i]})});function Tn(i,o,d){return o==null||typeof o=="boolean"||o===""?"":d||typeof o!="number"||o===0||yn.hasOwnProperty(i)&&yn[i]?(""+o).trim():o+"px"}function wn(i,o){i=i.style;for(var d in o)if(o.hasOwnProperty(d)){var p=d.indexOf("--")===0,x=Tn(d,o[d],p);d==="float"&&(d="cssFloat"),p?i.setProperty(d,x):i[d]=x}}var Pn=K({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 xn(i,o){if(o){if(Pn[i]&&(o.children!=null||o.dangerouslySetInnerHTML!=null))throw Error(n(137,i));if(o.dangerouslySetInnerHTML!=null){if(o.children!=null)throw Error(n(60));if(typeof o.dangerouslySetInnerHTML!="object"||!("__html"in o.dangerouslySetInnerHTML))throw Error(n(61))}if(o.style!=null&&typeof o.style!="object")throw Error(n(62))}}function Ss(i,o){if(i.indexOf("-")===-1)return typeof o.is=="string";switch(i){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Kn=null;function Ns(i){return i=i.target||i.srcElement||window,i.correspondingUseElement&&(i=i.correspondingUseElement),i.nodeType===3?i.parentNode:i}var jr=null,Dn=null,fe=null;function Se(i){if(i=Qa(i)){if(typeof jr!="function")throw Error(n(280));var o=i.stateNode;o&&(o=Bo(o),jr(i.stateNode,i.type,o))}}function et(i){Dn?fe?fe.push(i):fe=[i]:Dn=i}function Ze(){if(Dn){var i=Dn,o=fe;if(fe=Dn=null,Se(i),o)for(i=0;i<o.length;i++)Se(o[i])}}function ct(i,o){return i(o)}function mt(){}var It=!1;function Ct(i,o,d){if(It)return i(o,d);It=!0;try{return ct(i,o,d)}finally{It=!1,(Dn!==null||fe!==null)&&(mt(),Ze())}}function Qt(i,o){var d=i.stateNode;if(d===null)return null;var p=Bo(d);if(p===null)return null;d=p[o];e:switch(o){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(p=!p.disabled)||(i=i.type,p=!(i==="button"||i==="input"||i==="select"||i==="textarea")),i=!p;break e;default:i=!1}if(i)return null;if(d&&typeof d!="function")throw Error(n(231,o,typeof d));return d}var jt=!1;if(u)try{var en={};Object.defineProperty(en,"passive",{get:function(){jt=!0}}),window.addEventListener("test",en,en),window.removeEventListener("test",en,en)}catch{jt=!1}function Gt(i,o,d,p,x,j,P,ne,ae){var ve=Array.prototype.slice.call(arguments,3);try{o.apply(d,ve)}catch(Ie){this.onError(Ie)}}var Ut=!1,Pt=null,Dt=!1,We=null,ln={onError:function(i){Ut=!0,Pt=i}};function pt(i,o,d,p,x,j,P,ne,ae){Ut=!1,Pt=null,Gt.apply(ln,arguments)}function rn(i,o,d,p,x,j,P,ne,ae){if(pt.apply(this,arguments),Ut){if(Ut){var ve=Pt;Ut=!1,Pt=null}else throw Error(n(198));Dt||(Dt=!0,We=ve)}}function gt(i){var o=i,d=i;if(i.alternate)for(;o.return;)o=o.return;else{i=o;do o=i,(o.flags&4098)!==0&&(d=o.return),i=o.return;while(i)}return o.tag===3?d:null}function Bn(i){if(i.tag===13){var o=i.memoizedState;if(o===null&&(i=i.alternate,i!==null&&(o=i.memoizedState)),o!==null)return o.dehydrated}return null}function cn(i){if(gt(i)!==i)throw Error(n(188))}function Gs(i){var o=i.alternate;if(!o){if(o=gt(i),o===null)throw Error(n(188));return o!==i?null:i}for(var d=i,p=o;;){var x=d.return;if(x===null)break;var j=x.alternate;if(j===null){if(p=x.return,p!==null){d=p;continue}break}if(x.child===j.child){for(j=x.child;j;){if(j===d)return cn(x),i;if(j===p)return cn(x),o;j=j.sibling}throw Error(n(188))}if(d.return!==p.return)d=x,p=j;else{for(var P=!1,ne=x.child;ne;){if(ne===d){P=!0,d=x,p=j;break}if(ne===p){P=!0,p=x,d=j;break}ne=ne.sibling}if(!P){for(ne=j.child;ne;){if(ne===d){P=!0,d=j,p=x;break}if(ne===p){P=!0,p=j,d=x;break}ne=ne.sibling}if(!P)throw Error(n(189))}}if(d.alternate!==p)throw Error(n(190))}if(d.tag!==3)throw Error(n(188));return d.stateNode.current===d?i:o}function ls(i){return i=Gs(i),i!==null?qr(i):null}function qr(i){if(i.tag===5||i.tag===6)return i;for(i=i.child;i!==null;){var o=qr(i);if(o!==null)return o;i=i.sibling}return null}var hr=t.unstable_scheduleCallback,ni=t.unstable_cancelCallback,si=t.unstable_shouldYield,Ps=t.unstable_requestPaint,me=t.unstable_now,mr=t.unstable_getCurrentPriorityLevel,na=t.unstable_ImmediatePriority,_r=t.unstable_UserBlockingPriority,Sr=t.unstable_NormalPriority,Hr=t.unstable_LowPriority,dt=t.unstable_IdlePriority,fn=null,Ds=null;function Vr(i){if(Ds&&typeof Ds.onCommitFiberRoot=="function")try{Ds.onCommitFiberRoot(fn,i,void 0,(i.current.flags&128)===128)}catch{}}var cs=Math.clz32?Math.clz32:za,Da=Math.log,Fa=Math.LN2;function za(i){return i>>>=0,i===0?32:31-(Da(i)/Fa|0)|0}var Fn=64,pr=4194304;function Hn(i){switch(i&-i){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return i&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return i}}function sa(i,o){var d=i.pendingLanes;if(d===0)return 0;var p=0,x=i.suspendedLanes,j=i.pingedLanes,P=d&268435455;if(P!==0){var ne=P&~x;ne!==0?p=Hn(ne):(j&=P,j!==0&&(p=Hn(j)))}else P=d&~x,P!==0?p=Hn(P):j!==0&&(p=Hn(j));if(p===0)return 0;if(o!==0&&o!==p&&(o&x)===0&&(x=p&-p,j=o&-o,x>=j||x===16&&(j&4194240)!==0))return o;if((p&4)!==0&&(p|=d&16),o=i.entangledLanes,o!==0)for(i=i.entanglements,o&=p;0<o;)d=31-cs(o),x=1<<d,p|=i[d],o&=~x;return p}function ri(i,o){switch(i){case 1:case 2:case 4:return o+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 o+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 Mn(i,o){for(var d=i.suspendedLanes,p=i.pingedLanes,x=i.expirationTimes,j=i.pendingLanes;0<j;){var P=31-cs(j),ne=1<<P,ae=x[P];ae===-1?((ne&d)===0||(ne&p)!==0)&&(x[P]=ri(ne,o)):ae<=o&&(i.expiredLanes|=ne),j&=~ne}}function Fs(i){return i=i.pendingLanes&-1073741825,i!==0?i:i&1073741824?1073741824:0}function ps(){var i=Fn;return Fn<<=1,(Fn&4194240)===0&&(Fn=64),i}function Ks(i){for(var o=[],d=0;31>d;d++)o.push(i);return o}function gs(i,o,d){i.pendingLanes|=o,o!==536870912&&(i.suspendedLanes=0,i.pingedLanes=0),i=i.eventTimes,o=31-cs(o),i[o]=d}function So(i,o){var d=i.pendingLanes&~o;i.pendingLanes=o,i.suspendedLanes=0,i.pingedLanes=0,i.expiredLanes&=o,i.mutableReadLanes&=o,i.entangledLanes&=o,o=i.entanglements;var p=i.eventTimes;for(i=i.expirationTimes;0<d;){var x=31-cs(d),j=1<<x;o[x]=0,p[x]=-1,i[x]=-1,d&=~j}}function ra(i,o){var d=i.entangledLanes|=o;for(i=i.entanglements;d;){var p=31-cs(d),x=1<<p;x&o|i[p]&o&&(i[p]|=o),d&=~x}}var un=0;function No(i){return i&=-i,1<i?4<i?(i&268435455)!==0?16:536870912:4:1}var kc,Ba,ys,Nr,Cr,ia=!1,gr=[],Cs=null,yr=null,Er=null,Ys=new Map,Ci=new Map,us=[],$r="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 Co(i,o){switch(i){case"focusin":case"focusout":Cs=null;break;case"dragenter":case"dragleave":yr=null;break;case"mouseover":case"mouseout":Er=null;break;case"pointerover":case"pointerout":Ys.delete(o.pointerId);break;case"gotpointercapture":case"lostpointercapture":Ci.delete(o.pointerId)}}function wr(i,o,d,p,x,j){return i===null||i.nativeEvent!==j?(i={blockedOn:o,domEventName:d,eventSystemFlags:p,nativeEvent:j,targetContainers:[x]},o!==null&&(o=Qa(o),o!==null&&Ba(o)),i):(i.eventSystemFlags|=p,o=i.targetContainers,x!==null&&o.indexOf(x)===-1&&o.push(x),i)}function aa(i,o,d,p,x){switch(o){case"focusin":return Cs=wr(Cs,i,o,d,p,x),!0;case"dragenter":return yr=wr(yr,i,o,d,p,x),!0;case"mouseover":return Er=wr(Er,i,o,d,p,x),!0;case"pointerover":var j=x.pointerId;return Ys.set(j,wr(Ys.get(j)||null,i,o,d,p,x)),!0;case"gotpointercapture":return j=x.pointerId,Ci.set(j,wr(Ci.get(j)||null,i,o,d,p,x)),!0}return!1}function jc(i){var o=Mr(i.target);if(o!==null){var d=gt(o);if(d!==null){if(o=d.tag,o===13){if(o=Bn(d),o!==null){i.blockedOn=o,Cr(i.priority,function(){ys(d)});return}}else if(o===3&&d.stateNode.current.memoizedState.isDehydrated){i.blockedOn=d.tag===3?d.stateNode.containerInfo:null;return}}}i.blockedOn=null}function Ei(i){if(i.blockedOn!==null)return!1;for(var o=i.targetContainers;0<o.length;){var d=ue(i.domEventName,i.eventSystemFlags,o[0],i.nativeEvent);if(d===null){d=i.nativeEvent;var p=new d.constructor(d.type,d);Kn=p,d.target.dispatchEvent(p),Kn=null}else return o=Qa(d),o!==null&&Ba(o),i.blockedOn=d,!1;o.shift()}return!0}function Js(i,o,d){Ei(i)&&d.delete(o)}function Yu(){ia=!1,Cs!==null&&Ei(Cs)&&(Cs=null),yr!==null&&Ei(yr)&&(yr=null),Er!==null&&Ei(Er)&&(Er=null),Ys.forEach(Js),Ci.forEach(Js)}function Xs(i,o){i.blockedOn===o&&(i.blockedOn=null,ia||(ia=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Yu)))}function oa(i){function o(x){return Xs(x,i)}if(0<gr.length){Xs(gr[0],i);for(var d=1;d<gr.length;d++){var p=gr[d];p.blockedOn===i&&(p.blockedOn=null)}}for(Cs!==null&&Xs(Cs,i),yr!==null&&Xs(yr,i),Er!==null&&Xs(Er,i),Ys.forEach(o),Ci.forEach(o),d=0;d<us.length;d++)p=us[d],p.blockedOn===i&&(p.blockedOn=null);for(;0<us.length&&(d=us[0],d.blockedOn===null);)jc(d),d.blockedOn===null&&us.shift()}var Zs=A.ReactCurrentBatchConfig,Ua=!0;function ii(i,o,d,p){var x=un,j=Zs.transition;Zs.transition=null;try{un=1,ai(i,o,d,p)}finally{un=x,Zs.transition=j}}function Eo(i,o,d,p){var x=un,j=Zs.transition;Zs.transition=null;try{un=4,ai(i,o,d,p)}finally{un=x,Zs.transition=j}}function ai(i,o,d,p){if(Ua){var x=ue(i,o,d,p);if(x===null)fd(i,o,p,q,d),Co(i,p);else if(aa(x,i,o,d,p))p.stopPropagation();else if(Co(i,p),o&4&&-1<$r.indexOf(i)){for(;x!==null;){var j=Qa(x);if(j!==null&&kc(j),j=ue(i,o,d,p),j===null&&fd(i,o,p,q,d),j===x)break;x=j}x!==null&&p.stopPropagation()}else fd(i,o,p,null,d)}}var q=null;function ue(i,o,d,p){if(q=null,i=Ns(p),i=Mr(i),i!==null)if(o=gt(i),o===null)i=null;else if(d=o.tag,d===13){if(i=Bn(o),i!==null)return i;i=null}else if(d===3){if(o.stateNode.current.memoizedState.isDehydrated)return o.tag===3?o.stateNode.containerInfo:null;i=null}else o!==i&&(i=null);return q=i,null}function je(i){switch(i){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(mr()){case na:return 1;case _r:return 4;case Sr:case Hr:return 16;case dt:return 536870912;default:return 16}default:return 16}}var $e=null,Ee=null,Ve=null;function yt(){if(Ve)return Ve;var i,o=Ee,d=o.length,p,x="value"in $e?$e.value:$e.textContent,j=x.length;for(i=0;i<d&&o[i]===x[i];i++);var P=d-i;for(p=1;p<=P&&o[d-p]===x[j-p];p++);return Ve=x.slice(i,1<p?1-p:void 0)}function _t(i){var o=i.keyCode;return"charCode"in i?(i=i.charCode,i===0&&o===13&&(i=13)):i=o,i===10&&(i=13),32<=i||i===13?i:0}function vt(){return!0}function qt(){return!1}function Yt(i){function o(d,p,x,j,P){this._reactName=d,this._targetInst=x,this.type=p,this.nativeEvent=j,this.target=P,this.currentTarget=null;for(var ne in i)i.hasOwnProperty(ne)&&(d=i[ne],this[ne]=d?d(j):j[ne]);return this.isDefaultPrevented=(j.defaultPrevented!=null?j.defaultPrevented:j.returnValue===!1)?vt:qt,this.isPropagationStopped=qt,this}return K(o.prototype,{preventDefault:function(){this.defaultPrevented=!0;var d=this.nativeEvent;d&&(d.preventDefault?d.preventDefault():typeof d.returnValue!="unknown"&&(d.returnValue=!1),this.isDefaultPrevented=vt)},stopPropagation:function(){var d=this.nativeEvent;d&&(d.stopPropagation?d.stopPropagation():typeof d.cancelBubble!="unknown"&&(d.cancelBubble=!0),this.isPropagationStopped=vt)},persist:function(){},isPersistent:vt}),o}var ws={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(i){return i.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ft=Yt(ws),dn=K({},ws,{view:0,detail:0}),En=Yt(dn),vn,ts,Qs,Gr=K({},dn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:vl,button:0,buttons:0,relatedTarget:function(i){return i.relatedTarget===void 0?i.fromElement===i.srcElement?i.toElement:i.fromElement:i.relatedTarget},movementX:function(i){return"movementX"in i?i.movementX:(i!==Qs&&(Qs&&i.type==="mousemove"?(vn=i.screenX-Qs.screenX,ts=i.screenY-Qs.screenY):ts=vn=0,Qs=i),vn)},movementY:function(i){return"movementY"in i?i.movementY:ts}}),$i=Yt(Gr),$o=K({},Gr,{dataTransfer:0}),oh=Yt($o),Sc=K({},dn,{relatedTarget:0}),wl=Yt(Sc),Nc=K({},ws,{animationName:0,elapsedTime:0,pseudoElement:0}),Cc=Yt(Nc),Ec=K({},ws,{clipboardData:function(i){return"clipboardData"in i?i.clipboardData:window.clipboardData}}),lh=Yt(Ec),Wa=K({},ws,{data:0}),Ju=Yt(Wa),Xu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Zu={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},T_={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Qu(i){var o=this.nativeEvent;return o.getModifierState?o.getModifierState(i):(i=T_[i])?!!o[i]:!1}function vl(){return Qu}var an=K({},dn,{key:function(i){if(i.key){var o=Xu[i.key]||i.key;if(o!=="Unidentified")return o}return i.type==="keypress"?(i=_t(i),i===13?"Enter":String.fromCharCode(i)):i.type==="keydown"||i.type==="keyup"?Zu[i.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:vl,charCode:function(i){return i.type==="keypress"?_t(i):0},keyCode:function(i){return i.type==="keydown"||i.type==="keyup"?i.keyCode:0},which:function(i){return i.type==="keypress"?_t(i):i.type==="keydown"||i.type==="keyup"?i.keyCode:0}}),ed=Yt(an),M_=K({},Gr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),$c=Yt(M_),R_=K({},dn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:vl}),td=Yt(R_),L_=K({},ws,{propertyName:0,elapsedTime:0,pseudoElement:0}),er=Yt(L_),la=K({},Gr,{deltaX:function(i){return"deltaX"in i?i.deltaX:"wheelDeltaX"in i?-i.wheelDeltaX:0},deltaY:function(i){return"deltaY"in i?i.deltaY:"wheelDeltaY"in i?-i.wheelDeltaY:"wheelDelta"in i?-i.wheelDelta:0},deltaZ:0,deltaMode:0}),ch=Yt(la),I_=[9,13,27,32],ca=u&&"CompositionEvent"in window,qa=null;u&&"documentMode"in document&&(qa=document.documentMode);var xl=u&&"TextEvent"in window&&!qa,nd=u&&(!ca||qa&&8<qa&&11>=qa),uh=" ",dh=!1;function fh(i,o){switch(i){case"keyup":return I_.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function sd(i){return i=i.detail,typeof i=="object"&&"data"in i?i.data:null}var Ao=!1;function hh(i,o){switch(i){case"compositionend":return sd(o);case"keypress":return o.which!==32?null:(dh=!0,uh);case"textInput":return i=o.data,i===uh&&dh?null:i;default:return null}}function O_(i,o){if(Ao)return i==="compositionend"||!ca&&fh(i,o)?(i=yt(),Ve=Ee=$e=null,Ao=!1,i):null;switch(i){case"paste":return null;case"keypress":if(!(o.ctrlKey||o.altKey||o.metaKey)||o.ctrlKey&&o.altKey){if(o.char&&1<o.char.length)return o.char;if(o.which)return String.fromCharCode(o.which)}return null;case"compositionend":return nd&&o.locale!=="ko"?null:o.data;default:return null}}var mh={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function rd(i){var o=i&&i.nodeName&&i.nodeName.toLowerCase();return o==="input"?!!mh[i.type]:o==="textarea"}function Ac(i,o,d,p){et(p),o=Pc(o,"onChange"),0<o.length&&(d=new Ft("onChange","change",null,d,p),i.push({event:d,listeners:o}))}var oi=null,Ai=null;function To(i){cd(i,0)}function ua(i){var o=zo(i);if(ut(o))return i}function Tc(i,o){if(i==="change")return o}var Mc=!1;if(u){var Rc;if(u){var Ha="oninput"in document;if(!Ha){var id=document.createElement("div");id.setAttribute("oninput","return;"),Ha=typeof id.oninput=="function"}Rc=Ha}else Rc=!1;Mc=Rc&&(!document.documentMode||9<document.documentMode)}function Mo(){oi&&(oi.detachEvent("onpropertychange",Ro),Ai=oi=null)}function Ro(i){if(i.propertyName==="value"&&ua(Ai)){var o=[];Ac(o,Ai,i,Ns(i)),Ct(To,o)}}function P_(i,o,d){i==="focusin"?(Mo(),oi=o,Ai=d,oi.attachEvent("onpropertychange",Ro)):i==="focusout"&&Mo()}function ad(i){if(i==="selectionchange"||i==="keyup"||i==="keydown")return ua(Ai)}function D_(i,o){if(i==="click")return ua(o)}function F_(i,o){if(i==="input"||i==="change")return ua(o)}function Lc(i,o){return i===o&&(i!==0||1/i===1/o)||i!==i&&o!==o}var ns=typeof Object.is=="function"?Object.is:Lc;function li(i,o){if(ns(i,o))return!0;if(typeof i!="object"||i===null||typeof o!="object"||o===null)return!1;var d=Object.keys(i),p=Object.keys(o);if(d.length!==p.length)return!1;for(p=0;p<d.length;p++){var x=d[p];if(!f.call(o,x)||!ns(i[x],o[x]))return!1}return!0}function _h(i){for(;i&&i.firstChild;)i=i.firstChild;return i}function bl(i,o){var d=_h(i);i=0;for(var p;d;){if(d.nodeType===3){if(p=i+d.textContent.length,i<=o&&p>=o)return{node:d,offset:o-i};i=p}e:{for(;d;){if(d.nextSibling){d=d.nextSibling;break e}d=d.parentNode}d=void 0}d=_h(d)}}function ph(i,o){return i&&o?i===o?!0:i&&i.nodeType===3?!1:o&&o.nodeType===3?ph(i,o.parentNode):"contains"in i?i.contains(o):i.compareDocumentPosition?!!(i.compareDocumentPosition(o)&16):!1:!1}function Ic(){for(var i=window,o=De();o instanceof i.HTMLIFrameElement;){try{var d=typeof o.contentWindow.location.href=="string"}catch{d=!1}if(d)i=o.contentWindow;else break;o=De(i.document)}return o}function Va(i){var o=i&&i.nodeName&&i.nodeName.toLowerCase();return o&&(o==="input"&&(i.type==="text"||i.type==="search"||i.type==="tel"||i.type==="url"||i.type==="password")||o==="textarea"||i.contentEditable==="true")}function Ar(i){var o=Ic(),d=i.focusedElem,p=i.selectionRange;if(o!==d&&d&&d.ownerDocument&&ph(d.ownerDocument.documentElement,d)){if(p!==null&&Va(d)){if(o=p.start,i=p.end,i===void 0&&(i=o),"selectionStart"in d)d.selectionStart=o,d.selectionEnd=Math.min(i,d.value.length);else if(i=(o=d.ownerDocument||document)&&o.defaultView||window,i.getSelection){i=i.getSelection();var x=d.textContent.length,j=Math.min(p.start,x);p=p.end===void 0?j:Math.min(p.end,x),!i.extend&&j>p&&(x=p,p=j,j=x),x=bl(d,j);var P=bl(d,p);x&&P&&(i.rangeCount!==1||i.anchorNode!==x.node||i.anchorOffset!==x.offset||i.focusNode!==P.node||i.focusOffset!==P.offset)&&(o=o.createRange(),o.setStart(x.node,x.offset),i.removeAllRanges(),j>p?(i.addRange(o),i.extend(P.node,P.offset)):(o.setEnd(P.node,P.offset),i.addRange(o)))}}for(o=[],i=d;i=i.parentNode;)i.nodeType===1&&o.push({element:i,left:i.scrollLeft,top:i.scrollTop});for(typeof d.focus=="function"&&d.focus(),d=0;d<o.length;d++)i=o[d],i.element.scrollLeft=i.left,i.element.scrollTop=i.top}}var da=u&&"documentMode"in document&&11>=document.documentMode,Ti=null,fa=null,Ga=null,Ka=!1;function Mi(i,o,d){var p=d.window===d?d.document:d.nodeType===9?d:d.ownerDocument;Ka||Ti==null||Ti!==De(p)||(p=Ti,"selectionStart"in p&&Va(p)?p={start:p.selectionStart,end:p.selectionEnd}:(p=(p.ownerDocument&&p.ownerDocument.defaultView||window).getSelection(),p={anchorNode:p.anchorNode,anchorOffset:p.anchorOffset,focusNode:p.focusNode,focusOffset:p.focusOffset}),Ga&&li(Ga,p)||(Ga=p,p=Pc(fa,"onSelect"),0<p.length&&(o=new Ft("onSelect","select",null,o,d),i.push({event:o,listeners:p}),o.target=Ti)))}function Ya(i,o){var d={};return d[i.toLowerCase()]=o.toLowerCase(),d["Webkit"+i]="webkit"+o,d["Moz"+i]="moz"+o,d}var ci={animationend:Ya("Animation","AnimationEnd"),animationiteration:Ya("Animation","AnimationIteration"),animationstart:Ya("Animation","AnimationStart"),transitionend:Ya("Transition","TransitionEnd")},ha={},Ri={};u&&(Ri=document.createElement("div").style,"AnimationEvent"in window||(delete ci.animationend.animation,delete ci.animationiteration.animation,delete ci.animationstart.animation),"TransitionEvent"in window||delete ci.transitionend.transition);function vs(i){if(ha[i])return ha[i];if(!ci[i])return i;var o=ci[i],d;for(d in o)if(o.hasOwnProperty(d)&&d in Ri)return ha[i]=o[d];return i}var ma=vs("animationend"),Ja=vs("animationiteration"),kl=vs("animationstart"),_a=vs("transitionend"),Oc=new Map,jl="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 xs(i,o){Oc.set(i,o),l(o,[i])}for(var ui=0;ui<jl.length;ui++){var Tr=jl[ui],gh=Tr.toLowerCase(),Sl=Tr[0].toUpperCase()+Tr.slice(1);xs(gh,"on"+Sl)}xs(ma,"onAnimationEnd"),xs(Ja,"onAnimationIteration"),xs(kl,"onAnimationStart"),xs("dblclick","onDoubleClick"),xs("focusin","onFocus"),xs("focusout","onBlur"),xs(_a,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Lo="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(" "),od=new Set("cancel close invalid load scroll toggle".split(" ").concat(Lo));function ld(i,o,d){var p=i.type||"unknown-event";i.currentTarget=d,rn(p,o,void 0,i),i.currentTarget=null}function cd(i,o){o=(o&4)!==0;for(var d=0;d<i.length;d++){var p=i[d],x=p.event;p=p.listeners;e:{var j=void 0;if(o)for(var P=p.length-1;0<=P;P--){var ne=p[P],ae=ne.instance,ve=ne.currentTarget;if(ne=ne.listener,ae!==j&&x.isPropagationStopped())break e;ld(x,ne,ve),j=ae}else for(P=0;P<p.length;P++){if(ne=p[P],ae=ne.instance,ve=ne.currentTarget,ne=ne.listener,ae!==j&&x.isPropagationStopped())break e;ld(x,ne,ve),j=ae}}}if(Dt)throw i=We,Dt=!1,We=null,i}function Sn(i,o){var d=o[$l];d===void 0&&(d=o[$l]=new Set);var p=i+"__bubble";d.has(p)||(dd(o,i,2,!1),d.add(p))}function ud(i,o,d){var p=0;o&&(p|=4),dd(d,i,p,o)}var Nl="_reactListening"+Math.random().toString(36).slice(2);function Cl(i){if(!i[Nl]){i[Nl]=!0,r.forEach(function(d){d!=="selectionchange"&&(od.has(d)||ud(d,!1,i),ud(d,!0,i))});var o=i.nodeType===9?i:i.ownerDocument;o===null||o[Nl]||(o[Nl]=!0,ud("selectionchange",!1,o))}}function dd(i,o,d,p){switch(je(o)){case 1:var x=ii;break;case 4:x=Eo;break;default:x=ai}d=x.bind(null,o,d,i),x=void 0,!jt||o!=="touchstart"&&o!=="touchmove"&&o!=="wheel"||(x=!0),p?x!==void 0?i.addEventListener(o,d,{capture:!0,passive:x}):i.addEventListener(o,d,!0):x!==void 0?i.addEventListener(o,d,{passive:x}):i.addEventListener(o,d,!1)}function fd(i,o,d,p,x){var j=p;if((o&1)===0&&(o&2)===0&&p!==null)e:for(;;){if(p===null)return;var P=p.tag;if(P===3||P===4){var ne=p.stateNode.containerInfo;if(ne===x||ne.nodeType===8&&ne.parentNode===x)break;if(P===4)for(P=p.return;P!==null;){var ae=P.tag;if((ae===3||ae===4)&&(ae=P.stateNode.containerInfo,ae===x||ae.nodeType===8&&ae.parentNode===x))return;P=P.return}for(;ne!==null;){if(P=Mr(ne),P===null)return;if(ae=P.tag,ae===5||ae===6){p=j=P;continue e}ne=ne.parentNode}}p=p.return}Ct(function(){var ve=j,Ie=Ns(d),Oe=[];e:{var Le=Oc.get(i);if(Le!==void 0){var tt=Ft,it=i;switch(i){case"keypress":if(_t(d)===0)break e;case"keydown":case"keyup":tt=ed;break;case"focusin":it="focus",tt=wl;break;case"focusout":it="blur",tt=wl;break;case"beforeblur":case"afterblur":tt=wl;break;case"click":if(d.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":tt=$i;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":tt=oh;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":tt=td;break;case ma:case Ja:case kl:tt=Cc;break;case _a:tt=er;break;case"scroll":tt=En;break;case"wheel":tt=ch;break;case"copy":case"cut":case"paste":tt=lh;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":tt=$c}var ot=(o&4)!==0,os=!ot&&i==="scroll",ge=ot?Le!==null?Le+"Capture":null:Le;ot=[];for(var de=ve,we;de!==null;){we=de;var Fe=we.stateNode;if(we.tag===5&&Fe!==null&&(we=Fe,ge!==null&&(Fe=Qt(de,ge),Fe!=null&&ot.push(Io(de,Fe,we)))),os)break;de=de.return}0<ot.length&&(Le=new tt(Le,it,null,d,Ie),Oe.push({event:Le,listeners:ot}))}}if((o&7)===0){e:{if(Le=i==="mouseover"||i==="pointerover",tt=i==="mouseout"||i==="pointerout",Le&&d!==Kn&&(it=d.relatedTarget||d.fromElement)&&(Mr(it)||it[di]))break e;if((tt||Le)&&(Le=Ie.window===Ie?Ie:(Le=Ie.ownerDocument)?Le.defaultView||Le.parentWindow:window,tt?(it=d.relatedTarget||d.toElement,tt=ve,it=it?Mr(it):null,it!==null&&(os=gt(it),it!==os||it.tag!==5&&it.tag!==6)&&(it=null)):(tt=null,it=ve),tt!==it)){if(ot=$i,Fe="onMouseLeave",ge="onMouseEnter",de="mouse",(i==="pointerout"||i==="pointerover")&&(ot=$c,Fe="onPointerLeave",ge="onPointerEnter",de="pointer"),os=tt==null?Le:zo(tt),we=it==null?Le:zo(it),Le=new ot(Fe,de+"leave",tt,d,Ie),Le.target=os,Le.relatedTarget=we,Fe=null,Mr(Ie)===ve&&(ot=new ot(ge,de+"enter",it,d,Ie),ot.target=we,ot.relatedTarget=os,Fe=ot),os=Fe,tt&&it)t:{for(ot=tt,ge=it,de=0,we=ot;we;we=Xa(we))de++;for(we=0,Fe=ge;Fe;Fe=Xa(Fe))we++;for(;0<de-we;)ot=Xa(ot),de--;for(;0<we-de;)ge=Xa(ge),we--;for(;de--;){if(ot===ge||ge!==null&&ot===ge.alternate)break t;ot=Xa(ot),ge=Xa(ge)}ot=null}else ot=null;tt!==null&&yh(Oe,Le,tt,ot,!1),it!==null&&os!==null&&yh(Oe,os,it,ot,!0)}}e:{if(Le=ve?zo(ve):window,tt=Le.nodeName&&Le.nodeName.toLowerCase(),tt==="select"||tt==="input"&&Le.type==="file")var ft=Tc;else if(rd(Le))if(Mc)ft=F_;else{ft=ad;var xt=P_}else(tt=Le.nodeName)&&tt.toLowerCase()==="input"&&(Le.type==="checkbox"||Le.type==="radio")&&(ft=D_);if(ft&&(ft=ft(i,ve))){Ac(Oe,ft,d,Ie);break e}xt&&xt(i,Le,ve),i==="focusout"&&(xt=Le._wrapperState)&&xt.controlled&&Le.type==="number"&&Ae(Le,"number",Le.value)}switch(xt=ve?zo(ve):window,i){case"focusin":(rd(xt)||xt.contentEditable==="true")&&(Ti=xt,fa=ve,Ga=null);break;case"focusout":Ga=fa=Ti=null;break;case"mousedown":Ka=!0;break;case"contextmenu":case"mouseup":case"dragend":Ka=!1,Mi(Oe,d,Ie);break;case"selectionchange":if(da)break;case"keydown":case"keyup":Mi(Oe,d,Ie)}var bt;if(ca)e:{switch(i){case"compositionstart":var Mt="onCompositionStart";break e;case"compositionend":Mt="onCompositionEnd";break e;case"compositionupdate":Mt="onCompositionUpdate";break e}Mt=void 0}else Ao?fh(i,d)&&(Mt="onCompositionEnd"):i==="keydown"&&d.keyCode===229&&(Mt="onCompositionStart");Mt&&(nd&&d.locale!=="ko"&&(Ao||Mt!=="onCompositionStart"?Mt==="onCompositionEnd"&&Ao&&(bt=yt()):($e=Ie,Ee="value"in $e?$e.value:$e.textContent,Ao=!0)),xt=Pc(ve,Mt),0<xt.length&&(Mt=new Ju(Mt,i,null,d,Ie),Oe.push({event:Mt,listeners:xt}),bt?Mt.data=bt:(bt=sd(d),bt!==null&&(Mt.data=bt)))),(bt=xl?hh(i,d):O_(i,d))&&(ve=Pc(ve,"onBeforeInput"),0<ve.length&&(Ie=new Ju("onBeforeInput","beforeinput",null,d,Ie),Oe.push({event:Ie,listeners:ve}),Ie.data=bt))}cd(Oe,o)})}function Io(i,o,d){return{instance:i,listener:o,currentTarget:d}}function Pc(i,o){for(var d=o+"Capture",p=[];i!==null;){var x=i,j=x.stateNode;x.tag===5&&j!==null&&(x=j,j=Qt(i,d),j!=null&&p.unshift(Io(i,j,x)),j=Qt(i,o),j!=null&&p.push(Io(i,j,x))),i=i.return}return p}function Xa(i){if(i===null)return null;do i=i.return;while(i&&i.tag!==5);return i||null}function yh(i,o,d,p,x){for(var j=o._reactName,P=[];d!==null&&d!==p;){var ne=d,ae=ne.alternate,ve=ne.stateNode;if(ae!==null&&ae===p)break;ne.tag===5&&ve!==null&&(ne=ve,x?(ae=Qt(d,j),ae!=null&&P.unshift(Io(d,ae,ne))):x||(ae=Qt(d,j),ae!=null&&P.push(Io(d,ae,ne)))),d=d.return}P.length!==0&&i.push({event:o,listeners:P})}var wh=/\r\n?/g,El=/\u0000|\uFFFD/g;function vh(i){return(typeof i=="string"?i:""+i).replace(wh,`
|
|
38
|
-
`).replace(El,"")}function pa(i,o,d){if(o=vh(o),vh(i)!==o&&d)throw Error(n(425))}function Oo(){}var Po=null,Dc=null;function ga(i,o){return i==="textarea"||i==="noscript"||typeof o.children=="string"||typeof o.children=="number"||typeof o.dangerouslySetInnerHTML=="object"&&o.dangerouslySetInnerHTML!==null&&o.dangerouslySetInnerHTML.__html!=null}var hd=typeof setTimeout=="function"?setTimeout:void 0,Fc=typeof clearTimeout=="function"?clearTimeout:void 0,xh=typeof Promise=="function"?Promise:void 0,Do=typeof queueMicrotask=="function"?queueMicrotask:typeof xh<"u"?function(i){return xh.resolve(null).then(i).catch(z_)}:hd;function z_(i){setTimeout(function(){throw i})}function Fo(i,o){var d=o,p=0;do{var x=d.nextSibling;if(i.removeChild(d),x&&x.nodeType===8)if(d=x.data,d==="/$"){if(p===0){i.removeChild(x),oa(o);return}p--}else d!=="$"&&d!=="$?"&&d!=="$!"||p++;d=x}while(d);oa(o)}function ya(i){for(;i!=null;i=i.nextSibling){var o=i.nodeType;if(o===1||o===3)break;if(o===8){if(o=i.data,o==="$"||o==="$!"||o==="$?")break;if(o==="/$")return null}}return i}function Li(i){i=i.previousSibling;for(var o=0;i;){if(i.nodeType===8){var d=i.data;if(d==="$"||d==="$!"||d==="$?"){if(o===0)return i;o--}else d==="/$"&&o++}i=i.previousSibling}return null}var Za=Math.random().toString(36).slice(2),tr="__reactFiber$"+Za,Ii="__reactProps$"+Za,di="__reactContainer$"+Za,$l="__reactEvents$"+Za,Al="__reactListeners$"+Za,md="__reactHandles$"+Za;function Mr(i){var o=i[tr];if(o)return o;for(var d=i.parentNode;d;){if(o=d[di]||d[tr]){if(d=o.alternate,o.child!==null||d!==null&&d.child!==null)for(i=Li(i);i!==null;){if(d=i[tr])return d;i=Li(i)}return o}i=d,d=i.parentNode}return null}function Qa(i){return i=i[tr]||i[di],!i||i.tag!==5&&i.tag!==6&&i.tag!==13&&i.tag!==3?null:i}function zo(i){if(i.tag===5||i.tag===6)return i.stateNode;throw Error(n(33))}function Bo(i){return i[Ii]||null}var Tl=[],Uo=-1;function wa(i){return{current:i}}function mn(i){0>Uo||(i.current=Tl[Uo],Tl[Uo]=null,Uo--)}function Ht(i,o){Uo++,Tl[Uo]=i.current,i.current=o}var Kr={},ds=wa(Kr),nr=wa(!1),eo=Kr;function va(i,o){var d=i.type.contextTypes;if(!d)return Kr;var p=i.stateNode;if(p&&p.__reactInternalMemoizedUnmaskedChildContext===o)return p.__reactInternalMemoizedMaskedChildContext;var x={},j;for(j in d)x[j]=o[j];return p&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=o,i.__reactInternalMemoizedMaskedChildContext=x),x}function sr(i){return i=i.childContextTypes,i!=null}function to(){mn(nr),mn(ds)}function _d(i,o,d){if(ds.current!==Kr)throw Error(n(168));Ht(ds,o),Ht(nr,d)}function Ml(i,o,d){var p=i.stateNode;if(o=o.childContextTypes,typeof p.getChildContext!="function")return d;p=p.getChildContext();for(var x in p)if(!(x in o))throw Error(n(108,pe(i)||"Unknown",x));return K({},d,p)}function Rl(i){return i=(i=i.stateNode)&&i.__reactInternalMemoizedMergedChildContext||Kr,eo=ds.current,Ht(ds,i),Ht(nr,nr.current),!0}function pd(i,o,d){var p=i.stateNode;if(!p)throw Error(n(169));d?(i=Ml(i,o,eo),p.__reactInternalMemoizedMergedChildContext=i,mn(nr),mn(ds),Ht(ds,i)):mn(nr),Ht(nr,d)}var Oi=null,Ll=!1,zc=!1;function gd(i){Oi===null?Oi=[i]:Oi.push(i)}function B_(i){Ll=!0,gd(i)}function Pi(){if(!zc&&Oi!==null){zc=!0;var i=0,o=un;try{var d=Oi;for(un=1;i<d.length;i++){var p=d[i];do p=p(!0);while(p!==null)}Oi=null,Ll=!1}catch(x){throw Oi!==null&&(Oi=Oi.slice(i+1)),hr(na,Pi),x}finally{un=o,zc=!1}}return null}var Di=[],Wo=0,Bc=null,Uc=0,Rr=[],rr=0,no=null,Yr=1,Fi="";function xa(i,o){Di[Wo++]=Uc,Di[Wo++]=Bc,Bc=i,Uc=o}function bh(i,o,d){Rr[rr++]=Yr,Rr[rr++]=Fi,Rr[rr++]=no,no=i;var p=Yr;i=Fi;var x=32-cs(p)-1;p&=~(1<<x),d+=1;var j=32-cs(o)+x;if(30<j){var P=x-x%5;j=(p&(1<<P)-1).toString(32),p>>=P,x-=P,Yr=1<<32-cs(o)+x|d<<x|p,Fi=j+i}else Yr=1<<j|d<<x|p,Fi=i}function Il(i){i.return!==null&&(xa(i,1),bh(i,1,0))}function Pe(i){for(;i===Bc;)Bc=Di[--Wo],Di[Wo]=null,Uc=Di[--Wo],Di[Wo]=null;for(;i===no;)no=Rr[--rr],Rr[rr]=null,Fi=Rr[--rr],Rr[rr]=null,Yr=Rr[--rr],Rr[rr]=null}var on=null,zs=null,$n=!1,ir=null;function kh(i,o){var d=vi(5,null,null,0);d.elementType="DELETED",d.stateNode=o,d.return=i,o=i.deletions,o===null?(i.deletions=[d],i.flags|=16):o.push(d)}function jh(i,o){switch(i.tag){case 5:var d=i.type;return o=o.nodeType!==1||d.toLowerCase()!==o.nodeName.toLowerCase()?null:o,o!==null?(i.stateNode=o,on=i,zs=ya(o.firstChild),!0):!1;case 6:return o=i.pendingProps===""||o.nodeType!==3?null:o,o!==null?(i.stateNode=o,on=i,zs=null,!0):!1;case 13:return o=o.nodeType!==8?null:o,o!==null?(d=no!==null?{id:Yr,overflow:Fi}:null,i.memoizedState={dehydrated:o,treeContext:d,retryLane:1073741824},d=vi(18,null,null,0),d.stateNode=o,d.return=i,i.child=d,on=i,zs=null,!0):!1;default:return!1}}function yd(i){return(i.mode&1)!==0&&(i.flags&128)===0}function wd(i){if($n){var o=zs;if(o){var d=o;if(!jh(i,o)){if(yd(i))throw Error(n(418));o=ya(d.nextSibling);var p=on;o&&jh(i,o)?kh(p,d):(i.flags=i.flags&-4097|2,$n=!1,on=i)}}else{if(yd(i))throw Error(n(418));i.flags=i.flags&-4097|2,$n=!1,on=i}}}function vd(i){for(i=i.return;i!==null&&i.tag!==5&&i.tag!==3&&i.tag!==13;)i=i.return;on=i}function Ol(i){if(i!==on)return!1;if(!$n)return vd(i),$n=!0,!1;var o;if((o=i.tag!==3)&&!(o=i.tag!==5)&&(o=i.type,o=o!=="head"&&o!=="body"&&!ga(i.type,i.memoizedProps)),o&&(o=zs)){if(yd(i))throw Sh(),Error(n(418));for(;o;)kh(i,o),o=ya(o.nextSibling)}if(vd(i),i.tag===13){if(i=i.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(n(317));e:{for(i=i.nextSibling,o=0;i;){if(i.nodeType===8){var d=i.data;if(d==="/$"){if(o===0){zs=ya(i.nextSibling);break e}o--}else d!=="$"&&d!=="$!"&&d!=="$?"||o++}i=i.nextSibling}zs=null}}else zs=on?ya(i.stateNode.nextSibling):null;return!0}function Sh(){for(var i=zs;i;)i=ya(i.nextSibling)}function zi(){zs=on=null,$n=!1}function Wc(i){ir===null?ir=[i]:ir.push(i)}var Bs=A.ReactCurrentBatchConfig;function Wt(i,o,d){if(i=d.ref,i!==null&&typeof i!="function"&&typeof i!="object"){if(d._owner){if(d=d._owner,d){if(d.tag!==1)throw Error(n(309));var p=d.stateNode}if(!p)throw Error(n(147,i));var x=p,j=""+i;return o!==null&&o.ref!==null&&typeof o.ref=="function"&&o.ref._stringRef===j?o.ref:(o=function(P){var ne=x.refs;P===null?delete ne[j]:ne[j]=P},o._stringRef=j,o)}if(typeof i!="string")throw Error(n(284));if(!d._owner)throw Error(n(290,i))}return i}function ss(i,o){throw i=Object.prototype.toString.call(o),Error(n(31,i==="[object Object]"?"object with keys {"+Object.keys(o).join(", ")+"}":i))}function qc(i){var o=i._init;return o(i._payload)}function xd(i){function o(ge,de){if(i){var we=ge.deletions;we===null?(ge.deletions=[de],ge.flags|=16):we.push(de)}}function d(ge,de){if(!i)return null;for(;de!==null;)o(ge,de),de=de.sibling;return null}function p(ge,de){for(ge=new Map;de!==null;)de.key!==null?ge.set(de.key,de):ge.set(de.index,de),de=de.sibling;return ge}function x(ge,de){return ge=rl(ge,de),ge.index=0,ge.sibling=null,ge}function j(ge,de,we){return ge.index=we,i?(we=ge.alternate,we!==null?(we=we.index,we<de?(ge.flags|=2,de):we):(ge.flags|=2,de)):(ge.flags|=1048576,de)}function P(ge){return i&&ge.alternate===null&&(ge.flags|=2),ge}function ne(ge,de,we,Fe){return de===null||de.tag!==6?(de=G_(we,ge.mode,Fe),de.return=ge,de):(de=x(de,we),de.return=ge,de)}function ae(ge,de,we,Fe){var ft=we.type;return ft===H?Ie(ge,de,we.props.children,Fe,we.key):de!==null&&(de.elementType===ft||typeof ft=="object"&&ft!==null&&ft.$$typeof===M&&qc(ft)===de.type)?(Fe=x(de,we.props),Fe.ref=Wt(ge,de,we),Fe.return=ge,Fe):(Fe=Qh(we.type,we.key,we.props,null,ge.mode,Fe),Fe.ref=Wt(ge,de,we),Fe.return=ge,Fe)}function ve(ge,de,we,Fe){return de===null||de.tag!==4||de.stateNode.containerInfo!==we.containerInfo||de.stateNode.implementation!==we.implementation?(de=K_(we,ge.mode,Fe),de.return=ge,de):(de=x(de,we.children||[]),de.return=ge,de)}function Ie(ge,de,we,Fe,ft){return de===null||de.tag!==7?(de=tc(we,ge.mode,Fe,ft),de.return=ge,de):(de=x(de,we),de.return=ge,de)}function Oe(ge,de,we){if(typeof de=="string"&&de!==""||typeof de=="number")return de=G_(""+de,ge.mode,we),de.return=ge,de;if(typeof de=="object"&&de!==null){switch(de.$$typeof){case W:return we=Qh(de.type,de.key,de.props,null,ge.mode,we),we.ref=Wt(ge,null,de),we.return=ge,we;case z:return de=K_(de,ge.mode,we),de.return=ge,de;case M:var Fe=de._init;return Oe(ge,Fe(de._payload),we)}if(he(de)||U(de))return de=tc(de,ge.mode,we,null),de.return=ge,de;ss(ge,de)}return null}function Le(ge,de,we,Fe){var ft=de!==null?de.key:null;if(typeof we=="string"&&we!==""||typeof we=="number")return ft!==null?null:ne(ge,de,""+we,Fe);if(typeof we=="object"&&we!==null){switch(we.$$typeof){case W:return we.key===ft?ae(ge,de,we,Fe):null;case z:return we.key===ft?ve(ge,de,we,Fe):null;case M:return ft=we._init,Le(ge,de,ft(we._payload),Fe)}if(he(we)||U(we))return ft!==null?null:Ie(ge,de,we,Fe,null);ss(ge,we)}return null}function tt(ge,de,we,Fe,ft){if(typeof Fe=="string"&&Fe!==""||typeof Fe=="number")return ge=ge.get(we)||null,ne(de,ge,""+Fe,ft);if(typeof Fe=="object"&&Fe!==null){switch(Fe.$$typeof){case W:return ge=ge.get(Fe.key===null?we:Fe.key)||null,ae(de,ge,Fe,ft);case z:return ge=ge.get(Fe.key===null?we:Fe.key)||null,ve(de,ge,Fe,ft);case M:var xt=Fe._init;return tt(ge,de,we,xt(Fe._payload),ft)}if(he(Fe)||U(Fe))return ge=ge.get(we)||null,Ie(de,ge,Fe,ft,null);ss(de,Fe)}return null}function it(ge,de,we,Fe){for(var ft=null,xt=null,bt=de,Mt=de=0,Ms=null;bt!==null&&Mt<we.length;Mt++){bt.index>Mt?(Ms=bt,bt=null):Ms=bt.sibling;var _n=Le(ge,bt,we[Mt],Fe);if(_n===null){bt===null&&(bt=Ms);break}i&&bt&&_n.alternate===null&&o(ge,bt),de=j(_n,de,Mt),xt===null?ft=_n:xt.sibling=_n,xt=_n,bt=Ms}if(Mt===we.length)return d(ge,bt),$n&&xa(ge,Mt),ft;if(bt===null){for(;Mt<we.length;Mt++)bt=Oe(ge,we[Mt],Fe),bt!==null&&(de=j(bt,de,Mt),xt===null?ft=bt:xt.sibling=bt,xt=bt);return $n&&xa(ge,Mt),ft}for(bt=p(ge,bt);Mt<we.length;Mt++)Ms=tt(bt,ge,Mt,we[Mt],Fe),Ms!==null&&(i&&Ms.alternate!==null&&bt.delete(Ms.key===null?Mt:Ms.key),de=j(Ms,de,Mt),xt===null?ft=Ms:xt.sibling=Ms,xt=Ms);return i&&bt.forEach(function(il){return o(ge,il)}),$n&&xa(ge,Mt),ft}function ot(ge,de,we,Fe){var ft=U(we);if(typeof ft!="function")throw Error(n(150));if(we=ft.call(we),we==null)throw Error(n(151));for(var xt=ft=null,bt=de,Mt=de=0,Ms=null,_n=we.next();bt!==null&&!_n.done;Mt++,_n=we.next()){bt.index>Mt?(Ms=bt,bt=null):Ms=bt.sibling;var il=Le(ge,bt,_n.value,Fe);if(il===null){bt===null&&(bt=Ms);break}i&&bt&&il.alternate===null&&o(ge,bt),de=j(il,de,Mt),xt===null?ft=il:xt.sibling=il,xt=il,bt=Ms}if(_n.done)return d(ge,bt),$n&&xa(ge,Mt),ft;if(bt===null){for(;!_n.done;Mt++,_n=we.next())_n=Oe(ge,_n.value,Fe),_n!==null&&(de=j(_n,de,Mt),xt===null?ft=_n:xt.sibling=_n,xt=_n);return $n&&xa(ge,Mt),ft}for(bt=p(ge,bt);!_n.done;Mt++,_n=we.next())_n=tt(bt,ge,Mt,_n.value,Fe),_n!==null&&(i&&_n.alternate!==null&&bt.delete(_n.key===null?Mt:_n.key),de=j(_n,de,Mt),xt===null?ft=_n:xt.sibling=_n,xt=_n);return i&&bt.forEach(function(nS){return o(ge,nS)}),$n&&xa(ge,Mt),ft}function os(ge,de,we,Fe){if(typeof we=="object"&&we!==null&&we.type===H&&we.key===null&&(we=we.props.children),typeof we=="object"&&we!==null){switch(we.$$typeof){case W:e:{for(var ft=we.key,xt=de;xt!==null;){if(xt.key===ft){if(ft=we.type,ft===H){if(xt.tag===7){d(ge,xt.sibling),de=x(xt,we.props.children),de.return=ge,ge=de;break e}}else if(xt.elementType===ft||typeof ft=="object"&&ft!==null&&ft.$$typeof===M&&qc(ft)===xt.type){d(ge,xt.sibling),de=x(xt,we.props),de.ref=Wt(ge,xt,we),de.return=ge,ge=de;break e}d(ge,xt);break}else o(ge,xt);xt=xt.sibling}we.type===H?(de=tc(we.props.children,ge.mode,Fe,we.key),de.return=ge,ge=de):(Fe=Qh(we.type,we.key,we.props,null,ge.mode,Fe),Fe.ref=Wt(ge,de,we),Fe.return=ge,ge=Fe)}return P(ge);case z:e:{for(xt=we.key;de!==null;){if(de.key===xt)if(de.tag===4&&de.stateNode.containerInfo===we.containerInfo&&de.stateNode.implementation===we.implementation){d(ge,de.sibling),de=x(de,we.children||[]),de.return=ge,ge=de;break e}else{d(ge,de);break}else o(ge,de);de=de.sibling}de=K_(we,ge.mode,Fe),de.return=ge,ge=de}return P(ge);case M:return xt=we._init,os(ge,de,xt(we._payload),Fe)}if(he(we))return it(ge,de,we,Fe);if(U(we))return ot(ge,de,we,Fe);ss(ge,we)}return typeof we=="string"&&we!==""||typeof we=="number"?(we=""+we,de!==null&&de.tag===6?(d(ge,de.sibling),de=x(de,we),de.return=ge,ge=de):(d(ge,de),de=G_(we,ge.mode,Fe),de.return=ge,ge=de),P(ge)):d(ge,de)}return os}var fi=xd(!0),so=xd(!1),Et=wa(null),Hc=null,ba=null,bd=null;function kd(){bd=ba=Hc=null}function jd(i){var o=Et.current;mn(Et),i._currentValue=o}function Sd(i,o,d){for(;i!==null;){var p=i.alternate;if((i.childLanes&o)!==o?(i.childLanes|=o,p!==null&&(p.childLanes|=o)):p!==null&&(p.childLanes&o)!==o&&(p.childLanes|=o),i===d)break;i=i.return}}function ka(i,o){Hc=i,bd=ba=null,i=i.dependencies,i!==null&&i.firstContext!==null&&((i.lanes&o)!==0&&(Us=!0),i.firstContext=null)}function Yn(i){var o=i._currentValue;if(bd!==i)if(i={context:i,memoizedValue:o,next:null},ba===null){if(Hc===null)throw Error(n(308));ba=i,Hc.dependencies={lanes:0,firstContext:i}}else ba=ba.next=i;return o}var ja=null;function Bi(i){ja===null?ja=[i]:ja.push(i)}function Lr(i,o,d,p){var x=o.interleaved;return x===null?(d.next=d,Bi(o)):(d.next=x.next,x.next=d),o.interleaved=d,Ir(i,p)}function Ir(i,o){i.lanes|=o;var d=i.alternate;for(d!==null&&(d.lanes|=o),d=i,i=i.return;i!==null;)i.childLanes|=o,d=i.alternate,d!==null&&(d.childLanes|=o),d=i,i=i.return;return d.tag===3?d.stateNode:null}var Sa=!1;function Nd(i){i.updateQueue={baseState:i.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Vc(i,o){i=i.updateQueue,o.updateQueue===i&&(o.updateQueue={baseState:i.baseState,firstBaseUpdate:i.firstBaseUpdate,lastBaseUpdate:i.lastBaseUpdate,shared:i.shared,effects:i.effects})}function hi(i,o){return{eventTime:i,lane:o,tag:0,payload:null,callback:null,next:null}}function mi(i,o,d){var p=i.updateQueue;if(p===null)return null;if(p=p.shared,(tn&2)!==0){var x=p.pending;return x===null?o.next=o:(o.next=x.next,x.next=o),p.pending=o,Ir(i,d)}return x=p.interleaved,x===null?(o.next=o,Bi(p)):(o.next=x.next,x.next=o),p.interleaved=o,Ir(i,d)}function Gc(i,o,d){if(o=o.updateQueue,o!==null&&(o=o.shared,(d&4194240)!==0)){var p=o.lanes;p&=i.pendingLanes,d|=p,o.lanes=d,ra(i,d)}}function Un(i,o){var d=i.updateQueue,p=i.alternate;if(p!==null&&(p=p.updateQueue,d===p)){var x=null,j=null;if(d=d.firstBaseUpdate,d!==null){do{var P={eventTime:d.eventTime,lane:d.lane,tag:d.tag,payload:d.payload,callback:d.callback,next:null};j===null?x=j=P:j=j.next=P,d=d.next}while(d!==null);j===null?x=j=o:j=j.next=o}else x=j=o;d={baseState:p.baseState,firstBaseUpdate:x,lastBaseUpdate:j,shared:p.shared,effects:p.effects},i.updateQueue=d;return}i=d.lastBaseUpdate,i===null?d.firstBaseUpdate=o:i.next=o,d.lastBaseUpdate=o}function Pl(i,o,d,p){var x=i.updateQueue;Sa=!1;var j=x.firstBaseUpdate,P=x.lastBaseUpdate,ne=x.shared.pending;if(ne!==null){x.shared.pending=null;var ae=ne,ve=ae.next;ae.next=null,P===null?j=ve:P.next=ve,P=ae;var Ie=i.alternate;Ie!==null&&(Ie=Ie.updateQueue,ne=Ie.lastBaseUpdate,ne!==P&&(ne===null?Ie.firstBaseUpdate=ve:ne.next=ve,Ie.lastBaseUpdate=ae))}if(j!==null){var Oe=x.baseState;P=0,Ie=ve=ae=null,ne=j;do{var Le=ne.lane,tt=ne.eventTime;if((p&Le)===Le){Ie!==null&&(Ie=Ie.next={eventTime:tt,lane:0,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null});e:{var it=i,ot=ne;switch(Le=o,tt=d,ot.tag){case 1:if(it=ot.payload,typeof it=="function"){Oe=it.call(tt,Oe,Le);break e}Oe=it;break e;case 3:it.flags=it.flags&-65537|128;case 0:if(it=ot.payload,Le=typeof it=="function"?it.call(tt,Oe,Le):it,Le==null)break e;Oe=K({},Oe,Le);break e;case 2:Sa=!0}}ne.callback!==null&&ne.lane!==0&&(i.flags|=64,Le=x.effects,Le===null?x.effects=[ne]:Le.push(ne))}else tt={eventTime:tt,lane:Le,tag:ne.tag,payload:ne.payload,callback:ne.callback,next:null},Ie===null?(ve=Ie=tt,ae=Oe):Ie=Ie.next=tt,P|=Le;if(ne=ne.next,ne===null){if(ne=x.shared.pending,ne===null)break;Le=ne,ne=Le.next,Le.next=null,x.lastBaseUpdate=Le,x.shared.pending=null}}while(!0);if(Ie===null&&(ae=Oe),x.baseState=ae,x.firstBaseUpdate=ve,x.lastBaseUpdate=Ie,o=x.shared.interleaved,o!==null){x=o;do P|=x.lane,x=x.next;while(x!==o)}else j===null&&(x.shared.lanes=0);Ta|=P,i.lanes=P,i.memoizedState=Oe}}function Kc(i,o,d){if(i=o.effects,o.effects=null,i!==null)for(o=0;o<i.length;o++){var p=i[o],x=p.callback;if(x!==null){if(p.callback=null,p=d,typeof x!="function")throw Error(n(191,x));x.call(p)}}}var fs={},Jr=wa(fs),Ui=wa(fs),ro=wa(fs);function Xr(i){if(i===fs)throw Error(n(174));return i}function Dl(i,o){switch(Ht(ro,o),Ht(Ui,i),Ht(Jr,fs),i=o.nodeType,i){case 9:case 11:o=(o=o.documentElement)?o.namespaceURI:St(null,"");break;default:i=i===8?o.parentNode:o,o=i.namespaceURI||null,i=i.tagName,o=St(o,i)}mn(Jr),Ht(Jr,o)}function qo(){mn(Jr),mn(Ui),mn(ro)}function Nh(i){Xr(ro.current);var o=Xr(Jr.current),d=St(o,i.type);o!==d&&(Ht(Ui,i),Ht(Jr,d))}function Cd(i){Ui.current===i&&(mn(Jr),mn(Ui))}var An=wa(0);function Fl(i){for(var o=i;o!==null;){if(o.tag===13){var d=o.memoizedState;if(d!==null&&(d=d.dehydrated,d===null||d.data==="$?"||d.data==="$!"))return o}else if(o.tag===19&&o.memoizedProps.revealOrder!==void 0){if((o.flags&128)!==0)return o}else if(o.child!==null){o.child.return=o,o=o.child;continue}if(o===i)break;for(;o.sibling===null;){if(o.return===null||o.return===i)return null;o=o.return}o.sibling.return=o.return,o=o.sibling}return null}var Ed=[];function zl(){for(var i=0;i<Ed.length;i++)Ed[i]._workInProgressVersionPrimary=null;Ed.length=0}var Yc=A.ReactCurrentDispatcher,Wi=A.ReactCurrentBatchConfig,io=0,Nn=null,rs=null,is=null,Or=!1,Bl=!1,Ul=0,U_=0;function Es(){throw Error(n(321))}function $d(i,o){if(o===null)return!1;for(var d=0;d<o.length&&d<i.length;d++)if(!ns(i[d],o[d]))return!1;return!0}function Ad(i,o,d,p,x,j){if(io=j,Nn=o,o.memoizedState=null,o.updateQueue=null,o.lanes=0,Yc.current=i===null||i.memoizedState===null?pi:Ca,i=d(p,x),Bl){j=0;do{if(Bl=!1,Ul=0,25<=j)throw Error(n(301));j+=1,is=rs=null,o.updateQueue=null,Yc.current=Ea,i=d(p,x)}while(Bl)}if(Yc.current=Jn,o=rs!==null&&rs.next!==null,io=0,is=rs=Nn=null,Or=!1,o)throw Error(n(300));return i}function Td(){var i=Ul!==0;return Ul=0,i}function zt(){var i={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return is===null?Nn.memoizedState=is=i:is=is.next=i,is}function bn(){if(rs===null){var i=Nn.alternate;i=i!==null?i.memoizedState:null}else i=rs.next;var o=is===null?Nn.memoizedState:is.next;if(o!==null)is=o,rs=i;else{if(i===null)throw Error(n(310));rs=i,i={memoizedState:rs.memoizedState,baseState:rs.baseState,baseQueue:rs.baseQueue,queue:rs.queue,next:null},is===null?Nn.memoizedState=is=i:is=is.next=i}return is}function hs(i,o){return typeof o=="function"?o(i):o}function Wl(i){var o=bn(),d=o.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var p=rs,x=p.baseQueue,j=d.pending;if(j!==null){if(x!==null){var P=x.next;x.next=j.next,j.next=P}p.baseQueue=x=j,d.pending=null}if(x!==null){j=x.next,p=p.baseState;var ne=P=null,ae=null,ve=j;do{var Ie=ve.lane;if((io&Ie)===Ie)ae!==null&&(ae=ae.next={lane:0,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null}),p=ve.hasEagerState?ve.eagerState:i(p,ve.action);else{var Oe={lane:Ie,action:ve.action,hasEagerState:ve.hasEagerState,eagerState:ve.eagerState,next:null};ae===null?(ne=ae=Oe,P=p):ae=ae.next=Oe,Nn.lanes|=Ie,Ta|=Ie}ve=ve.next}while(ve!==null&&ve!==j);ae===null?P=p:ae.next=ne,ns(p,o.memoizedState)||(Us=!0),o.memoizedState=p,o.baseState=P,o.baseQueue=ae,d.lastRenderedState=p}if(i=d.interleaved,i!==null){x=i;do j=x.lane,Nn.lanes|=j,Ta|=j,x=x.next;while(x!==i)}else x===null&&(d.lanes=0);return[o.memoizedState,d.dispatch]}function Ho(i){var o=bn(),d=o.queue;if(d===null)throw Error(n(311));d.lastRenderedReducer=i;var p=d.dispatch,x=d.pending,j=o.memoizedState;if(x!==null){d.pending=null;var P=x=x.next;do j=i(j,P.action),P=P.next;while(P!==x);ns(j,o.memoizedState)||(Us=!0),o.memoizedState=j,o.baseQueue===null&&(o.baseState=j),d.lastRenderedState=j}return[j,p]}function Md(){}function Ch(i,o){var d=Nn,p=bn(),x=o(),j=!ns(p.memoizedState,x);if(j&&(p.memoizedState=x,Us=!0),p=p.queue,Hl(ql.bind(null,d,p,i),[i]),p.getSnapshot!==o||j||is!==null&&is.memoizedState.tag&1){if(d.flags|=2048,Vo(9,Rd.bind(null,d,p,x,o),void 0,null),as===null)throw Error(n(349));(io&30)!==0||Eh(d,o,x)}return x}function Eh(i,o,d){i.flags|=16384,i={getSnapshot:o,value:d},o=Nn.updateQueue,o===null?(o={lastEffect:null,stores:null},Nn.updateQueue=o,o.stores=[i]):(d=o.stores,d===null?o.stores=[i]:d.push(i))}function Rd(i,o,d,p){o.value=d,o.getSnapshot=p,$h(o)&&Ah(i)}function ql(i,o,d){return d(function(){$h(o)&&Ah(i)})}function $h(i){var o=i.getSnapshot;i=i.value;try{var d=o();return!ns(i,d)}catch{return!0}}function Ah(i){var o=Ir(i,1);o!==null&&se(o,i,1,-1)}function Th(i){var o=zt();return typeof i=="function"&&(i=i()),o.memoizedState=o.baseState=i,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:hs,lastRenderedState:i},o.queue=i,i=i.dispatch=Jc.bind(null,Nn,i),[o.memoizedState,i]}function Vo(i,o,d,p){return i={tag:i,create:o,destroy:d,deps:p,next:null},o=Nn.updateQueue,o===null?(o={lastEffect:null,stores:null},Nn.updateQueue=o,o.lastEffect=i.next=i):(d=o.lastEffect,d===null?o.lastEffect=i.next=i:(p=d.next,d.next=i,i.next=p,o.lastEffect=i)),i}function Ld(){return bn().memoizedState}function _i(i,o,d,p){var x=zt();Nn.flags|=i,x.memoizedState=Vo(1|o,d,void 0,p===void 0?null:p)}function Go(i,o,d,p){var x=bn();p=p===void 0?null:p;var j=void 0;if(rs!==null){var P=rs.memoizedState;if(j=P.destroy,p!==null&&$d(p,P.deps)){x.memoizedState=Vo(o,d,j,p);return}}Nn.flags|=i,x.memoizedState=Vo(1|o,d,j,p)}function Id(i,o){return _i(8390656,8,i,o)}function Hl(i,o){return Go(2048,8,i,o)}function Od(i,o){return Go(4,2,i,o)}function Mh(i,o){return Go(4,4,i,o)}function Rh(i,o){if(typeof o=="function")return i=i(),o(i),function(){o(null)};if(o!=null)return i=i(),o.current=i,function(){o.current=null}}function Lh(i,o,d){return d=d!=null?d.concat([i]):null,Go(4,4,Rh.bind(null,o,i),d)}function Pd(){}function Ih(i,o){var d=bn();o=o===void 0?null:o;var p=d.memoizedState;return p!==null&&o!==null&&$d(o,p[1])?p[0]:(d.memoizedState=[i,o],i)}function Oh(i,o){var d=bn();o=o===void 0?null:o;var p=d.memoizedState;return p!==null&&o!==null&&$d(o,p[1])?p[0]:(i=i(),d.memoizedState=[i,o],i)}function Dd(i,o,d){return(io&21)===0?(i.baseState&&(i.baseState=!1,Us=!0),i.memoizedState=d):(ns(d,o)||(d=ps(),Nn.lanes|=d,Ta|=d,i.baseState=!0),o)}function Fd(i,o){var d=un;un=d!==0&&4>d?d:4,i(!0);var p=Wi.transition;Wi.transition={};try{i(!1),o()}finally{un=d,Wi.transition=p}}function Ph(){return bn().memoizedState}function W_(i,o,d){var p=X(i);if(d={lane:p,action:d,hasEagerState:!1,eagerState:null,next:null},Dh(i))Na(o,d);else if(d=Lr(i,o,d,p),d!==null){var x=Y();se(d,i,p,x),$s(d,o,p)}}function Jc(i,o,d){var p=X(i),x={lane:p,action:d,hasEagerState:!1,eagerState:null,next:null};if(Dh(i))Na(o,x);else{var j=i.alternate;if(i.lanes===0&&(j===null||j.lanes===0)&&(j=o.lastRenderedReducer,j!==null))try{var P=o.lastRenderedState,ne=j(P,d);if(x.hasEagerState=!0,x.eagerState=ne,ns(ne,P)){var ae=o.interleaved;ae===null?(x.next=x,Bi(o)):(x.next=ae.next,ae.next=x),o.interleaved=x;return}}catch{}finally{}d=Lr(i,o,x,p),d!==null&&(x=Y(),se(d,i,p,x),$s(d,o,p))}}function Dh(i){var o=i.alternate;return i===Nn||o!==null&&o===Nn}function Na(i,o){Bl=Or=!0;var d=i.pending;d===null?o.next=o:(o.next=d.next,d.next=o),i.pending=o}function $s(i,o,d){if((d&4194240)!==0){var p=o.lanes;p&=i.pendingLanes,d|=p,o.lanes=d,ra(i,d)}}var Jn={readContext:Yn,useCallback:Es,useContext:Es,useEffect:Es,useImperativeHandle:Es,useInsertionEffect:Es,useLayoutEffect:Es,useMemo:Es,useReducer:Es,useRef:Es,useState:Es,useDebugValue:Es,useDeferredValue:Es,useTransition:Es,useMutableSource:Es,useSyncExternalStore:Es,useId:Es,unstable_isNewReconciler:!1},pi={readContext:Yn,useCallback:function(i,o){return zt().memoizedState=[i,o===void 0?null:o],i},useContext:Yn,useEffect:Id,useImperativeHandle:function(i,o,d){return d=d!=null?d.concat([i]):null,_i(4194308,4,Rh.bind(null,o,i),d)},useLayoutEffect:function(i,o){return _i(4194308,4,i,o)},useInsertionEffect:function(i,o){return _i(4,2,i,o)},useMemo:function(i,o){var d=zt();return o=o===void 0?null:o,i=i(),d.memoizedState=[i,o],i},useReducer:function(i,o,d){var p=zt();return o=d!==void 0?d(o):o,p.memoizedState=p.baseState=o,i={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:i,lastRenderedState:o},p.queue=i,i=i.dispatch=W_.bind(null,Nn,i),[p.memoizedState,i]},useRef:function(i){var o=zt();return i={current:i},o.memoizedState=i},useState:Th,useDebugValue:Pd,useDeferredValue:function(i){return zt().memoizedState=i},useTransition:function(){var i=Th(!1),o=i[0];return i=Fd.bind(null,i[1]),zt().memoizedState=i,[o,i]},useMutableSource:function(){},useSyncExternalStore:function(i,o,d){var p=Nn,x=zt();if($n){if(d===void 0)throw Error(n(407));d=d()}else{if(d=o(),as===null)throw Error(n(349));(io&30)!==0||Eh(p,o,d)}x.memoizedState=d;var j={value:d,getSnapshot:o};return x.queue=j,Id(ql.bind(null,p,j,i),[i]),p.flags|=2048,Vo(9,Rd.bind(null,p,j,d,o),void 0,null),d},useId:function(){var i=zt(),o=as.identifierPrefix;if($n){var d=Fi,p=Yr;d=(p&~(1<<32-cs(p)-1)).toString(32)+d,o=":"+o+"R"+d,d=Ul++,0<d&&(o+="H"+d.toString(32)),o+=":"}else d=U_++,o=":"+o+"r"+d.toString(32)+":";return i.memoizedState=o},unstable_isNewReconciler:!1},Ca={readContext:Yn,useCallback:Ih,useContext:Yn,useEffect:Hl,useImperativeHandle:Lh,useInsertionEffect:Od,useLayoutEffect:Mh,useMemo:Oh,useReducer:Wl,useRef:Ld,useState:function(){return Wl(hs)},useDebugValue:Pd,useDeferredValue:function(i){var o=bn();return Dd(o,rs.memoizedState,i)},useTransition:function(){var i=Wl(hs)[0],o=bn().memoizedState;return[i,o]},useMutableSource:Md,useSyncExternalStore:Ch,useId:Ph,unstable_isNewReconciler:!1},Ea={readContext:Yn,useCallback:Ih,useContext:Yn,useEffect:Hl,useImperativeHandle:Lh,useInsertionEffect:Od,useLayoutEffect:Mh,useMemo:Oh,useReducer:Ho,useRef:Ld,useState:function(){return Ho(hs)},useDebugValue:Pd,useDeferredValue:function(i){var o=bn();return rs===null?o.memoizedState=i:Dd(o,rs.memoizedState,i)},useTransition:function(){var i=Ho(hs)[0],o=bn().memoizedState;return[i,o]},useMutableSource:Md,useSyncExternalStore:Ch,useId:Ph,unstable_isNewReconciler:!1};function Vn(i,o){if(i&&i.defaultProps){o=K({},o),i=i.defaultProps;for(var d in i)o[d]===void 0&&(o[d]=i[d]);return o}return o}function zd(i,o,d,p){o=i.memoizedState,d=d(p,o),d=d==null?o:K({},o,d),i.memoizedState=d,i.lanes===0&&(i.updateQueue.baseState=d)}var ao={isMounted:function(i){return(i=i._reactInternals)?gt(i)===i:!1},enqueueSetState:function(i,o,d){i=i._reactInternals;var p=Y(),x=X(i),j=hi(p,x);j.payload=o,d!=null&&(j.callback=d),o=mi(i,j,x),o!==null&&(se(o,i,x,p),Gc(o,i,x))},enqueueReplaceState:function(i,o,d){i=i._reactInternals;var p=Y(),x=X(i),j=hi(p,x);j.tag=1,j.payload=o,d!=null&&(j.callback=d),o=mi(i,j,x),o!==null&&(se(o,i,x,p),Gc(o,i,x))},enqueueForceUpdate:function(i,o){i=i._reactInternals;var d=Y(),p=X(i),x=hi(d,p);x.tag=2,o!=null&&(x.callback=o),o=mi(i,x,p),o!==null&&(se(o,i,p,d),Gc(o,i,p))}};function Fh(i,o,d,p,x,j,P){return i=i.stateNode,typeof i.shouldComponentUpdate=="function"?i.shouldComponentUpdate(p,j,P):o.prototype&&o.prototype.isPureReactComponent?!li(d,p)||!li(x,j):!0}function Xc(i,o,d){var p=!1,x=Kr,j=o.contextType;return typeof j=="object"&&j!==null?j=Yn(j):(x=sr(o)?eo:ds.current,p=o.contextTypes,j=(p=p!=null)?va(i,x):Kr),o=new o(d,j),i.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,o.updater=ao,i.stateNode=o,o._reactInternals=i,p&&(i=i.stateNode,i.__reactInternalMemoizedUnmaskedChildContext=x,i.__reactInternalMemoizedMaskedChildContext=j),o}function zh(i,o,d,p){i=o.state,typeof o.componentWillReceiveProps=="function"&&o.componentWillReceiveProps(d,p),typeof o.UNSAFE_componentWillReceiveProps=="function"&&o.UNSAFE_componentWillReceiveProps(d,p),o.state!==i&&ao.enqueueReplaceState(o,o.state,null)}function Bd(i,o,d,p){var x=i.stateNode;x.props=d,x.state=i.memoizedState,x.refs={},Nd(i);var j=o.contextType;typeof j=="object"&&j!==null?x.context=Yn(j):(j=sr(o)?eo:ds.current,x.context=va(i,j)),x.state=i.memoizedState,j=o.getDerivedStateFromProps,typeof j=="function"&&(zd(i,o,j,d),x.state=i.memoizedState),typeof o.getDerivedStateFromProps=="function"||typeof x.getSnapshotBeforeUpdate=="function"||typeof x.UNSAFE_componentWillMount!="function"&&typeof x.componentWillMount!="function"||(o=x.state,typeof x.componentWillMount=="function"&&x.componentWillMount(),typeof x.UNSAFE_componentWillMount=="function"&&x.UNSAFE_componentWillMount(),o!==x.state&&ao.enqueueReplaceState(x,x.state,null),Pl(i,d,x,p),x.state=i.memoizedState),typeof x.componentDidMount=="function"&&(i.flags|=4194308)}function oo(i,o){try{var d="",p=o;do d+=ie(p),p=p.return;while(p);var x=d}catch(j){x=`
|
|
39
|
-
Error generating stack: `+j.message+`
|
|
40
|
-
`+j.stack}return{value:i,source:o,stack:x,digest:null}}function qi(i,o,d){return{value:i,source:null,stack:d??null,digest:o??null}}function lo(i,o){try{console.error(o.value)}catch(d){setTimeout(function(){throw d})}}var Bh=typeof WeakMap=="function"?WeakMap:Map;function Ud(i,o,d){d=hi(-1,d),d.tag=3,d.payload={element:null};var p=o.value;return d.callback=function(){Zl||(Zl=!0,mu=p),lo(i,o)},d}function Uh(i,o,d){d=hi(-1,d),d.tag=3;var p=i.type.getDerivedStateFromError;if(typeof p=="function"){var x=o.value;d.payload=function(){return p(x)},d.callback=function(){lo(i,o)}}var j=i.stateNode;return j!==null&&typeof j.componentDidCatch=="function"&&(d.callback=function(){lo(i,o),typeof p!="function"&&(Gi===null?Gi=new Set([this]):Gi.add(this));var P=o.stack;this.componentDidCatch(o.value,{componentStack:P!==null?P:""})}),d}function Wd(i,o,d){var p=i.pingCache;if(p===null){p=i.pingCache=new Bh;var x=new Set;p.set(o,x)}else x=p.get(o),x===void 0&&(x=new Set,p.set(o,x));x.has(d)||(x.add(d),i=Hj.bind(null,i,o,d),o.then(i,i))}function co(i){do{var o;if((o=i.tag===13)&&(o=i.memoizedState,o=o!==null?o.dehydrated!==null:!0),o)return i;i=i.return}while(i!==null);return null}function Wh(i,o,d,p,x){return(i.mode&1)===0?(i===o?i.flags|=65536:(i.flags|=128,d.flags|=131072,d.flags&=-52805,d.tag===1&&(d.alternate===null?d.tag=17:(o=hi(-1,1),o.tag=2,mi(d,o,1))),d.lanes|=1),i):(i.flags|=65536,i.lanes=x,i)}var Zc=A.ReactCurrentOwner,Us=!1;function Ws(i,o,d,p){o.child=i===null?so(o,null,d,p):fi(o,i.child,d,p)}function Qc(i,o,d,p,x){d=d.render;var j=o.ref;return ka(o,x),p=Ad(i,o,d,p,j,x),d=Td(),i!==null&&!Us?(o.updateQueue=i.updateQueue,o.flags&=-2053,i.lanes&=~x,gi(i,o,x)):($n&&d&&Il(o),o.flags|=1,Ws(i,o,p,x),o.child)}function qh(i,o,d,p,x){if(i===null){var j=d.type;return typeof j=="function"&&!V_(j)&&j.defaultProps===void 0&&d.compare===null&&d.defaultProps===void 0?(o.tag=15,o.type=j,Hh(i,o,j,p,x)):(i=Qh(d.type,null,p,o,o.mode,x),i.ref=o.ref,i.return=o,o.child=i)}if(j=i.child,(i.lanes&x)===0){var P=j.memoizedProps;if(d=d.compare,d=d!==null?d:li,d(P,p)&&i.ref===o.ref)return gi(i,o,x)}return o.flags|=1,i=rl(j,p),i.ref=o.ref,i.return=o,o.child=i}function Hh(i,o,d,p,x){if(i!==null){var j=i.memoizedProps;if(li(j,p)&&i.ref===o.ref)if(Us=!1,o.pendingProps=p=j,(i.lanes&x)!==0)(i.flags&131072)!==0&&(Us=!0);else return o.lanes=i.lanes,gi(i,o,x)}return $a(i,o,d,p,x)}function Vh(i,o,d){var p=o.pendingProps,x=p.children,j=i!==null?i.memoizedState:null;if(p.mode==="hidden")if((o.mode&1)===0)o.memoizedState={baseLanes:0,cachePool:null,transitions:null},Ht(el,cr),cr|=d;else{if((d&1073741824)===0)return i=j!==null?j.baseLanes|d:d,o.lanes=o.childLanes=1073741824,o.memoizedState={baseLanes:i,cachePool:null,transitions:null},o.updateQueue=null,Ht(el,cr),cr|=i,null;o.memoizedState={baseLanes:0,cachePool:null,transitions:null},p=j!==null?j.baseLanes:d,Ht(el,cr),cr|=p}else j!==null?(p=j.baseLanes|d,o.memoizedState=null):p=d,Ht(el,cr),cr|=p;return Ws(i,o,x,d),o.child}function ar(i,o){var d=o.ref;(i===null&&d!==null||i!==null&&i.ref!==d)&&(o.flags|=512,o.flags|=2097152)}function $a(i,o,d,p,x){var j=sr(d)?eo:ds.current;return j=va(o,j),ka(o,x),d=Ad(i,o,d,p,j,x),p=Td(),i!==null&&!Us?(o.updateQueue=i.updateQueue,o.flags&=-2053,i.lanes&=~x,gi(i,o,x)):($n&&p&&Il(o),o.flags|=1,Ws(i,o,d,x),o.child)}function Gh(i,o,d,p,x){if(sr(d)){var j=!0;Rl(o)}else j=!1;if(ka(o,x),o.stateNode===null)Hi(i,o),Xc(o,d,p),Bd(o,d,p,x),p=!0;else if(i===null){var P=o.stateNode,ne=o.memoizedProps;P.props=ne;var ae=P.context,ve=d.contextType;typeof ve=="object"&&ve!==null?ve=Yn(ve):(ve=sr(d)?eo:ds.current,ve=va(o,ve));var Ie=d.getDerivedStateFromProps,Oe=typeof Ie=="function"||typeof P.getSnapshotBeforeUpdate=="function";Oe||typeof P.UNSAFE_componentWillReceiveProps!="function"&&typeof P.componentWillReceiveProps!="function"||(ne!==p||ae!==ve)&&zh(o,P,p,ve),Sa=!1;var Le=o.memoizedState;P.state=Le,Pl(o,p,P,x),ae=o.memoizedState,ne!==p||Le!==ae||nr.current||Sa?(typeof Ie=="function"&&(zd(o,d,Ie,p),ae=o.memoizedState),(ne=Sa||Fh(o,d,ne,p,Le,ae,ve))?(Oe||typeof P.UNSAFE_componentWillMount!="function"&&typeof P.componentWillMount!="function"||(typeof P.componentWillMount=="function"&&P.componentWillMount(),typeof P.UNSAFE_componentWillMount=="function"&&P.UNSAFE_componentWillMount()),typeof P.componentDidMount=="function"&&(o.flags|=4194308)):(typeof P.componentDidMount=="function"&&(o.flags|=4194308),o.memoizedProps=p,o.memoizedState=ae),P.props=p,P.state=ae,P.context=ve,p=ne):(typeof P.componentDidMount=="function"&&(o.flags|=4194308),p=!1)}else{P=o.stateNode,Vc(i,o),ne=o.memoizedProps,ve=o.type===o.elementType?ne:Vn(o.type,ne),P.props=ve,Oe=o.pendingProps,Le=P.context,ae=d.contextType,typeof ae=="object"&&ae!==null?ae=Yn(ae):(ae=sr(d)?eo:ds.current,ae=va(o,ae));var tt=d.getDerivedStateFromProps;(Ie=typeof tt=="function"||typeof P.getSnapshotBeforeUpdate=="function")||typeof P.UNSAFE_componentWillReceiveProps!="function"&&typeof P.componentWillReceiveProps!="function"||(ne!==Oe||Le!==ae)&&zh(o,P,p,ae),Sa=!1,Le=o.memoizedState,P.state=Le,Pl(o,p,P,x);var it=o.memoizedState;ne!==Oe||Le!==it||nr.current||Sa?(typeof tt=="function"&&(zd(o,d,tt,p),it=o.memoizedState),(ve=Sa||Fh(o,d,ve,p,Le,it,ae)||!1)?(Ie||typeof P.UNSAFE_componentWillUpdate!="function"&&typeof P.componentWillUpdate!="function"||(typeof P.componentWillUpdate=="function"&&P.componentWillUpdate(p,it,ae),typeof P.UNSAFE_componentWillUpdate=="function"&&P.UNSAFE_componentWillUpdate(p,it,ae)),typeof P.componentDidUpdate=="function"&&(o.flags|=4),typeof P.getSnapshotBeforeUpdate=="function"&&(o.flags|=1024)):(typeof P.componentDidUpdate!="function"||ne===i.memoizedProps&&Le===i.memoizedState||(o.flags|=4),typeof P.getSnapshotBeforeUpdate!="function"||ne===i.memoizedProps&&Le===i.memoizedState||(o.flags|=1024),o.memoizedProps=p,o.memoizedState=it),P.props=p,P.state=it,P.context=ae,p=ve):(typeof P.componentDidUpdate!="function"||ne===i.memoizedProps&&Le===i.memoizedState||(o.flags|=4),typeof P.getSnapshotBeforeUpdate!="function"||ne===i.memoizedProps&&Le===i.memoizedState||(o.flags|=1024),p=!1)}return eu(i,o,d,p,j,x)}function eu(i,o,d,p,x,j){ar(i,o);var P=(o.flags&128)!==0;if(!p&&!P)return x&&pd(o,d,!1),gi(i,o,j);p=o.stateNode,Zc.current=o;var ne=P&&typeof d.getDerivedStateFromError!="function"?null:p.render();return o.flags|=1,i!==null&&P?(o.child=fi(o,i.child,null,j),o.child=fi(o,null,ne,j)):Ws(i,o,ne,j),o.memoizedState=p.state,x&&pd(o,d,!0),o.child}function or(i){var o=i.stateNode;o.pendingContext?_d(i,o.pendingContext,o.pendingContext!==o.context):o.context&&_d(i,o.context,!1),Dl(i,o.containerInfo)}function tu(i,o,d,p,x){return zi(),Wc(x),o.flags|=256,Ws(i,o,d,p),o.child}var nu={dehydrated:null,treeContext:null,retryLane:0};function su(i){return{baseLanes:i,cachePool:null,transitions:null}}function Kh(i,o,d){var p=o.pendingProps,x=An.current,j=!1,P=(o.flags&128)!==0,ne;if((ne=P)||(ne=i!==null&&i.memoizedState===null?!1:(x&2)!==0),ne?(j=!0,o.flags&=-129):(i===null||i.memoizedState!==null)&&(x|=1),Ht(An,x&1),i===null)return wd(o),i=o.memoizedState,i!==null&&(i=i.dehydrated,i!==null)?((o.mode&1)===0?o.lanes=1:i.data==="$!"?o.lanes=8:o.lanes=1073741824,null):(P=p.children,i=p.fallback,j?(p=o.mode,j=o.child,P={mode:"hidden",children:P},(p&1)===0&&j!==null?(j.childLanes=0,j.pendingProps=P):j=em(P,p,0,null),i=tc(i,p,d,null),j.return=o,i.return=o,j.sibling=i,o.child=j,o.child.memoizedState=su(d),o.memoizedState=nu,i):qd(o,P));if(x=i.memoizedState,x!==null&&(ne=x.dehydrated,ne!==null))return vr(i,o,P,p,ne,x,d);if(j){j=p.fallback,P=o.mode,x=i.child,ne=x.sibling;var ae={mode:"hidden",children:p.children};return(P&1)===0&&o.child!==x?(p=o.child,p.childLanes=0,p.pendingProps=ae,o.deletions=null):(p=rl(x,ae),p.subtreeFlags=x.subtreeFlags&14680064),ne!==null?j=rl(ne,j):(j=tc(j,P,d,null),j.flags|=2),j.return=o,p.return=o,p.sibling=j,o.child=p,p=j,j=o.child,P=i.child.memoizedState,P=P===null?su(d):{baseLanes:P.baseLanes|d,cachePool:null,transitions:P.transitions},j.memoizedState=P,j.childLanes=i.childLanes&~d,o.memoizedState=nu,p}return j=i.child,i=j.sibling,p=rl(j,{mode:"visible",children:p.children}),(o.mode&1)===0&&(p.lanes=d),p.return=o,p.sibling=null,i!==null&&(d=o.deletions,d===null?(o.deletions=[i],o.flags|=16):d.push(i)),o.child=p,o.memoizedState=null,p}function qd(i,o){return o=em({mode:"visible",children:o},i.mode,0,null),o.return=i,i.child=o}function ru(i,o,d,p){return p!==null&&Wc(p),fi(o,i.child,null,d),i=qd(o,o.pendingProps.children),i.flags|=2,o.memoizedState=null,i}function vr(i,o,d,p,x,j,P){if(d)return o.flags&256?(o.flags&=-257,p=qi(Error(n(422))),ru(i,o,P,p)):o.memoizedState!==null?(o.child=i.child,o.flags|=128,null):(j=p.fallback,x=o.mode,p=em({mode:"visible",children:p.children},x,0,null),j=tc(j,x,P,null),j.flags|=2,p.return=o,j.return=o,p.sibling=j,o.child=p,(o.mode&1)!==0&&fi(o,i.child,null,P),o.child.memoizedState=su(P),o.memoizedState=nu,j);if((o.mode&1)===0)return ru(i,o,P,null);if(x.data==="$!"){if(p=x.nextSibling&&x.nextSibling.dataset,p)var ne=p.dgst;return p=ne,j=Error(n(419)),p=qi(j,p,void 0),ru(i,o,P,p)}if(ne=(P&i.childLanes)!==0,Us||ne){if(p=as,p!==null){switch(P&-P){case 4:x=2;break;case 16:x=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:x=32;break;case 536870912:x=268435456;break;default:x=0}x=(x&(p.suspendedLanes|P))!==0?0:x,x!==0&&x!==j.retryLane&&(j.retryLane=x,Ir(i,x),se(p,i,x,-1))}return Cn(),p=qi(Error(n(421))),ru(i,o,P,p)}return x.data==="$?"?(o.flags|=128,o.child=i.child,o=Vj.bind(null,i),x._reactRetry=o,null):(i=j.treeContext,zs=ya(x.nextSibling),on=o,$n=!0,ir=null,i!==null&&(Rr[rr++]=Yr,Rr[rr++]=Fi,Rr[rr++]=no,Yr=i.id,Fi=i.overflow,no=o),o=qd(o,p.children),o.flags|=4096,o)}function Ko(i,o,d){i.lanes|=o;var p=i.alternate;p!==null&&(p.lanes|=o),Sd(i.return,o,d)}function iu(i,o,d,p,x){var j=i.memoizedState;j===null?i.memoizedState={isBackwards:o,rendering:null,renderingStartTime:0,last:p,tail:d,tailMode:x}:(j.isBackwards=o,j.rendering=null,j.renderingStartTime=0,j.last=p,j.tail=d,j.tailMode=x)}function Hd(i,o,d){var p=o.pendingProps,x=p.revealOrder,j=p.tail;if(Ws(i,o,p.children,d),p=An.current,(p&2)!==0)p=p&1|2,o.flags|=128;else{if(i!==null&&(i.flags&128)!==0)e:for(i=o.child;i!==null;){if(i.tag===13)i.memoizedState!==null&&Ko(i,d,o);else if(i.tag===19)Ko(i,d,o);else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===o)break e;for(;i.sibling===null;){if(i.return===null||i.return===o)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}p&=1}if(Ht(An,p),(o.mode&1)===0)o.memoizedState=null;else switch(x){case"forwards":for(d=o.child,x=null;d!==null;)i=d.alternate,i!==null&&Fl(i)===null&&(x=d),d=d.sibling;d=x,d===null?(x=o.child,o.child=null):(x=d.sibling,d.sibling=null),iu(o,!1,x,d,j);break;case"backwards":for(d=null,x=o.child,o.child=null;x!==null;){if(i=x.alternate,i!==null&&Fl(i)===null){o.child=x;break}i=x.sibling,x.sibling=d,d=x,x=i}iu(o,!0,d,null,j);break;case"together":iu(o,!1,null,null,void 0);break;default:o.memoizedState=null}return o.child}function Hi(i,o){(o.mode&1)===0&&i!==null&&(i.alternate=null,o.alternate=null,o.flags|=2)}function gi(i,o,d){if(i!==null&&(o.dependencies=i.dependencies),Ta|=o.lanes,(d&o.childLanes)===0)return null;if(i!==null&&o.child!==i.child)throw Error(n(153));if(o.child!==null){for(i=o.child,d=rl(i,i.pendingProps),o.child=d,d.return=o;i.sibling!==null;)i=i.sibling,d=d.sibling=rl(i,i.pendingProps),d.return=o;d.sibling=null}return o.child}function Vi(i,o,d){switch(o.tag){case 3:or(o),zi();break;case 5:Nh(o);break;case 1:sr(o.type)&&Rl(o);break;case 4:Dl(o,o.stateNode.containerInfo);break;case 10:var p=o.type._context,x=o.memoizedProps.value;Ht(Et,p._currentValue),p._currentValue=x;break;case 13:if(p=o.memoizedState,p!==null)return p.dehydrated!==null?(Ht(An,An.current&1),o.flags|=128,null):(d&o.child.childLanes)!==0?Kh(i,o,d):(Ht(An,An.current&1),i=gi(i,o,d),i!==null?i.sibling:null);Ht(An,An.current&1);break;case 19:if(p=(d&o.childLanes)!==0,(i.flags&128)!==0){if(p)return Hd(i,o,d);o.flags|=128}if(x=o.memoizedState,x!==null&&(x.rendering=null,x.tail=null,x.lastEffect=null),Ht(An,An.current),p)break;return null;case 22:case 23:return o.lanes=0,Vh(i,o,d)}return gi(i,o,d)}var Yh,Vd,Gd,uo;Yh=function(i,o){for(var d=o.child;d!==null;){if(d.tag===5||d.tag===6)i.appendChild(d.stateNode);else if(d.tag!==4&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===o)break;for(;d.sibling===null;){if(d.return===null||d.return===o)return;d=d.return}d.sibling.return=d.return,d=d.sibling}},Vd=function(){},Gd=function(i,o,d,p){var x=i.memoizedProps;if(x!==p){i=o.stateNode,Xr(Jr.current);var j=null;switch(d){case"input":x=Qe(i,x),p=Qe(i,p),j=[];break;case"select":x=K({},x,{value:void 0}),p=K({},p,{value:void 0}),j=[];break;case"textarea":x=Te(i,x),p=Te(i,p),j=[];break;default:typeof x.onClick!="function"&&typeof p.onClick=="function"&&(i.onclick=Oo)}xn(d,p);var P;d=null;for(ve in x)if(!p.hasOwnProperty(ve)&&x.hasOwnProperty(ve)&&x[ve]!=null)if(ve==="style"){var ne=x[ve];for(P in ne)ne.hasOwnProperty(P)&&(d||(d={}),d[P]="")}else ve!=="dangerouslySetInnerHTML"&&ve!=="children"&&ve!=="suppressContentEditableWarning"&&ve!=="suppressHydrationWarning"&&ve!=="autoFocus"&&(a.hasOwnProperty(ve)?j||(j=[]):(j=j||[]).push(ve,null));for(ve in p){var ae=p[ve];if(ne=x!=null?x[ve]:void 0,p.hasOwnProperty(ve)&&ae!==ne&&(ae!=null||ne!=null))if(ve==="style")if(ne){for(P in ne)!ne.hasOwnProperty(P)||ae&&ae.hasOwnProperty(P)||(d||(d={}),d[P]="");for(P in ae)ae.hasOwnProperty(P)&&ne[P]!==ae[P]&&(d||(d={}),d[P]=ae[P])}else d||(j||(j=[]),j.push(ve,d)),d=ae;else ve==="dangerouslySetInnerHTML"?(ae=ae?ae.__html:void 0,ne=ne?ne.__html:void 0,ae!=null&&ne!==ae&&(j=j||[]).push(ve,ae)):ve==="children"?typeof ae!="string"&&typeof ae!="number"||(j=j||[]).push(ve,""+ae):ve!=="suppressContentEditableWarning"&&ve!=="suppressHydrationWarning"&&(a.hasOwnProperty(ve)?(ae!=null&&ve==="onScroll"&&Sn("scroll",i),j||ne===ae||(j=[])):(j=j||[]).push(ve,ae))}d&&(j=j||[]).push("style",d);var ve=j;(o.updateQueue=ve)&&(o.flags|=4)}},uo=function(i,o,d,p){d!==p&&(o.flags|=4)};function fo(i,o){if(!$n)switch(i.tailMode){case"hidden":o=i.tail;for(var d=null;o!==null;)o.alternate!==null&&(d=o),o=o.sibling;d===null?i.tail=null:d.sibling=null;break;case"collapsed":d=i.tail;for(var p=null;d!==null;)d.alternate!==null&&(p=d),d=d.sibling;p===null?o||i.tail===null?i.tail=null:i.tail.sibling=null:p.sibling=null}}function As(i){var o=i.alternate!==null&&i.alternate.child===i.child,d=0,p=0;if(o)for(var x=i.child;x!==null;)d|=x.lanes|x.childLanes,p|=x.subtreeFlags&14680064,p|=x.flags&14680064,x.return=i,x=x.sibling;else for(x=i.child;x!==null;)d|=x.lanes|x.childLanes,p|=x.subtreeFlags,p|=x.flags,x.return=i,x=x.sibling;return i.subtreeFlags|=p,i.childLanes=d,o}function q_(i,o,d){var p=o.pendingProps;switch(Pe(o),o.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return As(o),null;case 1:return sr(o.type)&&to(),As(o),null;case 3:return p=o.stateNode,qo(),mn(nr),mn(ds),zl(),p.pendingContext&&(p.context=p.pendingContext,p.pendingContext=null),(i===null||i.child===null)&&(Ol(o)?o.flags|=4:i===null||i.memoizedState.isDehydrated&&(o.flags&256)===0||(o.flags|=1024,ir!==null&&(Me(ir),ir=null))),Vd(i,o),As(o),null;case 5:Cd(o);var x=Xr(ro.current);if(d=o.type,i!==null&&o.stateNode!=null)Gd(i,o,d,p,x),i.ref!==o.ref&&(o.flags|=512,o.flags|=2097152);else{if(!p){if(o.stateNode===null)throw Error(n(166));return As(o),null}if(i=Xr(Jr.current),Ol(o)){p=o.stateNode,d=o.type;var j=o.memoizedProps;switch(p[tr]=o,p[Ii]=j,i=(o.mode&1)!==0,d){case"dialog":Sn("cancel",p),Sn("close",p);break;case"iframe":case"object":case"embed":Sn("load",p);break;case"video":case"audio":for(x=0;x<Lo.length;x++)Sn(Lo[x],p);break;case"source":Sn("error",p);break;case"img":case"image":case"link":Sn("error",p),Sn("load",p);break;case"details":Sn("toggle",p);break;case"input":at(p,j),Sn("invalid",p);break;case"select":p._wrapperState={wasMultiple:!!j.multiple},Sn("invalid",p);break;case"textarea":Ye(p,j),Sn("invalid",p)}xn(d,j),x=null;for(var P in j)if(j.hasOwnProperty(P)){var ne=j[P];P==="children"?typeof ne=="string"?p.textContent!==ne&&(j.suppressHydrationWarning!==!0&&pa(p.textContent,ne,i),x=["children",ne]):typeof ne=="number"&&p.textContent!==""+ne&&(j.suppressHydrationWarning!==!0&&pa(p.textContent,ne,i),x=["children",""+ne]):a.hasOwnProperty(P)&&ne!=null&&P==="onScroll"&&Sn("scroll",p)}switch(d){case"input":Ue(p),oe(p,j,!0);break;case"textarea":Ue(p),ht(p);break;case"select":case"option":break;default:typeof j.onClick=="function"&&(p.onclick=Oo)}p=x,o.updateQueue=p,p!==null&&(o.flags|=4)}else{P=x.nodeType===9?x:x.ownerDocument,i==="http://www.w3.org/1999/xhtml"&&(i=lt(d)),i==="http://www.w3.org/1999/xhtml"?d==="script"?(i=P.createElement("div"),i.innerHTML="<script><\/script>",i=i.removeChild(i.firstChild)):typeof p.is=="string"?i=P.createElement(d,{is:p.is}):(i=P.createElement(d),d==="select"&&(P=i,p.multiple?P.multiple=!0:p.size&&(P.size=p.size))):i=P.createElementNS(i,d),i[tr]=o,i[Ii]=p,Yh(i,o,!1,!1),o.stateNode=i;e:{switch(P=Ss(d,p),d){case"dialog":Sn("cancel",i),Sn("close",i),x=p;break;case"iframe":case"object":case"embed":Sn("load",i),x=p;break;case"video":case"audio":for(x=0;x<Lo.length;x++)Sn(Lo[x],i);x=p;break;case"source":Sn("error",i),x=p;break;case"img":case"image":case"link":Sn("error",i),Sn("load",i),x=p;break;case"details":Sn("toggle",i),x=p;break;case"input":at(i,p),x=Qe(i,p),Sn("invalid",i);break;case"option":x=p;break;case"select":i._wrapperState={wasMultiple:!!p.multiple},x=K({},p,{value:void 0}),Sn("invalid",i);break;case"textarea":Ye(i,p),x=Te(i,p),Sn("invalid",i);break;default:x=p}xn(d,x),ne=x;for(j in ne)if(ne.hasOwnProperty(j)){var ae=ne[j];j==="style"?wn(i,ae):j==="dangerouslySetInnerHTML"?(ae=ae?ae.__html:void 0,ae!=null&&On(i,ae)):j==="children"?typeof ae=="string"?(d!=="textarea"||ae!=="")&&Bt(i,ae):typeof ae=="number"&&Bt(i,""+ae):j!=="suppressContentEditableWarning"&&j!=="suppressHydrationWarning"&&j!=="autoFocus"&&(a.hasOwnProperty(j)?ae!=null&&j==="onScroll"&&Sn("scroll",i):ae!=null&&$(i,j,ae,P))}switch(d){case"input":Ue(i),oe(i,p,!1);break;case"textarea":Ue(i),ht(i);break;case"option":p.value!=null&&i.setAttribute("value",""+ye(p.value));break;case"select":i.multiple=!!p.multiple,j=p.value,j!=null?Ce(i,!!p.multiple,j,!1):p.defaultValue!=null&&Ce(i,!!p.multiple,p.defaultValue,!0);break;default:typeof x.onClick=="function"&&(i.onclick=Oo)}switch(d){case"button":case"input":case"select":case"textarea":p=!!p.autoFocus;break e;case"img":p=!0;break e;default:p=!1}}p&&(o.flags|=4)}o.ref!==null&&(o.flags|=512,o.flags|=2097152)}return As(o),null;case 6:if(i&&o.stateNode!=null)uo(i,o,i.memoizedProps,p);else{if(typeof p!="string"&&o.stateNode===null)throw Error(n(166));if(d=Xr(ro.current),Xr(Jr.current),Ol(o)){if(p=o.stateNode,d=o.memoizedProps,p[tr]=o,(j=p.nodeValue!==d)&&(i=on,i!==null))switch(i.tag){case 3:pa(p.nodeValue,d,(i.mode&1)!==0);break;case 5:i.memoizedProps.suppressHydrationWarning!==!0&&pa(p.nodeValue,d,(i.mode&1)!==0)}j&&(o.flags|=4)}else p=(d.nodeType===9?d:d.ownerDocument).createTextNode(p),p[tr]=o,o.stateNode=p}return As(o),null;case 13:if(mn(An),p=o.memoizedState,i===null||i.memoizedState!==null&&i.memoizedState.dehydrated!==null){if($n&&zs!==null&&(o.mode&1)!==0&&(o.flags&128)===0)Sh(),zi(),o.flags|=98560,j=!1;else if(j=Ol(o),p!==null&&p.dehydrated!==null){if(i===null){if(!j)throw Error(n(318));if(j=o.memoizedState,j=j!==null?j.dehydrated:null,!j)throw Error(n(317));j[tr]=o}else zi(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;As(o),j=!1}else ir!==null&&(Me(ir),ir=null),j=!0;if(!j)return o.flags&65536?o:null}return(o.flags&128)!==0?(o.lanes=d,o):(p=p!==null,p!==(i!==null&&i.memoizedState!==null)&&p&&(o.child.flags|=8192,(o.mode&1)!==0&&(i===null||(An.current&1)!==0?Zn===0&&(Zn=3):Cn())),o.updateQueue!==null&&(o.flags|=4),As(o),null);case 4:return qo(),Vd(i,o),i===null&&Cl(o.stateNode.containerInfo),As(o),null;case 10:return jd(o.type._context),As(o),null;case 17:return sr(o.type)&&to(),As(o),null;case 19:if(mn(An),j=o.memoizedState,j===null)return As(o),null;if(p=(o.flags&128)!==0,P=j.rendering,P===null)if(p)fo(j,!1);else{if(Zn!==0||i!==null&&(i.flags&128)!==0)for(i=o.child;i!==null;){if(P=Fl(i),P!==null){for(o.flags|=128,fo(j,!1),p=P.updateQueue,p!==null&&(o.updateQueue=p,o.flags|=4),o.subtreeFlags=0,p=d,d=o.child;d!==null;)j=d,i=p,j.flags&=14680066,P=j.alternate,P===null?(j.childLanes=0,j.lanes=i,j.child=null,j.subtreeFlags=0,j.memoizedProps=null,j.memoizedState=null,j.updateQueue=null,j.dependencies=null,j.stateNode=null):(j.childLanes=P.childLanes,j.lanes=P.lanes,j.child=P.child,j.subtreeFlags=0,j.deletions=null,j.memoizedProps=P.memoizedProps,j.memoizedState=P.memoizedState,j.updateQueue=P.updateQueue,j.type=P.type,i=P.dependencies,j.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext}),d=d.sibling;return Ht(An,An.current&1|2),o.child}i=i.sibling}j.tail!==null&&me()>ho&&(o.flags|=128,p=!0,fo(j,!1),o.lanes=4194304)}else{if(!p)if(i=Fl(P),i!==null){if(o.flags|=128,p=!0,d=i.updateQueue,d!==null&&(o.updateQueue=d,o.flags|=4),fo(j,!0),j.tail===null&&j.tailMode==="hidden"&&!P.alternate&&!$n)return As(o),null}else 2*me()-j.renderingStartTime>ho&&d!==1073741824&&(o.flags|=128,p=!0,fo(j,!1),o.lanes=4194304);j.isBackwards?(P.sibling=o.child,o.child=P):(d=j.last,d!==null?d.sibling=P:o.child=P,j.last=P)}return j.tail!==null?(o=j.tail,j.rendering=o,j.tail=o.sibling,j.renderingStartTime=me(),o.sibling=null,d=An.current,Ht(An,p?d&1|2:d&1),o):(As(o),null);case 22:case 23:return Ot(),p=o.memoizedState!==null,i!==null&&i.memoizedState!==null!==p&&(o.flags|=8192),p&&(o.mode&1)!==0?(cr&1073741824)!==0&&(As(o),o.subtreeFlags&6&&(o.flags|=8192)):As(o),null;case 24:return null;case 25:return null}throw Error(n(156,o.tag))}function H_(i,o){switch(Pe(o),o.tag){case 1:return sr(o.type)&&to(),i=o.flags,i&65536?(o.flags=i&-65537|128,o):null;case 3:return qo(),mn(nr),mn(ds),zl(),i=o.flags,(i&65536)!==0&&(i&128)===0?(o.flags=i&-65537|128,o):null;case 5:return Cd(o),null;case 13:if(mn(An),i=o.memoizedState,i!==null&&i.dehydrated!==null){if(o.alternate===null)throw Error(n(340));zi()}return i=o.flags,i&65536?(o.flags=i&-65537|128,o):null;case 19:return mn(An),null;case 4:return qo(),null;case 10:return jd(o.type._context),null;case 22:case 23:return Ot(),null;case 24:return null;default:return null}}var Vl=!1,Ts=!1,Wn=typeof WeakSet=="function"?WeakSet:Set,Je=null;function Yo(i,o){var d=i.ref;if(d!==null)if(typeof d=="function")try{d(null)}catch(p){Qn(i,o,p)}else d.current=null}function au(i,o,d){try{d()}catch(p){Qn(i,o,p)}}var Kd=!1;function Jh(i,o){if(Po=Ua,i=Ic(),Va(i)){if("selectionStart"in i)var d={start:i.selectionStart,end:i.selectionEnd};else e:{d=(d=i.ownerDocument)&&d.defaultView||window;var p=d.getSelection&&d.getSelection();if(p&&p.rangeCount!==0){d=p.anchorNode;var x=p.anchorOffset,j=p.focusNode;p=p.focusOffset;try{d.nodeType,j.nodeType}catch{d=null;break e}var P=0,ne=-1,ae=-1,ve=0,Ie=0,Oe=i,Le=null;t:for(;;){for(var tt;Oe!==d||x!==0&&Oe.nodeType!==3||(ne=P+x),Oe!==j||p!==0&&Oe.nodeType!==3||(ae=P+p),Oe.nodeType===3&&(P+=Oe.nodeValue.length),(tt=Oe.firstChild)!==null;)Le=Oe,Oe=tt;for(;;){if(Oe===i)break t;if(Le===d&&++ve===x&&(ne=P),Le===j&&++Ie===p&&(ae=P),(tt=Oe.nextSibling)!==null)break;Oe=Le,Le=Oe.parentNode}Oe=tt}d=ne===-1||ae===-1?null:{start:ne,end:ae}}else d=null}d=d||{start:0,end:0}}else d=null;for(Dc={focusedElem:i,selectionRange:d},Ua=!1,Je=o;Je!==null;)if(o=Je,i=o.child,(o.subtreeFlags&1028)!==0&&i!==null)i.return=o,Je=i;else for(;Je!==null;){o=Je;try{var it=o.alternate;if((o.flags&1024)!==0)switch(o.tag){case 0:case 11:case 15:break;case 1:if(it!==null){var ot=it.memoizedProps,os=it.memoizedState,ge=o.stateNode,de=ge.getSnapshotBeforeUpdate(o.elementType===o.type?ot:Vn(o.type,ot),os);ge.__reactInternalSnapshotBeforeUpdate=de}break;case 3:var we=o.stateNode.containerInfo;we.nodeType===1?we.textContent="":we.nodeType===9&&we.documentElement&&we.removeChild(we.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(Fe){Qn(o,o.return,Fe)}if(i=o.sibling,i!==null){i.return=o.return,Je=i;break}Je=o.return}return it=Kd,Kd=!1,it}function Jo(i,o,d){var p=o.updateQueue;if(p=p!==null?p.lastEffect:null,p!==null){var x=p=p.next;do{if((x.tag&i)===i){var j=x.destroy;x.destroy=void 0,j!==void 0&&au(o,d,j)}x=x.next}while(x!==p)}}function Gl(i,o){if(o=o.updateQueue,o=o!==null?o.lastEffect:null,o!==null){var d=o=o.next;do{if((d.tag&i)===i){var p=d.create;d.destroy=p()}d=d.next}while(d!==o)}}function Kl(i){var o=i.ref;if(o!==null){var d=i.stateNode;switch(i.tag){case 5:i=d;break;default:i=d}typeof o=="function"?o(i):o.current=i}}function Xo(i){var o=i.alternate;o!==null&&(i.alternate=null,Xo(o)),i.child=null,i.deletions=null,i.sibling=null,i.tag===5&&(o=i.stateNode,o!==null&&(delete o[tr],delete o[Ii],delete o[$l],delete o[Al],delete o[md])),i.stateNode=null,i.return=null,i.dependencies=null,i.memoizedProps=null,i.memoizedState=null,i.pendingProps=null,i.stateNode=null,i.updateQueue=null}function Yl(i){return i.tag===5||i.tag===3||i.tag===4}function Yd(i){e:for(;;){for(;i.sibling===null;){if(i.return===null||Yl(i.return))return null;i=i.return}for(i.sibling.return=i.return,i=i.sibling;i.tag!==5&&i.tag!==6&&i.tag!==18;){if(i.flags&2||i.child===null||i.tag===4)continue e;i.child.return=i,i=i.child}if(!(i.flags&2))return i.stateNode}}function ou(i,o,d){var p=i.tag;if(p===5||p===6)i=i.stateNode,o?d.nodeType===8?d.parentNode.insertBefore(i,o):d.insertBefore(i,o):(d.nodeType===8?(o=d.parentNode,o.insertBefore(i,d)):(o=d,o.appendChild(i)),d=d._reactRootContainer,d!=null||o.onclick!==null||(o.onclick=Oo));else if(p!==4&&(i=i.child,i!==null))for(ou(i,o,d),i=i.sibling;i!==null;)ou(i,o,d),i=i.sibling}function lu(i,o,d){var p=i.tag;if(p===5||p===6)i=i.stateNode,o?d.insertBefore(i,o):d.appendChild(i);else if(p!==4&&(i=i.child,i!==null))for(lu(i,o,d),i=i.sibling;i!==null;)lu(i,o,d),i=i.sibling}var Rn=null,Zr=!1;function lr(i,o,d){for(d=d.child;d!==null;)cu(i,o,d),d=d.sibling}function cu(i,o,d){if(Ds&&typeof Ds.onCommitFiberUnmount=="function")try{Ds.onCommitFiberUnmount(fn,d)}catch{}switch(d.tag){case 5:Ts||Yo(d,o);case 6:var p=Rn,x=Zr;Rn=null,lr(i,o,d),Rn=p,Zr=x,Rn!==null&&(Zr?(i=Rn,d=d.stateNode,i.nodeType===8?i.parentNode.removeChild(d):i.removeChild(d)):Rn.removeChild(d.stateNode));break;case 18:Rn!==null&&(Zr?(i=Rn,d=d.stateNode,i.nodeType===8?Fo(i.parentNode,d):i.nodeType===1&&Fo(i,d),oa(i)):Fo(Rn,d.stateNode));break;case 4:p=Rn,x=Zr,Rn=d.stateNode.containerInfo,Zr=!0,lr(i,o,d),Rn=p,Zr=x;break;case 0:case 11:case 14:case 15:if(!Ts&&(p=d.updateQueue,p!==null&&(p=p.lastEffect,p!==null))){x=p=p.next;do{var j=x,P=j.destroy;j=j.tag,P!==void 0&&((j&2)!==0||(j&4)!==0)&&au(d,o,P),x=x.next}while(x!==p)}lr(i,o,d);break;case 1:if(!Ts&&(Yo(d,o),p=d.stateNode,typeof p.componentWillUnmount=="function"))try{p.props=d.memoizedProps,p.state=d.memoizedState,p.componentWillUnmount()}catch(ne){Qn(d,o,ne)}lr(i,o,d);break;case 21:lr(i,o,d);break;case 22:d.mode&1?(Ts=(p=Ts)||d.memoizedState!==null,lr(i,o,d),Ts=p):lr(i,o,d);break;default:lr(i,o,d)}}function uu(i){var o=i.updateQueue;if(o!==null){i.updateQueue=null;var d=i.stateNode;d===null&&(d=i.stateNode=new Wn),o.forEach(function(p){var x=Gj.bind(null,i,p);d.has(p)||(d.add(p),p.then(x,x))})}}function Pr(i,o){var d=o.deletions;if(d!==null)for(var p=0;p<d.length;p++){var x=d[p];try{var j=i,P=o,ne=P;e:for(;ne!==null;){switch(ne.tag){case 5:Rn=ne.stateNode,Zr=!1;break e;case 3:Rn=ne.stateNode.containerInfo,Zr=!0;break e;case 4:Rn=ne.stateNode.containerInfo,Zr=!0;break e}ne=ne.return}if(Rn===null)throw Error(n(160));cu(j,P,x),Rn=null,Zr=!1;var ae=x.alternate;ae!==null&&(ae.return=null),x.return=null}catch(ve){Qn(x,o,ve)}}if(o.subtreeFlags&12854)for(o=o.child;o!==null;)Jd(o,i),o=o.sibling}function Jd(i,o){var d=i.alternate,p=i.flags;switch(i.tag){case 0:case 11:case 14:case 15:if(Pr(o,i),yi(i),p&4){try{Jo(3,i,i.return),Gl(3,i)}catch(ot){Qn(i,i.return,ot)}try{Jo(5,i,i.return)}catch(ot){Qn(i,i.return,ot)}}break;case 1:Pr(o,i),yi(i),p&512&&d!==null&&Yo(d,d.return);break;case 5:if(Pr(o,i),yi(i),p&512&&d!==null&&Yo(d,d.return),i.flags&32){var x=i.stateNode;try{Bt(x,"")}catch(ot){Qn(i,i.return,ot)}}if(p&4&&(x=i.stateNode,x!=null)){var j=i.memoizedProps,P=d!==null?d.memoizedProps:j,ne=i.type,ae=i.updateQueue;if(i.updateQueue=null,ae!==null)try{ne==="input"&&j.type==="radio"&&j.name!=null&&Ke(x,j),Ss(ne,P);var ve=Ss(ne,j);for(P=0;P<ae.length;P+=2){var Ie=ae[P],Oe=ae[P+1];Ie==="style"?wn(x,Oe):Ie==="dangerouslySetInnerHTML"?On(x,Oe):Ie==="children"?Bt(x,Oe):$(x,Ie,Oe,ve)}switch(ne){case"input":ce(x,j);break;case"textarea":rt(x,j);break;case"select":var Le=x._wrapperState.wasMultiple;x._wrapperState.wasMultiple=!!j.multiple;var tt=j.value;tt!=null?Ce(x,!!j.multiple,tt,!1):Le!==!!j.multiple&&(j.defaultValue!=null?Ce(x,!!j.multiple,j.defaultValue,!0):Ce(x,!!j.multiple,j.multiple?[]:"",!1))}x[Ii]=j}catch(ot){Qn(i,i.return,ot)}}break;case 6:if(Pr(o,i),yi(i),p&4){if(i.stateNode===null)throw Error(n(162));x=i.stateNode,j=i.memoizedProps;try{x.nodeValue=j}catch(ot){Qn(i,i.return,ot)}}break;case 3:if(Pr(o,i),yi(i),p&4&&d!==null&&d.memoizedState.isDehydrated)try{oa(o.containerInfo)}catch(ot){Qn(i,i.return,ot)}break;case 4:Pr(o,i),yi(i);break;case 13:Pr(o,i),yi(i),x=i.child,x.flags&8192&&(j=x.memoizedState!==null,x.stateNode.isHidden=j,!j||x.alternate!==null&&x.alternate.memoizedState!==null||(hu=me())),p&4&&uu(i);break;case 22:if(Ie=d!==null&&d.memoizedState!==null,i.mode&1?(Ts=(ve=Ts)||Ie,Pr(o,i),Ts=ve):Pr(o,i),yi(i),p&8192){if(ve=i.memoizedState!==null,(i.stateNode.isHidden=ve)&&!Ie&&(i.mode&1)!==0)for(Je=i,Ie=i.child;Ie!==null;){for(Oe=Je=Ie;Je!==null;){switch(Le=Je,tt=Le.child,Le.tag){case 0:case 11:case 14:case 15:Jo(4,Le,Le.return);break;case 1:Yo(Le,Le.return);var it=Le.stateNode;if(typeof it.componentWillUnmount=="function"){p=Le,d=Le.return;try{o=p,it.props=o.memoizedProps,it.state=o.memoizedState,it.componentWillUnmount()}catch(ot){Qn(p,d,ot)}}break;case 5:Yo(Le,Le.return);break;case 22:if(Le.memoizedState!==null){Zo(Oe);continue}}tt!==null?(tt.return=Le,Je=tt):Zo(Oe)}Ie=Ie.sibling}e:for(Ie=null,Oe=i;;){if(Oe.tag===5){if(Ie===null){Ie=Oe;try{x=Oe.stateNode,ve?(j=x.style,typeof j.setProperty=="function"?j.setProperty("display","none","important"):j.display="none"):(ne=Oe.stateNode,ae=Oe.memoizedProps.style,P=ae!=null&&ae.hasOwnProperty("display")?ae.display:null,ne.style.display=Tn("display",P))}catch(ot){Qn(i,i.return,ot)}}}else if(Oe.tag===6){if(Ie===null)try{Oe.stateNode.nodeValue=ve?"":Oe.memoizedProps}catch(ot){Qn(i,i.return,ot)}}else if((Oe.tag!==22&&Oe.tag!==23||Oe.memoizedState===null||Oe===i)&&Oe.child!==null){Oe.child.return=Oe,Oe=Oe.child;continue}if(Oe===i)break e;for(;Oe.sibling===null;){if(Oe.return===null||Oe.return===i)break e;Ie===Oe&&(Ie=null),Oe=Oe.return}Ie===Oe&&(Ie=null),Oe.sibling.return=Oe.return,Oe=Oe.sibling}}break;case 19:Pr(o,i),yi(i),p&4&&uu(i);break;case 21:break;default:Pr(o,i),yi(i)}}function yi(i){var o=i.flags;if(o&2){try{e:{for(var d=i.return;d!==null;){if(Yl(d)){var p=d;break e}d=d.return}throw Error(n(160))}switch(p.tag){case 5:var x=p.stateNode;p.flags&32&&(Bt(x,""),p.flags&=-33);var j=Yd(i);lu(i,j,x);break;case 3:case 4:var P=p.stateNode.containerInfo,ne=Yd(i);ou(i,ne,P);break;default:throw Error(n(161))}}catch(ae){Qn(i,i.return,ae)}i.flags&=-3}o&4096&&(i.flags&=-4097)}function Jl(i,o,d){Je=i,Aa(i)}function Aa(i,o,d){for(var p=(i.mode&1)!==0;Je!==null;){var x=Je,j=x.child;if(x.tag===22&&p){var P=x.memoizedState!==null||Vl;if(!P){var ne=x.alternate,ae=ne!==null&&ne.memoizedState!==null||Ts;ne=Vl;var ve=Ts;if(Vl=P,(Ts=ae)&&!ve)for(Je=x;Je!==null;)P=Je,ae=P.child,P.tag===22&&P.memoizedState!==null?Zh(x):ae!==null?(ae.return=P,Je=ae):Zh(x);for(;j!==null;)Je=j,Aa(j),j=j.sibling;Je=x,Vl=ne,Ts=ve}Xh(i)}else(x.subtreeFlags&8772)!==0&&j!==null?(j.return=x,Je=j):Xh(i)}}function Xh(i){for(;Je!==null;){var o=Je;if((o.flags&8772)!==0){var d=o.alternate;try{if((o.flags&8772)!==0)switch(o.tag){case 0:case 11:case 15:Ts||Gl(5,o);break;case 1:var p=o.stateNode;if(o.flags&4&&!Ts)if(d===null)p.componentDidMount();else{var x=o.elementType===o.type?d.memoizedProps:Vn(o.type,d.memoizedProps);p.componentDidUpdate(x,d.memoizedState,p.__reactInternalSnapshotBeforeUpdate)}var j=o.updateQueue;j!==null&&Kc(o,j,p);break;case 3:var P=o.updateQueue;if(P!==null){if(d=null,o.child!==null)switch(o.child.tag){case 5:d=o.child.stateNode;break;case 1:d=o.child.stateNode}Kc(o,P,d)}break;case 5:var ne=o.stateNode;if(d===null&&o.flags&4){d=ne;var ae=o.memoizedProps;switch(o.type){case"button":case"input":case"select":case"textarea":ae.autoFocus&&d.focus();break;case"img":ae.src&&(d.src=ae.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(o.memoizedState===null){var ve=o.alternate;if(ve!==null){var Ie=ve.memoizedState;if(Ie!==null){var Oe=Ie.dehydrated;Oe!==null&&oa(Oe)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Ts||o.flags&512&&Kl(o)}catch(Le){Qn(o,o.return,Le)}}if(o===i){Je=null;break}if(d=o.sibling,d!==null){d.return=o.return,Je=d;break}Je=o.return}}function Zo(i){for(;Je!==null;){var o=Je;if(o===i){Je=null;break}var d=o.sibling;if(d!==null){d.return=o.return,Je=d;break}Je=o.return}}function Zh(i){for(;Je!==null;){var o=Je;try{switch(o.tag){case 0:case 11:case 15:var d=o.return;try{Gl(4,o)}catch(ae){Qn(o,d,ae)}break;case 1:var p=o.stateNode;if(typeof p.componentDidMount=="function"){var x=o.return;try{p.componentDidMount()}catch(ae){Qn(o,x,ae)}}var j=o.return;try{Kl(o)}catch(ae){Qn(o,j,ae)}break;case 5:var P=o.return;try{Kl(o)}catch(ae){Qn(o,P,ae)}}}catch(ae){Qn(o,o.return,ae)}if(o===i){Je=null;break}var ne=o.sibling;if(ne!==null){ne.return=o.return,Je=ne;break}Je=o.return}}var du=Math.ceil,Qo=A.ReactCurrentDispatcher,Xd=A.ReactCurrentOwner,Dr=A.ReactCurrentBatchConfig,tn=0,as=null,Xn=null,ms=0,cr=0,el=wa(0),Zn=0,tl=null,Ta=0,Xl=0,fu=0,nl=null,qs=null,hu=0,ho=1/0,wi=null,Zl=!1,mu=null,Gi=null,Ql=!1,Ki=null,v=0,C=0,I=null,B=-1,Z=0;function Y(){return(tn&6)!==0?me():B!==-1?B:B=me()}function X(i){return(i.mode&1)===0?1:(tn&2)!==0&&ms!==0?ms&-ms:Bs.transition!==null?(Z===0&&(Z=ps()),Z):(i=un,i!==0||(i=window.event,i=i===void 0?16:je(i.type)),i)}function se(i,o,d,p){if(50<C)throw C=0,I=null,Error(n(185));gs(i,d,p),((tn&2)===0||i!==as)&&(i===as&&((tn&2)===0&&(Xl|=d),Zn===4&&Ge(i,ms)),Re(i,p),d===1&&tn===0&&(o.mode&1)===0&&(ho=me()+500,Ll&&Pi()))}function Re(i,o){var d=i.callbackNode;Mn(i,o);var p=sa(i,i===as?ms:0);if(p===0)d!==null&&ni(d),i.callbackNode=null,i.callbackPriority=0;else if(o=p&-p,i.callbackPriority!==o){if(d!=null&&ni(d),o===1)i.tag===0?B_(nt.bind(null,i)):gd(nt.bind(null,i)),Do(function(){(tn&6)===0&&Pi()}),d=null;else{switch(No(p)){case 1:d=na;break;case 4:d=_r;break;case 16:d=Sr;break;case 536870912:d=dt;break;default:d=Sr}d=Xy(d,be.bind(null,i))}i.callbackPriority=o,i.callbackNode=d}}function be(i,o){if(B=-1,Z=0,(tn&6)!==0)throw Error(n(327));var d=i.callbackNode;if(_u()&&i.callbackNode!==d)return null;var p=sa(i,i===as?ms:0);if(p===0)return null;if((p&30)!==0||(p&i.expiredLanes)!==0||o)o=bs(i,p);else{o=p;var x=tn;tn|=2;var j=kn();(as!==i||ms!==o)&&(wi=null,ho=me()+500,He(i,o));do try{Qr();break}catch(ne){Nt(i,ne)}while(!0);kd(),Qo.current=j,tn=x,Xn!==null?o=0:(as=null,ms=0,o=Zn)}if(o!==0){if(o===2&&(x=Fs(i),x!==0&&(p=x,o=ke(i,x))),o===1)throw d=tl,He(i,0),Ge(i,p),Re(i,me()),d;if(o===6)Ge(i,p);else{if(x=i.current.alternate,(p&30)===0&&!qe(x)&&(o=bs(i,p),o===2&&(j=Fs(i),j!==0&&(p=j,o=ke(i,j))),o===1))throw d=tl,He(i,0),Ge(i,p),Re(i,me()),d;switch(i.finishedWork=x,i.finishedLanes=p,o){case 0:case 1:throw Error(n(345));case 2:ec(i,qs,wi);break;case 3:if(Ge(i,p),(p&130023424)===p&&(o=hu+500-me(),10<o)){if(sa(i,0)!==0)break;if(x=i.suspendedLanes,(x&p)!==p){Y(),i.pingedLanes|=i.suspendedLanes&x;break}i.timeoutHandle=hd(ec.bind(null,i,qs,wi),o);break}ec(i,qs,wi);break;case 4:if(Ge(i,p),(p&4194240)===p)break;for(o=i.eventTimes,x=-1;0<p;){var P=31-cs(p);j=1<<P,P=o[P],P>x&&(x=P),p&=~j}if(p=x,p=me()-p,p=(120>p?120:480>p?480:1080>p?1080:1920>p?1920:3e3>p?3e3:4320>p?4320:1960*du(p/1960))-p,10<p){i.timeoutHandle=hd(ec.bind(null,i,qs,wi),p);break}ec(i,qs,wi);break;case 5:ec(i,qs,wi);break;default:throw Error(n(329))}}}return Re(i,me()),i.callbackNode===d?be.bind(null,i):null}function ke(i,o){var d=nl;return i.current.memoizedState.isDehydrated&&(He(i,o).flags|=256),i=bs(i,o),i!==2&&(o=qs,qs=d,o!==null&&Me(o)),i}function Me(i){qs===null?qs=i:qs.push.apply(qs,i)}function qe(i){for(var o=i;;){if(o.flags&16384){var d=o.updateQueue;if(d!==null&&(d=d.stores,d!==null))for(var p=0;p<d.length;p++){var x=d[p],j=x.getSnapshot;x=x.value;try{if(!ns(j(),x))return!1}catch{return!1}}}if(d=o.child,o.subtreeFlags&16384&&d!==null)d.return=o,o=d;else{if(o===i)break;for(;o.sibling===null;){if(o.return===null||o.return===i)return!0;o=o.return}o.sibling.return=o.return,o=o.sibling}}return!0}function Ge(i,o){for(o&=~fu,o&=~Xl,i.suspendedLanes|=o,i.pingedLanes&=~o,i=i.expirationTimes;0<o;){var d=31-cs(o),p=1<<d;i[d]=-1,o&=~p}}function nt(i){if((tn&6)!==0)throw Error(n(327));_u();var o=sa(i,0);if((o&1)===0)return Re(i,me()),null;var d=bs(i,o);if(i.tag!==0&&d===2){var p=Fs(i);p!==0&&(o=p,d=ke(i,p))}if(d===1)throw d=tl,He(i,0),Ge(i,o),Re(i,me()),d;if(d===6)throw Error(n(345));return i.finishedWork=i.current.alternate,i.finishedLanes=o,ec(i,qs,wi),Re(i,me()),null}function Xe(i,o){var d=tn;tn|=1;try{return i(o)}finally{tn=d,tn===0&&(ho=me()+500,Ll&&Pi())}}function Kt(i){Ki!==null&&Ki.tag===0&&(tn&6)===0&&_u();var o=tn;tn|=1;var d=Dr.transition,p=un;try{if(Dr.transition=null,un=1,i)return i()}finally{un=p,Dr.transition=d,tn=o,(tn&6)===0&&Pi()}}function Ot(){cr=el.current,mn(el)}function He(i,o){i.finishedWork=null,i.finishedLanes=0;var d=i.timeoutHandle;if(d!==-1&&(i.timeoutHandle=-1,Fc(d)),Xn!==null)for(d=Xn.return;d!==null;){var p=d;switch(Pe(p),p.tag){case 1:p=p.type.childContextTypes,p!=null&&to();break;case 3:qo(),mn(nr),mn(ds),zl();break;case 5:Cd(p);break;case 4:qo();break;case 13:mn(An);break;case 19:mn(An);break;case 10:jd(p.type._context);break;case 22:case 23:Ot()}d=d.return}if(as=i,Xn=i=rl(i.current,null),ms=cr=o,Zn=0,tl=null,fu=Xl=Ta=0,qs=nl=null,ja!==null){for(o=0;o<ja.length;o++)if(d=ja[o],p=d.interleaved,p!==null){d.interleaved=null;var x=p.next,j=d.pending;if(j!==null){var P=j.next;j.next=x,p.next=P}d.pending=p}ja=null}return i}function Nt(i,o){do{var d=Xn;try{if(kd(),Yc.current=Jn,Or){for(var p=Nn.memoizedState;p!==null;){var x=p.queue;x!==null&&(x.pending=null),p=p.next}Or=!1}if(io=0,is=rs=Nn=null,Bl=!1,Ul=0,Xd.current=null,d===null||d.return===null){Zn=1,tl=o,Xn=null;break}e:{var j=i,P=d.return,ne=d,ae=o;if(o=ms,ne.flags|=32768,ae!==null&&typeof ae=="object"&&typeof ae.then=="function"){var ve=ae,Ie=ne,Oe=Ie.tag;if((Ie.mode&1)===0&&(Oe===0||Oe===11||Oe===15)){var Le=Ie.alternate;Le?(Ie.updateQueue=Le.updateQueue,Ie.memoizedState=Le.memoizedState,Ie.lanes=Le.lanes):(Ie.updateQueue=null,Ie.memoizedState=null)}var tt=co(P);if(tt!==null){tt.flags&=-257,Wh(tt,P,ne,j,o),tt.mode&1&&Wd(j,ve,o),o=tt,ae=ve;var it=o.updateQueue;if(it===null){var ot=new Set;ot.add(ae),o.updateQueue=ot}else it.add(ae);break e}else{if((o&1)===0){Wd(j,ve,o),Cn();break e}ae=Error(n(426))}}else if($n&&ne.mode&1){var os=co(P);if(os!==null){(os.flags&65536)===0&&(os.flags|=256),Wh(os,P,ne,j,o),Wc(oo(ae,ne));break e}}j=ae=oo(ae,ne),Zn!==4&&(Zn=2),nl===null?nl=[j]:nl.push(j),j=P;do{switch(j.tag){case 3:j.flags|=65536,o&=-o,j.lanes|=o;var ge=Ud(j,ae,o);Un(j,ge);break e;case 1:ne=ae;var de=j.type,we=j.stateNode;if((j.flags&128)===0&&(typeof de.getDerivedStateFromError=="function"||we!==null&&typeof we.componentDidCatch=="function"&&(Gi===null||!Gi.has(we)))){j.flags|=65536,o&=-o,j.lanes|=o;var Fe=Uh(j,ne,o);Un(j,Fe);break e}}j=j.return}while(j!==null)}Gy(d)}catch(ft){o=ft,Xn===d&&d!==null&&(Xn=d=d.return);continue}break}while(!0)}function kn(){var i=Qo.current;return Qo.current=Jn,i===null?Jn:i}function Cn(){(Zn===0||Zn===3||Zn===2)&&(Zn=4),as===null||(Ta&268435455)===0&&(Xl&268435455)===0||Ge(as,ms)}function bs(i,o){var d=tn;tn|=2;var p=kn();(as!==i||ms!==o)&&(wi=null,He(i,o));do try{Fr();break}catch(x){Nt(i,x)}while(!0);if(kd(),tn=d,Qo.current=p,Xn!==null)throw Error(n(261));return as=null,ms=0,Zn}function Fr(){for(;Xn!==null;)sl(Xn)}function Qr(){for(;Xn!==null&&!si();)sl(Xn)}function sl(i){var o=Jy(i.alternate,i,cr);i.memoizedProps=i.pendingProps,o===null?Gy(i):Xn=o,Xd.current=null}function Gy(i){var o=i;do{var d=o.alternate;if(i=o.return,(o.flags&32768)===0){if(d=q_(d,o,cr),d!==null){Xn=d;return}}else{if(d=H_(d,o),d!==null){d.flags&=32767,Xn=d;return}if(i!==null)i.flags|=32768,i.subtreeFlags=0,i.deletions=null;else{Zn=6,Xn=null;return}}if(o=o.sibling,o!==null){Xn=o;return}Xn=o=i}while(o!==null);Zn===0&&(Zn=5)}function ec(i,o,d){var p=un,x=Dr.transition;try{Dr.transition=null,un=1,qj(i,o,d,p)}finally{Dr.transition=x,un=p}return null}function qj(i,o,d,p){do _u();while(Ki!==null);if((tn&6)!==0)throw Error(n(327));d=i.finishedWork;var x=i.finishedLanes;if(d===null)return null;if(i.finishedWork=null,i.finishedLanes=0,d===i.current)throw Error(n(177));i.callbackNode=null,i.callbackPriority=0;var j=d.lanes|d.childLanes;if(So(i,j),i===as&&(Xn=as=null,ms=0),(d.subtreeFlags&2064)===0&&(d.flags&2064)===0||Ql||(Ql=!0,Xy(Sr,function(){return _u(),null})),j=(d.flags&15990)!==0,(d.subtreeFlags&15990)!==0||j){j=Dr.transition,Dr.transition=null;var P=un;un=1;var ne=tn;tn|=4,Xd.current=null,Jh(i,d),Jd(d,i),Ar(Dc),Ua=!!Po,Dc=Po=null,i.current=d,Jl(d),Ps(),tn=ne,un=P,Dr.transition=j}else i.current=d;if(Ql&&(Ql=!1,Ki=i,v=x),j=i.pendingLanes,j===0&&(Gi=null),Vr(d.stateNode),Re(i,me()),o!==null)for(p=i.onRecoverableError,d=0;d<o.length;d++)x=o[d],p(x.value,{componentStack:x.stack,digest:x.digest});if(Zl)throw Zl=!1,i=mu,mu=null,i;return(v&1)!==0&&i.tag!==0&&_u(),j=i.pendingLanes,(j&1)!==0?i===I?C++:(C=0,I=i):C=0,Pi(),null}function _u(){if(Ki!==null){var i=No(v),o=Dr.transition,d=un;try{if(Dr.transition=null,un=16>i?16:i,Ki===null)var p=!1;else{if(i=Ki,Ki=null,v=0,(tn&6)!==0)throw Error(n(331));var x=tn;for(tn|=4,Je=i.current;Je!==null;){var j=Je,P=j.child;if((Je.flags&16)!==0){var ne=j.deletions;if(ne!==null){for(var ae=0;ae<ne.length;ae++){var ve=ne[ae];for(Je=ve;Je!==null;){var Ie=Je;switch(Ie.tag){case 0:case 11:case 15:Jo(8,Ie,j)}var Oe=Ie.child;if(Oe!==null)Oe.return=Ie,Je=Oe;else for(;Je!==null;){Ie=Je;var Le=Ie.sibling,tt=Ie.return;if(Xo(Ie),Ie===ve){Je=null;break}if(Le!==null){Le.return=tt,Je=Le;break}Je=tt}}}var it=j.alternate;if(it!==null){var ot=it.child;if(ot!==null){it.child=null;do{var os=ot.sibling;ot.sibling=null,ot=os}while(ot!==null)}}Je=j}}if((j.subtreeFlags&2064)!==0&&P!==null)P.return=j,Je=P;else e:for(;Je!==null;){if(j=Je,(j.flags&2048)!==0)switch(j.tag){case 0:case 11:case 15:Jo(9,j,j.return)}var ge=j.sibling;if(ge!==null){ge.return=j.return,Je=ge;break e}Je=j.return}}var de=i.current;for(Je=de;Je!==null;){P=Je;var we=P.child;if((P.subtreeFlags&2064)!==0&&we!==null)we.return=P,Je=we;else e:for(P=de;Je!==null;){if(ne=Je,(ne.flags&2048)!==0)try{switch(ne.tag){case 0:case 11:case 15:Gl(9,ne)}}catch(ft){Qn(ne,ne.return,ft)}if(ne===P){Je=null;break e}var Fe=ne.sibling;if(Fe!==null){Fe.return=ne.return,Je=Fe;break e}Je=ne.return}}if(tn=x,Pi(),Ds&&typeof Ds.onPostCommitFiberRoot=="function")try{Ds.onPostCommitFiberRoot(fn,i)}catch{}p=!0}return p}finally{un=d,Dr.transition=o}}return!1}function Ky(i,o,d){o=oo(d,o),o=Ud(i,o,1),i=mi(i,o,1),o=Y(),i!==null&&(gs(i,1,o),Re(i,o))}function Qn(i,o,d){if(i.tag===3)Ky(i,i,d);else for(;o!==null;){if(o.tag===3){Ky(o,i,d);break}else if(o.tag===1){var p=o.stateNode;if(typeof o.type.getDerivedStateFromError=="function"||typeof p.componentDidCatch=="function"&&(Gi===null||!Gi.has(p))){i=oo(d,i),i=Uh(o,i,1),o=mi(o,i,1),i=Y(),o!==null&&(gs(o,1,i),Re(o,i));break}}o=o.return}}function Hj(i,o,d){var p=i.pingCache;p!==null&&p.delete(o),o=Y(),i.pingedLanes|=i.suspendedLanes&d,as===i&&(ms&d)===d&&(Zn===4||Zn===3&&(ms&130023424)===ms&&500>me()-hu?He(i,0):fu|=d),Re(i,o)}function Yy(i,o){o===0&&((i.mode&1)===0?o=1:(o=pr,pr<<=1,(pr&130023424)===0&&(pr=4194304)));var d=Y();i=Ir(i,o),i!==null&&(gs(i,o,d),Re(i,d))}function Vj(i){var o=i.memoizedState,d=0;o!==null&&(d=o.retryLane),Yy(i,d)}function Gj(i,o){var d=0;switch(i.tag){case 13:var p=i.stateNode,x=i.memoizedState;x!==null&&(d=x.retryLane);break;case 19:p=i.stateNode;break;default:throw Error(n(314))}p!==null&&p.delete(o),Yy(i,d)}var Jy;Jy=function(i,o,d){if(i!==null)if(i.memoizedProps!==o.pendingProps||nr.current)Us=!0;else{if((i.lanes&d)===0&&(o.flags&128)===0)return Us=!1,Vi(i,o,d);Us=(i.flags&131072)!==0}else Us=!1,$n&&(o.flags&1048576)!==0&&bh(o,Uc,o.index);switch(o.lanes=0,o.tag){case 2:var p=o.type;Hi(i,o),i=o.pendingProps;var x=va(o,ds.current);ka(o,d),x=Ad(null,o,p,i,x,d);var j=Td();return o.flags|=1,typeof x=="object"&&x!==null&&typeof x.render=="function"&&x.$$typeof===void 0?(o.tag=1,o.memoizedState=null,o.updateQueue=null,sr(p)?(j=!0,Rl(o)):j=!1,o.memoizedState=x.state!==null&&x.state!==void 0?x.state:null,Nd(o),x.updater=ao,o.stateNode=x,x._reactInternals=o,Bd(o,p,i,d),o=eu(null,o,p,!0,j,d)):(o.tag=0,$n&&j&&Il(o),Ws(null,o,x,d),o=o.child),o;case 16:p=o.elementType;e:{switch(Hi(i,o),i=o.pendingProps,x=p._init,p=x(p._payload),o.type=p,x=o.tag=Yj(p),i=Vn(p,i),x){case 0:o=$a(null,o,p,i,d);break e;case 1:o=Gh(null,o,p,i,d);break e;case 11:o=Qc(null,o,p,i,d);break e;case 14:o=qh(null,o,p,Vn(p.type,i),d);break e}throw Error(n(306,p,""))}return o;case 0:return p=o.type,x=o.pendingProps,x=o.elementType===p?x:Vn(p,x),$a(i,o,p,x,d);case 1:return p=o.type,x=o.pendingProps,x=o.elementType===p?x:Vn(p,x),Gh(i,o,p,x,d);case 3:e:{if(or(o),i===null)throw Error(n(387));p=o.pendingProps,j=o.memoizedState,x=j.element,Vc(i,o),Pl(o,p,null,d);var P=o.memoizedState;if(p=P.element,j.isDehydrated)if(j={element:p,isDehydrated:!1,cache:P.cache,pendingSuspenseBoundaries:P.pendingSuspenseBoundaries,transitions:P.transitions},o.updateQueue.baseState=j,o.memoizedState=j,o.flags&256){x=oo(Error(n(423)),o),o=tu(i,o,p,d,x);break e}else if(p!==x){x=oo(Error(n(424)),o),o=tu(i,o,p,d,x);break e}else for(zs=ya(o.stateNode.containerInfo.firstChild),on=o,$n=!0,ir=null,d=so(o,null,p,d),o.child=d;d;)d.flags=d.flags&-3|4096,d=d.sibling;else{if(zi(),p===x){o=gi(i,o,d);break e}Ws(i,o,p,d)}o=o.child}return o;case 5:return Nh(o),i===null&&wd(o),p=o.type,x=o.pendingProps,j=i!==null?i.memoizedProps:null,P=x.children,ga(p,x)?P=null:j!==null&&ga(p,j)&&(o.flags|=32),ar(i,o),Ws(i,o,P,d),o.child;case 6:return i===null&&wd(o),null;case 13:return Kh(i,o,d);case 4:return Dl(o,o.stateNode.containerInfo),p=o.pendingProps,i===null?o.child=fi(o,null,p,d):Ws(i,o,p,d),o.child;case 11:return p=o.type,x=o.pendingProps,x=o.elementType===p?x:Vn(p,x),Qc(i,o,p,x,d);case 7:return Ws(i,o,o.pendingProps,d),o.child;case 8:return Ws(i,o,o.pendingProps.children,d),o.child;case 12:return Ws(i,o,o.pendingProps.children,d),o.child;case 10:e:{if(p=o.type._context,x=o.pendingProps,j=o.memoizedProps,P=x.value,Ht(Et,p._currentValue),p._currentValue=P,j!==null)if(ns(j.value,P)){if(j.children===x.children&&!nr.current){o=gi(i,o,d);break e}}else for(j=o.child,j!==null&&(j.return=o);j!==null;){var ne=j.dependencies;if(ne!==null){P=j.child;for(var ae=ne.firstContext;ae!==null;){if(ae.context===p){if(j.tag===1){ae=hi(-1,d&-d),ae.tag=2;var ve=j.updateQueue;if(ve!==null){ve=ve.shared;var Ie=ve.pending;Ie===null?ae.next=ae:(ae.next=Ie.next,Ie.next=ae),ve.pending=ae}}j.lanes|=d,ae=j.alternate,ae!==null&&(ae.lanes|=d),Sd(j.return,d,o),ne.lanes|=d;break}ae=ae.next}}else if(j.tag===10)P=j.type===o.type?null:j.child;else if(j.tag===18){if(P=j.return,P===null)throw Error(n(341));P.lanes|=d,ne=P.alternate,ne!==null&&(ne.lanes|=d),Sd(P,d,o),P=j.sibling}else P=j.child;if(P!==null)P.return=j;else for(P=j;P!==null;){if(P===o){P=null;break}if(j=P.sibling,j!==null){j.return=P.return,P=j;break}P=P.return}j=P}Ws(i,o,x.children,d),o=o.child}return o;case 9:return x=o.type,p=o.pendingProps.children,ka(o,d),x=Yn(x),p=p(x),o.flags|=1,Ws(i,o,p,d),o.child;case 14:return p=o.type,x=Vn(p,o.pendingProps),x=Vn(p.type,x),qh(i,o,p,x,d);case 15:return Hh(i,o,o.type,o.pendingProps,d);case 17:return p=o.type,x=o.pendingProps,x=o.elementType===p?x:Vn(p,x),Hi(i,o),o.tag=1,sr(p)?(i=!0,Rl(o)):i=!1,ka(o,d),Xc(o,p,x),Bd(o,p,x,d),eu(null,o,p,!0,i,d);case 19:return Hd(i,o,d);case 22:return Vh(i,o,d)}throw Error(n(156,o.tag))};function Xy(i,o){return hr(i,o)}function Kj(i,o,d,p){this.tag=i,this.key=d,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=o,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=p,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vi(i,o,d,p){return new Kj(i,o,d,p)}function V_(i){return i=i.prototype,!(!i||!i.isReactComponent)}function Yj(i){if(typeof i=="function")return V_(i)?1:0;if(i!=null){if(i=i.$$typeof,i===D)return 11;if(i===L)return 14}return 2}function rl(i,o){var d=i.alternate;return d===null?(d=vi(i.tag,o,i.key,i.mode),d.elementType=i.elementType,d.type=i.type,d.stateNode=i.stateNode,d.alternate=i,i.alternate=d):(d.pendingProps=o,d.type=i.type,d.flags=0,d.subtreeFlags=0,d.deletions=null),d.flags=i.flags&14680064,d.childLanes=i.childLanes,d.lanes=i.lanes,d.child=i.child,d.memoizedProps=i.memoizedProps,d.memoizedState=i.memoizedState,d.updateQueue=i.updateQueue,o=i.dependencies,d.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext},d.sibling=i.sibling,d.index=i.index,d.ref=i.ref,d}function Qh(i,o,d,p,x,j){var P=2;if(p=i,typeof i=="function")V_(i)&&(P=1);else if(typeof i=="string")P=5;else e:switch(i){case H:return tc(d.children,x,j,o);case G:P=8,x|=8;break;case re:return i=vi(12,d,o,x|2),i.elementType=re,i.lanes=j,i;case T:return i=vi(13,d,o,x),i.elementType=T,i.lanes=j,i;case E:return i=vi(19,d,o,x),i.elementType=E,i.lanes=j,i;case ee:return em(d,x,j,o);default:if(typeof i=="object"&&i!==null)switch(i.$$typeof){case te:P=10;break e;case Q:P=9;break e;case D:P=11;break e;case L:P=14;break e;case M:P=16,p=null;break e}throw Error(n(130,i==null?i:typeof i,""))}return o=vi(P,d,o,x),o.elementType=i,o.type=p,o.lanes=j,o}function tc(i,o,d,p){return i=vi(7,i,p,o),i.lanes=d,i}function em(i,o,d,p){return i=vi(22,i,p,o),i.elementType=ee,i.lanes=d,i.stateNode={isHidden:!1},i}function G_(i,o,d){return i=vi(6,i,null,o),i.lanes=d,i}function K_(i,o,d){return o=vi(4,i.children!==null?i.children:[],i.key,o),o.lanes=d,o.stateNode={containerInfo:i.containerInfo,pendingChildren:null,implementation:i.implementation},o}function Jj(i,o,d,p,x){this.tag=o,this.containerInfo=i,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ks(0),this.expirationTimes=Ks(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ks(0),this.identifierPrefix=p,this.onRecoverableError=x,this.mutableSourceEagerHydrationData=null}function Y_(i,o,d,p,x,j,P,ne,ae){return i=new Jj(i,o,d,ne,ae),o===1?(o=1,j===!0&&(o|=8)):o=0,j=vi(3,null,null,o),i.current=j,j.stateNode=i,j.memoizedState={element:p,isDehydrated:d,cache:null,transitions:null,pendingSuspenseBoundaries:null},Nd(j),i}function Xj(i,o,d){var p=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:z,key:p==null?null:""+p,children:i,containerInfo:o,implementation:d}}function Zy(i){if(!i)return Kr;i=i._reactInternals;e:{if(gt(i)!==i||i.tag!==1)throw Error(n(170));var o=i;do{switch(o.tag){case 3:o=o.stateNode.context;break e;case 1:if(sr(o.type)){o=o.stateNode.__reactInternalMemoizedMergedChildContext;break e}}o=o.return}while(o!==null);throw Error(n(171))}if(i.tag===1){var d=i.type;if(sr(d))return Ml(i,d,o)}return o}function Qy(i,o,d,p,x,j,P,ne,ae){return i=Y_(d,p,!0,i,x,j,P,ne,ae),i.context=Zy(null),d=i.current,p=Y(),x=X(d),j=hi(p,x),j.callback=o??null,mi(d,j,x),i.current.lanes=x,gs(i,x,p),Re(i,p),i}function tm(i,o,d,p){var x=o.current,j=Y(),P=X(x);return d=Zy(d),o.context===null?o.context=d:o.pendingContext=d,o=hi(j,P),o.payload={element:i},p=p===void 0?null:p,p!==null&&(o.callback=p),i=mi(x,o,P),i!==null&&(se(i,x,P,j),Gc(i,x,P)),P}function nm(i){if(i=i.current,!i.child)return null;switch(i.child.tag){case 5:return i.child.stateNode;default:return i.child.stateNode}}function ew(i,o){if(i=i.memoizedState,i!==null&&i.dehydrated!==null){var d=i.retryLane;i.retryLane=d!==0&&d<o?d:o}}function J_(i,o){ew(i,o),(i=i.alternate)&&ew(i,o)}function Zj(){return null}var tw=typeof reportError=="function"?reportError:function(i){console.error(i)};function X_(i){this._internalRoot=i}sm.prototype.render=X_.prototype.render=function(i){var o=this._internalRoot;if(o===null)throw Error(n(409));tm(i,o,null,null)},sm.prototype.unmount=X_.prototype.unmount=function(){var i=this._internalRoot;if(i!==null){this._internalRoot=null;var o=i.containerInfo;Kt(function(){tm(null,i,null,null)}),o[di]=null}};function sm(i){this._internalRoot=i}sm.prototype.unstable_scheduleHydration=function(i){if(i){var o=Nr();i={blockedOn:null,target:i,priority:o};for(var d=0;d<us.length&&o!==0&&o<us[d].priority;d++);us.splice(d,0,i),d===0&&jc(i)}};function Z_(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11)}function rm(i){return!(!i||i.nodeType!==1&&i.nodeType!==9&&i.nodeType!==11&&(i.nodeType!==8||i.nodeValue!==" react-mount-point-unstable "))}function nw(){}function Qj(i,o,d,p,x){if(x){if(typeof p=="function"){var j=p;p=function(){var ve=nm(P);j.call(ve)}}var P=Qy(o,p,i,0,null,!1,!1,"",nw);return i._reactRootContainer=P,i[di]=P.current,Cl(i.nodeType===8?i.parentNode:i),Kt(),P}for(;x=i.lastChild;)i.removeChild(x);if(typeof p=="function"){var ne=p;p=function(){var ve=nm(ae);ne.call(ve)}}var ae=Y_(i,0,!1,null,null,!1,!1,"",nw);return i._reactRootContainer=ae,i[di]=ae.current,Cl(i.nodeType===8?i.parentNode:i),Kt(function(){tm(o,ae,d,p)}),ae}function im(i,o,d,p,x){var j=d._reactRootContainer;if(j){var P=j;if(typeof x=="function"){var ne=x;x=function(){var ae=nm(P);ne.call(ae)}}tm(o,P,i,x)}else P=Qj(d,o,i,x,p);return nm(P)}kc=function(i){switch(i.tag){case 3:var o=i.stateNode;if(o.current.memoizedState.isDehydrated){var d=Hn(o.pendingLanes);d!==0&&(ra(o,d|1),Re(o,me()),(tn&6)===0&&(ho=me()+500,Pi()))}break;case 13:Kt(function(){var p=Ir(i,1);if(p!==null){var x=Y();se(p,i,1,x)}}),J_(i,1)}},Ba=function(i){if(i.tag===13){var o=Ir(i,134217728);if(o!==null){var d=Y();se(o,i,134217728,d)}J_(i,134217728)}},ys=function(i){if(i.tag===13){var o=X(i),d=Ir(i,o);if(d!==null){var p=Y();se(d,i,o,p)}J_(i,o)}},Nr=function(){return un},Cr=function(i,o){var d=un;try{return un=i,o()}finally{un=d}},jr=function(i,o,d){switch(o){case"input":if(ce(i,d),o=d.name,d.type==="radio"&&o!=null){for(d=i;d.parentNode;)d=d.parentNode;for(d=d.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),o=0;o<d.length;o++){var p=d[o];if(p!==i&&p.form===i.form){var x=Bo(p);if(!x)throw Error(n(90));ut(p),ce(p,x)}}}break;case"textarea":rt(i,d);break;case"select":o=d.value,o!=null&&Ce(i,!!d.multiple,o,!1)}},ct=Xe,mt=Kt;var eS={usingClientEntryPoint:!1,Events:[Qa,zo,Bo,et,Ze,Xe]},Zd={findFiberByHostInstance:Mr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},tS={bundleType:Zd.bundleType,version:Zd.version,rendererPackageName:Zd.rendererPackageName,rendererConfig:Zd.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:A.ReactCurrentDispatcher,findHostInstanceByFiber:function(i){return i=ls(i),i===null?null:i.stateNode},findFiberByHostInstance:Zd.findFiberByHostInstance||Zj,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 am=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!am.isDisabled&&am.supportsFiber)try{fn=am.inject(tS),Ds=am}catch{}}return zr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=eS,zr.createPortal=function(i,o){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Z_(o))throw Error(n(200));return Xj(i,o,null,d)},zr.createRoot=function(i,o){if(!Z_(i))throw Error(n(299));var d=!1,p="",x=tw;return o!=null&&(o.unstable_strictMode===!0&&(d=!0),o.identifierPrefix!==void 0&&(p=o.identifierPrefix),o.onRecoverableError!==void 0&&(x=o.onRecoverableError)),o=Y_(i,1,!1,null,null,d,!1,p,x),i[di]=o.current,Cl(i.nodeType===8?i.parentNode:i),new X_(o)},zr.findDOMNode=function(i){if(i==null)return null;if(i.nodeType===1)return i;var o=i._reactInternals;if(o===void 0)throw typeof i.render=="function"?Error(n(188)):(i=Object.keys(i).join(","),Error(n(268,i)));return i=ls(o),i=i===null?null:i.stateNode,i},zr.flushSync=function(i){return Kt(i)},zr.hydrate=function(i,o,d){if(!rm(o))throw Error(n(200));return im(null,i,o,!0,d)},zr.hydrateRoot=function(i,o,d){if(!Z_(i))throw Error(n(405));var p=d!=null&&d.hydratedSources||null,x=!1,j="",P=tw;if(d!=null&&(d.unstable_strictMode===!0&&(x=!0),d.identifierPrefix!==void 0&&(j=d.identifierPrefix),d.onRecoverableError!==void 0&&(P=d.onRecoverableError)),o=Qy(o,null,i,1,d??null,x,!1,j,P),i[di]=o.current,Cl(i),p)for(i=0;i<p.length;i++)d=p[i],x=d._getVersion,x=x(d._source),o.mutableSourceEagerHydrationData==null?o.mutableSourceEagerHydrationData=[d,x]:o.mutableSourceEagerHydrationData.push(d,x);return new sm(o)},zr.render=function(i,o,d){if(!rm(o))throw Error(n(200));return im(null,i,o,!1,d)},zr.unmountComponentAtNode=function(i){if(!rm(i))throw Error(n(40));return i._reactRootContainer?(Kt(function(){im(null,null,i,!1,function(){i._reactRootContainer=null,i[di]=null})}),!0):!1},zr.unstable_batchedUpdates=Xe,zr.unstable_renderSubtreeIntoContainer=function(i,o,d,p){if(!rm(d))throw Error(n(200));if(i==null||i._reactInternals===void 0)throw Error(n(38));return im(i,o,d,!1,p)},zr.version="18.3.1-next-f1338f8080-20240426",zr}var uw;function Yx(){if(uw)return tp.exports;uw=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(),tp.exports=uS(),tp.exports}var dw;function dS(){if(dw)return om;dw=1;var e=Yx();return om.createRoot=e.createRoot,om.hydrateRoot=e.hydrateRoot,om}var fS=dS();const hS=Jg(fS),Jx=[{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"]}];Jx.map(e=>({id:e.id,label:e.label}));function mS(e){return`theme-${String(e||"").trim()||"dark"}`}function fw(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(mS(e))}catch{}}const Qp=[{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}],eg=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function _S(e){const t=String(e).trim();return Qp.find(n=>n.id===t)||Qp[1]}function pS(e){const t=String(e).trim();return eg.find(n=>n.id===t)||eg[1]}function hw(e){try{const t=document.documentElement,n=_S(e.font_scale||"md"),r=pS(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const rp={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function gS(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function mw(e){const[t,n]=_.useState(()=>gS(e));return _.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),a=()=>n(r.matches);return a(),typeof r.addEventListener=="function"?r.addEventListener("change",a):r.addListener(a),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",a):r.removeListener(a)}},[e]),t}let ef=null;function yS(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))),a=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:a}}function wS(){if(ef)return ef;if(typeof window>"u"||typeof document>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};const t=document.documentElement;let n=0;const r=()=>{n=0;const{vvHeight:l,keyboardInset:c}=yS(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${l}px`),t.style.setProperty("--keyboard-inset",`${c}px`)},a=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",a),e.addEventListener("scroll",a),window.addEventListener("orientationchange",a),ef=()=>{e.removeEventListener("resize",a),e.removeEventListener("scroll",a),window.removeEventListener("orientationchange",a),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),ef=null},ef}var Xx=Yx();function pu(...e){return e.filter(Boolean).join(" ")}function ei({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:a=!1,searchable:l=!0,searchPlaceholder:c="Search…",allowCustom:u=!1,clearable:f=!1,minPopoverWidth:h=240,variant:m="panel",className:g,triggerClassName:y,ariaLabel:w,id:k,includeValueOption:b=!1,onOpen:S,customOptionLabel:N,validateCustomValue:R,onChange:$,renderOption:A,renderValue:W}){const z=_.useRef(null),H=_.useRef(null),G=_.useRef(null),re=_.useRef(S),te=_.useId(),Q=k||`af-select-${te.replace(/[^a-zA-Z0-9_-]/g,"")}`,D=`${Q}-listbox`,[T,E]=_.useState(!1),[L,M]=_.useState(""),[ee,F]=_.useState(0),[U,K]=_.useState("bottom"),[O,V]=_.useState({left:0,top:0,width:0});_.useEffect(()=>{re.current=S},[S]);const J=_.useMemo(()=>{if(!b)return t;const he=String(e??"").trim();return!he||t.some(Ce=>Ce.value===he)?t:[...t,{value:he,label:he}]},[b,t,e]),le=_.useMemo(()=>{const he=String(e??"");return J.find(Ce=>Ce.value===he)||null},[J,e]),ie=_.useMemo(()=>(le==null?void 0:le.label)||String(e||"").trim()||"",[le,e]),_e=_.useMemo(()=>{const he=L.trim().toLowerCase();return he?J.filter(Ce=>Ce.label.toLowerCase().includes(he)||Ce.value.toLowerCase().includes(he)):J},[J,L]),pe=_.useMemo(()=>{if(!u)return null;const he=L.trim();if(!he||J.some(Ye=>Ye.value===he))return null;const Te=(R==null?void 0:R(he,{options:J}))||"";return{value:he,label:N?N(he):`Use "${he}"`,disabled:!!Te,reason:Te}},[u,N,J,L,R]),ye=_.useMemo(()=>{const he=pe?[pe,..._e]:_e;if(he.length>0)return he;const Ce=String(e??"").trim();return a&&Ce?[{value:Ce,label:ie||Ce}]:he},[pe,_e,a,ie,e]),Ne=_.useCallback(()=>{const he=z.current;if(!he)return;const Ce=he.getBoundingClientRect(),Te=Math.max(Ce.width,h),Ye=Math.max(8,Math.min(Ce.left,window.innerWidth-Te-8)),rt=window.innerHeight-Ce.bottom,ht=Ce.top,lt=rt>=220||rt>=ht?"bottom":"top";K(lt);const St=lt==="bottom"?Ce.bottom+6:Ce.top-6;V({left:Ye,top:St,width:Te})},[h]),Be=_.useCallback(()=>{E(!1),M("")},[]);_.useEffect(()=>{var he;T&&((he=re.current)==null||he.call(re))},[T]),_.useEffect(()=>{if(!T)return;Ne();const he=()=>Ne();return window.addEventListener("resize",he),window.addEventListener("scroll",he,!0),()=>{window.removeEventListener("resize",he),window.removeEventListener("scroll",he,!0)}},[T,Ne]),_.useEffect(()=>{if(!T)return;const he=Ce=>{var Ye,rt;const Te=Ce.target;Te&&((Ye=z.current)!=null&&Ye.contains(Te)||(rt=H.current)!=null&&rt.contains(Te)||Be())};return document.addEventListener("mousedown",he,!0),()=>document.removeEventListener("mousedown",he,!0)},[T,Be]),_.useEffect(()=>{if(!T)return;const he=Math.max(0,ye.findIndex(Ce=>Ce.value===e));F(he===-1?0:he),l&&setTimeout(()=>{var Ce;return(Ce=G.current)==null?void 0:Ce.focus()},0)},[T,l,e,ye]);const Ue=he=>{var Te;const Ce=ye.find(Ye=>Ye.value===he);Ce!=null&&Ce.disabled||($(he),Be(),(Te=z.current)==null||Te.focus())},ut=he=>{var Ce,Te;if(he.key==="Escape")return he.preventDefault(),Be(),(Ce=z.current)==null||Ce.focus(),!0;if(he.key==="Tab")return Be(),(Te=z.current)==null||Te.focus(),!1;if(he.key==="ArrowDown")return he.preventDefault(),F(Ye=>Math.min(Ye+1,Math.max(0,ye.length-1))),!0;if(he.key==="ArrowUp")return he.preventDefault(),F(Ye=>Math.max(Ye-1,0)),!0;if(he.key==="Home")return he.preventDefault(),F(0),!0;if(he.key==="End")return he.preventDefault(),F(Math.max(0,ye.length-1)),!0;if(he.key==="Enter"){he.preventDefault();const Ye=ye[ee];return Ye&&Ue(Ye.value),!0}return!1},De=he=>{if(!r){if(T){if(ut(he))return;if(he.key===" "&&!l){he.preventDefault();const Ce=ye[ee];Ce&&Ue(Ce.value)}return}(he.key==="Enter"||he.key===" "||he.key==="ArrowDown"||he.key==="ArrowUp")&&(he.preventDefault(),E(!0))}},Qe=!!String(e||"").trim(),at=Qe?ie:n,Ke=pe!=null&&pe.disabled?pe.reason||"Unavailable":"",ce=T&&ye.length>0?`${Q}-opt-${ee}`:void 0,oe=s.jsx("span",{className:pu("af-select-value",!Qe&&"af-select-value--placeholder"),children:a&&!Qe?"Loading…":at}),Ae=W?W(le,String(e||"")):oe;return s.jsxs("span",{className:pu("af-select",m==="pin"?"af-select--pin":"af-select--panel",g),children:[s.jsxs("button",{ref:z,id:Q,type:"button",className:pu("af-select-trigger",f&&Qe&&"af-select-trigger--clearable",y),disabled:r,onMouseDown:he=>he.stopPropagation(),onClick:he=>{he.stopPropagation(),!r&&E(Ce=>!Ce)},onKeyDown:De,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":T,"aria-controls":T?D:void 0,"aria-activedescendant":l?void 0:ce,"aria-label":w,children:[Ae,s.jsx("span",{className:pu("af-select-caret",T&&"af-select-caret--open"),children:"▾"})]}),f&&Qe?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:he=>{he.preventDefault(),he.stopPropagation()},onClick:he=>{var Ce;he.preventDefault(),he.stopPropagation(),$(""),Be(),(Ce=z.current)==null||Ce.focus()},title:"Clear",children:"×"}):null,T?Xx.createPortal(s.jsxs("div",{ref:H,className:pu("af-select-popover",U==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${O.left}px`,top:`${O.top}px`,width:`${O.width}px`},onMouseDown:he=>he.stopPropagation(),onClick:he=>he.stopPropagation(),onWheel:he=>he.stopPropagation(),onKeyDown:ut,tabIndex:-1,children:[l?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:G,className:"af-select-search-input",value:L,onChange:he=>M(he.target.value),placeholder:c,onKeyDown:ut,role:"combobox","aria-expanded":!0,"aria-controls":D,"aria-activedescendant":ce,"aria-invalid":!!Ke,"aria-describedby":Ke?`${Q}-custom-error`:void 0}),Ke?s.jsx("div",{id:`${Q}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ke}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:D,"aria-label":w,children:a&&ye.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):ye.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):ye.map((he,Ce)=>{var St;const Te=he.value===e,Ye=Ce===ee,rt=String(he.group||"").trim(),ht=Ce>0?String(((St=ye[Ce-1])==null?void 0:St.group)||"").trim():"",lt=!!rt&&rt!==ht;return s.jsxs(xe.Fragment,{children:[lt?s.jsx("div",{className:"af-select-group",role:"presentation",children:rt}):null,s.jsx("div",{id:`${Q}-opt-${Ce}`,role:"option","aria-selected":Te,className:pu("af-select-option",Te&&"af-select-option--selected",Ye&&"af-select-option--highlighted",he.disabled&&"af-select-option--disabled"),title:he.disabled?he.reason||"Unavailable":void 0,onMouseEnter:()=>F(Ce),onMouseDown:Zt=>{Zt.preventDefault(),Zt.stopPropagation()},onClick:()=>Ue(he.value),"aria-disabled":he.disabled?!0:void 0,children:A?A(he,{selected:Te,highlighted:Ye}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:he.label}),he.reason?s.jsx("small",{className:"af-select-option-reason",children:he.reason}):null]}),Te?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},he.value)})})]}),document.body):null]})}function vS(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const a=String(r.name||"").trim();!a||t.has(a)||(t.add(a),n.push({name:a,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,a)=>r.name.localeCompare(a.name)),n}function xS(e){const t=new Set,n=[];for(const r of e||[]){const a=String(r||"").trim();!a||t.has(a)||(t.add(a),n.push(a))}return n.sort(),n}function Zx(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,a=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),c=String(e.modelLabel||"Model"),u=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),h=String(e.provider||"").trim(),m=String(e.model||"").trim(),g=vS(e.providers),y=xS(e.models),w=t||!!e.loadingProviders,k=t||!!e.loadingModels,b=[...r?[{value:"",label:a}]:[],...g.map(N=>({value:N.name,label:N.display_name?`${N.display_name} (${N.name})`:N.name}))],S=[...r?[{value:"",label:a}]:[],...y.map(N=>({value:N,label:N}))];return s.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:l}),s.jsx(ei,{value:h,options:b,placeholder:r?a:u,disabled:w,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:N=>e.onChange({provider:String(N||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:c}),s.jsx(ei,{value:m,options:S,placeholder:r?a:f,disabled:k,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:c,onChange:N=>e.onChange({provider:h,model:String(N||"").trim()})}),e.loadingModels?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function bS(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 kS(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 _w(e){const t=bS(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function jS(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 SS(e){const t=kS(e.capabilities),n=_w(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],a=_w(t==null?void 0:t.default),l=e.inheritLabel||"Workflow / Gateway default",c=a?`${l} (${a==="off"?"Off":`depth ${a}`})`:l,u=e.error||(e.loading?"Checking MTP capability…":t?t.reason||(t.requires_reload?"Model reload required before MTP can run.":t.ready===!1?"MTP is supported but not ready on this instance.":t.ready===null&&t.supported?"MTP support verified; loaded-instance readiness is unknown.":t.supported?"":"MTP is not supported on this model/backend."):"MTP capability unknown; no depth is assumed.");return s.jsxs("div",{className:"af-pmp__speculation",children:[s.jsx("label",{children:"MTP depth"}),s.jsx(ei,{ariaLabel:"MTP depth",value:n,placeholder:c,disabled:e.disabled||e.loading,options:[{value:"",label:c},{value:"off",label:"Off"},...r.map(f=>({value:f,label:`Depth ${f}`})),...n&&n!=="off"&&!r.includes(n)?[{value:n,label:`Depth ${n} (saved; not available)`}]:[]],onChange:f=>e.onChange(jS(f))}),u&&!e.hideNote?s.jsx("div",{role:"status",className:"af-pmp__hint",children:u}):null]})}const NS="Reasoning and MTP choices appear when the gateway can describe the selected model.",CS="Reasoning choices appear when the gateway can describe the selected model.";function Qx(e){var K,O;const t=e.disabled===!0,n=e.value||{provider:"",model:""},r=!String(n.provider||"").trim()&&!String(n.model||"").trim(),[a,l]=_.useState(!r),c=r&&!a,u=_.useRef(r);_.useEffect(()=>{r&&!u.current&&l(!1),u.current=r},[r]);const[f,h]=_.useState([]),[m,g]=_.useState(!1),[y,w]=_.useState(""),[k,b]=_.useState([]),[S,N]=_.useState(!1),[R,$]=_.useState(""),A=_.useRef(e);A.current=e,_.useEffect(()=>{if(c||t)return;let V=!0;return g(!0),(async()=>{try{const J=await A.current.fetchProviders();if(!V)return;h(Array.isArray(J)?J:[]),w("")}catch(J){if(!V)return;h([]),w(`#FALLBACK provider discovery failed: ${String((J==null?void 0:J.message)||J)}`)}finally{V&&g(!1)}})(),()=>{V=!1}},[c,t]);const W=String(n.provider||"").trim();_.useEffect(()=>{if(!W||t){b([]),$(""),N(!1);return}let V=!0;return b([]),N(!0),$(""),(async()=>{try{const J=await A.current.fetchModels(W);if(!V)return;b(Array.isArray(J)?J:[])}catch(J){if(!V)return;b([]),$(`#FALLBACK model discovery failed: ${String((J==null?void 0:J.message)||J)}`)}finally{V&&N(!1)}})(),()=>{V=!1}},[W,t]);const z=_.useMemo(()=>{const V=[...f];return W&&!V.some(J=>J.name===W)&&V.unshift({name:W}),V},[f,W]),H=String(n.model||"").trim(),G=_.useMemo(()=>{const V=[...k];return H&&!V.includes(H)&&V.unshift(H),V},[k,H]),re=e.defaultModeLabel||"Gateway default",te=e.customModeLabel||"Custom",Q=W||((K=e.effectiveDefault)==null?void 0:K.provider)||"",D=H||(W?"":(O=e.effectiveDefault)==null?void 0:O.model)||"",[T,E]=_.useState({levels:[],error:"",loading:!1}),L=!!e.fetchModelCapabilities,[M,ee]=_.useState();_.useEffect(()=>{let V=!0;if(ee(void 0),E({levels:[],error:"",loading:L&&!!D}),!(!L||!D||t))return A.current.fetchModelCapabilities(D,Q).then(J=>{var pe;if(!V)return;if(J!=null&&J.error)throw new Error(String(J.error));ee(J);const le=(J==null?void 0:J.capabilities)||J||{},ie=le.reasoning_levels||le.thinking_levels,_e=Array.isArray(ie)?[...new Set(ie.filter(ye=>typeof ye=="string"&&!!ye.trim()))]:[];!_e.length&&le.thinking_support===!0&&((pe=le.thinking_control)!=null&&pe.prompt_disable_token)&&_e.push("off","auto"),E({levels:_e,error:"",loading:!1})}).catch(J=>{V&&E({levels:[],error:String((J==null?void 0:J.message)||J),loading:!1})}),()=>{V=!1}},[Q,D,L,t]);const F=e.inheritLabel||"Workflow / Gateway default",U=!c||e.optionsInDefaultMode!==!1;return s.jsxs("div",{className:`af-pmp${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-pmp__seg",role:"tablist","aria-label":"Provider mode",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":c,className:`af-pmp__seg-btn${c?" is-active":""}`,onClick:()=>{l(!1),e.onChange({...n,provider:"",model:"",...L?{reasoning:""}:{}})},disabled:t,children:re}),s.jsx("button",{type:"button",role:"tab","aria-selected":!c,className:`af-pmp__seg-btn${c?"":" is-active"}`,onClick:()=>{l(!0)},disabled:t,children:te})]}),c?s.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}):s.jsx(Zx,{provider:W,model:H,providers:z,models:G,disabled:t,loadingProviders:m,loadingModels:S,providerError:y||void 0,modelError:R||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:!1,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:V=>e.onChange({...n,provider:V.provider,model:V.model,...L?{reasoning:""}:{}})}),U&&L&&(T.levels.length>0||n.reasoning)?s.jsxs("div",{className:"af-pmp__reasoning",children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx(ei,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:F,value:n.reasoning||"",options:[{value:"",label:F},...T.levels.map(V=>({value:V,label:V})),...n.reasoning&&!T.levels.includes(n.reasoning)?[{value:n.reasoning,label:`${n.reasoning} (saved; not advertised)`}]:[]],disabled:t||T.loading,onChange:V=>e.onChange({...n,reasoning:V})})]}):null,U&&e.enableSpeculation?s.jsx(SS,{value:n.speculation,inheritLabel:F,onChange:V=>e.onChange({...n,speculation:V}),capabilities:M,disabled:t,loading:T.loading,hideNote:!!T.error}):null,U&&T.error?s.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?NS:CS,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:T.error})]})]}):null]})}function pw(...e){return e.filter(Boolean).join(" ")}function ES({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:a="neutral",showGatewayUrl:l=!1,gatewayUrl:c="",gatewayUrlPlaceholder:u="http://127.0.0.1:8080",onGatewayUrlChange:f,userId:h,userPlaceholder:m="admin",onUserIdChange:g,token:y,tokenPlaceholder:w="Paste Gateway user token",showToken:k=!1,onTokenChange:b,onShowTokenChange:S,remember:N=!1,rememberLabel:R="Remember this browser",onRememberChange:$,loading:A=!1,submitting:W=!1,submitDisabled:z=!1,submitLabel:H="Sign in",submittingLabel:G="Signing in...",closeLabel:re="Close",signOutLabel:te="Sign out",showClose:Q=!1,showSignOut:D=!1,error:T,message:E,className:L,onSubmit:M,onClose:ee,onSignOut:F}){const U=A||W,K=U||z||!String(h||"").trim()||!String(y||"").trim(),O=V=>{V.preventDefault(),!K&&M()};return s.jsxs("form",{className:pw("af-gateway-signin",L),onSubmit:O,children:[s.jsxs("div",{className:"af-gateway-signin__hero",children:[s.jsxs("div",{children:[s.jsx("div",{className:"af-gateway-signin__kicker",children:e}),s.jsx("h2",{children:t}),n?s.jsx("p",{children:n}):null]}),s.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),s.jsx("div",{className:"af-gateway-signin__status-row",children:s.jsx("span",{className:pw("af-gateway-signin__status",`af-gateway-signin__status--${a}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[l?s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),s.jsx("input",{id:"gateway-session-url",value:c,onChange:V=>f==null?void 0:f(V.target.value),placeholder:u,autoComplete:"url",disabled:U})]}):null,s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),s.jsx("input",{id:"gateway-session-user",value:h,onChange:V=>g(V.target.value),placeholder:m,autoComplete:"username",disabled:U}),s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),s.jsxs("div",{className:"af-gateway-signin__token-input",children:[s.jsx("input",{id:"gateway-session-token",type:k?"text":"password",value:y,onChange:V=>b(V.target.value),placeholder:w,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:U}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>S==null?void 0:S(!k),disabled:U,children:k?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!N,onChange:V=>$==null?void 0:$(V.target.checked),disabled:U}),R]})]}),T?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:T}):null,!T&&E?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:E}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[Q?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:ee,disabled:U,children:re}):null,D?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(F==null?void 0:F()),disabled:U,children:te}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:K,children:W?G:H})]})]})}function $S(e){return e==="light"?"Light":"Dark"}function AS(e){const t=e.themes&&e.themes.length?e.themes:Jx,n=e.showSwatches!==!1,r=e.variant||"panel",a=_.useMemo(()=>{const c={};for(const u of t)c[u.id]=u;return c},[t]),l=_.useMemo(()=>t.map(c=>({value:c.id,label:c.label,group:$S(c.group)})),[t]);return s.jsx(ei,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:c=>e.onChange(String(c||"").trim()),renderValue:(c,u)=>{const f=String(u||"").trim(),h=a[f],m=(h==null?void 0:h.label)||f||e.placeholder||"Select theme…",g=(h==null?void 0:h.swatches)||null,y=!f;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${y?"af-theme-label--placeholder":""}`.trim(),children:m}),n&&g?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((w,k)=>s.jsx("span",{className:"af-theme-swatch",style:{background:w}},`${f}:${k}`))}):null]})},renderOption:(c,u)=>{const f=String(c.value||"").trim(),h=a[f],m=(h==null?void 0:h.swatches)||null;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"af-theme-option-label",children:c.label}),s.jsxs("span",{className:"af-theme-option-right",children:[n&&m?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:m.map((g,y)=>s.jsx("span",{className:"af-theme-swatch",style:{background:g}},`${f}:${y}`))}):null,u.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function TS(e){const t=e.scales&&e.scales.length?e.scales:Qp,n=e.variant||"panel",r=_.useMemo(()=>t.map(a=>({value:a.id,label:a.label})),[t]);return s.jsx(ei,{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:a=>e.onChange(String(a||"").trim())})}function MS(e){const t=e.densities&&e.densities.length?e.densities:eg,n=e.variant||"panel",r=_.useMemo(()=>t.map(a=>({value:a.id,label:a.label})),[t]);return s.jsx(ei,{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:a=>e.onChange(String(a||"").trim())})}const RS=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function LS(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 ze({name:e,size:t=16,className:n,title:r,...a}){const l=r?void 0:!0,c=RS.has(e);return s.jsxs("svg",{width:t,height:t,viewBox:c?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:c?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":l,role:r?"img":"presentation",...a,children:[r?s.jsx("title",{children:r}):null,LS(e)]})}const Mf="api/gateway",Zf="api/connection/gateway";function st(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?`${Mf}/${t}`:Mf}function Xg(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 IS(e){const t=String(e||""),n=`/${Mf}/`;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 a of r.split("/")){const l=a.replace(/%2e/gi,".");if(l==="."||l==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function OS(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function PS(e){return OS(e)?!e.checked:null}let DS=0;function Ni(e){const{label:t,checked:n,onChange:r,description:a,reasonVisible:l=!0,describedBy:c,hint:u,busy:f=!1,variant:h="inline",ariaLabel:m,className:g,id:y,action:w}=e,k=String(e.unavailableReason||"").trim(),b=!!k,S=c||(y?`${y}-reason`:b?`af-switch-reason-${++DS}`:void 0),N=["af-switch",h==="row"?"af-switch--row":h==="sm"?"af-switch--sm":"",b?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),R=A=>{const W=PS({checked:n,unavailableReason:k,busy:f});if(W===null){A.preventDefault();return}r==null||r(W)},$=s.jsxs("button",{type:"button",role:"switch",id:y,className:N,"data-action":w,"aria-checked":n?"true":"false","aria-disabled":b?"true":void 0,"aria-describedby":b?S:void 0,"aria-busy":f?"true":void 0,"aria-label":m,"aria-description":a?void 0:u,title:b?u?`${k}
|
|
41
|
-
${u}`:k:u,onClick:R,children:[s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsxs("span",{className:"af-switch__text",children:[s.jsx("span",{className:"af-switch__label",children:t}),a?s.jsx("span",{className:"af-switch__desc",children:a}):null]})]});return!b||c?$:s.jsxs("span",{className:h==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[$,s.jsx("span",{id:S,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:k})]})}function FS(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,a=s.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[s.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:l=>{var c;return(c=e.onChange)==null?void 0:c.call(e,l.target.checked)},disabled:!!t,"aria-describedby":r}),s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsx("span",{className:"af-switch__text",children:s.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?s.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[a,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):a}const zS=150,Zg="data-af-tip";function BS(e,t,n,r=6,a=8){let l="top",c=e.top-r-t.height;if(c<a){const h=e.bottom+r;(h+t.height<=n.height-a||n.height-e.bottom>e.top)&&(c=h,l="bottom")}let f=(e.left+e.right)/2-t.width/2;return f=Math.max(a,Math.min(f,n.width-a-t.width)),c=Math.max(a,Math.min(c,n.height-a-t.height)),{top:Math.round(c),left:Math.round(f),side:l}}let gw=0;function eb(e){return e?String(e.getAttribute(Zg)||"").trim():""}function ip(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${Zg}]`);return!r||!t.contains(r)||!eb(r)?null:r}function US(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,a=typeof t.delayMs=="number"&&t.delayMs>=0?t.delayMs:zS;gw+=1;const l=n.createElement("div");l.className="af-tooltip",l.setAttribute("role","tooltip");const c=`af-tooltip-${gw}`;l.setAttribute("id",c),l.hidden=!0,(n.body||n.documentElement).appendChild(l);let u=null,f=null,h=null,m=null,g=!1,y=null;const w=()=>{h&&clearTimeout(h),h=null,f=null},k=()=>{m&&clearTimeout(m),m=null},b=()=>{if(!u)return;const L=u.getBoundingClientRect(),M=l.getBoundingClientRect(),ee=BS(L,{width:M.width,height:M.height},{width:r.innerWidth,height:r.innerHeight});l.style.top=`${ee.top}px`,l.style.left=`${ee.left}px`,l.setAttribute("data-side",ee.side)},S=()=>{if(w(),k(),!u)return;String(u.getAttribute("aria-describedby")||"").split(/\s+/).includes(c)&&(y?u.setAttribute("aria-describedby",y):u.removeAttribute("aria-describedby")),y=null,u=null,l.hidden=!0,l.textContent=""},N=L=>{w(),k(),u&&u!==L&&S();const M=eb(L);if(!M||L.isConnected===!1)return;if(u=L,l.textContent=M,l.hidden=!1,String(L.getAttribute("aria-label")||"").trim()!==M){const F=L.getAttribute("aria-describedby");y=F&&F!==c?F:null,L.setAttribute("aria-describedby",y?`${y} ${c}`:c)}b()},R=L=>{k(),u!==L&&f!==L&&(w(),f=L,h=setTimeout(()=>{const M=f;h=null,f=null,M&&N(M)},a))},$=()=>{w(),u&&(k(),m=setTimeout(S,100))},A=L=>{try{if(typeof L.matches=="function")return L.matches(":focus-visible")}catch{}return g},W=L=>{if(L.pointerType==="touch")return;if(l.contains(L.target)){k();return}const ee=ip(L.target,e);ee&&R(ee)},z=L=>{const ee=L.relatedTarget||null;if(!(ee&&(l.contains(ee)||u&&u.contains(ee)||f&&f.contains(ee)))){if(f&&!u){w();return}u&&$()}},H=L=>{const M=L.relatedTarget||null;M&&(l.contains(M)||u&&u.contains(M))||$()},G=L=>{const M=ip(L.target,e);M&&A(M)&&R(M)},re=L=>{const M=ip(L.target,e);M&&(M===u||M===f)&&S()},te=()=>{g=!1,S()},Q=L=>{if(L.key==="Escape"||L.key==="Esc"){u?(L.preventDefault(),S()):w();return}!L.metaKey&&!L.ctrlKey&&!L.altKey&&(g=!0)},D=()=>S(),T=e;T.addEventListener("pointerover",W),T.addEventListener("pointerout",z),T.addEventListener("focusin",G),T.addEventListener("focusout",re),l.addEventListener("pointerover",W),l.addEventListener("pointerout",H),n.addEventListener("pointerdown",te,!0),r.addEventListener("keydown",Q,!0),r.addEventListener("scroll",D,!0),r.addEventListener("resize",D);let E=!1;return()=>{E||(E=!0,S(),T.removeEventListener("pointerover",W),T.removeEventListener("pointerout",z),T.removeEventListener("focusin",G),T.removeEventListener("focusout",re),l.removeEventListener("pointerover",W),l.removeEventListener("pointerout",H),n.removeEventListener("pointerdown",te,!0),r.removeEventListener("keydown",Q,!0),r.removeEventListener("scroll",D,!0),r.removeEventListener("resize",D),l.parentNode&&l.parentNode.removeChild(l))}}const lm=new WeakMap;function WS(e){let t=lm.get(e);t||(t={count:0,release:US(e)},lm.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=lm.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),lm.delete(e)))}}function Vu(){_.useEffect(()=>{if(!(typeof document>"u"))return WS(document)},[])}function yw(e){Vu();const t=xe.Children.only(e.children),n=String(e.content||"").trim();return n?xe.cloneElement(t,{[Zg]:n}):t}async function tg(e=Zf){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 qS(e,t=Zf){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 a=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(a)}return r}async function tb(e=Zf){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 ap(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const l=JSON.parse(t);if(typeof l=="string"&&l!==t){t=l.trim();continue}}catch{}const r=t[0],a=t[t.length-1];if(r==='"'&&a==='"'||r==="'"&&a==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function nb(e){var l,c;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(l=t.principal)==null?void 0:l.user_id,r=(c=t.principal)==null?void 0:c.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const a=t.error||t.detail;return typeof a=="string"&&a.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function HS(e){const t=e.connectionPath||Zf,[n,r]=_.useState(!1),[a,l]=_.useState(!1),[c,u]=_.useState(null),[f,h]=_.useState(!1);_.useEffect(()=>{e.isOpen||h(!1)},[e.isOpen]);const[m,g]=_.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[y,w]=_.useState("admin"),[k,b]=_.useState(""),[S,N]=_.useState(!1),[R,$]=_.useState(!0),[A,W]=_.useState(""),[z,H]=_.useState(""),G=_.useMemo(()=>nb(c),[c]),re=T=>{var E;u(T),(E=e.onStatusChange)==null||E.call(e,T)},te=_.useRef(!1);if(_.useEffect(()=>{var E;if(!e.isOpen)return;const T=!te.current;if(te.current=!0,T&&e.initialStatus!==void 0&&e.initialStatus!==null){const L=e.initialStatus;re(L),typeof L.gateway_url=="string"&&L.gateway_url.trim()&&g(ap(L.gateway_url));const M=(E=L.gateway)==null?void 0:E.principal;M!=null&&M.user_id&&w(M.user_id);return}r(!0),W(""),tg(t).then(L=>{var ee;re(L),typeof L.gateway_url=="string"&&L.gateway_url.trim()&&g(ap(L.gateway_url));const M=(ee=L.gateway)==null?void 0:ee.principal;M!=null&&M.user_id&&w(M.user_id)}).catch(L=>W(`Failed to load connection status: ${String((L==null?void 0:L.message)||L)}`)).finally(()=>r(!1))},[e.isOpen]),_.useEffect(()=>{if(!e.isOpen)return;const T=E=>{E.key==="Escape"&&!E.defaultPrevented&&!e.blocking&&(E.preventDefault(),e.onClose())};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const Q=async()=>{l(!0),W(""),H("");try{const T=ap(m);g(T);const E=await qS({gateway_url:T,gateway_user_id:y,gateway_token:k,persist:R},t);re(E),b(""),h(!0),e.onClose()}catch(T){W(String((T==null?void 0:T.message)||T))}finally{l(!1)}},D=async()=>{l(!0),W(""),H("");try{await tb(t),b("");const T=await tg(t).catch(()=>null);re(T),H("Signed out. This browser no longer holds a gateway session.")}catch(T){W(String((T==null?void 0:T.message)||T))}finally{l(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:T=>{!e.blocking&&T.target===T.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(ES,{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:G.label,statusTone:G.tone,showGatewayUrl:!0,gatewayUrl:m,onGatewayUrlChange:T=>g(T),userId:y,onUserIdChange:w,token:k,tokenPlaceholder:c!=null&&c.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:S,onTokenChange:b,onShowTokenChange:N,remember:R,rememberLabel:"Keep this browser signed in",onRememberChange:$,loading:n,submitting:a,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(c!=null&&c.has_session),onSignOut:D,error:A,message:z,onSubmit:Q})})})}function VS(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function GS(e){const t=e||{},n=t.connectionPath||Zf,r=t.variant||"dismissable",a=_.useRef(t.onStatusChange);a.current=t.onStatusChange;const l=_.useRef(r);l.current=r;const c=_.useRef(!!t.autoOpenMidSession);c.current=!!t.autoOpenMidSession;const[u,f]=_.useState(null),[h,m]=_.useState("loading"),[g,y]=_.useState(!1),w=_.useRef(!1),k=_.useRef(!1),b=_.useRef("loading"),S=_.useRef("none"),N=_.useRef(!1),R=_.useRef(0),$=_.useCallback(E=>{var M;R.current+=1,f(E),(M=a.current)==null||M.call(a,E);const L=VS(E);if(L)m("connected"),b.current="connected",w.current=!1,S.current="none",k.current||y(!1);else if(E!==null){const ee=b.current;m("disconnected"),b.current="disconnected",ee!=="disconnected"&&(S.current=N.current?"signout":ee==="connected"?"mid":"boot");const F=l.current==="blocking"||S.current!=="mid"||c.current;!w.current&&F&&y(!0)}E!==null&&(k.current=L)},[]),A=_.useCallback(async()=>{const E=R.current;try{const L=await tg(n);if(R.current!==E)return;$(L)}catch{if(R.current!==E)return;$(null)}},[n,$]),[W,z]=_.useState(!1),[H,G]=_.useState(null),re=_.useCallback(async()=>{z(!0),G(null),R.current+=1;let E=null;try{await tb(n)}catch(L){E=String((L==null?void 0:L.message)||L||"Sign-out request failed")}N.current=!0;try{await A()}finally{N.current=!1}G(E),z(!1)},[n,A]),te=_.useRef(!1);_.useEffect(()=>{te.current||(te.current=!0,A())},[A]);const Q=_.useCallback(()=>{y(!0)},[]),D=_.useCallback(()=>{const E=b.current;r==="blocking"&&E==="disconnected"||(E==="disconnected"&&(w.current=!0),y(!1))},[r]),T=_.useMemo(()=>({isOpen:g,onClose:D,blocking:r==="blocking"&&h!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:u,onStatusChange:$}),[g,D,r,h,t.appName,n,t.defaultGatewayUrl,u,$]);return{status:u,phase:h,connected:h==="connected",modalOpen:g,signingOut:W,signOutError:H,openModal:Q,refresh:A,signOut:re,modalProps:T}}function KS(){return globalThis.crypto}function YS(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 xo(){const e=KS();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return YS(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function m_(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 JS(){return xo()}function XS(){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 a=t.slice(n+1).trim();let l=a;try{l=decodeURIComponent(a)}catch{}l&&!e.includes(l)&&e.push(l)}}catch{}return e}async function ZS(e){const t=e.commandsPath||st("commands"),n=JS(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),a=e.csrfToken!==void 0?[e.csrfToken]:XS();a.length===0&&a.push("");let l=null;for(const c of a){const u=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...c?{"x-abstract-csrf":c}:{}},body:r}),f=await u.json().catch(()=>null);if(!u.ok){const h=f&&typeof f=="object"&&f.detail?String(f.detail):`HTTP ${u.status}`;if(l=new Error(h),u.status===403&&f&&typeof f=="object"&&f.reason_code==="csrf_required")continue;throw l}return{accepted:!!(f!=null&&f.accepted),duplicate:!!(f!=null&&f.duplicate),seq:Number((f==null?void 0:f.seq)??0)}}throw l||new Error("Steer submit failed")}function QS(e){const[t,n]=_.useState(""),[r,a]=_.useState({kind:"idle"}),l=_.useRef(!1),c=_.useRef(0);_.useEffect(()=>{c.current+=1,a({kind:"idle"})},[e.runId]);const u=!e.disabled&&t.trim().length>0&&r.kind!=="sending",f=_.useMemo(()=>e.parked?"Run is waiting — your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary.",[e.parked]),h=async()=>{var w;const g=t.trim();if(!g||l.current||e.disabled)return;l.current=!0;const y=c.current;a({kind:"sending"});try{const k=e.submit?await e.submit(e.runId,g):await ZS({runId:e.runId,guidance:g,commandsPath:e.commandsPath});if(c.current!==y)return;if(!k.accepted&&!k.duplicate){a({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}a({kind:"queued",seq:k.seq,duplicate:k.duplicate}),n(""),(w=e.onSent)==null||w.call(e,{...k,guidance:g})}catch(k){c.current===y&&a({kind:"error",detail:String((k==null?void 0:k.message)||k)})}finally{l.current=!1}},m=g=>{g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),h())};return s.jsxs("div",{className:`af-steer${e.className?` ${e.className}`:""}`,children:[s.jsxs("div",{className:"af-steer__row",children:[s.jsx("textarea",{className:"af-steer__input",value:t,rows:2,placeholder:e.placeholder||"Steer this run…","aria-label":e.ariaLabel||"Steer message",disabled:e.disabled||r.kind==="sending",onChange:g=>{n(g.target.value),(r.kind==="error"||r.kind==="queued")&&a({kind:"idle"})},onKeyDown:m}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!u,onClick:()=>void h(),title:"Send guidance (Cmd/Ctrl+Enter)",children:r.kind==="sending"?"Sending…":"Steer"})]}),s.jsx("div",{className:"af-steer__status",role:"status","aria-live":"polite",children:r.kind==="queued"?s.jsxs("span",{className:"af-steer__ok",children:[r.duplicate?`Already queued (seq ${r.seq}).`:`Queued (seq ${r.seq}).`," ",f," ","Watch for the steer_seen ack in the run ledger."]}):r.kind==="error"?s.jsx("span",{className:"af-steer__err",children:r.detail}):s.jsx("span",{className:"af-steer__hint",children:f})})]})}const op={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},e1=/^var\(--[a-z0-9-]+\)$/i;function t1(e,t){const n=e||"neutral";if(n==="custom"){const r=String(t||"").trim();return e1.test(r)?r:op.neutral}return op[n]||op.neutral}function n1(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n,t.className||""].filter(Boolean).join(" ")}function s1(e){return{"--af-chip-hue":t1(e.tone,e.hue)}}function r1(e){return s.jsx("button",{type:"button",className:n1("af-chip",e,"af-chip--button"),style:s1(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 i1(e){const t=e.closeOnEscape!==!1,n=_.useRef(null);return _.useEffect(()=>{if(!e.open||!t)return;const r=a=>{a.key!=="Escape"||a.defaultPrevented||(a.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 a1={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"},o1={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"}},l1={framework:a1,apps:o1},Hm=l1;function sb(){return{...Hm.framework}}function c1(){return Object.keys(Hm.apps).sort()}function u1(e,t){const n=Object.prototype.hasOwnProperty.call(Hm.apps,e)?Hm.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${c1().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 Eu(e){return typeof e=="string"?e.trim():""}function ww(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=Eu(n.abstractgateway),a=Eu(n.abstractframework);return{framework:a||null,gateway:r||null,...r&&!a?{frameworkNote:"not installed on the gateway host"}:{},...r?{}:{gatewayNote:"unavailable (the gateway did not report its version)"}}}function d1(e){const t=sb();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 f1(e){const t=e||{},n=Eu(t.framework),r=Eu(t.gateway);return[["AbstractFramework",n||Eu(t.frameworkNote)||"not reported"],["AbstractGateway",r||Eu(t.gatewayNote)||"not connected"]]}const h1='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function m1(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(h1));if(r.length===0){e.preventDefault();return}const a=r[0],l=r[r.length-1],c=!!n&&t.contains(n);e.shiftKey?(n===a||!c)&&(e.preventDefault(),l.focus()):(n===l||!c)&&(e.preventDefault(),a.focus())}function _1(e){const t=sb();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:f1(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:d1(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 p1(e){Vu();const t=_.useRef(null),n=_.useRef(null),r=_.useId(),a=_.useRef(e.onClose);return a.current=e.onClose,_.useEffect(()=>{var u;if(!e.open)return;const l=document.activeElement;(u=t.current)==null||u.focus();const c=f=>{if(!f.defaultPrevented){if(f.key==="Escape"){f.preventDefault(),a.current();return}m1(f,n.current,document.activeElement)}};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c),l&&typeof l.focus=="function"&&l.focus()}},[e.open]),e.open?s.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:s.jsx("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":r,onClick:l=>l.stopPropagation(),children:s.jsx(_1,{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(ze,{name:"x",size:16})})})})}):null}function g1(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[a,l]=_.useState(!1);Vu();const c=e.about,u=r?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",f=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return s.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.docs?s.jsx("button",{type:"button",className:`af-topbar__btn af-topbar__btn--docs${e.docs.open?" is-active":""}`,"aria-pressed":e.docs.open,"aria-label":e.docs.label||"Docs assistant","data-af-tip":e.docs.label||"Docs assistant",onClick:e.docs.onToggle,children:s.jsx(ze,{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(ze,{name:"sparkle",size:16})}):null,e.appearance?s.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)","data-af-tip":e.appearance.label||"Appearance (theme and text size)",onClick:e.appearance.onOpen,children:s.jsx(ze,{name:"contrast",size:16})}):null,c?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":c.label||`About ${c.identity.name}`,"data-af-tip":c.label||`About ${c.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var h;l(!0),(h=c.onOpen)==null||h.call(c)},children:s.jsx(ze,{name:"info",size:16})}):null,e.extraActions,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:r,title:f,"aria-label":f,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:u})]}),c?s.jsx(p1,{open:a,onClose:()=>l(!1),identity:c.identity,versions:c.versions}):null]})}const Om={theme:"dark",font_scale:"md",header_density:"standard"};function y1(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Om.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Om.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Om.header_density}}function w1(e){return`af_appearance_${e}_v1`}function v1(e,t){const n=w1(e),r=_.useMemo(()=>({...Om,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[a,l]=_.useState(()=>{let c=r;try{const u=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);u&&(c=y1({...r,...JSON.parse(u)}))}catch{}try{fw(c.theme),hw({font_scale:c.font_scale,header_density:c.header_density})}catch{}return c});return _.useEffect(()=>{fw(a.theme),hw({font_scale:a.font_scale,header_density:a.header_density});try{localStorage.setItem(n,JSON.stringify(a))}catch{}},[n,a]),[a,l]}function x1(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(AS,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(TS,{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(MS,{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 ng(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function vw(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":ng(r)||"not set"}function b1(e,t){var n;return e.stt_provider?ng({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?ng(t.stt):""}function rb(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function k1(e,t,n){return`Transcribing… ${rb(e,t)}${n?` · ${n}`:""}`}const __=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function sg(e){var a;const t=m_("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(!((a=__())!=null&&a.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 j1(e){const t=__();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(c=>c.kind===e),a=r.some(c=>!!c.label);return{devices:r.filter(c=>c.deviceId&&c.deviceId!=="default"&&c.deviceId!=="communications").map((c,u)=>({id:String(c.deviceId),label:String(c.label||`${e==="audioinput"?"Microphone":"Speaker"} ${u+1}`)})),labelled:a}}async function S1(){const e=__();if(!(e!=null&&e.getUserMedia))throw new Error(m_("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function ib(e){const t=__();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 p_(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function ab(){const e=p_();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function N1(e,t,n=1){const r=p_();if(!r)return()=>{};const a=new r,l=a.createMediaStreamSource(e),c=a.createAnalyser();c.fftSize=1024,l.connect(c);const u=new Float32Array(c.fftSize);let f=!0;const m=setInterval(()=>{if(!f)return;c.getFloatTimeDomainData(u);let g=0;for(let y=0;y<u.length;y+=1)g+=u[y]*u[y];t(Math.min(1,Math.sqrt(g/u.length)*4*n))},50);return()=>{var g;f=!1,clearInterval(m);try{l.disconnect()}catch{}(g=a.close)==null||g.call(a)}}const C1=.02;async function E1(e){var l;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});const n=await ib(e.deviceId);let r=0;const a=N1(n,c=>{var u;r=Math.max(r,c),(u=e.onLevel)==null||u.call(e,c)},e.gain??1);try{const c=new t(n),u=[],f=new Promise((m,g)=>{c.ondataavailable=y=>(y==null?void 0:y.data)&&u.push(y.data),c.onstop=()=>m(),c.onerror=y=>g((y==null?void 0:y.error)||new Error("Recording failed."))});c.start(),await new Promise(m=>{var y;const g=setTimeout(m,e.ms??3e3);(y=e.signal)==null||y.addEventListener("abort",()=>{clearTimeout(g),m()},{once:!0})}),c.stop(),await f;const h=String(c.mimeType||"audio/webm");return{blob:new Blob(u,{type:h}),peak:r,mime:h}}finally{a(),n.getTracks().forEach(c=>c.stop()),(l=e.onLevel)==null||l.call(e,0)}}async function $1(e,t={}){var a;const n=p_();if(!n)throw new Error("This browser cannot play audio.");const r=new n;try{t.deviceId&&typeof r.setSinkId=="function"&&await r.setSinkId(t.deviceId);const l=e instanceof Blob?await e.arrayBuffer():e,c=await r.decodeAudioData(l.slice(0)),u=r.createGain();u.gain.value=Qg(t.volume),u.connect(r.destination);const f=r.createBufferSource();f.buffer=c,f.connect(u),await new Promise(h=>{f.onended=()=>h(),f.start()})}finally{(a=r.close)==null||a.call(r)}}async function A1(e={}){var r,a;const t=p_();if(!t)throw new Error("This browser cannot play audio.");const n=new t;try{e.deviceId&&typeof n.setSinkId=="function"&&await n.setSinkId(e.deviceId),n.state==="suspended"&&await((r=n.resume)==null?void 0:r.call(n));const l=n.createGain();l.connect(n.destination);const c=.3*Qg(e.volume),u=n.currentTime+.02;[660,880].forEach((f,h)=>{const m=n.createOscillator(),g=n.createGain();m.frequency.value=f,m.connect(g),g.connect(l);const y=u+h*.22;g.gain.setValueAtTime(0,y),g.gain.linearRampToValueAtTime(c,y+.02),g.gain.exponentialRampToValueAtTime(1e-4,y+.2),m.start(y),m.stop(y+.21)}),await new Promise(f=>setTimeout(f,520))}finally{(a=n.close)==null||a.call(n)}}function Qg(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}async function*T1(e){var r,a,l;const t=new AbortController,n=()=>t.abort();(r=e.signal)!=null&&r.aborted?n():(a=e.signal)==null||a.addEventListener("abort",n,{once:!0});try{const c=await fetch(e.path,{method:"POST",headers:{"Content-Type":"application/json",...e.csrfToken?{"x-abstract-csrf":e.csrfToken}:{},...e.headers||{}},body:JSON.stringify(e.body),signal:t.signal});if(!c.ok){const m=await c.json().catch(()=>null),g=m&&typeof m=="object"&&m.detail?String(m.detail):`HTTP ${c.status}`;throw new Error(g)}if(!c.body)throw new Error("TTS stream has no body");const u=c.body.getReader(),f=new TextDecoder;let h="";for(;;){const{done:m,value:g}=await u.read();h+=m?f.decode():f.decode(g,{stream:!0}),m&&h.trim()&&(h+=`
|
|
42
|
-
`);let y;for(;(y=h.indexOf(`
|
|
43
|
-
`))>=0;){const w=h.slice(0,y).trim();if(h=h.slice(y+1),!w)continue;let k=null;try{k=JSON.parse(w)}catch{throw new Error("TTS stream returned invalid JSON.")}if(k&&k.type==="error")throw new Error(String(k.error||"TTS stream error"));const b=k&&typeof k.audio_b64=="string"?k.audio_b64:"";if(b){const S=atob(b),N=new Uint8Array(S.length);for(let R=0;R<S.length;R+=1)N[R]=S.charCodeAt(R);yield N.buffer}if(k&&(k.type==="done"||k.type==="cancelled"))return}if(m)throw new Error("TTS stream ended before synthesis completed.")}}finally{(l=e.signal)==null||l.removeEventListener("abort",n),t.abort()}}function tf(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const M1=350;function R1(){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 L1(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function I1(){const e=window.MediaRecorder,t=r=>{var a;try{return!!((a=e==null?void 0:e.isTypeSupported)!=null&&a.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 lp(e,t){var a;const n=t.slice(0),r=(a=e.decodeAudioData)==null?void 0:a.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const l=r(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,c)=>{try{r(n,l,c)}catch(u){c(u)}})}function O1(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=l=>String.fromCharCode(t[l],t[l+1],t[l+2],t[l+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const r=new DataView(e);let a=12;for(;a+8<=t.length;){const l=n(a),c=r.getUint32(a+4,!0);if(l==="data")return t.slice(0,a+8);a+=8+c+c%2}return null}function P1(e,t){const n=new Uint8Array(t),r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length);const a=new DataView(r.buffer);return a.setUint32(4,r.length-8,!0),a.setUint32(e.length-4,n.length,!0),r.buffer}function D1(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const cm=new WeakMap;function F1(e,t){const n=e;if(!(typeof n.setSinkId!="function"||cm.get(e)===t)){cm.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>cm.delete(e))}catch{cm.delete(e)}}}function z1(e){const t=_.useRef(e);t.current=e;const n=ce=>{var oe,Ae;return(Ae=(oe=t.current).on_error)==null?void 0:Ae.call(oe,ce)},r=_.useMemo(()=>L1()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),a=_.useMemo(()=>R1()&&typeof e.transcribe=="function",[e.transcribe]),[l,c]=_.useState({key:"",status:"idle"}),u=_.useRef(l),f=_.useCallback(ce=>{u.current=ce,c(oe=>oe.key===ce.key&&oe.status===ce.status?oe:ce)},[]),h=_.useRef(""),m=_.useRef(""),g=_.useRef(null),y=_.useRef(null),w=_.useRef(null),k=_.useRef(null),b=_.useRef(0),S=_.useRef(0),N=_.useRef(0),R=_.useRef(null),$=_.useRef([]),A=_.useRef(0),W=_.useRef(!0),z=_.useRef(!1),H=()=>{try{const ce=globalThis,oe=(ce==null?void 0:ce.AudioContext)||(ce==null?void 0:ce.webkitAudioContext);if(!oe)return null;if(!g.current){const Ce=new oe,Te=Ce.createGain();Te.gain.value=1,Te.connect(Ce.destination),g.current=Ce,y.current=Te}const Ae=g.current,he=y.current;if(!Ae||!he)return null;F1(Ae,t.current.output_device_id||""),he.gain.value=Qg(t.current.volume);try{Ae.state==="suspended"&&Ae.resume()}catch{}return{ctx:Ae,gain:he}}catch{return null}},G=_.useCallback(()=>{const ce=w.current;if(w.current=null,!!ce){try{ce.onended=null}catch{}try{ce.stop()}catch{}try{ce.disconnect()}catch{}}},[]),re=_.useCallback(()=>{var ce;G(),N.current+=1,(ce=R.current)==null||ce.abort(),R.current=null,$.current=[],A.current=0,W.current=!0,z.current=!1,m.current="",h.current="",k.current=null,b.current=0,S.current=0,f({key:"",status:"idle"})},[G,f]);_.useEffect(()=>()=>{var ce,oe;re();try{(ce=y.current)==null||ce.disconnect()}catch{}try{(oe=g.current)==null||oe.close()}catch{}g.current=null,y.current=null,k.current=null},[]);const te=async(ce,oe,Ae)=>{const he=N.current,Ce=H();if(!Ce)throw new Error("TTS playback is not supported in this browser");const{ctx:Te,gain:Ye}=Ce;try{Te.state==="suspended"&&await Te.resume()}catch{}if(he!==N.current)return;G();const rt=Te.createBufferSource();rt.buffer=oe,rt.connect(Ye);const ht=Number.isFinite(Number(oe.duration))?Number(oe.duration):0,lt=Math.max(0,Math.min(Number(Ae||0),ht>0?Math.max(0,ht-.01):0));S.current=Te.currentTime-lt,b.current=lt,w.current=rt,h.current=ce,rt.onended=()=>{w.current===rt&&(w.current=null,b.current=0,S.current=0,h.current="",f({key:"",status:"idle"}))},rt.start(0,lt),f({key:ce,status:"playing"})},Q=(ce,oe)=>{if(oe!==N.current)return;const Ae=H();if(!Ae)return;const he=$.current,Ce=A.current;if(Ce>=he.length){W.current&&(h.current="",b.current=0,S.current=0,f({key:"",status:"idle"}));return}const Te=he[Ce],{ctx:Ye,gain:rt}=Ae;G();const ht=Ye.createBufferSource();ht.buffer=Te,ht.connect(rt);const lt=Number.isFinite(Number(Te.duration))?Number(Te.duration):0,St=Math.max(0,Math.min(Number(b.current||0),lt>0?Math.max(0,lt-.01):0));S.current=Ye.currentTime-St,w.current=ht,h.current=ce,ht.onended=()=>{oe===N.current&&w.current===ht&&(w.current=null,A.current=Ce+1,b.current=0,Q(ce,oe))};try{Ye.state==="suspended"&&Ye.resume()}catch{}ht.start(0,St),f({key:ce,status:"playing"})},D=async(ce,oe,Ae)=>{var rt;const he=H();if(!he){n==null||n("This browser cannot play spoken replies.");return}G();const Ce=++N.current;(rt=R.current)==null||rt.abort();const Te=new AbortController;R.current=Te,$.current=[],A.current=0,W.current=!1,z.current=!1,k.current=null,b.current=0,S.current=0,h.current=ce,m.current=ce,f({key:ce,status:"loading"}),n==null||n("");let Ye=null;try{for await(const ht of Ae(oe,Te.signal)){if(Ce!==N.current)return;let lt;try{lt=await lp(he.ctx,ht),Ye||(Ye=O1(ht))}catch{if(!Ye)continue;try{lt=await lp(he.ctx,P1(Ye,ht))}catch{continue}}if(Ce!==N.current)return;$.current.push(lt),!w.current&&!z.current&&(m.current="",Q(ce,Ce))}if(Ce!==N.current)return;if(W.current=!0,$.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),re();return}!w.current&&!z.current&&Q(ce,Ce)}catch(ht){if(Ce!==N.current)return;n==null||n(tf("Reading aloud failed",ht)),re()}finally{R.current===Te&&(R.current=null)}},T=_.useCallback(async(ce,oe)=>{var St;const Ae=String(ce||"").trim(),he=String(oe||"").trim();if(!Ae||!he)return;const Ce=t.current.tts,Te=t.current.tts_stream;if(typeof Ce!="function"&&typeof Te!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Ye=H();if(!Ye){n==null||n("This browser cannot play spoken replies.");return}const rt=u.current,ht=rt.key===Ae;if(ht&&rt.status==="playing"){if(w.current){const Zt=Math.max(0,Ye.ctx.currentTime-Number(S.current||0));b.current=Zt}else b.current=0;z.current=!0,G(),f({key:Ae,status:"paused"});return}if(ht&&rt.status==="paused"){if($.current.length>0){n==null||n(""),z.current=!1,f({key:Ae,status:"playing"}),Q(Ae,N.current);return}const Zt=k.current;if(Zt){n==null||n(""),z.current=!1;try{await te(Ae,Zt,b.current)}catch(On){n==null||n(tf("Reading aloud failed",On)),f({key:"",status:"idle"})}return}}if(ht&&rt.status==="loading")return;if(typeof Te=="function"){await D(Ae,he,Te);return}G(),N.current+=1,(St=R.current)==null||St.abort(),R.current=null;const lt=N.current;$.current=[],A.current=0,W.current=!0,z.current=!1,k.current=null,b.current=0,S.current=0,h.current=Ae,m.current=Ae,f({key:Ae,status:"loading"}),n==null||n("");try{const Zt=await Ce(he);if(m.current!==Ae||N.current!==lt)return;const On=await lp(Ye.ctx,Zt);if(m.current!==Ae||N.current!==lt)return;k.current=On,b.current=0,await te(Ae,On,0)}catch(Zt){if(N.current!==lt)return;m.current===Ae&&(m.current="",h.current="",f({key:"",status:"idle"})),n==null||n(tf("Reading aloud failed",Zt))}},[]),[E,L]=_.useState(!1),[M,ee]=_.useState(!1),F=_.useRef(!1),U=_.useRef(a);U.current=a;const K=_.useCallback(ce=>{F.current=ce,L(oe=>oe===ce?oe:ce)},[]),O=_.useRef(!1),V=_.useRef(null),J=_.useRef(null),le=_.useRef([]),ie=_.useRef(""),_e=_.useRef(0),pe=_.useRef(!1),[ye,Ne]=_.useState(0),Be=_.useRef(0),Ue=_.useRef(null);function ut(){var oe,Ae;try{(Ae=(oe=V.current)==null?void 0:oe.getTracks)==null||Ae.call(oe).forEach(he=>{try{he.stop()}catch{}})}catch{}V.current=null;const ce=Ue.current;Ue.current=null;try{ce==null||ce.close()}catch{}}const De=_.useCallback(()=>{_e.current+=1,pe.current=!1;const ce=J.current;if(ce){ce.onstop=null,ce.ondataavailable=null,ce.onerror=null;try{ce.stop()}catch{}}J.current=null,ut(),K(!1),O.current=!1,ee(!1),Ne(0),le.current=[]},[K]);_.useEffect(()=>()=>De(),[De]);async function Qe(ce,oe){var Te,Ye;if(n==null||n(""),O.current)return;const Ae=Be.current?Date.now()-Be.current:1/0;if(!ce||!ce.size||Ae<M1){Ne(0),n==null||n("The recording was too short. Hold the microphone button while you speak, or tap it once to start and again to stop.");return}const he=t.current.transcribe;if(typeof he!="function"){n==null||n("Speech to text is not available on this gateway.");return}O.current=!0;const Ce=_e.current;ee(!0),Ne(Date.now());try{const rt=await he(ce,oe),ht=typeof rt=="string"||!rt?{text:String(rt||"")}:rt,lt=String(ht.text||"").trim();if(Ce!==_e.current)return;lt?(Ye=(Te=t.current).on_transcript)==null||Ye.call(Te,lt,{...ht,text:lt}):n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(rt){if(Ce===_e.current){const ht=String((rt==null?void 0:rt.message)||rt||"").trim().replace(/\.$/,"");n==null||n(ht?`Transcription failed: ${ht}.`:"Transcription failed.")}}finally{Ce===_e.current&&(O.current=!1,ee(!1),Ne(0))}}const at=_.useCallback(async()=>{if(n==null||n(""),!U.current){n==null||n(m_("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(O.current||pe.current||F.current||J.current)return;le.current=[];const ce=_e.current;pe.current=!0;try{const oe=await ib(t.current.input_device_id||"");if(ce!==_e.current){oe.getTracks().forEach(Ye=>Ye.stop());return}V.current=oe;const Ae=I1();ie.current=Ae;let he=oe;const Ce=Number(t.current.input_gain??1);if(Number.isFinite(Ce)&&Ce>0&&Ce!==1&&ab()){const Ye=globalThis.AudioContext||globalThis.webkitAudioContext,rt=new Ye,ht=rt.createGain();ht.gain.value=Ce;const lt=rt.createMediaStreamDestination();rt.createMediaStreamSource(oe).connect(ht),ht.connect(lt),Ue.current=rt,he=lt.stream}const Te=Ae?new MediaRecorder(he,{mimeType:Ae}):new MediaRecorder(he);J.current=Te,Te.ondataavailable=Ye=>{if(ce===_e.current)try{Ye!=null&&Ye.data&&le.current.push(Ye.data)}catch{}},Te.onerror=()=>{ce===_e.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Te.onstop=()=>{if(ce===_e.current){K(!1),ut(),J.current=null;try{const Ye=new Blob(le.current,{type:ie.current||""});Qe(Ye,ie.current)}catch(Ye){n==null||n(tf("The recording could not be prepared",Ye))}}},Te.start(),Be.current=Date.now(),Ne(Be.current),K(!0)}catch(oe){if(ce!==_e.current)return;ut(),J.current=null,K(!1),Ne(0),n==null||n(sg(oe))}finally{ce===_e.current&&(pe.current=!1)}},[]),Ke=_.useCallback(()=>{const ce=J.current;if(!(!F.current||!ce)){K(!1);try{ce.stop()}catch(oe){n==null||n(tf("The recording could not stop",oe))}}},[]);return _.useEffect(()=>{if(!E||t.current.stop_on_pointerup===!1)return;const ce=()=>Ke();return window.addEventListener("pointerup",ce),window.addEventListener("pointercancel",ce),()=>{window.removeEventListener("pointerup",ce),window.removeEventListener("pointercancel",ce)}},[E]),{tts_supported:r,tts_playback:l,toggle_tts:T,stop_tts:re,voice_ptt_supported:a,voice_ptt_recording:E,voice_ptt_busy:M,start_voice_ptt_recording:at,stop_voice_ptt_recording:Ke,cancel_voice_ptt_recording:De,voice_ptt_since:ye}}const B1={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function xw(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function cp(e){const[t,n]=_.useState(!1),[r,a]=_.useState(null),l=_.useRef(!1),c=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,u=e.kind&&B1[e.kind]||"var(--text-muted)",f=_.useCallback(async()=>{if(!(!c||!e.onOpen||l.current)){l.current=!0,n(!0),a(null);try{await e.onOpen(c)}catch(h){a(String((h==null?void 0:h.message)||h||"could not open"))}finally{l.current=!1,n(!1)}}},[c,e.onOpen]);return!c||!e.onOpen?s.jsxs("span",{className:["af-memory-hint","af-memory-hint--text",e.className||""].filter(Boolean).join(" "),title:e.title,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:u},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),c&&e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:xw(c)}):null]}):s.jsxs("span",{className:["af-memory-hint",e.className||""].filter(Boolean).join(" "),children:[s.jsxs("button",{type:"button",className:"af-memory-hint__btn",onClick:()=>void f(),disabled:t,title:e.title||(e.command?e.command:`open ${c}`),"aria-label":`Open ${e.kind||"memory"} entry: ${e.label}`,children:[s.jsx("span",{className:"af-memory-hint__dot",style:{background:u},"aria-hidden":"true"}),s.jsx("span",{className:"af-memory-hint__label",children:e.label}),e.showId!==!1?s.jsx("code",{className:"af-memory-hint__id",children:xw(c)}):null,s.jsx("span",{className:"af-memory-hint__act","aria-hidden":"true",children:t?"…":"↗"})]}),e.command?s.jsx("code",{className:"af-memory-hint__cmd",children:e.command}):null,r?s.jsx("span",{className:"af-memory-hint__err",role:"alert",children:r}):null]})}const um=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 U1({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:a=!0,quality:l=!0,showReset:c=!0,defaultHint:u,voiceDefaultLabel:f}){var z,H,G,re;const h=_.useRef(n);h.current=n;const[m,g]=_.useState({}),[y,w]=_.useState(""),[k,b]=_.useState(!1);_.useEffect(()=>{let te=!0;return b(!0),g({}),w(""),h.current(e.provider,e.model).then(Q=>{te&&(g(Q),w(Q.error?String(Q.error):""))}).catch(Q=>{te&&w(String((Q==null?void 0:Q.message)||Q))}).finally(()=>{te&&b(!1)}),()=>{te=!1}},[e.provider,e.model]);const S=Array.isArray(m.items)?m.items:[...Array.isArray(m.profiles)?m.profiles.map(te=>({...te,voice_kind:"profile"})):[],...Array.isArray(m.voices)?m.voices.map(te=>({...te,voice_kind:"voice"})):[]],N=te=>JSON.stringify([te.provider||"",te.model||"",te.voice_kind==="profile"?"profile":"voice",te.id]),R=S.find(te=>te.id===(e.profile||e.voice)&&te.voice_kind==="profile"==!!e.profile&&(!e.provider||!te.provider||te.provider===e.provider)&&(!e.model||!te.model||te.model===e.model)),$=R?N(R):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",A=S.filter(te=>(te==null?void 0:te.id)&&(!e.provider||!te.provider||te.provider===e.provider)).map(te=>({value:N(te),label:`${te.label||te.name||te.id}${!e.provider&&te.provider?` · ${te.provider}`:""}`}));$&&!A.some(te=>te.value===$)&&A.unshift({value:$,label:`${e.profile||e.voice} (saved)`});const W=te=>t({...e,...te});return s.jsxs("div",{className:"af-voice-settings",children:[r===void 0?s.jsx("p",{children:"Speech is generated by your authenticated Gateway. Leave routing and voice unset to use its defaults."}):r,s.jsx(Qx,{defaultHint:u,value:{provider:e.provider||"",model:e.model||""},onChange:te=>t({...e,...te,voice:"",profile:""}),fetchProviders:async()=>{const te=await h.current();if(te.error&&!um(te.tts_providers||te.providers).length)throw new Error(te.error);return um(te.tts_providers||te.providers).map(Q=>({name:Q}))},fetchModels:async te=>{var D;const Q=await h.current(te);return um(((D=Q.tts_models_by_provider)==null?void 0:D[te])||Q.tts_models||Q.models)},providerLabel:"Speech provider",modelLabel:"Speech model"}),s.jsxs("label",{children:["Voice / profile",s.jsx(ei,{ariaLabel:"AI voice",placeholder:f||"Gateway / provider default",value:$,disabled:k,options:[{value:"",label:f||"Gateway / provider default"},...A],onChange:te=>{if(!te){W({voice:"",profile:""});return}const[Q,D,T,E]=JSON.parse(te);W({provider:Q||e.provider||"",model:D||(Q&&Q!==e.provider?"":e.model)||"",voice:T==="voice"?E:"",profile:T==="profile"?E:""})}})]}),k?s.jsx("p",{role:"status",children:"Loading available voices…"}):null,y?s.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",y,". Your saved choice is preserved."]}):null,a?s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Speaking speed",s.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:te=>W({speed:te.target.value?Number(te.target.value):void 0}),children:[s.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(te=>s.jsxs("option",{value:te,children:[te,"×"]},te))]})]}),l&&((H=(z=m.controls)==null?void 0:z.quality_preset)!=null&&H.supported)?s.jsxs("label",{children:["Quality",s.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:te=>W({quality_preset:te.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),um(m.controls.quality_preset.values).map(te=>s.jsx("option",{value:te,children:te},te))]})]}):null,(re=(G=m.controls)==null?void 0:G.instructions)!=null&&re.supported?s.jsxs("label",{children:["Delivery instructions",s.jsx("textarea",{"aria-label":"Voice delivery instructions",rows:3,placeholder:"For example: calm, clear, and conversational",value:e.instructions||"",onChange:te=>W({instructions:te.target.value})})]}):null]}):null,c?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const up=st("automations"),W1=st("trigger-sources"),q1=st("me/email"),H1=st("automations/schedule-preview");class bw 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 V1(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 a={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(a.field=r.field),typeof r.command_id=="string"&&(a.command_id=r.command_id),a}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function dp(e){const t=new URLSearchParams;for(const[r,a]of Object.entries(e))a!==void 0&&t.set(r,String(a));const n=t.toString();return n?`?${n}`:""}function G1(){return xo()}function K1(e){const t=e.newId??G1,n=a=>`${up}/${encodeURIComponent(a)}`;async function r(a,l,c){const u={accept:"application/json",...e.headers?e.headers():{}},f={method:a,headers:u};c!==void 0&&(u["content-type"]="application/json",f.body=JSON.stringify(c));const h=await e.fetch(Xg(e.baseUrl,l),f),m=await h.text();let g,y=!1;if(m)try{g=JSON.parse(m),y=!0}catch{y=!1}if(!h.ok)throw new bw(V1(h.status,g));if(!y||g===null||typeof g!="object")throw new bw({status:h.status,code:"invalid_response",message:`The gateway answered ${a} ${l} with a body that is not a JSON object.`});return g}return{listAutomations:(a={})=>r("GET",`${up}${dp({status:a.status,cursor:a.cursor,limit:a.limit})}`),getAutomation:a=>r("GET",n(a)),createAutomation:a=>r("POST",up,a),reviseAutomation:(a,l)=>r("PATCH",n(a),{command_id:l.command_id??t(),...l.expected_revision!==void 0?{expected_revision:l.expected_revision}:{},changes:l.changes}),sendAutomationCommand:(a,l)=>r("POST",`${n(a)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(a,l={})=>r("GET",`${n(a)}/occurrences${dp({cursor:l.cursor,limit:l.limit})}`),discuss:(a,l)=>r("POST",`${n(a)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(a,l)=>r("POST",`${n(a)}/seen`,{attention_cursor:l}),listAttention:(a,l={})=>r("GET",`${n(a)}/attention${dp({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>r("GET",W1),getMyEmail:()=>r("GET",q1),previewSchedule:a=>r("POST",H1,{trigger:a})}}function ob(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(a=>typeof a=="string"&&(!n||n.includes(a))):null}function lb(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 Y1(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const a of t)a in e&&(n[a]=e[a]);const r=e._runtime;if(r&&typeof r=="object"){const a={};for(const l of["allowed_tools","provider","model","thinking","speculation","stream"])l in r&&(a[l]=r[l]);Object.keys(a).length&&(n._runtime=a)}return n}function rg(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const J1={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},X1={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.`},Z1="Next scheduled run: {time}.",Q1="Growing context: later runs see this run in their history.",eN={run_now:{name:"playCircle"}},tN={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."},nN={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."},ey={labels:J1,hints:X1,run_now_next_run_line:Z1,run_now_growing_line:Q1,icons:eN,email:tN,schedule:nN},sN=/^([1-9][0-9]*)([smhd])$/,rN={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Qf(e){if(typeof e!="string")return null;const t=sN.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function iN(e){const t=Qf(e);if(!t)return`every ${e}`;const[n,r]=rN[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function ig(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 ty(e,t){return e.source_id==="schedule"?NN(t,e.source_version):e.source_id==="manual"&&e.source_version===1?"manual runs only":g_(e)?pb(e.config):`${e.source_id}@${e.source_version}`}function cb(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const aN={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},Vt=ey.email,ub="email.received",db=1,oN="1h",lN="60s",fb=60,ny=100,ag=1e3,kw=200,jw=200,Sw=50;function g_(e){return!!e&&e.source_id===ub&&e.source_version===db}function y_(e){return!!e&&e.effective_enabled===!0}function hb(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 cN=/[\s<>,;:"()[\]]/;function og(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!cN.test(t)}function uN(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const mb={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function sy(e){return e?oN:lN}function _b(e){const t=Qf(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function fp(e,t,n,r,a){const l=hb(e);if(!l.length)return null;const c=l.filter(u=>!n(u));return c.length&&a.push(`${t}: ${c.join(", ")} ${c.length===1?"is not":"are not"} ${r}.`),l.length>kw&&a.push(`${t}: at most ${kw} entries.`),l}function dN(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=sy(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&&(_b(n.every)??0)<fb&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=ny:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>ag?t.push(`At most this many emails per run: a whole number from 1 to ${ag}.`):n.max_batch=e.maxBatch;const r={},a=fp(e.fromIn,Vt.from_in,og,"an email address",t);a&&(r.from_in=a);const l=fp(e.fromDomainIn,Vt.from_domain_in,uN,"a domain like example.com",t);l&&(r.from_domain_in=l);const c=fp(e.toIn,Vt.to_in,og,"an email address",t);c&&(r.to_in=c);const u=e.subjectContains.trim();return u&&(u.length>jw||/[\r\n]/.test(u)?t.push(`${Vt.subject_contains}: one line of at most ${jw} characters.`):r.subject_contains=u),e.hasAttachment==="yes"?r.has_attachment=!0:e.hasAttachment==="no"&&(r.has_attachment=!1),Object.keys(r).length&&(n.filter=r),{config:n,errors:t}}function pb(e){const t=e,n=t.filter??{},r=["when an email arrives"],a=[...n.from_in??[],...n.from_domain_in??[]];a.length&&r.push(`from ${a.join(", ")}`),n.to_in&&n.to_in.length&&r.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&r.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&r.push("with attachments"),n.has_attachment===!1&&r.push("without attachments");const l=typeof t.every=="string"?t.every:sy(t.uses_model!==!1);r.push(`checked ${iN(l)}`);const c=typeof t.max_batch=="number"?t.max_batch:ny;return r.push(`up to ${c} per run`),r.join(" · ")}const $f={mode:"self",addresses:""};function lg(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=hb(e.addresses).filter(a=>a!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(a=>!og(a));return r.length&&t.push(`${Vt.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Sw&&t.push(`At most ${Sw-1} addresses.`),{recipients:["self",...n],errors:t}}function fN(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function hN(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function gb(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function yb(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function mN(e){return yb(e)?"In the console and by email":"In the console"}const xi={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},_N=new Set(["running","waiting","backoff"]);function pN(e,t=[]){return e.current_occurrence!=null}function wb(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 vb(e,t){return e.next_run_at&&e.next_run_local?`${Cb(e.next_run_local,e.time_zone)} (${gN(e.next_run_at,t)})`:e.status==="paused"?"none while paused":"none scheduled"}function gN(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 a=Math.floor(r/60);return a<24?`in ${a} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(a/24)} d${a%24?` ${a%24} h`:""}`}function Vm(e,t=[],n=!1){const r=new Set(e.capabilities),a=e.status,l=pN(e,t),c=(m,g,y)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(m)?a==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:g?{enabled:!0}:{enabled:!1,reason:y}:{enabled:!1,reason:"Not permitted for this automation."},u=a==="active"||a==="paused",f=a==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:a==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:u?r.has(f)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:c("pause",a==="active",a==="paused"?"Already paused.":"The automation has ended."),resume:c("resume",a==="paused",a==="active"?"Already running on schedule.":"The automation has ended."),run_now:c("run_now",u&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:c("stop_current",l,"Nothing is running."),revise:c("revise",!0,""),archive:c("archive",!0,""),unarchive:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:a!=="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 yN(e){return e.status==="active"?xi.pause:xi.resume}function wN(e){return e.status==="failed"?"failed":e.waits.length>0||e.status==="waiting"?"waiting":e.notify!==null?"notified":e.status==="running"||e.status==="backoff"?"running":"quiet"}function vN(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=wN(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,a=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:a,statusText:l,canDiscuss:!_N.has(t.status)}})}function xN(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function xb(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 bN={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 Gm(e){return{title:bN[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function ry(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 bb(e,t){var l,c,u;const n=e.trigger,r=n.source_id==="schedule"||g_(n)?n.config.every:void 0,a=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,calendar:SN(n)?AN(n.config):null,context:e.context_mode,growingMaxTokens:Number(((c=(l=t==null?void 0:t.context)==null?void 0:l.growing)==null?void 0:c.max_tokens)??e.growing_max_tokens??Rf),prompt:typeof a=="string"?a:null,toolApproval:t?t.policy.tool_approval:null,tools:ob(t==null?void 0:t.target.input_data),notifyEmail:t?yb(t.notify):null,emailRecipients:t?fN((u=t.notify)==null?void 0:u.recipients):null}}function kN(e,t,n){var f;const r=[],a={},l=t.title.trim();l?l.length>120?r.push("Title is at most 120 characters."):l!==e.title&&(a.title=l):r.push("Title is required.");const c=bb(e,n);if(t.every!==c.every&&t.every!==null){const h=g_(e.trigger);if(!Qf(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(h&&(_b(t.every)??0)<fb)r.push("The check interval is at least 60 seconds.");else{const m={...e.trigger.config,every:t.every};h&&delete m.start_at,a.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:m}}}if(t.calendar&&c.calendar&&JSON.stringify(t.calendar)!==JSON.stringify(c.calendar)){const h=ay(t.calendar);if(!h.config)r.push(...h.errors);else{const m=e.trigger.config,g={...h.config,...typeof m.time_zone=="string"?{time_zone:m.time_zone}:{},...typeof m.count=="number"?{count:m.count}:{},...typeof m.until=="string"?{until:m.until}:{}};a.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:g}}}const u=t.context==="growing"?t.growingMaxTokens??c.growingMaxTokens:c.growingMaxTokens;if(jb(u)||r.push(kb),(t.context!==e.context_mode||u!==c.growingMaxTokens)&&(a.context=Sb(t.context,u)),n&&typeof c.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==c.prompt.trim()){const h=t.prompt.trim();h?a.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:h}}:r.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(c.tools)){const h=a.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};a.target={...h,input_data:lb(h.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==c.toolApproval&&(a.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const h=lg(t.notifyEmail?t.emailRecipients??$f:c.emailRecipients??$f),m=lg(c.emailRecipients??$f).recipients;h.errors.length?r.push(...h.errors):(t.notifyEmail!==c.notifyEmail||JSON.stringify(h.recipients)!==JSON.stringify(m))&&(a.notify=gb(t.notifyEmail,h.recipients))}if(r.length)return{errors:r};if(n&&t.target&&rg(t.target)!==rg(n.target)){const h=((f=a.target)==null?void 0:f.input_data)||n.target.input_data;a.target={...t.target,input_data:Y1(h)}}return Object.keys(a).length?a:null}const Rf=5e4,jN="Limits history carried into the next run, keeping recent whole turns. The newest turn is kept even if oversized. New messages and tool results can grow context beyond this budget.",kb="Max growing context must be a positive whole number of tokens.";function jb(e){return Number.isSafeInteger(e)&&e>0}function Sb(e,t){return{mode:e,...t!==Rf?{growing:{max_tokens:t}}:{}}}const Ln=ey.schedule,Km=["mon","tue","wed","thu","fri","sat","sun"],Nb=["daily","weekly","monthly"],iy=2;function SN(e){return e.source_id==="schedule"&&e.source_version===iy}function NN(e,t=iy){const n=e==null?void 0:e.schedule_rule_text;return typeof n=="string"&&n?n:`schedule@${t}`}const CN=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function Cb(e,t){if(!e)return"";const n=CN.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function EN(e,t="account"){return(t==="account"?Ln.time_zone_line:Ln.time_zone_line_automation).replace("{time_zone}",e)}const $N=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function Eb(e){return Nb.includes(e.kind)}function ay(e){const t=[];if($N.test(e.at)||t.push(Ln.error_at),e.kind==="weekly"){const n=Km.filter(r=>e.days.includes(r));return n.length||t.push(Ln.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(Ln.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 AN(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)?Km.filter(r=>t.days.includes(r)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const TN=[{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 $b(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 MN(e){const t=e.trim().split(`
|
|
56
|
-
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const RN=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function Nw(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=$b(e.until);r?n.until=r:t.push("Stop at must be a date and time (UTC).")}return n}function LN(e){const t=[],n=e.when;if(n.kind==="once"){const u=(n.at||"").trim().slice(0,16);return RN.test(u)?{config:{kind:"once",at:u},errors:t}:{config:null,errors:[Ln.error_once]}}if(Eb(n)){const u=ay(n),f=Nw(e,u.errors);return u.config&&!u.errors.length?{config:{...u.config,...f},errors:[]}:{config:null,errors:u.errors}}const r=n.amount;let a=null;!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):a=`${r}${n.unit}`;let l=null;e.startAt&&(l=$b(e.startAt),l||t.push("First run must be a date and time (UTC)."));const c=Nw(e,t);return t.length||!a?{config:null,errors:t}:{config:{kind:"every",every:a,...l?{start_at:l}:{},...c},errors:t}}function Ab(e){const t=LN(e);return t.config?{trigger:{source_id:"schedule",source_version:iy,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function IN(e){return e.kind==="every"||e.kind==="once"||Eb(e)}function Tb(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 a=(e.title??"").trim()||MN(r);a.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",c=l?dN(e.email??mb):null,u=l?null:Ab(e);n.push(...c?c.errors:u.errors);const f=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?lg(e.emailRecipients):null;f&&n.push(...f.errors);const h=e.growingMaxTokens??Rf;if(e.context==="growing"&&!jb(h)&&n.push(kb),n.length||!t.target)return{ok:!1,errors:n};const m={...t.target,input_data:{...t.target.input_data??{},prompt:r}},g={request_id:t.requestId,title:a,target:m,trigger:c?{source_id:ub,source_version:db,config:c.config}:u.trigger,context:Sb(e.context,e.context==="growing"?h:Rf),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(g.notify=gb(!0,f==null?void 0:f.recipients)),{ok:!0,body:g}}const ON="Tools run without asking (you approve them now by creating this automation)";function PN(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 DN(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 Mb={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class FN{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||zN(n.error))&&this.open.delete(t)}}function zN(e){return ry(e)&&e.status>0&&e.code!=="invalid_response"}function BN(){return xo()}class UN{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 Cw(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 WN="08:00",qN=["mon"],Rb={at:WN,days:[...qN],day:1};function oy(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 ly(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function Ew(e){return ly(Rb,e)}const HN=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function Lb(e){const t=e.value,n=r=>{if(t.kind!=="weekly")return;const a=t.days.includes(r);e.onChange({...t,days:Km.filter(l=>l===r?!a:t.days.includes(l))})};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":Ln.days_legend,children:[s.jsx("span",{children:Ln.days_legend}),Km.map(r=>s.jsx(r1,{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:Ln.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:Ln.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:HN.map(r=>s.jsx("option",{value:r,children:r==="last"?Ln.last_day:r},r))})]}):null,s.jsx("label",{htmlFor:`${e.idBase}-at`,children:Ln.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":Ln.time_label,onChange:r=>e.onChange({...t,at:r.target.value.slice(0,5)})})]})]})}function VN(e){return s.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[s.jsx(yw,{content:Ln.time_zone_hint,children:s.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:EN(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?s.jsxs(s.Fragment,{children:[" · ",s.jsx(yw,{content:Ln.time_zone_change_hint,children:s.jsx("button",{type:"button",className:"af-auto__link af-schedule__tz-change",onClick:e.onOpenPreferences,children:Ln.time_zone_change})})]}):null]})}function GN(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function Ib(e,t,n=250){const r=e?JSON.stringify(e):"",[a,l]=_.useState({phase:"idle"}),c=_.useRef(0),u=_.useRef(t);return u.current=t,_.useEffect(()=>{const f=++c.current;if(!r){l({phase:"idle"});return}l({phase:"loading"});const h=setTimeout(()=>{u.current(JSON.parse(r)).then(m=>{c.current===f&&l({phase:"ok",description:m})},m=>{c.current===f&&l({phase:"error",message:GN(m)})})},n);return()=>clearTimeout(h)},[r,n]),a}function Ob(e){const t=e.state;return t.phase==="ok"?s.jsxs(s.Fragment,{children:[e.showZone===!1?null:s.jsx(VN,{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"?Ln.describing:e.incompleteText??Ln.incomplete})}function $w(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 cg(e){const t=e.disabled===!0,n=_.useMemo(()=>$w([...e.options||[],...e.value||[]]),[e.options,e.value]),r=_.useMemo(()=>$w(e.value||[]),[e.value]),[a,l]=_.useState(!1),[c,u]=_.useState(""),f=_.useMemo(()=>{const g=c.trim().toLowerCase();return g?n.filter(y=>y.toLowerCase().includes(g)):n},[n,c]),h=_.useMemo(()=>new Set(r),[r]),m=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return s.jsxs("div",{className:"af_multi_select",children:[s.jsxs("div",{className:"af_multi_select_row",children:[s.jsxs("button",{className:"btn",type:"button",onClick:()=>l(g=>!g),disabled:t||!n.length,"aria-expanded":a,children:[a?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?s.jsx("div",{className:"af_multi_select_chips",children:r.map(g=>s.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${g}`,className:"af_multi_select_chip",title:g,onClick:()=>{if(t)return;const y=new Set(h);y.delete(g),e.onChange(Array.from(y.values()))},children:[g,t?null:s.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},g))}):null,a?s.jsxs("div",{className:"af_multi_select_panel",children:[s.jsx("input",{className:"mono",value:c,onChange:g=>u(String(g.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),s.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${m}px`},children:[f.map(g=>{const y=h.has(g);return s.jsxs("label",{className:`af_multi_select_item mono ${y?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:y,disabled:t,onChange:w=>{const k=new Set(h);w.target.checked?k.add(g):k.delete(g),e.onChange(Array.from(k.values()))}}),s.jsx("span",{children:g})]},g)}),f.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function Pb(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(cg,{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 Db="@default",Fb="No workflows available for this app — ask your admin.",zb={shared:"Shared",mine:"Mine"};class al extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function KN(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 YN(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function JN(e,t={}){return e===null?YN(t):KN(e,t)}function wo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ls(e){return typeof e=="string"?e.trim():""}const dm="update the gateway";function XN(e,t){var u,f;const n=wo(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=wo(n[t]);if(!r)return{status:"unavailable",reason:Ls((f=wo((u=wo(e.default_agent_workflows_unavailable))==null?void 0:u[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const a=Ls(r.bundle_id),l=Ls(r.flow_id);if(!a||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const c=Ls(r.bundle_version);return{status:"ok",name:Ls(r.name)||l,bundleId:a,bundleVersion:c,flowId:l,workflowId:Ls(r.workflow_id)||`${a}${c?`@${c}`:""}:${l}`}}function ZN(e,t,n={}){var u;const r=wo(e);if(!r)throw new al("The gateway's workflow list is not a JSON object.");const a=Ls(r.executable_for);if(t===null){if(a)throw new al(`Asked for every workflow, the gateway listed only ${a}.`)}else if(a!==t)throw new al(a?`The gateway listed workflows for ${a}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${dm}.`);if(!Array.isArray(r.items))throw new al("The gateway's workflow list has no items.");const l=[];for(const f of r.items){const h=wo(f),m=Ls(h==null?void 0:h.bundle_id);if(!h||!m)throw new al("The gateway listed a workflow without a bundle id.");const g=wo(h.owner),y=Ls(g==null?void 0:g.kind);if(y!=="gateway"&&y!=="user")throw new al(`The gateway did not say who owns ${m} (owner missing): ${dm}.`);if(typeof h.shipped!="boolean")throw new al(`The gateway did not say whether ${m} ships with it (shipped missing): ${dm}.`);const w=Ls(h.bundle_version),k=Array.isArray(h.entrypoints)?h.entrypoints:[];for(const b of k){const S=wo(b),N=Ls(S==null?void 0:S.flow_id);if(!S||!N)continue;const R=Array.isArray(S.interfaces)?S.interfaces.map(Ls).filter(Boolean):[];if(t===null){if(!R.length)continue}else if(!R.includes(t))throw new al(`The gateway offered ${m}:${N}, which does not declare ${t}: ${dm}.`);l.push({value:Ls(S.workflow_id)||`${m}${w?`@${w}`:""}:${N}`,bundleId:m,bundleVersion:w,flowId:N,name:Ls(S.name)||Ls((u=wo(h.metadata))==null?void 0:u.name)||m,description:Ls(S.description)||Ls(h.description),registryScope:Ls(h.registry_scope)||"private",group:y==="user"?"mine":"shared",shipped:h.shipped,interfaces:R,...t===null?{showInterfaces:!0}:{}})}}const c=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:c?XN(r,c):{status:"unavailable",reason:"no interface named for the gateway default"}}}function QN(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:zb[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const e2={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function t2(e){return e2[e]??e}function n2(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(t2))].join(", "),n].filter(Boolean).join(" · "):n}function s2(e){return e.value}function r2(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function i2(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 a2(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:Db,name:"Gateway default",detail:r2((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const a of QN(n))for(const l of a.entries)r.push({key:l.value,value:l.value,name:l.name,detail:n2(l,n),title:s2(l),group:a.id,entry:l});return r}async function o2(e,t,n){var l;const r=await fetch(Xg(e,st(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),a=await r.json().catch(()=>null);if(!r.ok){const c=((l=a==null?void 0:a.detail)==null?void 0:l.message)||(a==null?void 0:a.message)||(typeof(a==null?void 0:a.detail)=="string"?a.detail:"");throw new Error(c||`The gateway answered ${r.status}.`)}return a}function l2(e){var n;const t=e;return String(((n=t==null?void 0:t.detail)==null?void 0:n.message)||(t==null?void 0:t.message)||t||"The workflow list could not be loaded.")}function Bb(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:a=!0,gatewayBaseUrl:l,reloadKey:c}=e,u=_.useRef(e.request);u.current=e.request;const[f,h]=_.useState(0),[m,g]=_.useState({status:"idle",data:null,error:""});_.useEffect(()=>{if(!a){g({status:"idle",data:null,error:""});return}const w=new AbortController;g(S=>({...S,status:"loading",error:""}));const k=JN(t,{allVersions:r});return(u.current?u.current(k,{signal:w.signal}):o2(l,k,w.signal)).then(S=>{w.signal.aborted||g({status:"ready",data:ZN(S,t,{defaultInterface:n}),error:""})}).catch(S=>{w.signal.aborted||g({status:"error",data:null,error:l2(S)})}),()=>w.abort()},[t,n,r,a,l,c,f]);const y=_.useCallback(()=>h(w=>w+1),[]);return{...m,reload:y}}function c2(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,a=Math.min(Math.max(t.width,300),440,n-32),l=Math.max(16,Math.min(t.left,n-16-a)),c=r-t.bottom-16;return c>=220||c>=t.top?{position:"fixed",left:l,width:a,top:t.bottom+4,maxHeight:Math.max(160,c)}:{position:"fixed",left:l,width:a,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function Ub(...e){return e.filter(Boolean).join(" ")}function Wb(e){const t=Bb({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,r=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),a=_.useId().replace(/:/g,""),l=`${a}-list`,[c,u]=_.useState(!1),[f,h]=_.useState(-1),m=_.useRef(null),g=_.useRef(null),[y,w]=_.useState({}),k=_.useMemo(()=>a2(n.data,r),[n.data,r]),b=k.find(H=>H.value===e.value),S=b?{name:b.name,detail:b.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===Db?"Gateway default":"Choose a workflow",detail:""},N=String(e.unavailableReason||"").trim(),R=!N&&n.status==="ready",$=_.useCallback(()=>{u(!1),h(-1)},[]),A=_.useCallback(()=>{if(!R)return;w(c2(g.current)),u(!0);const H=k.findIndex(G=>G.value===e.value);h(H>=0?H:0)},[R,k,e.value]),W=_.useCallback(H=>{var G;$(),H.value!==e.value&&e.onChange(H.value,H.entry),(G=g.current)==null||G.focus()},[$,e]);_.useEffect(()=>{if(!c)return;const H=re=>{m.current&&!m.current.contains(re.target)&&$()},G=()=>$();return document.addEventListener("mousedown",H),document.addEventListener("touchstart",H),window.addEventListener("resize",G),()=>{document.removeEventListener("mousedown",H),document.removeEventListener("touchstart",H),window.removeEventListener("resize",G)}},[c,$]),_.useEffect(()=>{var G;if(!c||f<0)return;const H=typeof document<"u"?document.getElementById(`${a}-opt-${f}`):null;(G=H==null?void 0:H.scrollIntoView)==null||G.call(H,{block:"nearest"})},[c,f,a]);const z=H=>{if(!c){["Enter"," ","ArrowDown","ArrowUp"].includes(H.key)&&(H.preventDefault(),A());return}if(H.key==="Escape"){H.preventDefault(),$();return}if(H.key==="Tab"){$();return}if(H.key==="Enter"||H.key===" "){H.preventDefault(),f>=0&&k[f]&&W(k[f]);return}const G=i2(H.key,f,k.length);G!==null&&(H.preventDefault(),h(G))};return s.jsxs("div",{ref:m,className:Ub("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:g,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${a}-value`,"aria-haspopup":"listbox","aria-expanded":c,"aria-controls":l,"aria-activedescendant":c&&f>=0?`${a}-opt-${f}`:void 0,"aria-disabled":R?void 0:!0,title:N||void 0,onClick:()=>c?$():A(),onKeyDown:z,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${a}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:S.name}),S.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:S.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),c?s.jsx(u2,{id:l,idBase:a,rows:k,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:y,onHighlight:h,onChoose:W}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&k.every(H=>!H.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:Fb}):null]})}function u2(e){const t=(l,c)=>s.jsxs("div",{id:`${e.idBase}-opt-${c}`,role:"option","aria-selected":l.value===e.value,"data-value":l.value,title:l.title,className:Ub("af-workflow-picker__option",c===e.highlight&&"af-workflow-picker__option--highlighted",l.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(c),onMouseDown:u=>u.preventDefault(),onClick:()=>e.onChoose(l),children:[s.jsx("span",{className:"af-workflow-picker__name",children:l.name}),l.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:l.detail}):null]},l.key),n=e.rows.map((l,c)=>({row:l,index:c})),r=n.filter(l=>l.row.group===null),a=["shared","mine"].map(l=>({g:l,items:n.filter(c=>c.row.group===l)})).filter(l=>l.items.length>0);return s.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[r.map(l=>t(l.row,l.index)),a.map(({g:l,items:c})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${l}`,"data-group":l,children:[s.jsx("div",{id:`${e.idBase}-g-${l}`,className:"af-workflow-picker__group",role:"presentation",children:zb[l]}),c.map(u=>t(u.row,u.index))]},l)),a.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:Fb}):null]})}function d2(e){const t=rg(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Workflow"}),s.jsx(Wb,{...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 f2(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}`:"",a=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!r||!a||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const l=r.lastIndexOf("@"),c=l<0?r:r.slice(0,l),u=l<0?"":r.slice(l+1),f=await t.request(`bundles/${encodeURIComponent(c)}/flows/${encodeURIComponent(a)}/input_schema${u?`?bundle_version=${encodeURIComponent(u)}`:""}`,{signal:new AbortController().signal}),h=(f==null?void 0:f.input_data_schema)||f;if(!h||typeof h!="object"||!h.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const m={...f.defaults||{}};for(const[k,b]of Object.entries(h.properties))b&&"default"in b&&(m[k]=b.default);Object.assign(m,e.input_data||{});const g=(Array.isArray(h.required)?h.required:[]).filter(k=>m[k]===void 0);if(g.length)throw new Error(`This workflow needs additional inputs: ${g.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:m}}function ug(e){if(y_(e.status))return null;const t=Vt.not_set_up,n=Vt.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,a=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,a?s.jsxs("span",{className:"af-email__cause",children:[" (",a,")"]}):null]})}function h2(e){const t=e.value,n=u=>e.onChange({...t,...u}),r=u=>`${e.idBase}-email-${u}`,a=Qf(sy(t.usesModel)),l=t.every??(a&&a.unit==="s"?{amount:Math.max(1,Math.round(a.amount/60)),unit:"m"}:{amount:a?a.amount:1,unit:a?a.unit:"h"}),c=e.disabled===!0;return s.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[s.jsxs("div",{className:"af-auto__row",children:[s.jsx("span",{children:Vt.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(l.amount),disabled:c,"aria-label":"Check interval amount",name:"email_every_amount",onChange:u=>n({every:{amount:Number(u.target.value),unit:l.unit}})}),s.jsxs("select",{value:l.unit,disabled:c,"aria-label":"Check interval unit",name:"email_every_unit",onChange:u=>n({every:{amount:l.amount,unit:u.target.value}}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]}),s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Vt.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:Vt.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:ag,step:1,disabled:c,value:String(t.maxBatch??ny),onChange:u=>n({maxBatch:u.target.value.trim()===""?null:Number(u.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:Vt.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:c,children:[s.jsx("legend",{children:Vt.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:Vt.from_in}),s.jsx("input",{id:r("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:u=>n({fromIn:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:Vt.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:u=>n({fromDomainIn:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:Vt.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:u=>n({toIn:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:Vt.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:u=>n({subjectContains:u.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:Vt.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:u=>n({hasAttachment:u.target.value}),children:[s.jsx("option",{value:"any",children:Vt.has_attachment_any}),s.jsx("option",{value:"yes",children:Vt.has_attachment_yes}),s.jsx("option",{value:"no",children:Vt.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:Vt.list_hint})]})]})}function m2(e){const t=r=>`${e.idBase}-email-${r}`,n=e.disabled===!0;return s.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[s.jsx(Ni,{variant:"row",action:"notify-email",label:Vt.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:[Vt.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:Vt.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"})})," ",Vt.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"})})," ",Vt.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":Vt.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:Vt.recipients_hint})]}):null]})}const _2={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function qb(e){const t=String(e.status),n=_2[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:aN[t]??t}),n?s.jsx(ze,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const dg="Discuss — fork at this occurrence (own workspace, automation files read-only)",w_=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function p2(e){return ry(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Aw(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(xe.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function g2(e,t){const n=e.trigger,r=t.find(a=>a.id===n.source_id&&a.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 y2(e){const t=e.summary,n=wb(t),r=g2(t,e.triggerSources),a=vb(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(qb,{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:[ty(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:cb(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:a}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Workspace"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?s.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
|
|
57
|
-
${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[s.jsx(ze,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Aw,{path:t.workspace_root})]}):s.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[s.jsx(ze,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx(Aw,{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:xb(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 w2(e){var c,u;const t=e.definition,n=e.renderText??w_,r=t.target.input_data.prompt,a=t.policy.retry,l=t.policy.tool_approval;return s.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[s.jsxs("summary",{children:[s.jsx(ze,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(ze,{name:"file",size:14}),s.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),s.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Target"}),s.jsx("dd",{"data-def":"target",children:s.jsx("code",{children:t.target.workflow_id})}),typeof r=="string"&&r?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Task"}),s.jsx("dd",{"data-def":"prompt",children:n(r)})]}):null,s.jsx("dt",{children:"Trigger"}),s.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",ty(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:[cb(t.context.mode),t.context.mode==="growing"?` · ${Number(((c=t.context.growing)==null?void 0:c.max_tokens)??5e4).toLocaleString()} tokens`:""]}),s.jsx("dt",{children:"Tools"}),s.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:mN(t.notify)}),(u=t.notify)!=null&&u.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:hN(t.notify.recipients)})]}):null,s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[a.max_attempts," ",a.max_attempts===1?"attempt":"attempts",", backoff ",a.backoff.initial," ×",a.backoff.factor," up to ",a.backoff.max]}),s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const eh=ey,Ra=eh.labels,Xi={active:"play",pause:"pause",resume:"play",run_now:eh.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},fg=eh.hints,v2=eh.run_now_next_run_line,x2=eh.run_now_growing_line;function Ym(e,t){const n=[fg[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(v2.replace("{time}",Cb(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(x2)),n.join(`
|
|
58
|
-
`)}function b2(e,t,n){const r=new Map;for(const c of t){const u=e[c];if(u.enabled)continue;const f=u.reason??"Not available now.";r.set(f,[...r.get(f)??[],c])}const a=[],l={};return[...r.entries()].forEach(([c,u],f)=>{const h=`${n}-why-${f}`;a.push({id:h,text:`${u.map(m=>Ra[m]).join(", ")}: ${c}`});for(const m of u)l[m]=h}),{lines:a,describedBy:l}}function fr(e){return s.jsxs(s.Fragment,{children:[s.jsx(ze,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function k2(e){const t=Vm(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",a=b2(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),l=(c,u,f)=>{const h=Ym(c,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${f!=null&&f.danger?" af-auto__btn--danger":""}`,"data-action":(f==null?void 0:f.action)??c,disabled:!t[c].enabled,title:t[c].enabled?h:`${t[c].reason}
|
|
59
|
-
${h}`,"aria-description":h,"aria-describedby":a.describedBy[c],"aria-pressed":f==null?void 0:f.pressed,onClick:u,children:s.jsx(fr,{icon:Xi[c],label:(f==null?void 0:f.label)??Ra[c]})},c)};return s.jsxs("div",{className:"af-auto__controls-wrap",children:[s.jsxs("div",{className:"af-auto__actionbar",children:[s.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[s.jsx(Ni,{className:"af-auto__switch",action:"active",label:Ra.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:a.describedBy.active,busy:e.busy,hint:Ym("active",e.summary),onChange:()=>e.onCommand(yN(e.summary))},"active"),l("run_now",()=>e.onCommand(xi.run_now)),l("stop_current",()=>e.onCommand(xi.stop_current)),l("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?l("unarchive",()=>e.onCommand(xi.unarchive)):l("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),s.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?s.jsxs(s.Fragment,{children:[s.jsx(ze,{name:"check",size:13}),s.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.onDismissNotice,children:s.jsx(ze,{name:"x",size:12})}):null]}):null})]}),a.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(ze,{name:"info",size:12,className:"af-auto__reasons-icon"}),a.lines.map(c=>s.jsx("span",{id:c.id,children:c.text},c.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?s.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive&&!n?s.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(xi.archive),children:s.jsx(fr,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(fr,{icon:"x",label:"Keep it"})})]})]}):null]})}const Tw=[["m","minutes"],["h","hours"],["d","days"]];function j2(e,t){const n=S=>{const N=e.elements.namedItem(S);return N&&typeof N.value=="string"?N.value:null},r=n("every_amount"),a=n("every_unit"),l=r!==null&&a!==null?`${r.trim()}${a}`:t.every,c=e.elements.namedItem("context"),u=c&&(c.value==="growing"||c.value==="independent")?c.value:t.context,f=n("prompt"),h=e.elements.namedItem("tool_approval"),m=h&&(h.value==="auto"||h.value==="ask")?h.value:t.toolApproval??null,g=e.elements.namedItem("notify_email"),y=g&&typeof g.checked=="boolean"?g.checked:t.notifyEmail??null,w=e.elements.namedItem("email_recipients"),k=n("email_recipient_list"),b=w&&(w.value==="self"||w.value==="list")?{mode:w.value,addresses:k??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:u,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:f??t.prompt??null,toolApproval:m,notifyEmail:y,emailRecipients:b}}function S2(e){var z;const t=bb(e.summary,e.definition),[n,r]=_.useState(),[a,l]=_.useState(t.tools??null),[c,u]=_.useState(t.context),[f,h]=_.useState(!!t.notifyEmail),[m,g]=_.useState(((z=t.calendar)==null?void 0:z.kind)??null),[y,w]=_.useState(t.calendar?Ew(t.calendar):null),k=m&&y?oy(m,y):null,b=(()=>{if(!k)return null;const H=ay(k);if(!H.config)return null;const G=e.summary.trigger.config.time_zone;return{source_id:e.summary.trigger.source_id,source_version:e.summary.trigger.source_version,config:{...H.config,...typeof G=="string"?{time_zone:G}:{}}}})(),S=Ib(b,e.previewSchedule),N=t.every?Qf(t.every):null,R=N&&N.unit==="s"?[["s","seconds"],...Tw]:Tw,$=`af-auto-revise-${e.summary.automation_id}`,A=y_(e.emailStatus),W=g_(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${$}-heading`,onSubmit:H=>{H.preventDefault(),e.onSubmit({...j2(H.currentTarget,t),...k?{calendar:k}:{},...n?{target:n}:{},...e.availableTools!==void 0?{tools:a}:{}})},onKeyDown:H=>{H.key==="Escape"&&e.onCancel&&(H.preventDefault(),e.onCancel())},children:[e.heading===null?s.jsx("span",{id:`${$}-heading`,hidden:!0,children:"Edit automation"}):s.jsxs("h3",{className:"af-auto__form-title",id:`${$}-heading`,children:[s.jsx(ze,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?s.jsx(d2,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,s.jsxs("label",{className:"af-auto__field",htmlFor:`${$}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${$}-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:`${$}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${$}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
|
|
60
|
-
`).length+1)),required:!0})]}):null,N?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:W?Vt.every_label:"Repeat every (UTC)"}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:N.amount,"aria-label":"Interval amount"}),s.jsx("select",{name:"every_unit",defaultValue:N.unit,"aria-label":"Interval unit",children:R.map(([H,G])=>s.jsx("option",{value:H,children:G},H))})]}),W?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:Vt.interval_rule}):null]}):k?s.jsxs("fieldset",{className:"af-auto__field","data-field":"calendar",children:[s.jsx("legend",{children:Ln.legend}),s.jsx("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:Nb.map(H=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`${$}-calendar-kind`,value:H,checked:k.kind===H,disabled:e.busy,onChange:()=>g(H)})," ",Ln[`kind_${H}`]]},H))}),s.jsx(Lb,{value:k,onChange:H=>w(G=>ly(G??Ew(H),H)),idBase:$,disabled:e.busy}),s.jsx(Ob,{state:S,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:()=>u("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>u("growing")})," Growing — each run sees the previous runs"]}),s.jsx("div",{hidden:c!=="growing",children:s.jsxs("label",{className:"af-auto__field",children:[s.jsx("span",{children:"Max growing context (tokens)"}),s.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||c!=="growing",defaultValue:t.growingMaxTokens}),s.jsx("span",{className:"af-auto__hint",children:jN})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(Pb,{availableTools:e.availableTools,value:a,onChange:l,disabled:e.busy}):null,s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"tool_approval",value:"ask",defaultChecked:t.toolApproval==="ask"})," Ask before each tool call"]})]}):null,t.notifyEmail!==null&&t.notifyEmail!==void 0&&t.emailRecipients?s.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[s.jsx("legend",{children:"Mailbox"}),A?null:s.jsx(ug,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(FS,{variant:"row",action:"notify-email",name:"notify_email",label:Vt.notify_label,defaultChecked:!!t.notifyEmail,onChange:h,unavailableReason:!A&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[Vt.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),s.jsx("div",{hidden:!f,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!f,"data-field":"email-recipients",children:[s.jsx("legend",{children:Vt.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",Vt.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!A&&t.emailRecipients.mode!=="list"})," ",Vt.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":Vt.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!A&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:Vt.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(H=>s.jsx("li",{children:H},H))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(fr,{icon:"check",label:e.submitLabel??"Save changes"})}),e.onCancel?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(fr,{icon:"x",label:"Cancel"})}):null]})]})}function hg(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function N2(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=c=>e.onAnswerWait(t.run_id,t.wait_key,c),a=e.renderText??w_,l=c=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:Mb[t.kind]??"Waiting"}),t.prompt?a(t.prompt):s.jsxs("span",{children:[" ",c]})]});if(t.kind==="tool_approval"){const c=PN(t);return s.jsxs("div",{className:"af-auto-wait af-auto-wait--tool_approval",role:"group","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,children:[l("A tool call needs your approval."),c&&c.length?s.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:c.map((u,f)=>s.jsxs("li",{"data-tool":u.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:u.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(u.arguments,null,2)})]},u.call_id??`${u.name}:${f}`))}):s.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:s.jsx(fr,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:s.jsx(fr,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:c=>{var f;c.preventDefault();const u=DN(hg(c.currentTarget,"payload"));u.ok?r({payload:u.payload}):(f=e.onWaitError)==null||f.call(e,u.error)},children:[l("The run waits for an event."),s.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),s.jsx("div",{className:"af-auto__row",children:s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:s.jsx(fr,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:c=>{c.preventDefault();const u=hg(c.currentTarget,"response");u&&r({response:u})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?s.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(c=>s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:c}),children:c},c))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:s.jsx(fr,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[l("The run is waiting."),s.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function C2(e){const{row:t,tone:n,badge:r,statusText:a}=e.view,l=`af-auto-occ-${t.run_id}`,c=e.renderText??w_,u=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",h=(y,w)=>e.renderTurn?e.renderTurn({kind:y,role:y==="trigger"?"user":"assistant",text:w,index:t.index,runId:t.run_id}):c(w),m=e.renderTurn?" af-auto-turn--card":"",g=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return s.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[s.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${m}`,"data-turn":"trigger",children:[s.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",ig(t.fired_at)]}),s.jsx("div",{className:"af-auto-turn__text",children:h("trigger",t.user_turn)})]}),s.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${m}`,"data-turn":"answer",children:[s.jsxs("div",{className:"af-auto-turn__meta",children:[r?s.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:r}):null,s.jsx("span",{className:"af-auto-turn__status",children:a}),t.finished_at?s.jsxs("span",{children:[" · ",ig(t.finished_at)]}):null]}),t.notify?s.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[s.jsx("strong",{children:t.notify.title}),t.notify.body?s.jsx("div",{className:"af-auto-notify__body",children:c(t.notify.body)}):null]}):null,t.failure?s.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[s.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?s.jsx("div",{className:"af-auto-turn__text",children:h("answer",t.answer)}):s.jsx("div",{className:"af-auto-turn__empty",children:g}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(y=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var w;return(w=e.onOpenResource)==null?void 0:w.call(e,{kind:"artifact",url:y.url,name:y.name,mimeType:y.mime_type,runId:t.run_id})},children:[s.jsx(ze,{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(N2,{wait:y,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${y.run_id}:${y.wait_key}`))]}),s.jsxs("div",{className:"af-auto-occ__foot",children:[s.jsxs("details",{className:"af-auto-occ__details",children:[s.jsx("summary",{children:"Run details"}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Run"}),s.jsx("dd",{children:s.jsx("code",{children:t.run_id})}),s.jsx("dt",{children:"Attempts"}),s.jsx("dd",{children:t.attempts})]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:s.jsx(fr,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var y;return(y=e.onOpenResource)==null?void 0:y.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(fr,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var y;return(y=e.onOpenWorkspace)==null?void 0:y.call(e,t.run_id)},children:s.jsx(fr,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${dg}, from occurrence ${t.index}`,onSubmit:y=>{y.preventDefault();const w=hg(y.currentTarget,"prompt");w&&e.onDiscussSubmit(t.index,w)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),s.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:s.jsx(fr,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(fr,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!u,title:fg.discuss,"aria-description":fg.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(fr,{icon:Xi.discuss,label:dg})}),f?s.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const E2=5e3,$2={[xi.pause]:"Automation paused.",[xi.resume]:"Automation active.",[xi.run_now]:"Run requested.",[xi.stop_current]:"Stop requested.",[xi.unarchive]:"Unarchived: it is paused until you make it active."};function A2(e){var le;const{summary:t,busy:n}=e,r=e.renderText??w_,a=_.useId(),l=_.useRef(null),[c,u]=_.useState(!1),f=e.editOpen!==void 0,m=Vm(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:c),g=_.useRef(null);m?(!g.current||g.current.summary.automation_id!==t.automation_id)&&(g.current={summary:t,definition:e.definition}):g.current=null;const y=g.current,w=_.useRef(e.onEditOpenChange);w.current=e.onEditOpenChange;const k=ie=>{var _e;f||u(ie),(_e=w.current)==null||_e.call(w,ie)},[b,S]=_.useState([]),[N,R]=_.useState(!1),[$,A]=_.useState(null),[W,z]=_.useState(null),[H,G]=_.useState(null);_.useEffect(()=>{if(!H)return;const ie=setTimeout(()=>G(null),E2);return()=>clearTimeout(ie)},[H]),_.useEffect(()=>{var _e;if(!m)return;S([]);const ie=Cw(l.current,['.af-auto__revise [name="title"]']);ie==null||ie.focus(),(_e=ie==null?void 0:ie.scrollIntoView)==null||_e.call(ie,{block:"nearest"})},[m,t.automation_id]);const[re,te]=_.useState(null);_.useEffect(()=>{var ie;re&&((ie=Cw(l.current,[...re,".af-auto__notice",".af-auto__title"]))==null||ie.focus(),te(null))},[re]);const Q=_.useRef(null);Q.current||(Q.current=new FN(e.newId??BN));const D=Q.current,T=ie=>z(p2(ie)),E=(ie,_e,pe)=>{z(null),G(null),_e(D.idFor(ie)).then(ye=>{D.settle(ie,{ok:!0}),pe(ye)},ye=>{D.settle(ie,{ok:!1,error:ye}),T(ye)})},L=xN(t),M=_.useRef(e.onSeen);M.current=e.onSeen;const ee=_.useRef(null);ee.current||(ee.current=new UN),_.useEffect(()=>{const ie=ee.current,_e=L?`${t.automation_id}|${L}`:null;if(!L||!ie.next(_e,t))return;const pe=t;M.current(L).then(()=>ie.succeeded(_e),ye=>{ie.failed(_e,pe),T(ye)})});const F=Vm(t,e.occurrences,n),U=vN(e.occurrences),K=t.occurrence_count-e.occurrences.length,O=W??e.error??null,V=O?Gm(O):null,J=t.attention;return s.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,...e.hideHeader?{"aria-label":t.title}:{"aria-labelledby":a},"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[e.hideHeader?null:s.jsxs(s.Fragment,{children:[s.jsx(y2,{summary:t,workflowLabel:(le=e.definition)==null?void 0:le.target.workflow_id,triggerSources:e.triggerSources,titleId:a,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),s.jsx(k2,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:m,notice:H,onDismissNotice:()=>G(null),idBase:`${a}-ctl`,onCommand:ie=>E(`command:${ie}`,_e=>e.onCommand(ie,void 0,{command_id:_e}),()=>{ie===xi.archive?(R(!1),G("Archive requested."),te(['[data-action="archive"]'])):G($2[ie]??"Command sent.")}),onToggleRevise:()=>{S([]),k(!m)},onAskArchive:()=>R(!0),onCancelArchive:()=>{R(!1),te(['[data-action="archive"]'])}})]}),m&&y?s.jsx(S2,{summary:y.summary,definition:y.definition,busy:n,errors:b,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,previewSchedule:e.previewSchedule,onCancel:()=>{k(!1),te(['[data-action="edit"]'])},onSubmit:ie=>{const _e=y.summary,pe=kN(_e,ie,y.definition);if(pe===null){S(["Nothing changed."]);return}if("errors"in pe){S(pe.errors);return}S([]),E(`revise:${_e.revision}:${JSON.stringify(pe)}`,async ye=>{const Ne=ie.target&&pe.target?{...pe,target:await(e.prepareTarget?e.prepareTarget(pe.target):f2(pe.target,e.workflowPickerOptions))}:pe;return e.onRevise(Ne,_e.revision,{command_id:ye})},()=>{G("Saved; applies from the next run."),k(!1),te(['[data-action="edit"]'])})}}):e.definition?s.jsx(w2,{definition:e.definition,renderText:r,served:t}):null,V?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":O==null?void 0:O.code,children:[s.jsx(ze,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:V.title})," ",s.jsx("span",{children:V.detail})]}),W?s.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>z(null),children:s.jsx(ze,{name:"x",size:12})}):null]}):null,J.items.length||J.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[J.items.map(ie=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ie.kind}`,"data-cursor":ie.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${ie.kind==="failure"?"failed":"notified"}`,children:ie.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:ie.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ie.index," · ",ig(ie.at)]}),ie.body?s.jsx("div",{className:"af-auto__attention-body",children:r(ie.body)}):null]},ie.cursor)),J.waits.map(ie=>s.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[s.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":ie.kind,children:Mb[ie.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ie.index]}),ie.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(ie.prompt)}):null]},`${ie.run_id}:${ie.wait_key}`))]})}):null,K>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(fr,{icon:"history",label:`Load earlier occurrences (${K} more)`})}):null,U.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:U.map(ie=>{const _e=`[data-index="${ie.row.index}"]`;return s.jsx(C2,{view:ie,busy:n,discuss:F.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?pe=>{var ye;z(null);try{Promise.resolve((ye=e.onOpenResource)==null?void 0:ye.call(e,pe)).catch(T)}catch(Ne){T(Ne)}}:void 0,discussOpen:$===ie.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(pe,ye,Ne)=>{z(null),e.onAnswerWait(pe,ye,Ne).then(()=>G("Answer sent."),T)},onWaitError:pe=>z({status:0,code:"invalid_payload",message:pe}),onDiscussOpen:A,onDiscussCancel:()=>{A(null),te([`${_e} [data-action="discuss"]`])},onDiscussSubmit:(pe,ye)=>E(`discuss:${pe}:${ye}`,Ne=>e.onDiscuss(pe,ye,{request_id:Ne}),Ne=>{A(null),G(`Discussion started (session ${Ne.session_id}).`),te([`${_e} [data-action="discuss"]`])})},ie.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}const Hb=72;function T2(e,t=Hb){const n=Math.max(1,Math.floor(t)),r=new Array(n).fill(0),a=e.length;if(!a)return r;const l=a/n;let c=0;for(let u=0;u<n;u+=1){const f=Math.floor(u*l),h=Math.max(f+1,Math.floor((u+1)*l));let m=0;for(let g=f;g<h&&g<a;g+=1){const y=Math.abs(Number(e[g])||0);y>m&&(m=y)}r[u]=m,m>c&&(c=m)}return c<=0?r:r.map(u=>u/c)}function fm(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),a=String(t%60).padStart(2,"0");return n>0?`${n}:${String(r).padStart(2,"0")}:${a}`:`${r}:${a}`}function M2(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function R2(e,t){const[n,r]=_.useState({peaks:t??null,note:""});return _.useEffect(()=>{if(t){r({peaks:t,note:""});return}let a=!0;r({peaks:null,note:""});const l=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!l||typeof fetch!="function"){r({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let c=null;try{const u=await(await fetch(e)).arrayBuffer();c=new l;const f=await c.decodeAudioData(u);a&&r({peaks:T2(f.getChannelData(0)),note:""})}catch(u){a&&r({peaks:null,note:`Waveform unavailable: ${u instanceof Error?u.message:String(u)}`})}finally{c&&c.close().catch(()=>{})}})(),()=>{a=!1}},[e,t]),n}function v_(e){const t=_.useRef(null),n=_.useRef(null),[r,a]=_.useState(!1),[l,c]=_.useState(0),[u,f]=_.useState(null),[h,m]=_.useState(""),{peaks:g,note:y}=R2(e.src,e.peaks),w=g??new Array(Hb).fill(0),k=u&&u>0?Math.min(1,l/u):0,b=e.name?`Audio ${e.name}`:"Audio",S=_.useCallback(()=>{const A=t.current;A&&(A.paused?A.play().catch(W=>m(W instanceof Error?W.message:String(W))):A.pause())},[]),N=_.useCallback(A=>{const W=t.current;!W||!Number.isFinite(A)||(W.currentTime=A,c(A))},[]),R=A=>{var z;const W=(z=n.current)==null?void 0:z.getBoundingClientRect();!W||!u||N(M2(A-W.left,W.width,u))},$=A=>{if(!u)return;const W=A.key==="ArrowRight"||A.key==="ArrowUp"?5:A.key==="ArrowLeft"||A.key==="ArrowDown"?-5:0;W?(A.preventDefault(),N(Math.min(u,Math.max(0,l+W)))):A.key==="Home"?(A.preventDefault(),N(0)):A.key==="End"?(A.preventDefault(),N(u)):(A.key===" "||A.key==="Enter")&&(A.preventDefault(),S())};return s.jsxs("div",{className:`af-audio${e.className?` ${e.className}`:""}`,"data-playing":r?"true":"false",children:[s.jsx("audio",{ref:t,src:e.src,preload:"metadata",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:A=>c(A.currentTarget.currentTime),onLoadedMetadata:A=>f(Number.isFinite(A.currentTarget.duration)?A.currentTarget.duration:null),onDurationChange:A=>f(Number.isFinite(A.currentTarget.duration)?A.currentTarget.duration:null),onError:()=>m("This audio cannot be played in this browser. Use Download to open it.")}),s.jsx("button",{type:"button",className:"af-audio__play","data-action":r?"pause-audio":"play-audio","aria-label":r?`Pause ${b}`:`Play ${b}`,title:r?"Pause":"Play",onClick:S,children:s.jsx(ze,{name:r?"pause":"play",size:16})}),s.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${b}`,"aria-valuemin":0,"aria-valuemax":Math.round(u??0),"aria-valuenow":Math.round(l),"aria-valuetext":`${fm(l)} of ${fm(u)}`,title:y||void 0,"data-waveform":g?"decoded":"flat",onKeyDown:$,onPointerDown:A=>{var W,z;(z=(W=A.currentTarget).setPointerCapture)==null||z.call(W,A.pointerId),R(A.clientX)},onPointerMove:A=>{A.buttons&1&&R(A.clientX)},children:s.jsx("svg",{viewBox:`0 0 ${w.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:w.map((A,W)=>{const z=Math.max(1.5,A*30),H=(W+.5)/w.length<=k;return s.jsx("rect",{className:H?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:W*2+.3,y:16-z/2,width:1.4,height:z,rx:.6},W)})})}),s.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[fm(l)," / ",fm(u)]}),h?s.jsx("p",{className:"af-audio__error",role:"alert",children:h}):null]})}const gc=e=>new Set(e.split(/\s+/).filter(Boolean)),L2=gc("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"),I2=gc("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"),O2=gc("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),P2=gc("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"),Mw=gc("true false null yes no on off"),D2={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:L2},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:I2},shell:{line:["#"],strings:['"',"'"],keywords:O2},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:P2},data:{line:["#"],strings:['"',"'"],keywords:Mw},json:{line:[],strings:['"'],keywords:Mw},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:gc("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:gc("")}},F2={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 cy(e){const t=String(e||"").trim().toLowerCase(),n=t.split("/").pop()||t;if(n==="dockerfile"||n==="makefile")return"shell";const r=n.lastIndexOf("."),a=r>=0?n.slice(r+1):n;return F2[a]||""}const z2=e=>e>="0"&&e<="9",B2=e=>/[A-Za-z_$]/.test(e),Rw=e=>/[A-Za-z0-9_$]/.test(e);function Vb(e,t){const n=String(e??""),r=D2[t];if(!r)return n?[{kind:"plain",text:n}]:[];const a=[];let l="";const c=(f,h)=>{if(h){if(f==="plain"){l+=h;return}l&&a.push({kind:"plain",text:l}),l="",a.push({kind:f,text:h})}};let u=0;for(;u<n.length;){const f=n[u];if(r.line.find(m=>n.startsWith(m,u))){const m=n.indexOf(`
|
|
61
|
-
`,u),g=m===-1?n.length:m;c("comment",n.slice(u,g)),u=g;continue}if(r.block&&n.startsWith(r.block[0],u)){const m=n.indexOf(r.block[1],u+r.block[0].length),g=m===-1?n.length:m+r.block[1].length;c("comment",n.slice(u,g)),u=g;continue}if(r.strings.includes(f)){const m=r.triple&&n.startsWith(f.repeat(3),u)?f.repeat(3):"";if(m){const w=n.indexOf(m,u+3),k=w===-1?n.length:w+3;c("string",n.slice(u,k)),u=k;continue}let g=u+1;for(;g<n.length&&n[g]!==f&&(f==="`"||n[g]!==`
|
|
62
|
-
`);)g+=n[g]==="\\"?2:1;const y=Math.min(n.length,g+1);c("string",n.slice(u,y)),u=y;continue}if(z2(f)&&!(u>0&&Rw(n[u-1]))){let m=u+1;for(;m<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[m]);)m+=1;c("number",n.slice(u,m)),u=m;continue}if(B2(f)){let m=u+1;for(;m<n.length&&Rw(n[m]);)m+=1;const g=n.slice(u,m),y=t==="sql"?r.keywords.has(g.toLowerCase()):r.keywords.has(g);c(y?"keyword":"plain",g),u=m;continue}c("plain",f),u+=1}return l&&a.push({kind:"plain",text:l}),a}function hm({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:a}){const l=cy(t),c=Vb(e,l),u=n?String(e??"").split(`
|
|
63
|
-
`).length:0;return s.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${r?` ${r}`:""}`,"data-language":l||"text","aria-label":a,style:n?{"--af-code-gutter":`${String(u).length+1}ch`}:void 0,children:s.jsx("code",{children:n?U2(c).map((f,h)=>s.jsxs("span",{className:"af-code__line","data-line":h+1,children:[f.map((m,g)=>Lw(m,g)),`
|
|
64
|
-
`]},h)):c.map((f,h)=>Lw(f,h))})})}function Lw(e,t){return e.kind==="plain"?s.jsx(xe.Fragment,{children:e.text},t):s.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function U2(e){const t=[[]];for(const n of e)n.text.split(`
|
|
65
|
-
`).forEach((a,l)=>{l>0&&t.push([]),a&&t[t.length-1].push({kind:n.kind,text:a})});return t}const Gb=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],vf=6e4,xf=60*vf,mm=24*xf;function th(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)?th(Number(t)):Date.parse(t)}function Iw(e){return e<10?`0${e}`:String(e)}function Ow(e,t){const n=th(e);if(!Number.isFinite(n))return"";const r=new Date(n),a=r.getFullYear()===new Date(t).getFullYear();return`${Gb[r.getMonth()]} ${r.getDate()}${a?"":`, ${r.getFullYear()}`}`}function Kb(e){const t=th(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${Gb[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${Iw(n.getHours())}:${Iw(n.getMinutes())}`}function Jm(e,t){const n=th(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const l=-r;if(l<vf)return"due now";if(l<xf)return`in ${Math.round(l/vf)} min`;if(l<mm)return`in ${Math.round(l/xf)} h`;const c=Math.round(l/mm);return c<7?`in ${c} ${c===1?"day":"days"}`:Ow(n,t)}if(r<vf)return"just now";if(r<xf)return`${Math.floor(r/vf)} min ago`;if(r<mm)return`${Math.floor(r/xf)} h ago`;const a=Math.floor(r/mm);return a===1?"yesterday":a<7?`${a} days ago`:Ow(n,t)}const W2=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),q2=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),H2=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function V2(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function mg(e,t=""){const n=V2(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":W2.has(n)||r.startsWith("image/")&&r!=="image/svg+xml"?"image":q2.has(n)||r.startsWith("audio/")?"audio":cy(e)?"code":H2.has(n)||r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function Pw(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function uy(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 G2(e){const t=e.kind??mg(e.name,e.contentType),n=uy(e.sizeBytes),r=e.modified!==void 0?Jm(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(ze,{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:Kb(e.modified),dateTime:new Date(th(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(ze,{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(ze,{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(K2,{kind:t,p:e})]})})]})}function K2({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(_m,{});case"audio":return t.url?s.jsx(v_,{src:t.url,name:t.name}):s.jsx(_m,{});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(_m,{});case"markdown":return t.renderMarkdown?s.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):s.jsx(hm,{text:n,language:""});case"json":{let r=n,a="";try{r=JSON.stringify(JSON.parse(n),null,2)}catch{a=t.partialNote?"":"Not valid JSON; shown as text."}return s.jsxs(s.Fragment,{children:[a?s.jsx("p",{className:"af-file-viewer__muted",children:a}):null,s.jsx(hm,{text:r,language:"json"})]})}case"code":return s.jsx(hm,{text:n,language:t.name});case"text":return s.jsx(hm,{text:n,language:"",lineNumbers:!1});default:return s.jsx(_m,{})}}function _m(){return s.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function bf(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 ic(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 Dw(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(ic,{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 pn={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."},kr=pn;function Y2(e){return e==="any_except_denied"?kr.postureAnyExceptDenied:kr.postureAllowedOnly}function J2(e){return e==="any_except_denied"?kr.postureAnyExceptDeniedHelp:kr.postureAllowedOnlyHelp}function Fw(e){return e==="ro"?kr.accessRead:e==="deny"?kr.accessDenied:kr.accessReadWrite}function X2(e){return e==="gateway"?kr.gatewayHelp:e==="account"?kr.accountHelp:e==="session"?kr.sessionHelp:kr.runHelp}const zw={deny:0,ro:1,rw:2},hp=["rw","ro","deny"];function Z2(e){if(e===null)return{allowed:[...hp],reasons:{}};const t=e==="deny"?kr.capRefused:kr.capReadOnly,n=hp.filter(a=>zw[a]<=zw[e]),r={};for(const a of hp)n.includes(a)||(r[a]=t);return{allowed:n,reasons:r}}function Q2(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 a=e!=="gateway"&&n.configured===!1,l=t.can_edit===!1,c=new Map(((r==null?void 0:r.folders)??[]).map(w=>[w.path,w.cap])),u=r,f=a?u.folders.map(w=>({path:w.path,mode:w.mode})):n.folders,h=a?u.posture:n.posture,m=a?u.default_mode??n.default_mode:n.default_mode,g=!a&&!l,y=f.map(w=>{const k=e==="gateway"?null:c.get(w.path)??null,{allowed:b,reasons:S}=Z2(k);return{path:w.path,mode:w.mode,cap:k,allowed:b,reasons:S,builtin:!1,editable:g}});if(e==="gateway")for(const w of n.builtin_refused??[])y.push({path:w,mode:"deny",cap:null,allowed:[],reasons:{},builtin:!0,editable:!1});return{level:e,posture:h,following:a,rows:y,everythingElse:h==="any_except_denied"?{mode:m,editable:g}:null,canAdd:g,gatewayLine:e==="gateway"?null:`${kr.gatewayPrefix} ${u.gateway_summary}`,summary:e==="gateway"?n.summary:u.summary,locked:l}}function eC(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function nh(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 tC(e,t,n,r){return nh(e,{...t,folders:t.folders.map(a=>a.path===n?{path:n,mode:r}:a)})}function nC(e,t,n){return nh(e,{...t,posture:n})}function sC(e,t,n){return nh(e,{...t,default_mode:n})}function rC(e,t,n,r){const a=String(n).trim();return nh(e,{...t,folders:[...t.folders,{path:a,mode:eC(e,t.posture)}]})}function iC(e,t,n){return nh(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function aC(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 oC(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function lC(e="me",t=Mf){return`${oC(t)}/workspace/effective/${encodeURIComponent(e)}`}const Bw=e=>e==="ro"||e==="rw"||e==="deny",cC=e=>e==="ro"||e==="rw",uC=e=>e==="allowed_only"||e==="any_except_denied",Uw="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function dC(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(Uw);if(!(uC(t.posture)&&(cC(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"&&Bw(r.mode)&&Bw(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${Uw}`);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 Lf(e,t="me",n=Mf){const r=lC(t,n);return async(a,l)=>dC(await e(r,{method:"POST",body:l?{workspace:a,session:l}:{workspace:a}}))}function x_(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 Ww(e){const t=x_(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${kr.notSaved}`}const fC=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function hC(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 Yb(e){Vu();const t=e.idPrefix||"af-workspace",[n,r]=_.useState(null),[a,l]=_.useState({}),[c,u]=_.useState(null),[f,h]=_.useState(""),[m,g]=_.useState(null),y=String(e.unavailableReason||"").trim(),w=e.level,k=e.level==="run"?hC(e.value,e.effective):e.state,b=e.level==="run"?e.effective:e.state,S=m&&m.base===b?m.value:k,N=S?Q2(w,S):null,R=L=>{if(e.level==="run"){const M=e,ee=L.configured===!1?null:{posture:L.posture,default_mode:L.default_mode,folders:L.folders};return Promise.resolve(M.onChange(ee))}return e.save(L)};async function $(L,M){if(n!==null||y)return!1;r(L),u(null),l(ee=>{const F={...ee};return delete F[L],F});try{const ee=await R(M);return fC(ee)&&g({base:b,value:ee}),u(L),!0}catch(ee){return l(F=>({...F,[L]:Ww(ee)})),!1}finally{r(null)}}const A=L=>a[L]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:a[L]}):c===L?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:pn.saved}):null,W=(L,M)=>s.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":L,"data-af-tip":M,tabIndex:M?0:void 0,children:Fw(L)}),z=(L,M,ee,F,U)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":L,"data-workspace":U,"data-access":M,children:ee.map(K=>{const O=!!K.reason||!!y;return s.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":M===K.value?"true":"false","aria-disabled":O?"true":void 0,"data-af-tip":K.reason||void 0,"data-action":`${U}-${K.value}`,onClick:()=>O||n!==null||K.value===M?void 0:F(K.value),children:K.text},K.value)})}),H=L=>{if(L.builtin)return W("deny",pn.builtinRefused);if(!L.editable||!S)return W(L.mode);const M=S.policy;return s.jsxs(s.Fragment,{children:[z(`${pn.accessLabel} ${L.path}`,L.mode,["rw","ro","deny"].map(ee=>({value:ee,text:Fw(ee),reason:L.reasons[ee]})),ee=>void $(L.path,tC(w,M,L.path,ee)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${pn.remove} ${L.path}`,"data-af-tip":`${pn.remove} ${L.path}`,"aria-disabled":y||n!==null?"true":void 0,onClick:()=>y||n!==null?void 0:void $(L.path,iC(w,M,L.path)),children:s.jsx(ze,{name:"x",size:16})})]})};async function G(L){if(!S||!N||!N.canAdd)return;const M=L.trim();M&&await $("add",rC(w,S.policy,M))&&h("")}async function re(){if(!e.choose||n!==null||y)return;let L;try{L=await e.choose()}catch(M){l(ee=>({...ee,add:Ww(M)}));return}L&&await G(L)}const te=N?N.rows.filter(L=>L.mode!=="deny"):[],Q=N?N.rows.filter(L=>L.mode==="deny"):[],D=L=>s.jsxs("li",{className:"af-workspace__row","data-workspace":L.builtin?"builtin":"row","data-path":L.path,"data-mode":L.mode,"data-cap":L.cap??void 0,children:[s.jsx("code",{className:"af-workspace__path",children:L.path}),s.jsx("span",{className:"af-workspace__controls",children:H(L)}),A(L.path)]},`${L.builtin?"builtin:":""}${L.path}`),T=w==="account"?pn.followGateway:pn.useDefault,E=w==="account"?pn.followGatewayHelp:pn.useDefaultHelp;return s.jsx(bf,{id:t,className:`af-workspace af-workspace--${w}${e.className?` ${e.className}`:""}`,title:w==="gateway"?pn.gatewayTitle:pn.title,help:X2(w),children:e.loadError?s.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!N||!S?s.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:pn.loading}):s.jsxs("div",{className:"af-workspace__body","data-level":w,"data-following":N.following?"true":"false",children:[N.gatewayLine?s.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:N.gatewayLine}):null,y?s.jsx("p",{className:"af-workspace__note",id:`${t}-blocked`,"data-workspace":"blocked",children:y}):null,w!=="gateway"?s.jsxs("div",{className:"af-workspace__follow","data-workspace":"follow",children:[s.jsx(Ni,{variant:"row",label:T,description:E,checked:N.following,busy:n==="follow",unavailableReason:y||(N.locked?pn.locked:null),reasonVisible:!1,describedBy:y?`${t}-blocked`:void 0,action:w==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:L=>void $("follow",aC(S,L))}),A("follow")]}):null,s.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":N.posture,children:[N.following||N.locked?s.jsx("span",{className:"af-workspace__badge",children:Y2(N.posture)}):z(pn.postureLabel,N.posture,[{value:"allowed_only",text:pn.postureAllowedOnly},{value:"any_except_denied",text:pn.postureAnyExceptDenied}],L=>void $("posture",nC(w,S.policy,L)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:J2(N.posture)}),A("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":pn.title,"data-workspace":"list",children:[te.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:pn.allowedTitle}):null,te.map(D),Q.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:pn.deniedTitle}):null,Q.map(D),N.everythingElse?s.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":N.everythingElse.mode,children:[s.jsx("span",{className:"af-workspace__name",children:pn.everythingElse}),s.jsx("span",{className:"af-workspace__controls",children:N.everythingElse.editable?z(`${pn.accessLabel} ${pn.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:pn.accessReadWrite},{value:"ro",text:pn.accessRead}],L=>void $("everything-else",sC(w,S.policy,L)),"workspace-default"):W(N.everythingElse.mode)}),A("everything-else")]}):null,N.canAdd?s.jsxs("li",{className:"af-workspace__add","data-workspace":"add",children:[s.jsx("input",{type:"text",className:"af-workspace__input","aria-label":pn.addPlaceholder,placeholder:pn.addPlaceholder,value:f,disabled:!!y||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:L=>h(L.target.value),onKeyDown:L=>{L.key==="Enter"?(L.preventDefault(),G(f)):L.key==="Escape"&&(L.preventDefault(),h(""),l(M=>{const ee={...M};return delete ee.add,ee}))}}),s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!y||!f.trim()||n!==null,onClick:()=>void G(f),children:pn.add}),e.choose?s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!y||n!==null,onClick:()=>void re(),children:pn.choose}):null,A("add")]}):null]}),N.posture==="allowed_only"&&!te.length?s.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:pn.emptyAllowed}):null,w==="session"||w==="run"?s.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:pn.privateNote}):null,s.jsx("p",{className:"af-workspace__effective","data-workspace":"effective",children:N.summary}),e.footer?s.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const mC=["provider","model","voice","profile","speed","quality_preset","instructions"];function _C(e){const t={};for(const n of mC){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function pC(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 gC=[{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 yC(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function wC(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const vC=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],qw=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):[],nf=e=>`${Math.round(e*100)} %`;function xC(e){var ut,De,Qe,at,Ke,ce;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,r=_.useRef(e.fetchCatalog);r.current=e.fetchCatalog;const a=_.useRef(e.fetchDefaults);a.current=e.fetchDefaults;const[l,c]=_.useState({}),[u,f]=_.useState({value:null,failed:!1}),h=e.defaults!==void 0?{value:e.defaults,failed:!1}:u,m=e.defaults!==void 0,[g,y]=_.useState(""),[w,k]=_.useState({devices:[],labelled:!0}),[b,S]=_.useState({devices:[],labelled:!0}),[N,R]=_.useState(""),[$,A]=_.useState({text:"",tone:"info"}),[W,z]=_.useState({phase:"idle",message:"",tone:"info"}),[H,G]=_.useState(0),re=e.outputSelectable??D1(),te=ab(),Q=e.value,D=e.nested?"flat":"card",T=oe=>e.onChange({...Q,...oe}),E=Q.reply_volume===void 0?1:Math.min(1,Math.max(0,Number(Q.reply_volume)||0)),L=Q.input_gain===void 0?1:Math.min(1.5,Math.max(.5,Number(Q.input_gain)||1));_.useEffect(()=>{if(n)return;let oe=!0;return r.current().then(Ae=>oe&&c(Ae||{})).catch(()=>oe&&c({})),m||a.current().then(Ae=>oe&&f({value:Ae||{},failed:!1})).catch(()=>oe&&f({value:null,failed:!0})),()=>{oe=!1}},[n,m]);const M=e.listDevices||j1,ee=()=>{re&&M("audiooutput").then(k).catch(()=>k({devices:[],labelled:!1})),M("audioinput").then(S).catch(()=>S({devices:[],labelled:!1}))};_.useEffect(()=>{n||ee()},[re,n]);const F=()=>{R(""),S1().then(ee).catch(oe=>R(sg(oe)))},U=()=>{A({text:"Playing a short chime…",tone:"info"}),A1({deviceId:re&&Q.output_device||"",volume:E}).then(()=>A({text:"Chime played. Heard nothing? Pick another output or raise the volume.",tone:"ok"})).catch(oe=>A({text:`The speaker test failed: ${String((oe==null?void 0:oe.message)||oe).replace(/\.$/,"")}.`,tone:"error"}))},K=()=>{z({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),E1({deviceId:Q.input_device||"",ms:3e3,gain:L,onLevel:G}).then(async({blob:oe,peak:Ae})=>{if(Ae<C1){z({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}z({phase:"playing",message:"Playing it back…",tone:"info"}),await $1(oe,{deviceId:re&&Q.output_device||"",volume:E}),z({phase:"idle",message:`The microphone works (peak level ${nf(Ae)}).`,tone:"ok"}),ee()}).catch(oe=>z({phase:"idle",message:sg(oe),tone:"error"}))},O=vw(h.value,"tts",h.failed),V=vw(h.value,"stt",h.failed),J=[(ut=h.value)==null?void 0:ut.tts,(De=h.value)==null?void 0:De.stt].map(oe=>oe&&!oe.configured?oe.note:"").filter(Boolean),le=[(Qe=h.value)==null?void 0:Qe.tts,(at=h.value)==null?void 0:at.stt].map(oe=>{var Ae;return oe&&oe.configured?String(((Ae=oe.hint)==null?void 0:Ae.sentence)||"").trim():""}).filter(Boolean),ie=!!((ce=(Ke=l.controls)==null?void 0:Ke.quality_preset)!=null&&ce.supported),_e=Q.output_device||"",pe=[{value:"",label:"System default"},...w.devices.map(oe=>({value:oe.id,label:oe.label})),..._e&&!w.devices.some(oe=>oe.id===_e)?[{value:_e,label:"Saved speaker (not connected)"}]:[]],ye=Q.input_device||"",Ne=[{value:"",label:"System default"},...b.devices.map(oe=>({value:oe.id,label:oe.label})),...ye&&!b.devices.some(oe=>oe.id===ye)?[{value:ye,label:"Saved microphone (not connected)"}]:[]],Be=!b.labelled||re&&!w.labelled,Ue=W.phase!=="idle";return s.jsxs("div",{className:`af-voice-section${e.className?` ${e.className}`:""}`,children:[e.unavailableReason?s.jsx("p",{className:"af-settings-group__help",role:"status",children:e.unavailableReason}):null,s.jsxs(bf,{variant:D,title:"Engines",help:"Which engines speak and listen.",children:[s.jsx(Dw,{label:"Text → speech",setting:"tts",defaultSummary:O,overrideSummary:yC(Q),overrideOwner:t,open:g==="tts",onToggle:()=>y(g==="tts"?"":"tts"),onReset:()=>T({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(U1,{value:Q,onChange:oe=>e.onChange({...Q,...oe}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default"})}),s.jsx(Dw,{label:"Speech → text",setting:"stt",defaultSummary:V,overrideSummary:wC(Q),overrideOwner:t,open:g==="stt",onToggle:()=>y(g==="stt"?"":"stt"),onReset:()=>T({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(Qx,{value:{provider:Q.stt_provider||"",model:Q.stt_model||""},onChange:oe=>T({stt_provider:oe.provider,stt_model:oe.model}),fetchProviders:async()=>{const oe=await r.current();return qw(oe.stt_providers).map(Ae=>({name:Ae}))},fetchModels:async oe=>{var he;const Ae=await r.current(oe);return qw(((he=Ae.stt_models_by_provider)==null?void 0:he[oe])||Ae.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}),h.failed?s.jsx("p",{className:"af-settings-group__help","data-voice-note":"defaults",role:"status",children:"The gateway's default voice routes could not be read. Requests still use them."}):null,J.map(oe=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:oe},oe)),le.map(oe=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:oe},oe))]}),s.jsxs(bf,{variant:D,title:"Output",children:[s.jsx(ic,{label:"Output device",setting:"output-device",help:re?void 0:"Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:n,onClick:U,children:"Test"}),children:s.jsx(ei,{ariaLabel:"Output device",placeholder:"System default",value:re?_e:"",options:pe,disabled:n||!re,searchable:!1,onOpen:ee,onChange:oe=>T({output_device:oe})})}),$.text?s.jsx("p",{className:`af-voice-note af-voice-note--${$.tone}`,role:"status","data-voice-note":"speaker",children:$.text}):null,s.jsxs(ic,{label:"Reply volume",setting:"reply-volume",htmlFor:"af-voice-volume",children:[s.jsx("input",{id:"af-voice-volume",className:"af-voice-range",type:"range",min:0,max:100,step:5,value:Math.round(E*100),disabled:n,"aria-valuetext":nf(E),onChange:oe=>T({reply_volume:Number(oe.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:nf(E)})]})]}),s.jsxs(bf,{variant:D,title:"Microphone",children:[s.jsx(ic,{label:"Input device",setting:"input-device",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:n||Ue,onClick:K,children:W.phase==="recording"?"Recording…":W.phase==="playing"?"Playing…":"Test"}),children:s.jsx(ei,{ariaLabel:"Input device",placeholder:"System default",value:ye,options:Ne,disabled:n,searchable:!1,onOpen:ee,onChange:oe=>T({input_device:oe})})}),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(H*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(H*100)}%`}})}),W.message?s.jsx("p",{className:`af-voice-note af-voice-note--${W.tone}`,role:"status","data-voice-note":"microphone",children:W.message}):null,Be&&!n?s.jsxs("p",{className:"af-voice-note","data-voice-note":"labels",children:["Device names appear once the microphone is allowed."," ",s.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"show-device-names",onClick:F,children:"Show names"})]}):null,N?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:N}):null,s.jsx(ic,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:s.jsx(ei,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:Q.stt_language||"",options:gC,disabled:n,searchable:!1,onChange:oe=>T({stt_language:oe})})}),te?s.jsxs(ic,{label:"Input level",setting:"input-gain",htmlFor:"af-voice-gain",help:"Raises a quiet microphone.",children:[s.jsx("input",{id:"af-voice-gain",className:"af-voice-range",type:"range",min:50,max:150,step:10,value:Math.round(L*100),disabled:n,"aria-valuetext":nf(L),onChange:oe=>T({input_gain:Number(oe.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:nf(L)})]}):null]}),s.jsxs(bf,{variant:D,title:"Replies",children:[s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:s.jsx(Ni,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:Q.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:oe=>T({read_aloud:oe})})}),s.jsx(ic,{label:"Voice latency",setting:"latency",help:ie?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:s.jsx(ei,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:ie&&Q.quality_preset||"",options:vC,disabled:n||!ie,searchable:!1,onChange:oe=>T({quality_preset:oe})})})]})]})}function b_(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 bC(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function kC(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),a=[t];return n&&a.push(n),r&&a.push(r),a.join(" · ")}function jC(e){return e.endsWith(`
|
|
66
|
-
`)?e:`${e}
|
|
67
|
-
`}function SC(e){return String(e||"").trimStart().startsWith("```")}function NC(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const a of e){const l=kC(a);r.push(`## ${l}`,"");const c=String(a.content||""),u=b_(c);u!==null&&!SC(c)?r.push("```json",bC(u).trimEnd(),"```",""):r.push(jC(c).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
|
|
68
|
-
`).trimEnd()}
|
|
69
|
-
`}async function yl(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 a=document.execCommand("copy")===!0;return document.body.removeChild(r),a}catch{return!1}}function CC(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime),a=new Blob([n],{type:r}),l=URL.createObjectURL(a),c=document.createElement("a");c.href=l,c.download=t,document.body.appendChild(c),c.click(),c.remove(),window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}const EC=3,$C=Number.MAX_SAFE_INTEGER;function Jb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xb(e){return Array.isArray(e)}function AC(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function $u({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function TC(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,a]=_.useState(!n||e.expansionMode==="unfolded");return _.useEffect(()=>{n&&a(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:()=>a(l=>!l),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?s.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):s.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>a(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),s.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):s.jsx($u,{kind:"string",children:t})}function MC(e,t,n){return e===null?s.jsx($u,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(TC,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx($u,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx($u,{kind:"boolean",children:e?"true":"false"}):s.jsx($u,{kind:"string",children:JSON.stringify(String(e))})}function RC(e){return Xb(e)?e.length===1?"1 item":`${e.length} items`:Jb(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Zb(e){const{label:t,value:n,depth:r,collapseAfterDepth:a,expansionMode:l,expansionVersion:c,trailingComma:u}=e,f=r*14,h=Jb(n),m=Xb(n),g=h||m,y=r<a,[w,k]=_.useState(y);_.useEffect(()=>{k(y)},[y,c]);const b=t?s.jsxs(s.Fragment,{children:[s.jsx($u,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,MC(n,l,c),u?",":""]});const S=m?"[":"{",N=m?"]":"}",R=RC(n),$=w?`${S}`:`${S}…${N}${R?` (${R})`:""}`,A=m?n.map((W,z)=>({key:String(z),label:void 0,value:W})):Object.entries(n).map(([W,z])=>({key:W,label:W,value:z}));return s.jsxs("details",{className:"pc-json-viewer__details",open:w,onToggle:W=>k(W.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[b,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:w?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:$}),!w&&u?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),w?s.jsx("div",{className:"pc-json-viewer__children",children:A.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),u?",":""]}):s.jsxs(s.Fragment,{children:[A.map((W,z)=>{const H=z===A.length-1;return s.jsx(Zb,{label:W.label,value:W.value,depth:r+1,collapseAfterDepth:a,expansionMode:l,expansionVersion:c,trailingComma:!H},`${r}:${t||"root"}:${W.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),u?",":""]})]})}):null]})}function LC(e){const t=e.trim();if(!t)return e;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}function Is(e){const{value:t,className:n,showCopy:r=!0}=e,[a,l]=_.useState({mode:"folded",version:0}),[c,u]=_.useState("idle"),f=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):EC,h=a.mode==="unfolded"?$C:f,m=_.useMemo(()=>typeof t=="string"?LC(t):t,[t]),g=_.useMemo(()=>AC(t),[t]),y=["pc-json-viewer",n].filter(Boolean).join(" ");_.useEffect(()=>{l(k=>({mode:"folded",version:k.version+1}))},[m]);const w=()=>{l(k=>({mode:k.mode==="unfolded"?"folded":"unfolded",version:k.version+1}))};return s.jsxs("div",{className:y,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:w,"aria-expanded":a.mode==="unfolded",children:a.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void yl(g).then(k=>{u(k?"copied":"failed"),window.setTimeout(()=>u("idle"),2e3)}),children:c==="copied"?"Copied":c==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),s.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:s.jsx(Zb,{value:m,depth:0,collapseAfterDepth:h,expansionMode:a.mode,expansionVersion:a.version,trailingComma:!1})})]})}function IC({code:e,lang:t}){const[n,r]=_.useState("idle"),a=_.useRef(null);_.useEffect(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);const l=Vb(e,cy(t));return s.jsxs("div",{className:"pc-md_codeblock",children:[s.jsx("button",{type:"button",className:`pc-md_copy${n!=="idle"?` pc-md_copy--${n}`:""}`,"aria-label":"Copy code",title:n==="idle"?"Copy":n==="copied"?"Copied":"Copy failed",onClick:async()=>{const c=await yl(e);r(c?"copied":"failed"),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>r("idle"),900)},children:s.jsx(ze,{name:n==="copied"?"check":"copy",size:14})}),s.jsx("pre",{className:"pc-md_pre",children:s.jsx("code",{className:t?`language-${t}`:void 0,children:l.map((c,u)=>c.kind==="plain"?s.jsx(xe.Fragment,{children:c.text},u):s.jsx("span",{className:`af-code__${c.kind}`,children:c.text},u))})})]})}function sf(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],a=n.toLowerCase();let l=0;for(;l<n.length;){let c=-1,u="";for(let m=0;m<t.needlesLower.length;m++){const g=t.needlesLower[m];if(!g)continue;const y=a.indexOf(g,l);if(y===-1)continue;const w=t.needles[m]||"";w&&(c===-1||y<c||y===c&&w.length>u.length)&&(c=y,u=w)}if(c===-1||!u){r.push(n.slice(l));break}c>l&&r.push(n.slice(l,c));const f=t.hits===0&&t.id?t.id:void 0,h=n.slice(c,c+u.length);r.push(s.jsx("span",{id:f,className:t.className,children:h},`hl:${t.hits}`)),t.hits+=1,l=c+u.length}return r}function Qb(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const _g="http://same-origin.invalid/";function OC(e){try{const t=new URL(e,_g);return t.protocol==="http:"&&t.origin===new URL(_g).origin}catch{return!1}}function e0(e){const t=String(e||"").trim();return Qb(t)??(t&&OC(t)?t:void 0)}let fc=null;function PC(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??_g;let a,l;try{a=new URL(r).origin,l=new URL(t,r)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===a}function t0(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 Hw(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function yo(e,t){const n=[],r=String(e??"");let a=0,l="";const c=()=>{if(l){for(const u of sf(l,t))n.push(u);l=""}};for(;a<r.length;){const u=r[a];if(u==="!"&&r[a+1]==="["){const f=r.indexOf("]",a+2);if(f!==-1&&r[f+1]==="("){const h=r.indexOf(")",f+2);if(h!==-1){const m=r.slice(a+2,f),g=e0(r.slice(f+2,h));if(g&&fc&&!fc(g)){c(),n.push(t0(`img:${a}`,g,m)),a=h+1;continue}if(g){c(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:g,alt:m,loading:"lazy"}),m?s.jsx("span",{className:"pc-md_img_caption",children:t?sf(m,t):m}):null]},`img:${a}`)),a=h+1;continue}}}}if(u==="["){const f=r.indexOf("]",a+1);if(f!==-1&&r[f+1]==="("){const h=r.indexOf(")",f+2);if(h!==-1){const m=r.slice(a+1,f),g=Qb(r.slice(f+2,h));if(g){c(),n.push(s.jsx("a",{className:"pc-md_link",href:g,target:g.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:yo(m,t)},`link:${a}`)),a=h+1;continue}}}}if(u==="`"){const f=r.indexOf("`",a+1);if(f!==-1){c();const h=r.slice(a+1,f);n.push(s.jsx("code",{children:t?sf(h,t):h},`code:${a}`)),a=f+1;continue}}if(u==="_"&&!Hw(r[a-1])){const f=r[a+1]==="_"?"__":"_",h=f.length;if(r[a+h]&&!/\s/.test(r[a+h])&&r[a+h]!=="_"){let m=r.indexOf(f,a+h);for(;m!==-1&&(/\s/.test(r[m-1]||" ")||Hw(r[m+h])||h===1&&r[m+1]==="_");)m=r.indexOf(f,m+1);if(m!==-1&&m>a+h){c();const g=r.slice(a+h,m),y=yo(g,t);n.push(h===2?s.jsx("strong",{children:y},`ubold:${a}`):s.jsx("em",{children:y},`uem:${a}`)),a=m+h;continue}}}if(u==="*"&&r[a+1]==="*"){const f=r.indexOf("**",a+2);if(f!==-1){c();const h=r.slice(a+2,f);n.push(s.jsx("strong",{children:t?sf(h,t):h},`bold:${a}`)),a=f+2;continue}}if(u==="*"&&r[a+1]!=="*"){const f=r.indexOf("*",a+1);if(f!==-1){c();const h=r.slice(a+1,f);n.push(s.jsx("em",{children:t?sf(h,t):h},`em:${a}`)),a=f+1;continue}}l+=u,a+=1}return c(),n}function DC(e){return String(e??"").replace(/\r\n/g,`
|
|
70
|
-
`).replace(/\r/g,`
|
|
71
|
-
`).split(`
|
|
72
|
-
`)}function Pm(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 FC(e){const t=[];for(const a of e){const l=Pm(a);l?t.push(l):t.length>0&&a.trim()&&(t[t.length-1].content+=` ${a.trim()}`)}const n=[],r=[];for(const a of t){for(;r.length>0&&a.indent<r[r.length-1].indent;)r.pop();let l=r.length>0?r[r.length-1]:null;if(l&&a.indent>l.indent){const c=l.node.items,u=c[c.length-1];if(u){const f={ordered:a.ordered,start:a.start,items:[]};u.children.push(f),r.push({indent:a.indent,node:f}),l=r[r.length-1]}}else if(l&&l.node.ordered!==a.ordered){r.pop();const c=r.length>0?r[r.length-1]:null,u={ordered:a.ordered,start:a.start,items:[]};if(c){const f=c.node.items,h=f[f.length-1];h?h.children.push(u):c.node.items.push({content:"",children:[u]})}else n.push(u);r.push({indent:a.indent,node:u}),l=r[r.length-1]}if(!l){const c={ordered:a.ordered,start:a.start,items:[]};n.push(c),r.push({indent:a.indent,node:c}),l=r[r.length-1]}l.node.items.push({content:a.content,children:[]})}return n}function n0(e,t,n){const r=e.items.map((a,l)=>s.jsxs("li",{children:[yo(a.content,t),a.children.map((c,u)=>n0(c,t,`${n}:${l}:${u}`))]},`${n}:li:${l}`));return e.ordered?s.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:r},n):s.jsx("ul",{className:"pc-md_ul",children:r},n)}function zC(e,t,n){return FC(e).map((r,a)=>n0(r,t,`${n}:${a}`))}function Vw(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 Gw(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 Kw=/^(#{1,5})\s+(.*)$/;function Yw(e){return e.trim().startsWith("```")}function Jw(e){return e.trimStart().startsWith(">")}function Si(e){const t=fc;fc=e.images==="link"?e.inlineImage||PC:null;try{return BC(e)}finally{fc=t}}function BC({text:e,className:t,highlight:n,highlights:r,highlightClassName:a,highlightId:l}){const c=DC(e),u=[],f=[];Array.isArray(r)&&f.push(...r),typeof n=="string"&&n.trim()&&f.push(n);const h=Array.from(new Set(f.map(w=>String(w??"").trim()).filter(Boolean))).filter(w=>w.length>=4),m=h.length?{needles:h,needlesLower:h.map(w=>w.toLowerCase()),className:a||"pc-md_hl",id:l,hits:0}:null;let g=0;for(;g<c.length;){const w=String(c[g]??"");if(!w.trim()){g+=1;continue}const k=w.trim();if(/^([-_*])(\s*\1){2,}$/.test(k)){u.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${g}`)),g+=1;continue}const b=w.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){const R=e0(b[2]||"");if(R&&fc&&!fc(R)){u.push(s.jsx("p",{className:"pc-md_p",children:t0(`img:${g}`,R,b[1]||"")},`p:${g}`)),g+=1;continue}if(R){const $=b[1]||"";u.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:R,alt:$,loading:"lazy"}),$?s.jsx("figcaption",{children:yo($,m)}):null]},`figure:${g}`)),g+=1;continue}}if(Yw(w)){const $=w.trim().replace(/```/g,"").trim(),A=[];for(g+=1;g<c.length&&!String(c[g]??"").trim().startsWith("```");)A.push(String(c[g]??"")),g+=1;g<c.length&&(g+=1);const W=A.join(`
|
|
73
|
-
`);u.push(s.jsx(IC,{code:W,lang:$},`pre:${g}`));continue}const S=w.match(Kw);if(S){const R=S[1].length,$=S[2]||"",A=yo($,m);R===1?u.push(s.jsx("h1",{children:A},`h1:${g}`)):R===2?u.push(s.jsx("h2",{children:A},`h2:${g}`)):R===3?u.push(s.jsx("h3",{children:A},`h3:${g}`)):R===4?u.push(s.jsx("h4",{children:A},`h4:${g}`)):u.push(s.jsx("h5",{children:A},`h5:${g}`)),g+=1;continue}if(Jw(w)){const R=[];for(;g<c.length&&String(c[g]??"").trimStart().startsWith(">");){const A=String(c[g]??"").trimStart();R.push(A.replace(/^>\s?/,"")),g+=1}u.push(s.jsx("blockquote",{className:"pc-md_quote",children:R.map(($,A)=>s.jsxs(xe.Fragment,{children:[yo($,m),A<R.length-1?s.jsx("br",{}):null]},`q:${g}:${A}`))},`quote:${g}`));continue}if(w.includes("|")&&g+1<c.length&&Gw(String(c[g+1]??""))){const R=Vw(w),$=Math.max(1,R.length),A=[];for(g+=2;g<c.length;){const W=String(c[g]??"");if(!W.trim()||!W.includes("|"))break;const z=Vw(W),H=[];for(let G=0;G<$;G++)H.push(z[G]??"");A.push(H),g+=1}u.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:R.slice(0,$).map((W,z)=>s.jsx("th",{children:yo(W,m)},`th:${g}:${z}`))})}),s.jsx("tbody",{children:A.map((W,z)=>s.jsx("tr",{children:W.map((H,G)=>s.jsx("td",{children:yo(H,m)},`td:${g}:${z}:${G}`))},`tr:${g}:${z}`))})]})},`table:${g}`));continue}if(Pm(w)){const R=[];for(;g<c.length;){const $=String(c[g]??"");if(!$.trim()||$.trimStart().startsWith("```"))break;if(Pm($)||/^\s{2,}\S/.test($)){R.push($),g+=1;continue}break}u.push(s.jsx(xe.Fragment,{children:zC(R,m,`list:${g}`)},`list:${g}`));continue}const N=[];for(;g<c.length&&String(c[g]??"").trim()&&!(N.length>0&&Pm(String(c[g]??"")));){const R=String(c[g]??"");if(N.length>0&&(Kw.test(R)||Yw(R)||Jw(R))||N.length>0&&R.includes("|")&&g+1<c.length&&Gw(String(c[g+1]??"")))break;N.push(R),g+=1}u.push(s.jsx("p",{className:"pc-md_p",children:N.map((R,$)=>s.jsxs(xe.Fragment,{children:[yo(R,m),$<N.length-1?s.jsx("br",{}):null]},`pl:${g}:${$}`))},`p:${g}`))}const y=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:y,children:u})}function s0(e){const t=String(e.text??""),n=_.useMemo(()=>b_(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(Is,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Si,{text:t,images:e.images,inlineImage:e.inlineImage})})}function kf(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function dl(e){return typeof e=="string"?e.trim():""}function UC(e){var a;const t=kf(e);if(!t)return null;const n=kf(t.sandbox);if(n&&dl(n.kind))return n;const r=kf((a=kf(t.output))==null?void 0:a.sandbox);return r&&dl(r.kind)?r:null}function pg(e){const t=UC(e);if(!t)return null;const n=dl(t.kind),r=dl(t.label)||n,a=Number.isFinite(Number(t.builtin_refused))?Math.max(0,Math.trunc(Number(t.builtin_refused))):0;if(n==="none")return{state:"refused",kind:n,label:r,line:`Sandbox: ${r} — refused`,rows:[],builtinRefused:0};const l=[],c=dl(t.private_workspace);c&&l.push({path:c,mode:"Read & write",private:!0});for(const f of Array.isArray(t.allowed)?t.allowed:[]){const h=kf(f),m=dl(h==null?void 0:h.path);m&&l.push({path:m,mode:dl(h==null?void 0:h.mode)==="ro"?"Read-only":"Read & write"})}for(const f of Array.isArray(t.refused)?t.refused:[]){const h=dl(f);h&&l.push({path:h,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:r,line:`Sandbox: ${r}`,rows:[],builtinRefused:0};const u=l.length;return{state:"sandboxed",kind:n,label:r,line:`Sandbox: ${r} · ${u} ${u===1?"workspace":"workspaces"} enforced`,rows:l,builtinRefused:a}}function r0({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 i0(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function WC(e){const t=i0(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),a=["command","query","url","file_path","path","pattern","name"].map(l=>n.find(([c])=>c===l)).find(Boolean)||n[0];return a?{label:a[0].replace(/_/g," "),value:typeof a[1]=="string"?a[1]:JSON.stringify(a[1])??""}:{label:"",value:""}}function a0({tool:e,showCopy:t=!0}){const[n,r]=_.useState(!1),a=i0(e.arguments),l=WC(e.arguments),c=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,u=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},h=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,m=a&&typeof a=="object"&&!Array.isArray(a)?Object.entries(a):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(ze,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),s.jsx("strong",{children:e.name}),s.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:l.label}),c]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),Number.isFinite(h)&&h>=0?s.jsxs("span",{className:"pc-tool-activity__duration",children:[(h/1e3).toFixed(1),"s"]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(ze,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:u}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[s.jsx(r0,{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 yl(JSON.stringify(e,null,2))),children:[s.jsx(ze,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),m?s.jsx("dl",{className:"pc-tool-activity__parameters",children:m.map(([g,y])=>s.jsxs(xe.Fragment,{children:[s.jsx("dt",{children:g}),s.jsx("dd",{children:y&&typeof y=="object"?s.jsx(Is,{value:y}):s.jsx("code",{children:typeof y=="string"?y:JSON.stringify(y)})})]},g))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(Is,{value:a}),e.output!==void 0?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Result"}),typeof e.output=="string"?s.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):s.jsx("div",{className:"pc-tool-activity__output",children:s.jsx(Is,{value:e.output})})]}):null]})]})}function o0({tools:e,showCopy:t}){const n=r=>e.filter(a=>a.status===r).length;return s.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[s.jsxs("div",{className:"pc-tool-group__heading",children:[s.jsx(ze,{name:"terminal",size:14}),s.jsx("strong",{children:"Tools"}),s.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),s.jsx("div",{}),n("running")?s.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?s.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?s.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?s.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(r=>s.jsx(a0,{tool:r,showCopy:t},r.id))]})}const Hs="not reported",br=e=>e===void 0?Hs:Math.round(e).toLocaleString(),Ur=e=>{if(e===void 0)return Hs;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.round(e/1e3);return`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`},l0=e=>e===void 0?Hs:`${Math.round(e).toLocaleString()} tok/s`,qC=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",hc=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,HC=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function VC(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 Xm(e){const t=[],n=(e.models||[]).map(HC),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 GC(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:br(e.inputTokens)},{label:"Output",value:br(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:br(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:br(e.totalTokens)}),n.push({heading:`Usage · ${hc(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const l=e.cachedTokens||0,c=e.fedTokens||0,u=[{label:"Reused from cache",value:`${br(l)}${l+c?` (${qC(l,l+c)})`:""}`},{label:"Newly processed",value:br(e.fedTokens)},{label:"Outcome",value:VC(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Hs},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Hs}];e.measuredCacheCalls!==e.llmCalls&&u.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:u})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Hs}]});const a=t.filter(l=>l.inputTokens!==void 0);return a.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${br(a[0].inputTokens)} tokens`}]}):a.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${br(a[0].inputTokens)} → ${br(a[a.length-1].inputTokens)} tokens`}],note:"Each call re-sends the conversation, so the input total counts the context once per call."}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Input","Cached","New","Output","Cache"],rows:t.map((l,c)=>[String(c+1),br(l.inputTokens),l.cachedTokens===void 0?"—":br(l.cachedTokens),l.fedTokens===void 0?"—":br(l.fedTokens),br(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Hs:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:Xm(e)}}function pm(e,t,n,r){if(e===void 0)return Hs;const a=[Ur(e)];return t!==void 0&&a.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${l0(n)}`:""}`),a.join(" · ")}function KC(e){var h,m,g;const t=e.modelCalls||[],n=[],r=e.durationMs,a=[{label:"Wall clock",value:Ur(r)}];if(a.push({label:"Model",value:e.genTimeMs===void 0?Hs:`${Ur(e.genTimeMs)} · ${hc(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),a.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Ur(e.toolTimeMs)} · ${hc(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Hs:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const y=r-e.genTimeMs-(e.toolTimeMs||0);a.push({label:"Orchestration",value:y>=0?Ur(y):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:a});const l=[],c=e.ttftCalls||0,u=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?l.push({label:c&&c===u?"Prefill (TTFT)":"Prefill",value:pm(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:c===u?"measured time to first token":c?`TTFT measured on ${c} of ${u}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?l.push({label:"Prefill",value:pm(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Ur(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${l0(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Hs}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&l.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),l.push({label:"Generation",value:e.generationPhaseMs!==void 0?pm(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):pm(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const y=(f.draftKinds||[]).map(k=>k.toUpperCase()).join(", "),w=[{label:"Mode",value:`${f.used?"on":"off"}${y?` · ${y}`:""}${(h=f.modes)!=null&&h.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?Hs:`${Math.round(f.acceptanceRate*100)}% · ${br(f.acceptedTokens)} of ${br(f.draftedTokens)} drafted`}];((m=f.draftLengths)!=null&&m.length||f.rounds!==void 0)&&w.push({label:"Draft length",value:`${(g=f.draftLengths)!=null&&g.length?`${f.draftLengths.join("/")} tok/round`:Hs}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:w})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${Ur(e.toolTimeMs)} · ${hc(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Ur(e.slowestToolBatch.ms)} · ${c0(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?"—":`${Ur(y.promptMs)}${y.promptSource==="rate"?"*":""}`,y.promptNewTokensPerSecond===void 0?"—":Math.round(y.promptNewTokensPerSecond).toLocaleString(),y.generationMs===void 0?"—":Ur(y.generationMs),y.generationTokensPerSecond===void 0?"—":Math.round(y.generationTokensPerSecond).toLocaleString(),y.cacheOutcome||"—"])},note:t.some(y=>y.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?Hs:`${Ur(r)} wall clock`,sections:n,footer:Xm(e)}}function c0(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${hc(e.calls,"call")} (${e.tools.join(", ")})`}function YC(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:Xm(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 a=Object.entries(e.toolBreakdown||{}).sort((u,f)=>f[1].calls-u[1].calls||u[0].localeCompare(f[0]));a.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:a.map(([u,f])=>[u,f.calls.toLocaleString(),f.failed.toLocaleString(),f.ms!==void 0?`${Ur(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Hs])},note:a.some(([,u])=>u.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=a.filter(([,u])=>u.errors&&Object.keys(u.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([u,f])=>({label:u,value:Object.entries(f.errors).sort((h,m)=>m[1]-h[1]).map(([h,m])=>m>1?`${h} ×${m}`:h).join(" · ")}))});const c=[{label:"Tool time",value:e.toolTimeMs===void 0?Hs:`${Ur(e.toolTimeMs)} · ${hc(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&c.push({label:"Slowest batch",value:`${Ur(e.slowestToolBatch.ms)} · ${c0(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:c,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${hc(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:Xm(e)}}function mp(e,t){return e==="tokens"?GC(t):e==="time"?KC(t):YC(t)}function JC(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(a=>s.jsxs(xe.Fragment,{children:[s.jsx("dt",{children:a.label}),s.jsxs("dd",{children:[s.jsx("span",{className:a.value===Hs?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:a.value}),a.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:a.hint}):null]})]},a.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(a=>s.jsx("th",{scope:"col",children:a},a))})}),s.jsx("tbody",{children:n.table.rows.map((a,l)=>s.jsx("tr",{children:a.map((c,u)=>s.jsx("td",{children:c},u))},l))})]}):null,n.note?s.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),s.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>s.jsx("div",{children:n},n))})]})}const mo=8;function XC(e){const[t,n]=_.useState(!!e.defaultOpen),[r,a]=_.useState(null),l=_.useRef(null),c=_.useRef(null),u=_.useRef(null),f=`pc-stat-${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,h=_.useCallback(()=>{u.current!==null&&window.clearTimeout(u.current),u.current=null},[]),m=_.useCallback(()=>{h(),n(!0)},[h]),g=_.useCallback(()=>{h(),u.current=window.setTimeout(()=>n(!1),120)},[h]);_.useEffect(()=>h,[h]),_.useLayoutEffect(()=>{if(!t){a(null);return}const b=()=>{const S=l.current,N=c.current;if(!S||!N)return;const R=S.getBoundingClientRect(),$=N.offsetWidth,A=N.offsetHeight,W=window.innerWidth,z=window.innerHeight,H=R.top-mo-A,G=R.bottom+mo,re=H>=mo?H:G+A<=z-mo?G:Math.max(mo,z-mo-A),te=Math.min(Math.max(mo,R.left),Math.max(mo,W-mo-$));a({top:re,left:te})};return b(),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[t]),_.useEffect(()=>{if(!t)return;const b=S=>{S.key==="Escape"&&n(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const y=typeof e.onClick=="function",w=y?"button":"span",k=t?s.jsx(JC,{detail:e.detail,id:f,panelRef:c,onMouseEnter:h,onMouseLeave:g,style:{position:"fixed",top:(r==null?void 0:r.top)??0,left:(r==null?void 0:r.left)??0,visibility:r?"visible":"hidden"}}):null;return s.jsxs(s.Fragment,{children:[s.jsxs(w,{ref:l,...y?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",y?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?f:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:m,onMouseLeave:g,onFocus:m,onBlur:()=>n(!1),onKeyDown:b=>{b.key==="Escape"&&n(!1)},onClick:y?()=>{var b;return(b=e.onClick)==null?void 0:b.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),k&&typeof document<"u"?Xx.createPortal(k,document.body):k]})}function ZC(e){const t=e.totalTokens!==void 0?mp("tokens",e):null,n=mp("tools",e),r=e.durationMs!==void 0?mp("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 QC(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 eE=new Set(["blob:","data:","http:","https:"]);function Xw(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return eE.has(new URL(t,n).protocol)?t:void 0}catch{return}}function tE({item:e}){const[t,n]=_.useState(!1),r=Xw(e.src),a=e.href?Xw(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!r&&!a)return null;const c=l==="image"?"Image":l==="video"?"Video":"Audio",u=String(e.label||"").trim()||`Generated ${c.toLowerCase()}`,f=()=>n(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[r&&l==="image"?s.jsx("img",{className:"pc-chat-media__image",src:r,alt:u,loading:"lazy",onError:f}):null,r&&l==="video"?s.jsx("video",{className:"pc-chat-media__video",src:r,controls:!0,playsInline:!0,preload:"metadata","aria-label":u,onError:f}):null,r&&l==="audio"?s.jsx(v_,{className:"pc-chat-media__audio",src:r,name:u}):null,t?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[c," could not be decoded by this browser",a?"; open the raw file with the link.":"."]}):null,a?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",href:a,target:"_blank",rel:"noopener noreferrer",children:u})}):null]})}function dy(e){var W;const t=e.message,n=_.useMemo(()=>QC(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),a=_.useMemo(()=>{if(!r)return"";const z=new Date(r);return Number.isFinite(z.getTime())?z.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[l,c]=_.useState("idle"),u=_.useRef(null);_.useEffect(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]);const f=t.live,h=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),m=h&&((W=e.getSpeakState)==null?void 0:W.call(e,t))||"idle",g=m==="loading"?"loader":m==="playing"?"pause":"speaker",y=m==="loading"?"Generating audio…":m==="playing"?"Pause":m==="paused"?"Resume":"Speak (TTS)",w=e.showCopy!==!1,k=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],b=t.statistics,S=t.stats,N=_.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(S)?S:b?ZC(b):[],[e.stats,S,b]),R=Array.isArray(t.media)?t.media:[],$=String(f?f.reasoning||"":t.reasoning||""),A=!!String(t.content||"").trim();return t.toolActivity?s.jsx(a0,{tool:t.toolActivity,showCopy:e.showCopy}):s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"aria-busy":!0}:{},children:[s.jsxs("div",{className:"pc-chat-header",children:[s.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:s.jsx(ze,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),f?s.jsxs("span",{className:"pc-chat-live-indicator",title:f.label?`Pending: ${f.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),f.label||"streaming"]}):null,f!=null&&f.caption?s.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),a?s.jsx("span",{className:"pc-chat-time",children:a}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[h?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":y,title:y,onClick:()=>{var z;return(z=e.onSpeakToggle)==null?void 0:z.call(e,t)},children:s.jsx(ze,{name:g,size:22,className:m==="loading"?"pc-chat-speak-spinner":void 0})}):null,w?s.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const z=await yl(String(t.content||""));c(z?"copied":"failed"),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>c("idle"),900)},children:s.jsx(ze,{name:"copy",size:22})}):null]})]}),$.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:$})]}):null,A||!f&&!R.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(s0,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,R.length?s.jsx("div",{className:"pc-chat-media",children:R.slice(0,24).map((z,H)=>s.jsx(tE,{item:z},z.id||`${z.kind}:${z.src}:${H}`))}):null,k.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:k.slice(0,24).map((z,H)=>{const G=String(z.label||"").trim()||"attachment",re=String(z.target||"").trim(),te=String(z.title||"").trim(),Q=!!z.disabled||typeof z.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:te||G,onClick:Q?void 0:z.onClick,disabled:Q,children:[s.jsx(ze,{name:"paperclip",size:14}),re?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${re}`,children:re}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:G})]},z.id||`${G}:${H}`)})}):null,N.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:N.slice(0,12).map((z,H)=>{const G=String(z.label||"").trim();if(!G)return null;if(z.detail)return s.jsx(XC,{label:G,detail:z.detail,icon:z.icon,onClick:z.onClick},z.id||`${G}:${H}`);const re=String(z.title||"").trim(),te=typeof z.onClick=="function",Q=te?"button":"span";return s.jsxs(Q,{...te?{type:"button"}:{},className:["pc-chat-stat",te?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:re||void 0,onClick:te?()=>{var D;return(D=z.onClick)==null?void 0:D.call(z)}:void 0,children:[z.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:z.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:G})]},z.id||`${G}:${H}`)})}):null]})}function nE(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function fy(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=_.useRef(null),a=_.useRef(null),[l,c]=_.useState(!0),u=_.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=_.useMemo(()=>{var g;const m=[];for(const y of u){const w=m[m.length-1];y.toolActivity&&((g=w==null?void 0:w[0])!=null&&g.toolActivity)&&w[0].runId===y.runId?w.push(y):m.push([y])}return m},[u]);_.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const g=()=>{c(nE(m,t))};return m.addEventListener("scroll",g,{passive:!0}),g(),()=>m.removeEventListener("scroll",g)},[n,t]);const h=_.useMemo(()=>{let m=0;for(const g of u)if(m+=String(g.content??"").length,Array.isArray(g.media))for(const y of g.media)m+=String((y==null?void 0:y.src)??"").length+1;return`${u.length}:${m}:${String(e.afterKey??"")}`},[u,e.afterKey]);return _.useEffect(()=>{if(!n||!l)return;const m=r.current;m&&(m.scrollTop=m.scrollHeight)},[n,l,h]),_.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const g=()=>{l&&(m.scrollTop=m.scrollHeight)};return m.addEventListener("load",g,!0),m.addEventListener("loadedmetadata",g,!0),()=>{m.removeEventListener("load",g,!0),m.removeEventListener("loadedmetadata",g,!0)}},[n,l]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[u.length?null:e.empty||null,f.map((m,g)=>{var k;const y=m[0],w=String(y.id||"")||String(y.ts||"")+":"+String(y.role||"")+":"+g;return y.toolActivity?s.jsx(o0,{tools:m.map(b=>b.toolActivity),showCopy:(k=e.messageProps)==null?void 0:k.showCopy},w):s.jsx(dy,{message:y,...e.messageProps||{}},w)}),e.after,s.jsx("div",{ref:a})]})}const hy=xe.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,a=!!t.disabled,l=!!t.busy,c=!a&&!l&&!!String(t.value||"").trim();return s.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,s.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:u=>t.onChange(u.target.value),rows:r,style:{"--pc-composer-rows":String(r)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:a,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:u=>{u.key!=="Enter"||u.shiftKey||u.nativeEvent.isComposing||u.keyCode===229||(u.preventDefault(),c&&t.onSubmit())}}),s.jsxs("div",{className:"pc-composer__row",children:[s.jsx("div",{className:"pc-composer__actions",children:t.actions}),s.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!c,onClick:()=>t.onSubmit(),children:l?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function jf(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Zw(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let a=0;a<t.length;a+=1)((r=t[a])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function Qw(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function my(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let l=0;l<r.length;l+=1){const c=r[l];if(!c||c.kind!=="file")continue;const u=typeof c.webkitGetAsEntry=="function"?c.webkitGetAsEntry():null,f=typeof c.getAsFile=="function"?c.getAsFile():null;u!=null&&u.isDirectory?n.push(u.name||(f==null?void 0:f.name)||"folder"):f&&t.push(f)}return{files:t,folders:n}}const a=e==null?void 0:e.files;if(a)for(let l=0;l<a.length;l+=1)a[l]&&t.push(a[l]);return{files:t,folders:n}}function u0(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 sE={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function rf(e){return String(e).padStart(2,"0")}function rE(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 a=sE[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",l=`${n.getFullYear()}-${rf(n.getMonth()+1)}-${rf(n.getDate())} at ${rf(n.getHours())}.${rf(n.getMinutes())}.${rf(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${l}.${a}`}function d0(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}=my(e);return r.map(a=>{const l=rE(a.name,a.type,t);return l===a.name?a:new File([a],l,{type:a.type,lastModified:a.lastModified})})}class iE{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 Sf="llm.delta",Su="llm.delta_end";function aE(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nc(e){return typeof e=="string"&&e.trim()!==""}function oE(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function f0(e){return"reason"in e}function h0(e,t){const n=aE(e),r=n==null?void 0:n.kind,a=t||(typeof r=="string"&&r?r:n&&"reason"in n?Su:Sf),l=f=>{throw new Error(`Malformed ${a} event from the gateway: ${f}`)};if(t!==void 0&&t!==Sf&&t!==Su&&l(`unknown event name ${JSON.stringify(t)}`),!n)return l("the payload is not an object");r!==void 0&&r!==Sf&&r!==Su&&l(`unknown kind ${JSON.stringify(r)}`),r!==void 0&&t!==void 0&&r!==t&&l(`kind ${JSON.stringify(r)} does not match the event name`),nc(n.run_id)||l("run_id is missing"),nc(n.call_id)||l("call_id is missing"),oE(n.seq)||l("seq is not a non-negative integer");const c=t||r?(t||r)===Su:"reason"in n;n.root_run_id!==void 0&&!nc(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!nc(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const u={run_id:n.run_id,...nc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...nc(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return c?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||l(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&l("detail is not a string"),{kind:Su,...u,reason:n.reason,...nc(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&l("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&l(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&l("snapshot is not a boolean"),{kind:Sf,...u,text:n.text,channel:n.channel,snapshot:n.snapshot})}function lE(e,t){if(e!==Sf&&e!==Su)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 h0(n,e)}const cE={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 uE(e){return`This reply is not streamed: ${e?cE[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const ev=1024*1024,dE="1 MiB",fE=25*1024*1024,m0=(e,t)=>`${st(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function hE(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 mE(e,t,n){var h;const r=new TextDecoder;let a="",l=0;const c=(h=e.body)==null?void 0:h.getReader();if(c){for(;l<t;){const{done:m,value:g}=await c.read();if(m)break;const y=g.subarray(0,t-l);l+=y.length,a+=r.decode(y,{stream:!0})}await c.cancel().catch(()=>{})}else a=(await e.text()).slice(0,t),l=a.length;const u=hE(e)??n,f=u!==void 0?u>l:l>=t;return{text:a,received:l,total:u,partial:f}}function _E(e){return`Showing the first ${dE} of ${e!==void 0?uy(e):"a file of unknown size"}; download for the rest.`}function pE(e){try{return decodeURIComponent(e)}catch{return e}}function gE(e,t,n){const r=`${st(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,a=n.split("/").slice(0,-1),l=f=>{if(/^[a-z][a-z0-9+.-]*:/i.test(f)||f.startsWith("/")||f.startsWith("#"))return null;const h=[...a];for(const m of f.split(/[?#]/,1)[0].split("/"))if(!(!m||m==="."))if(m===".."){if(!h.length)return null;h.pop()}else h.push(pE(m));return h.length?m0(t,h.join("/")):null},c=f=>{let h="",m=0;for(;m<f.length;){if(f[m]==="!"&&f[m+1]==="["){const g=f.indexOf("]",m+2);if(g!==-1&&f[g+1]==="("){const y=f.indexOf(")",g+2);if(y!==-1){const w=f.slice(m+2,g),k=f.slice(g+2,y).trim(),b=k.startsWith(r)?k:l(k);h+=b?``:`[image: ${w||k}](${k})`,m=y+1;continue}}}h+=f[m],m+=1}return h};let u=!1;return e.split(`
|
|
75
|
-
`).map(f=>/^\s*(```|~~~)/.test(f)?(u=!u,f):u?f:c(f)).join(`
|
|
76
|
-
`)}function yE(e,t,n,r){const[a,l]=_.useState({status:"idle"});return _.useEffect(()=>{if(!n||!t){l({status:"idle"});return}const c=new AbortController;let u="";const f=mg(n.name);if(f==="binary"){l({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((f==="image"||f==="audio"||f==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>fE){l({status:"error",kind:f,message:`Too large to preview (${uy(n.size_bytes)}); use Download.`});return}l({status:"loading",kind:f});const h=Pw(f);return(async()=>{var m;try{const g=await e(m0(t,n.path),{signal:c.signal,...h?{headers:{Range:`bytes=0-${ev-1}`}}:{}});if(!g.ok)throw new Error(`Preview failed (HTTP ${g.status}): ${await g.text().catch(()=>"")||g.statusText||"no reason given"}`);const y=g.headers.get("content-type")||"",w=mg(n.name,y);if(Pw(w)){const k=await mE(g,ev,n.size_bytes);if(c.signal.aborted)return;l({status:"ready",kind:w,contentType:y,text:w==="markdown"?gE(k.text,t,n.path):k.text,partial:k.partial,total:k.total});return}if(w==="image"||w==="audio"||w==="pdf"){const k=await g.blob();if(c.signal.aborted)return;u=URL.createObjectURL(k.type?k:new Blob([k],{type:w==="pdf"?"application/pdf":y})),l({status:"ready",kind:w,contentType:y,url:u,partial:!1});return}await((m=g.body)==null?void 0:m.cancel().catch(()=>{})),c.signal.aborted||l({status:"ready",kind:"binary",contentType:y,partial:!1})}catch(g){c.signal.aborted||l({status:"error",kind:f,message:String((g==null?void 0:g.message)||g)})}})(),()=>{c.abort(),u&&URL.revokeObjectURL(u)}},[e,t,n==null?void 0:n.path,n==null?void 0:n.name,n==null?void 0:n.size_bytes,r]),a}function wE(e){return s.jsx(G2,{...e,nowMs:e.nowMs??Date.now(),renderMarkdown:t=>s.jsx(Si,{text:t})})}function vE(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:_E(e.total)}:{}}}const _y=e=>st(`runs/${encodeURIComponent(e)}/workspace`);function xE(e){return _y(e)}function bE(e,t){return`${_y(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function kE(e,t){return`${_y(e)}/content?${new URLSearchParams({path:t})}`}async function Gu(e,t){let n="";try{const r=await e.text();try{const a=JSON.parse(r),l=(a==null?void 0:a.detail)??(a==null?void 0:a.error)??(a==null?void 0:a.message);n=typeof l=="string"?l:l&&typeof l.message=="string"?l.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function jE(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=c=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${c}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const a=n.entries.map((c,u)=>{const f=c&&typeof c=="object"?c:{};return(typeof f.name!="string"||typeof f.path!="string"||f.type!=="file"&&f.type!=="dir")&&r(`entry ${u+1} lacks a name, path or file/dir type`),f}),l=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:a,truncated:n.truncated,...l?{hidden:l}:{}}}async function SE(e,t,n){const r=await e(xE(t),{signal:n});if(!r.ok)throw await Gu(r,"The workspace is not available");const a=await r.json();if(!a||typeof a.workspace_root!="string"||typeof a.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return a}async function NE(e,t,n,r){const a=await e(bE(t,n),{signal:r});if(!a.ok)throw await Gu(a,"The folder could not be listed");return jE(await a.json(),n)}async function CE(e,t,n,r){const a=await e(kE(t,n),{signal:r});if(!a.ok)throw await Gu(a,"The file could not be read");return await a.blob()}async function EE(e,t,n,r){const a=await SE(e,t,r);return{where:a,listing:a.exists?await NE(e,t,n,r):null}}function $E(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,a)=>n.push({label:r,path:t.slice(0,a+1).join("/")})),n}function AE(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 TE(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function ME(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 RE=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function LE(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return RE.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 _0(e,t,n){const r=n==="open"?LE(e.type):{mode:"download"},a=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,l=URL.createObjectURL(a);if(r.mode==="open")window.open(l,"_blank","noopener");else{const c=document.createElement("a");c.href=l,c.download=t,document.body.appendChild(c),c.click(),c.remove()}window.setTimeout(()=>URL.revokeObjectURL(l),6e4)}async function IE(e,t,n){const r=await e(IS(t),{signal:n.signal});if(!r.ok)throw await Gu(r,`${n.name} could not be read`);_0(await r.blob(),n.name,n.mode??"open")}function OE(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function PE(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 DE(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function p0(e){var D;const{fetchGateway:t,runId:n}=e,[r,a]=_.useState({runId:n,path:""}),l=r.runId===n?r.path:"",[c,u]=_.useState(null),[f,h]=_.useState(""),[m,g]=_.useState(""),[y,w]=_.useState(!!n),[k,b]=_.useState(""),[S,N]=_.useState(!1),[R,$]=_.useState(0),[A,W]=_.useState(null),z=A&&A.runId===n&&!e.onSelectFile?A.entry:null,H=yE(t,n,z,`${e.refreshKey??""}:${R}`);_.useEffect(()=>{if(!n)return;const T=new AbortController;return w(!0),h(""),(async()=>{try{const E=await EE(t,n,l,T.signal);T.signal.aborted||u({runId:n,...E})}catch(E){T.signal.aborted||h(String((E==null?void 0:E.message)||E))}finally{T.signal.aborted||w(!1)}})(),()=>T.abort()},[t,n,l,R,e.refreshKey]),_.useEffect(()=>g(""),[n]);const G=c&&c.runId===n?c:null,re=_.useCallback(async T=>{b(T.path),h("");try{_0(await CE(t,n,T.path),T.name,"download")}catch(E){h(String((E==null?void 0:E.message)||E))}finally{b("")}},[t,n]),te=(G==null?void 0:G.where.workspace_root)||"",Q=e.nowMs??Date.now();return s.jsx(FE,{title:e.title,note:e.note,where:(G==null?void 0:G.where)??null,path:l,listing:(G==null?void 0:G.listing)??null,error:f,notice:m,loading:y,fileBusy:k,selectedPath:e.onSelectFile?e.selectedPath:z==null?void 0:z.path,className:e.className,nowMs:Q,openingFolder:S,onNavigate:T=>{W(null),a({runId:n,path:T})},onRefresh:()=>$(T=>T+1),onFile:T=>void re(T),onSelectFile:e.onSelectFile??(T=>W({runId:n,entry:T})),onClose:e.onClose,onCopyPath:te?()=>{(e.copyText||DE)(te).then(T=>g(T?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&PE(G==null?void 0:G.where)?()=>{N(!0),g(""),e.onOpenFolder().then(()=>g("Folder opened on this machine.")).catch(T=>g(`Open folder failed: ${String((T==null?void 0:T.message)||T)}`)).finally(()=>N(!1))}:void 0,preview:z?s.jsx(wE,{name:z.name,path:z.path,sizeBytes:z.size_bytes,modified:z.mtime,nowMs:Q,...vE(H),actions:(D=e.fileActions)==null?void 0:D.call(e,z),onDownload:()=>void re(z),onClose:()=>W(null)}):null})}function FE(e){var l,c,u,f;const t=e.listing?ME(e.listing):"",n=(c=(l=e.where)==null?void 0:l.host)==null?void 0:c.hostname,r=((u=e.where)==null?void 0:u.workspace_root)||"",a=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(ze,{name:"folder",size:15})," ",e.title]}),s.jsx("span",{className:"pc-ws__spacer"}),s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"refresh-folder",onClick:e.onRefresh,disabled:e.loading,title:"Refresh","aria-label":"Refresh the folder",children:s.jsx(ze,{name:"refresh",size:14})}),e.onClose?s.jsx("button",{type:"button",className:"pc-ws__icon-btn","data-action":"close-folder",onClick:e.onClose,title:"Close","aria-label":"Close the file browser",children:s.jsx(ze,{name:"x",size:14})}):null]}),e.where?s.jsxs("div",{className:"pc-ws__root",children:[s.jsx("span",{className:"pc-ws__root-name",title:r,"data-root-name":"true",children:OE(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(ze,{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(ze,{name:"copy",size:14})}):null,n&&((f=e.where.host)==null?void 0:f.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,e.notice?s.jsx("div",{className:"pc-ws__muted",role:"status",children:e.notice}):null,e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.preview?s.jsx("div",{className:"pc-ws__preview",children:e.preview}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:$E(e.path).map((h,m,g)=>m===g.length-1?s.jsx("span",{"aria-current":"page",children:h.label},h.path):s.jsxs(xe.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(h.path),children:h.label}),s.jsx("span",{className:"pc-ws__muted",children:" / "})]},h.path))}),e.loading&&!e.listing?s.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?s.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?s.jsx("ul",{className:"pc-ws__entries",children:TE(e.listing.entries).map(h=>s.jsx("li",{className:`pc-ws__entry${e.selectedPath===h.path?" is-selected":""}`,"data-type":h.type,"data-path":h.path,children:h.type==="dir"?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(h.path),children:[s.jsx(ze,{name:"folder",size:14})," ",s.jsxs("span",{className:"pc-ws__label",children:[h.name,"/"]})]}):s.jsxs(s.Fragment,{children:[e.onSelectFile?s.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===h.path,title:`Preview ${h.name}`,onClick:()=>{var m;return(m=e.onSelectFile)==null?void 0:m.call(e,h)},children:[s.jsx(ze,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(ze,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}),s.jsxs("span",{className:"pc-ws__meta",children:[s.jsx("span",{className:"pc-ws__size",children:AE(h.size_bytes)}),h.mtime!==void 0&&Jm(h.mtime,a)?s.jsx("time",{className:"pc-ws__time",title:Kb(h.mtime),"data-meta":"modified",children:Jm(h.mtime,a)}):null]}),e.onFile?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"download-file",disabled:e.fileBusy===h.path,onClick:()=>{var m;return(m=e.onFile)==null?void 0:m.call(e,h,"download")},title:"Download","aria-label":`Download ${h.name}`,children:s.jsx(ze,{name:"download",size:14})}):null]})},h.path))}):s.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?s.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})]})}const zE={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},g0="docs";function BE(e){return st(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function _p(e){return`${String(e||"app")}-docs-assistant:${xo()}`}function UE(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}),{...zE,session_id:e.sessionId,kind:g0,input_data:t}}function y0(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 WE(e){const t=e&&typeof e=="object"?e:{},n=u=>typeof u=="number"&&Number.isFinite(u)&&u>0?Math.trunc(u):0,r=n(t.dropped_messages);if(!r)return"";const a=n(t.replayed_messages),l=n(t.dropped_tokens),c=n(t.max_tokens);return`Earlier messages not replayed: ${r.toLocaleString("en-US")}${l?` (~${l.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${a.toLocaleString("en-US")} message${a===1?"":"s"}`+(c?` (history window: the most recent ${c.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*qE(e,t){const n=e.getReader(),r=new TextDecoder;let a="";const l=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",l,{once:!0});try{for(;;){const{value:c,done:u}=await n.read();if(u)break;a+=r.decode(c,{stream:!0}).replace(/\r\n/g,`
|
|
77
|
-
`);let f=a.indexOf(`
|
|
78
|
-
|
|
79
|
-
`);for(;f>=0;){const h=a.slice(0,f);a=a.slice(f+2);let m="message";const g=[];for(const y of h.split(`
|
|
80
|
-
`))y.startsWith("event:")?m=y.slice(6).trim():y.startsWith("data:")&&g.push(y.slice(5).replace(/^ /,""));g.length&&(yield{event:m,data:g.join(`
|
|
81
|
-
`)}),f=a.indexOf(`
|
|
82
|
-
|
|
83
|
-
`)}}}finally{t==null||t.removeEventListener("abort",l)}}function HE(e,t){return new Promise((n,r)=>{if(t.aborted)return r(new DOMException("Aborted","AbortError"));const a=setTimeout(()=>{t.removeEventListener("abort",l),n()},e),l=()=>{clearTimeout(a),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",l,{once:!0})})}async function _l(e,t){if(!e.ok)throw await Gu(e,t);return e.json()}function VE(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(a,l)=>{var k;const{fetchGateway:c,source:u}=e;if(r===null){const b=await c(BE(u.app),{signal:l.signal,headers:{Accept:"application/json"}}),S=await _l(b,`The ${u.name} documentation could not be read, so nothing was asked`),N=typeof(S==null?void 0:S.text)=="string"?S.text:"";if(!N.trim())throw new Error(`The gateway returned an empty ${u.name} documentation corpus, so nothing was asked.`);r=N}const f=String(r),h=[];for(const b of l.files||[]){const S=new FormData;S.append("session_id",l.sessionId),S.append("file",b,b.name||"upload.bin"),S.append("filename",b.name||"upload.bin"),b.type&&S.append("content_type",b.type);const N=await _l(await c(st("attachments/upload"),{method:"POST",body:S,signal:l.signal}),`"${b.name}" could not be attached`),R=N==null?void 0:N.attachment;if(!R||typeof R.$artifact!="string"||!R.$artifact)throw new Error(`"${b.name}" could not be attached: the gateway returned no attachment reference.`);h.push(R)}const m=await _l(await c(st("runs/start"),{method:"POST",signal:l.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(UE({question:a,docs:f,appName:u.name,sessionId:l.sessionId,attachments:h}))}),"The docs-qa workflow could not start"),g=String((m==null?void 0:m.run_id)||"");if(!g)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const y=new AbortController,w=()=>y.abort();l.signal.addEventListener("abort",w,{once:!0}),l.onText&&(async()=>{var b;try{const S=await c(st(`runs/${encodeURIComponent(g)}/ledger/stream?after=0`),{signal:y.signal,headers:{Accept:"text/event-stream"}});if(!S.ok||!S.body)return;let N="",R="";for await(const $ of qE(S.body,y.signal)){const A=lE($.event,$.data);!A||f0(A)||A.channel!=="content"||A.run_id!==g||(A.call_id!==N&&(N=A.call_id,R=""),R=A.snapshot?A.text:R+A.text,(b=l.onText)==null||b.call(l,R))}}catch{}})();try{const b=Date.now()+n;for(;;){await HE(t,l.signal);const S=await _l(await c(st(`runs/${encodeURIComponent(g)}`),{signal:l.signal}),"The docs-qa run could not be read"),N=String((S==null?void 0:S.status)||"").toLowerCase();if(N==="completed"){(k=l.onHistory)==null||k.call(l,(S==null?void 0:S.session_history)??null);const R=y0(S);if(!R)throw new Error(`The docs-qa run ${g} completed without an answer.`);return R}if(N==="failed"||N==="cancelled"){const R=S==null?void 0:S.error,$=typeof R=="string"?R:typeof(R==null?void 0:R.message)=="string"?R.message:"";throw new Error(`The docs-qa run ${N}${$?`: ${$}`:""}.`)}if(N==="waiting")throw new Error(`The docs-qa run ${g} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=b)throw new Error(`The docs-qa run ${g} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{l.signal.removeEventListener("abort",w),y.abort()}}}async function GE(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:g0,limit:"500",include_ledger_len:"false"}),a=await _l(await e(st(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),l=`${String(t||"app")}-docs-assistant:`,c=new Map;for(const f of Array.isArray(a==null?void 0:a.items)?a.items:[]){const h=String((f==null?void 0:f.session_id)||"");if(!h.startsWith(l)||!(f!=null&&f.run_id))continue;const m=c.get(h)||{runs:[],updatedAt:""};m.runs.push({id:String(f.run_id),created:String(f.created_at||"")});const g=String(f.updated_at||f.created_at||"");g>m.updatedAt&&(m.updatedAt=g),c.set(h,m)}const u=[...c.entries()].sort((f,h)=>f[1].updatedAt<h[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(u.map(async([f,h])=>{var y;const m=h.runs.sort((w,k)=>w.created<k.created?-1:1).map(w=>w.id);let g="";try{const w=await _l(await e(st(`runs/${encodeURIComponent(m[0])}/input_data`),{signal:n.signal}),"");g=String(((y=w==null?void 0:w.input_data)==null?void 0:y.prompt)||"").trim()}catch{g=""}return{sessionId:f,title:g||"Untitled question",updatedAt:h.updatedAt,runIds:m}}))}async function KE(e,t,n,r){var l;const a=[];for(const c of t.runIds){const[u,f]=await Promise.all([_l(await e(st(`runs/${encodeURIComponent(c)}/input_data`),{signal:r}),"A past question could not be read"),_l(await e(st(`runs/${encodeURIComponent(c)}`),{signal:r}),"A past answer could not be read")]),h=String(((l=u==null?void 0:u.input_data)==null?void 0:l.prompt)||"").trim();h&&a.push({id:`u-${c}`,role:"user",content:h,ts:String((f==null?void 0:f.created_at)||"")||void 0});const m=y0(f),g=String((f==null?void 0:f.status)||"").toLowerCase();a.push(m?{id:`a-${c}`,role:"assistant",title:n,content:m,ts:String((f==null?void 0:f.updated_at)||"")||void 0}:{id:`a-${c}`,role:"assistant",title:n,level:"warn",content:g==="completed"?"This answer was empty.":`No answer: the run is ${g||"unknown"}.`})}return a}function YE(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:[Jm(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(ze,{name:"archive",size:16})})]})},r.sessionId))}):s.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const JE=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function XE(e){const t=_.useRef(null),[n,r]=_.useState(!1),a=!!e.blockedNotice,l=!!e.busy,c=e.files||[],u=typeof e.onAddFiles=="function"&&!a,f=s.jsxs("div",{className:"pc-docs-assistant__empty",children:[s.jsxs("p",{className:"pc-docs-assistant__empty-text",children:["Ask anything about ",e.source.name,"."]}),e.suggestions&&e.suggestions.length?s.jsx("div",{className:"pc-docs-assistant__suggestions",children:e.suggestions.map(h=>s.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:l||a,onClick:()=>{var m;return(m=e.onSuggestion)==null?void 0:m.call(e,h)},children:h},h))}):null]});return s.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:h=>{var m;!u||!jf((m=h.dataTransfer)==null?void 0:m.types)||(h.preventDefault(),r(!0))},onDragLeave:()=>r(!1),onDrop:h=>{var g,y;if(!u)return;h.preventDefault(),r(!1);const m=my(h.dataTransfer);m.files.length&&((g=e.onAddFiles)==null||g.call(e,m.files)),m.folders.length&&((y=e.onNotice)==null||y.call(e,u0(m.folders)))},children:[s.jsx(fy,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:f,messageProps:{showCopy:!0}}),a?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(hy,{value:e.draft,onChange:e.onDraftChange,onSubmit:e.onSend,placeholder:e.placeholder||`Ask about ${e.source.name}…`,ariaLabel:`Question about ${e.source.name}`,disabled:a,busy:l,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:h=>{var g;if(!u)return;const m=d0(h.clipboardData);m.length&&(h.preventDefault(),(g=e.onAddFiles)==null||g.call(e,m))},leading:c.length?s.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:c.map(h=>s.jsxs("span",{role:"listitem",className:"pc-chat-attachment-chip",children:[s.jsx(ze,{name:"paperclip",size:14}),s.jsx("span",{className:"pc-chat-attachment-name",children:h.name}),e.onRemoveFile&&!l?s.jsx("button",{type:"button",className:"pc-docs-assistant__file-remove","aria-label":`Remove ${h.name}`,"data-af-tip":`Remove ${h.name}`,onClick:()=>{var m;return(m=e.onRemoveFile)==null?void 0:m.call(e,h.id)},children:s.jsx(ze,{name:"x",size:12})}):null]},h.id))}):null,actions:s.jsxs(s.Fragment,{children:[u?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Attach files","data-af-tip":"Attach files to your question",disabled:l,onClick:()=>{var h;return(h=t.current)==null?void 0:h.click()},children:s.jsx(ze,{name:"paperclip",size:16})}),s.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:h=>{var g;const m=Array.from(h.currentTarget.files||[]);h.currentTarget.value="",m.length&&((g=e.onAddFiles)==null||g.call(e,m))}})]}):null,l&&e.onStop?s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Stop","data-af-tip":"Stop the answer",onClick:e.onStop,children:s.jsx(ze,{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 gm(){return new Date().toISOString()}function ZE(e){Vu();const{source:t}=e,n=_.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=_.useMemo(()=>e.ask||VE({fetchGateway:(Q,D)=>n.current(Q,D),source:t}),[e.ask,t.app,t.name]),a=_.useRef(_p(t.app)),[l,c]=_.useState([]),u=_.useRef(l);u.current=l;const[f,h]=_.useState(""),[m,g]=_.useState([]),[y,w]=_.useState(!1),[k,b]=_.useState(""),S=_.useRef(null),[N,R]=_.useState(!1),[$,A]=_.useState({state:"loading",items:[]});_.useEffect(()=>()=>{var Q;return(Q=S.current)==null?void 0:Q.abort()},[]);const W=_.useCallback(async()=>{A(Q=>({...Q,state:"loading"}));try{const Q=await GE((D,T)=>n.current(D,T),t.app);A({state:"ready",items:Q})}catch(Q){A({state:"error",items:[],error:String((Q==null?void 0:Q.message)||Q)})}},[t.app]),z=_.useCallback(async Q=>{var D;(D=S.current)==null||D.abort(),A(T=>({...T,state:"loading"}));try{const T=await KE((E,L)=>n.current(E,L),Q,t.name);a.current=Q.sessionId,c(T),b(""),R(!1),A(E=>({...E,state:"ready"}))}catch(T){A(E=>({...E,state:"error",error:String((T==null?void 0:T.message)||T)}))}},[t.name]),H=_.useCallback(async Q=>{try{const D=await n.current(st(`sessions/${encodeURIComponent(Q.sessionId)}/archive`),{method:"POST"});if(!D.ok)throw await Gu(D,"The conversation could not be archived");a.current===Q.sessionId&&(a.current=_p(t.app),c([])),A(T=>({...T,items:T.items.filter(E=>E.sessionId!==Q.sessionId)}))}catch(D){A(T=>({...T,state:"error",error:String((D==null?void 0:D.message)||D)}))}},[t.app]);_.useEffect(()=>{var Q;e.connected||(Q=S.current)==null||Q.abort()},[e.connected]),_.useEffect(()=>()=>{for(const Q of m)Q.preview&&URL.revokeObjectURL(Q.preview)},[]);const G=_.useCallback(Q=>{b(""),g(D=>[...D,...Q.map(T=>({id:xo(),file:T,preview:JE.test(T.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(T):void 0}))])},[]),re=_.useCallback(async Q=>{const D=String(Q||"").trim();if(!D||y||!e.connected)return;const T=m;h(""),g([]),b("");const E=T.filter(V=>V.preview).map(V=>({kind:"image",src:V.preview,label:V.file.name})),L=T.map(V=>({id:V.id,label:V.file.name,title:V.file.name,disabled:!0})),M={id:`u-${xo()}`,role:"user",content:D,ts:gm(),...E.length?{media:E}:{},...L.length?{attachments:L}:{}},ee=`a-${xo()}`,F=[...u.current,M],U={id:ee,role:"assistant",title:t.name,content:"",ts:gm(),live:{callId:ee,reasoning:"",label:"answering"}};c([...F,U]),w(!0);const K=new AbortController;S.current=K;const O=V=>c([...F,V]);try{const V=await r(D,{signal:K.signal,sessionId:a.current,files:T.map(J=>J.file),onText:J=>{K.signal.aborted||O({...U,content:J,live:{callId:ee,reasoning:"",label:"streaming"}})},onHistory:J=>b(WE(J))});K.signal.aborted||O({id:ee,role:"assistant",title:t.name,content:V,ts:gm()})}catch(V){const J=K.signal.aborted;O({id:ee,role:"assistant",title:t.name,level:J?"warn":"error",content:J?"Stopped. Nothing more will be shown for this question.":String((V==null?void 0:V.message)||V||"The docs assistant failed."),ts:gm()})}finally{S.current===K&&(S.current=null),w(!1)}},[r,y,m,e.connected,t.name]),te=()=>{var Q;(Q=S.current)==null||Q.abort(),a.current=_p(t.app),c([]),g([]),h(""),b("")};return s.jsxs(i1,{open:e.open,onClose:e.onClose,label:"Docs assistant",title:s.jsxs("span",{className:"pc-docs-assistant__title",children:[s.jsx(ze,{name:"book",size:16}),"Docs assistant"]}),width:e.width||420,topOffset:e.topOffset,className:`pc-docs-assistant-drawer${e.className?` ${e.className}`:""}`,headerActions:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:`pc-docs-assistant__icon-btn${N?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":N,disabled:!e.connected||y,onClick:()=>{const Q=!N;R(Q),Q&&W()},children:s.jsx(ze,{name:"history",size:16})}),s.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"New conversation","data-af-tip":"Start a new conversation",disabled:!l.length&&!f&&!m.length&&!N,onClick:()=>{te(),R(!1)},children:s.jsx(ze,{name:"compose",size:16})})]}),children:[N?s.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:s.jsx(YE,{items:$.items,state:$.state,error:$.error,nowMs:Date.now(),activeSessionId:a.current,onOpen:Q=>void z(Q),onArchive:Q=>void H(Q)})}):null,s.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:s.jsx(XE,{source:t,messages:l,draft:f,onDraftChange:h,onSend:()=>void re(f),onStop:()=>{var Q;return(Q=S.current)==null?void 0:Q.abort()},busy:y,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:m.map(Q=>({id:Q.id,name:Q.file.name})),onAddFiles:G,onNotice:b,onRemoveFile:Q=>g(D=>{const T=D.find(E=>E.id===Q);return T!=null&&T.preview&&URL.revokeObjectURL(T.preview),D.filter(E=>E.id!==Q)}),notice:k,suggestions:e.suggestions,onSuggestion:Q=>void re(Q),placeholder:e.placeholder})})]})}const jn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Dm=e=>Array.isArray(e)?e.map(jn):[],nn=e=>typeof e=="string"?e:"",af=e=>nn(e.runtime_call_id||e.call_uid),of=e=>nn(e.call_id||e.id);function w0(e,t){const n=t.record,r=jn(n.effect);if(r.type!=="tool_calls")return[];const a=jn(n.result),l=Dm(jn(r.payload).tool_calls),c=l.length||n.status!=="waiting"?l:Dm(jn(jn(a.wait).details).tool_calls),u=Dm(a.results),f=c.length?c:u,h=[];return f.forEach((m,g)=>{let y=af(m)?u.filter(z=>af(z)===af(m)):[];!y.length&&of(m)&&c.filter(z=>of(z)===of(m)).length===1&&(y=u.filter(z=>of(z)===of(m)));const w=c.length?y.length===1?y[0]:c.length===u.length?u[g]:{}:m,k=af(m)||af(w)||`${nn(n.idempotency_key)||nn(n.step_id)||t.cursor}:${g}`,b=`${t.runId}:${k}`,S=e.get(b),N=nn(m.name||w.name)||(S==null?void 0:S.name);if(!N)return;const R=n.status==="completed"||n.status==="failed",$=n.status==="failed"||w.success===!1||!!w.error,A=m.arguments??w.arguments??(S==null?void 0:S.arguments),W={...S,id:b,runId:t.runId,name:N,arguments:A,status:R?$?"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)}:{},...pg(w)?{sandbox:pg(w)}:{},startedAt:(S==null?void 0:S.startedAt)||nn(n.started_at)||void 0,endedAt:R&&nn(n.ended_at)||(S==null?void 0:S.endedAt)};S&&["completed","failed"].includes(S.status)&&!R||(e.set(b,W),h.push(W))}),h}function Nu(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Ma(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const a=Number(r);if(Number.isFinite(a)&&a>=0)return Math.trunc(a)}}function v0(e){if(typeof e=="string")try{return jn(JSON.parse(e))}catch{return{}}return jn(e)}function gu(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function QE(e){return Ma(e,["reasoning_tokens","thinking_tokens"])??Ma(jn(e.completion_tokens_details),["reasoning_tokens"])??Ma(jn(e.output_tokens_details),["reasoning_tokens"])}function e$(e){const t=jn(typeof e=="string"&&e.trim().startsWith("{")?v0(e):e);return nn(t.error_class)}function t$(e){const t=new Map;for(const n of e){const r=n.record;if(jn(r.effect).type!=="emit_event")continue;const a=jn(r.result);if(nn(a.name)!=="abstract.progress")continue;const l=jn(a.payload);if(nn(l.kind)!=="llm"||!nn(l.step_id))continue;const c=`${nn(l.run_id)||n.runId}:${nn(l.step_id)}`,u=t.get(c)||{},f=Nu(l.ttft_s);f!==void 0&&(u.ttftS=f),u.provider=u.provider||nn(l.provider)||void 0,u.model=u.model||nn(l.model)||void 0,t.set(c,u)}return t}function pp(e){var b,S,N,R;const t=new Map,n=new Set,r=new Set,a={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,c=-1/0,u=!1,f=0,h=0,m=0;const g=t$(e),y=[],w=new Set;for(const $ of e){const A=$.record,W=`${$.runId}:${A.step_id||$.cursor}:${A.status}`;if(n.has(W))continue;n.add(W);for(const ye of[A.started_at,A.ended_at]){const Ne=Date.parse(nn(ye));Number.isFinite(Ne)&&(l=Math.min(l,Ne),c=Math.max(c,Ne))}for(const ye of w0(t,$))ye.status==="waiting"&&w.add(ye.id);if(jn(A.effect).type!=="llm_call"||A.status!=="completed")continue;a.llmCalls+=1;const z=jn(A.result),H=jn(z.output),G=jn(z.usage||z.token_usage||z.tokens||H.usage||H.token_usage||H.tokens),re=Ma(G,["input_tokens","prompt_tokens","prompt","input","in"]),te=Ma(G,["output_tokens","completion_tokens","completion","output","out"]),Q=Ma(G,["total_tokens","total"])??(re!==void 0||te!==void 0?(re||0)+(te||0):void 0);Q!==void 0&&(re===void 0||te===void 0||re+te!==Q)&&(u=!0),re!==void 0&&(a.inputTokens=(a.inputTokens||0)+re),te!==void 0&&(a.outputTokens=(a.outputTokens||0)+te),Q!==void 0&&(a.totalTokens=(a.totalTokens||0)+Q);const D=Nu(z.gen_time??H.gen_time);D!==void 0&&(a.genTimeMs=(a.genTimeMs||0)+D,a.timedCalls=(a.timedCalls||0)+1);const T=jn(z.metadata||H.metadata),E=jn(T.performance),L=Nu(E.prompt_tokens_per_second),M=Nu(E.generation_tokens_per_second),ee=jn(T.prompt_cache),F=Nu(ee.cached_tokens),U=Nu(ee.fed_tokens);if(L!==void 0||M!==void 0){if(a.measuredSpeedCalls=(a.measuredSpeedCalls||0)+1,L!==void 0&&L>0&&(a.promptTokensPerSecond=(a.promptTokensPerSecond||0)+L,re!==void 0)){const ye=re/L*1e3;a.prefillMs=(a.prefillMs||0)+ye,U!==void 0&&(f+=U,h+=ye)}M!==void 0&&M>0&&(a.generationTokensPerSecond=(a.generationTokensPerSecond||0)+M,te!==void 0&&(a.decodeMs=(a.decodeMs||0)+te/M*1e3))}if(F!==void 0||U!==void 0){a.measuredCacheCalls=(a.measuredCacheCalls||0)+1,a.cachedTokens=(a.cachedTokens||0)+(F||0),a.fedTokens=(a.fedTokens||0)+(U||0);const ye=nn(ee.outcome);if(ye){const Ne=a.cacheOutcomes||[];Ne.includes(ye)||Ne.push(ye),a.cacheOutcomes=Ne}}const K=nn(A.step_id)||void 0,O=K&&g.get(`${$.runId}:${K}`)||{},V=jn(z.route),J={runId:$.runId};K&&(J.stepId=K),nn(A.started_at)&&(J.startedAt=nn(A.started_at));const le=nn(z.model||H.model)||nn(V.model)||O.model,ie=nn(V.provider)||nn(jn(T._provider_request).provider)||O.provider||nn(z.provider);le&&(J.model=le),ie&&(J.provider=ie),le&&(a.models=gu(a.models,le)),ie&&(a.providers=gu(a.providers,ie)),(Q===void 0||re!==void 0&&te!==void 0&&re+te===Q)&&(re!==void 0&&(J.inputTokens=re),te!==void 0&&(J.outputTokens=te)),Q!==void 0&&(J.totalTokens=Q);const _e=QE(G);_e!==void 0&&(J.reasoningTokens=_e,a.reasoningTokens=(a.reasoningTokens||0)+_e),F!==void 0&&(J.cachedTokens=F),U!==void 0&&(J.fedTokens=U),nn(ee.outcome)&&(J.cacheOutcome=nn(ee.outcome)),nn(ee.backend)&&(J.cacheBackend=nn(ee.backend),a.cacheBackends=gu(a.cacheBackends,J.cacheBackend)),D!==void 0&&(J.genTimeMs=D),L!==void 0&&L>0&&(J.promptTokensPerSecond=L),M!==void 0&&M>0&&(J.generationTokensPerSecond=M),O.ttftS!==void 0?(J.ttftMs=O.ttftS*1e3,J.promptMs=J.ttftMs,J.promptSource="ttft",a.ttftMs=(a.ttftMs||0)+J.ttftMs,a.ttftCalls=(a.ttftCalls||0)+1):J.promptTokensPerSecond!==void 0&&re!==void 0&&(J.promptMs=re/J.promptTokensPerSecond*1e3,J.promptSource="rate"),J.promptMs!==void 0&&(a.promptPhaseMs=(a.promptPhaseMs||0)+J.promptMs,a.promptPhaseCalls=(a.promptPhaseCalls||0)+1,U!==void 0&&J.promptMs>0&&(J.promptNewTokensPerSecond=U/(J.promptMs/1e3),a.promptPhaseNewTokens=(a.promptPhaseNewTokens||0)+U,m+=J.promptMs)),J.ttftMs!==void 0&&D!==void 0&&D>=J.ttftMs?J.generationMs=D-J.ttftMs:J.generationTokensPerSecond!==void 0&&te!==void 0&&(J.generationMs=te/J.generationTokensPerSecond*1e3),J.generationMs!==void 0&&te!==void 0&&(a.generationPhaseMs=(a.generationPhaseMs||0)+J.generationMs,a.generationPhaseTokens=(a.generationPhaseTokens||0)+te);const pe=jn(T.speculation);if(Object.keys(pe).length){const ye={};nn(pe.mode)&&(ye.mode=nn(pe.mode)),typeof pe.used=="boolean"&&(ye.used=pe.used),nn(pe.draft_kind)&&(ye.draftKind=nn(pe.draft_kind));const Ne=Ma(pe,["accepted_tokens"]),Be=Ma(pe,["drafted_tokens"]),Ue=Ma(pe,["rounds"]),ut=Ma(pe,["num_draft_tokens"]);Ne!==void 0&&(ye.acceptedTokens=Ne),Be!==void 0&&(ye.draftedTokens=Be),Ne!==void 0&&Be&&(ye.acceptanceRate=Ne/Be),Ue!==void 0&&(ye.rounds=Ue),ut!==void 0&&(ye.draftLength=ut),J.speculation=ye;const De=a.speculation||(a.speculation={calls:0,used:0});De.calls+=1,ye.used&&(De.used+=1),ye.mode&&(De.modes=gu(De.modes,ye.mode)),ye.draftKind&&(De.draftKinds=gu(De.draftKinds,ye.draftKind)),Ne!==void 0&&Be!==void 0&&(De.acceptedTokens=(De.acceptedTokens||0)+Ne,De.draftedTokens=(De.draftedTokens||0)+Be),Ue!==void 0&&(De.rounds=(De.rounds||0)+Ue),ut!==void 0&&(De.draftLengths=gu(De.draftLengths,ut))}y.push(J)}y.length&&(y.every($=>$.startedAt)&&y.sort(($,A)=>Date.parse($.startedAt)-Date.parse(A.startedAt)),a.modelCalls=y),m>0&&a.promptPhaseNewTokens!==void 0&&(a.promptPhaseTokensPerSecond=a.promptPhaseNewTokens/(m/1e3)),a.generationPhaseMs&&a.generationPhaseTokens!==void 0&&(a.generationPhaseTokensPerSecond=a.generationPhaseTokens/(a.generationPhaseMs/1e3)),(b=a.speculation)!=null&&b.draftedTokens&&(a.speculation.acceptanceRate=(a.speculation.acceptedTokens||0)/a.speculation.draftedTokens),a.measuredSpeedCalls&&(a.promptTokensPerSecond!==void 0&&(a.promptTokensPerSecond/=a.measuredSpeedCalls),a.generationTokensPerSecond!==void 0&&(a.generationTokensPerSecond/=a.measuredSpeedCalls)),h>0&&(a.prefillNewTokens=f,a.prefillNewTokensPerSecond=f/(h/1e3));const k=new Map;for(const $ of t.values()){if($.status==="waiting"){a.toolsWaiting=(a.toolsWaiting||0)+1;continue}if($.status==="running"){a.toolsRunning=(a.toolsRunning||0)+1;continue}if(!["completed","failed"].includes($.status))continue;a.toolCalls+=1;const A=$.status==="failed";A&&(a.toolsFailed=(a.toolsFailed||0)+1);const W=a.toolBreakdown||(a.toolBreakdown={}),z=W[$.name]||(W[$.name]={calls:0,failed:0});if(z.calls+=1,A){z.failed+=1;const Q=e$($.output);Q&&((z.errors||(z.errors={}))[Q]=(((S=z.errors)==null?void 0:S[Q])||0)+1)}const H=Date.parse(nn($.startedAt)),G=Date.parse(nn($.endedAt));if(Number.isFinite(H)&&Number.isFinite(G)&&G>=H){const Q=`${$.runId}|${$.startedAt}|${$.endedAt}`,D=k.get(Q)||{ms:G-H,calls:0,names:new Map,waited:!1};D.calls+=1,D.names.set($.name,(D.names.get($.name)||0)+1),w.has($.id)&&(D.waited=!0),k.set(Q,D)}if($.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($.name))continue;const re=v0($.arguments),te=nn(re.destination||re.destination_path||re.file_path||re.path||re.filename);te&&r.add(te)}for(const $ of k.values()){a.toolBatches=(a.toolBatches||0)+1,a.toolTimeMs=(a.toolTimeMs||0)+$.ms,$.waited&&(a.toolTimeIncludesApproval=!0);const A=[...$.names.keys()].sort();(!a.slowestToolBatch||$.ms>a.slowestToolBatch.ms)&&(a.slowestToolBatch={ms:$.ms,calls:$.calls,tools:A});const W=(N=a.toolBreakdown)==null?void 0:N[A[0]];if(A.length===1&&W)W.ms=(W.ms||0)+$.ms;else for(const z of A){const H=(R=a.toolBreakdown)==null?void 0:R[z];H&&(H.sharedBatches=(H.sharedBatches||0)+1)}}return a.changedFiles=[...r],u&&(delete a.inputTokens,delete a.outputTokens),Number.isFinite(l)&&Number.isFinite(c)&&(a.durationMs=Math.max(0,c-l)),{tools:[...t.values()],statistics:a}}function n$(e){const t=jn(jn(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Dm(jn(r).items).map((a,l)=>({runId:n,cursor:Number(a.cursor)||l+1,record:Object.keys(jn(a.record)).length?jn(a.record):a})))}function s$(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 r$(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function i$(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 a$(e){var H;const t=e.interaction,[n,r]=_.useState(""),[a,l]=_.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[c,u]=_.useState(null),[f,h]=_.useState(!1),[m,g]=_.useState(""),[y,w]=_.useState(null),k=`${t.kind}:${t.id}`,b=_.useRef(k),S=_.useRef(!1),N=_.useRef(!1),R=_.useRef(!0),$=_.useRef(0);b.current!==k&&(b.current=k,S.current=!1,N.current=!1,$.current+=1);const A=!!e.disabled||c!==null||f||S.current||N.current,W=async(G,re)=>{var D;if(e.disabled||S.current||N.current)return;const te=k,Q=++$.current;S.current=!0,w(null),g(""),u(G);try{if(await re(),!R.current||b.current!==te||$.current!==Q)return;N.current=!0,h(!0),g("Response sent. Waiting for the workflow to continue.")}catch(T){if(!R.current||b.current!==te||$.current!==Q)return;w({submission:G,message:r$(T)}),g("The action failed. You can try again."),(D=e.onError)==null||D.call(e,T)}finally{if(!R.current||b.current!==te||$.current!==Q)return;S.current=!1,u(null)}};_.useEffect(()=>{r(""),l(t.kind==="event-wait"&&t.initialPayload||""),w(null),u(null),h(!1),g("")},[k]),_.useEffect(()=>(R.current=!0,()=>{R.current=!1,$.current+=1,S.current=!1}),[]);const z=()=>{y&&W(y.submission,()=>s$(t,y.submission))};return s.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${k}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(ze,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${k}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(H=t.choices)!=null&&H.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(G=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:A||G.disabled,onClick:()=>void W({kind:"choice",answer:G.id},()=>t.onSubmit(G.id)),children:[s.jsx("span",{children:G.label}),G.description?s.jsx("small",{children:G.description}):null]},G.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:n,onChange:G=>r(G.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:A,onKeyDown:G=>{G.key!=="Enter"||G.shiftKey||G.nativeEvent.isComposing||G.keyCode===229||(G.preventDefault(),n.trim()&&W({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${k}:text`),s.jsx("button",{type:"button",className:"pc-btn",disabled:A||!n.trim(),onClick:()=>void W({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(c==null?void 0:c.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",s.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:A,onClick:()=>void W({kind:"deny"},t.onDeny),children:(c==null?void 0:c.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),s.jsx("button",{type:"button",className:"pc-btn",disabled:A,onClick:()=>void W({kind:"approve"},t.onApprove),children:(c==null?void 0:c.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:A,onClick:()=>void W({kind:"approve-all"},t.onApproveAll),children:(c==null?void 0:c.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?s.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:a,onChange:G=>l(G.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:A},`${k}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn",disabled:A,onClick:()=>void W({kind:"event",payload:a},()=>t.onSend(a)),children:(c==null?void 0:c.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),y?s.jsx(i$,{message:y.message,onRetry:z,disabled:A}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:m})]})}function ym(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function o$(e){Vu();const[t,n]=_.useState(!1),[r,a]=_.useState(!1),[l,c]=_.useState(!1),[u,f]=_.useState(null),h=_.useRef(!0),m=_.useRef(!1),g=_.useRef(!1),y=_.useRef(!1),w=_.useRef(0),k=_.useRef(0),b=_.useRef(0);_.useEffect(()=>(h.current=!0,()=>{h.current=!1,w.current+=1,k.current+=1,b.current+=1,m.current=!1,g.current=!1,y.current=!1}),[]);const S=!!e.blockedNotice,N=!!e.disabled||S,R=!!e.busy||t,$=t||!!e.busy&&!e.sendWhileBusy,A=e.stopState||null,W=(A==null?void 0:A.phase)==="stopping",z=typeof e.onFiles=="function",H=_.useRef(null),[G,re]=_.useState(null),[te,Q]=_.useState(""),D=_.useRef(e.onFiles);D.current=e.onFiles;const T=_.useRef(N);T.current=N;const E=async(J,le)=>{const ie=D.current;if(ie){if(T.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(le.length)f({action:"attach",message:u0(le)});else if(J.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(J.length){Q(`Attaching ${J.length} ${J.length===1?"file":"files"}…`);try{await ie(J)}catch(_e){h.current&&f({action:"attach",message:ym(_e)})}}}},L=_.useRef(E);L.current=E,_.useEffect(()=>{if(!z||typeof window>"u")return;const J=new iE;let le=0;const ie=De=>!!(H.current&&De instanceof Node&&H.current.contains(De)),_e=()=>{J.reset(),le&&window.clearInterval(le),le=0,re(null)},pe=()=>{le||(le=window.setInterval(()=>{J.active(Date.now())||_e()},250))},ye=De=>{var Ke;if(!jf((Ke=De.dataTransfer)==null?void 0:Ke.types))return;J.enter(Date.now());const Qe=ie(De.target),at=Zw(De.dataTransfer);re(ce=>ce&&ce.over===Qe&&ce.count===(at??ce.count)?ce:{count:at??(ce==null?void 0:ce.count)??null,over:Qe}),pe()},Ne=De=>{var at;if(!jf((at=De.dataTransfer)==null?void 0:at.types))return;De.preventDefault(),J.over(Date.now());const Qe=ie(De.target);De.dataTransfer&&(De.dataTransfer.dropEffect=Qe&&!T.current?"copy":"none"),re(Ke=>Ke&&Ke.over===Qe?Ke:{count:(Ke==null?void 0:Ke.count)??Zw(De.dataTransfer),over:Qe}),pe()},Be=De=>{var Qe;jf((Qe=De.dataTransfer)==null?void 0:Qe.types)&&(J.leave(Date.now())||_e())},Ue=De=>{var oe;if(!jf((oe=De.dataTransfer)==null?void 0:oe.types))return;const Qe=ie(De.target),at=De.defaultPrevented&&!Qe;if(De.preventDefault(),_e(),at)return;if(!Qe){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ke,folders:ce}=my(De.dataTransfer);L.current(Ke,ce)},ut=De=>{De.key==="Escape"&&J.depth>0&&_e()};return window.addEventListener("dragenter",ye),window.addEventListener("dragover",Ne),window.addEventListener("dragleave",Be),window.addEventListener("drop",Ue),window.addEventListener("dragend",_e),window.addEventListener("blur",_e),window.addEventListener("keydown",ut),()=>{window.removeEventListener("dragenter",ye),window.removeEventListener("dragover",Ne),window.removeEventListener("dragleave",Be),window.removeEventListener("drop",Ue),window.removeEventListener("dragend",_e),window.removeEventListener("blur",_e),window.removeEventListener("keydown",ut),le&&window.clearInterval(le)}},[z]);const M=J=>{if(!z||N)return;const le=d0(J.clipboardData);le.length&&(J.preventDefault(),E(le,[]))},ee=G?s.jsxs("div",{className:["pc-workflow-chat__dropzone",G.over?"is-over":"",N?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(ze,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:N?"Attachments are unavailable right now":Qw(G.count)}),N?null:s.jsx("span",{children:G.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,F=G?N?"Attachments are unavailable right now":Qw(G.count):te,U=async()=>{const J=String(e.draft||"");if(N||m.current||!e.sendWhileBusy&&e.busy||!J.trim())return;const le=++w.current;m.current=!0,f(null),n(!0);try{await e.onSend(J)}catch(ie){h.current&&w.current===le&&f({action:"send",message:ym(ie)})}finally{h.current&&w.current===le&&(m.current=!1,n(!1))}},K=async()=>{if(N||g.current||!e.onCancel)return;const J=++k.current;g.current=!0,f(null),a(!0);try{await e.onCancel()}catch(le){h.current&&k.current===J&&f({action:"cancel",message:ym(le)})}finally{h.current&&k.current===J&&(g.current=!1,a(!1))}},O=async()=>{if(N||y.current||!e.onAttach)return;const J=++b.current;y.current=!0,f(null),c(!0);try{await e.onAttach()}catch(le){h.current&&b.current===J&&f({action:"attach",message:ym(le)})}finally{h.current&&b.current===J&&(y.current=!1,c(!1))}},V=()=>{u&&(u.action==="send"&&U(),u.action==="cancel"&&K(),u.action==="attach"&&O())};return s.jsxs("section",{ref:H,className:["pc-workflow-chat",G?"pc-workflow-chat--dragging":"",G!=null&&G.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(fy,{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(a$,{interaction:e.interaction,disabled:N}):null,S?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${S?"blocked":""}`})}),u?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not ",u.action==="send"?"send this message":u.action==="attach"?"attach a file":"stop the run",": ",u.message]}),s.jsx("button",{type:"button",onClick:V,disabled:N,children:"Try again"})]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(hy,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void U(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:N,busy:$,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?s.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:ee,onPaste:z?M:void 0,actions:s.jsxs(s.Fragment,{children:[e.onAttach?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file","data-af-tip":"Attach a file",disabled:N||l,onClick:()=>void O(),children:[s.jsx(ze,{name:"paperclip",size:16}),s.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,R&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:N||r||W,onClick:()=>void K(),children:[s.jsx(ze,{name:"x",size:14}),s.jsx("span",{children:r||W?"Stopping…":"Stop"})]}):A?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${A.phase}`,role:"status","aria-live":"polite",children:A.label}):null]})}),z?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:F}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function l$(e){return e.toolApprovalGranted?null:e.interaction}const tv={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Tt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function kt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Nf(e){return Array.isArray(e)?e:[]}function Br(e){return kt(e==null?void 0:e.status).toLowerCase()||"unknown"}function ks(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function ol(e){const t=Tt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function c$(e){const t=Tt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function gp(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Tt(n);if(!r)return n;const a={};for(const l of Object.keys(r).sort())a[l]=t(r[l]);return a};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function gg(e){if(typeof e=="string")return e.trim();const t=Tt(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return""}function yu(e){const t=gg(e);if(t)return t;if(!Tt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function nv(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const a=kt(e[r]);if(a)return a}const t=Tt(e.context);for(const r of["task","message"]){const a=kt(t==null?void 0:t[r]);if(a)return a}const n=Nf(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const a=Tt(n[r]);if(kt(a==null?void 0:a.role).toLowerCase()!=="user")continue;const l=kt(a==null?void 0:a.content);if(l)return l}return""}function x0(e){const t=Tt(e.result);return Tt(t==null?void 0:t.wait)}function yp(e){return e?kt(e.reason)==="subworkflow"||kt(e.wait_key).startsWith("subworkflow:"):!1}function sv(e,t){return!!(e&&e.runId===t.runId&&kt(e.wait.wait_key)===kt(t.wait.wait_key))}function yg(e){return Tt(e.effect)||{}}function u$(e,t){return kt(e.run_id)||t}function rv(e){return kt(e.ended_at)||kt(e.started_at)||void 0}function iv(e){const t=new Set,n=h=>{const m=kt(h);m&&t.add(m)},r=Tt(e.result);n(r==null?void 0:r.sub_run_id),n(r==null?void 0:r.subRunId),n(r==null?void 0:r.child_run_id);const a=yg(e),l=Tt(a.payload);kt(a.type)==="start_subworkflow"&&(n(l==null?void 0:l.sub_run_id),n(l==null?void 0:l.subRunId),n(l==null?void 0:l.child_run_id));const c=x0(e),u=Tt(c==null?void 0:c.details);n(u==null?void 0:u.sub_run_id),n(u==null?void 0:u.subRunId),n(u==null?void 0:u.child_run_id);const f=kt(c==null?void 0:c.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}class d${constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...tv},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({...tv})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=kt(t);if(this.reset(),!n)return;const r=++this.generation,a=new AbortController;this.controller=a,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[l,c]=await Promise.all([this.transport.getRun(n,a.signal),this.transport.getHistory(n,a.signal)]);if(!this.live(r))return;const u=Tt(l),f=Tt(u==null?void 0:u.waiting),h=Br(u);if(await this.ingestHistory(c,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:u,status:h,loading:!1,...f&&!ks(h)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),u&&this.updateRunState(n,u),f)for(const m of iv({result:{wait:f}}))m!==n&&this.catchUpAndWatch(m,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(l){!a.signal.aborted&&this.live(r)&&this.fail(l)}}async sendCommand(t,n={}){var m,g;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=kt(n.wait_key),a=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!a)throw new Error("No workflow run is loaded");const l=t==="resume"&&r&&((m=this.snapshot.interaction)==null?void 0:m.stepId)||"",c=`${a}\0${t}\0${l}\0${gp(n)}`;let u=this.commandIds.get(c);u||(u=this.newCommandId(),this.commandIds.set(c,u));const f=this.generation,h=(g=this.controller)==null?void 0:g.signal;try{const y=await this.transport.submitCommand({command_id:u,run_id:a,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},h);if(!this.live(f))return y;const w=Tt(y);if(w&&w.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(kt(w.detail)||"Gateway did not accept the command");return this.commandIds.delete(c),a===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(a,f),y}catch(y){throw this.live(f)&&this.fail(y,!1),y}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:kt(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(ks(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||kt(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 a=this.generation;return this.sendCommand("resume",{wait_key:kt(r.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(a))return l;const c=this.occurrenceKey(r);return this.approvedWaits.add(c),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(c)&&(this.grantedToolWaits.add(c),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const r=this.generation,a=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)||a!==this.approvalEpoch||this.toolApprovalStopped||ks(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,a=this.requireInteraction();if(!this.isToolApproval(a))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||ks(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${a.stepId?`:${a.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){gp(t)!==gp(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}:${kt(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&yp(t.wait)&&!yp(n.wait)?n:n&&sv(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Tt(n.waiting);if(!r||Br(n)!=="waiting"||yp(r)||ks(this.snapshot.status)||this.resolvedWaits.has(`${t}:${kt(r.wait_key)}`))return;const a=this.interactionWith({runId:t,wait:r}),l=this.snapshot.interaction;l&&sv(l,a)&&l.stepId===a.stepId||this.set({...this.snapshot,interaction:a})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||ks(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:!!kt(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",a=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!a&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let l=!1;const c=t.messages.map(u=>{var m;const f=u.toolActivity;if(!f||((m=this.toolActivities.get(f.id))==null?void 0:m.status)!=="waiting")return u;const h=a&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===h?u:(l=!0,this.toolMessage({...f,status:h}))});return{...t,toolApprovalGranted:a,...l?{messages:c}:{}}}toolCallsMatch(t,n){var a;const r=Nf((a=Tt(t.wait.details))==null?void 0:a.tool_calls);return r.length>0&&r.every(l=>{var u;const c=kt((u=Tt(l))==null?void 0:u.name);return!!c&&n.includes(c)})}isToolApproval(t){const n=Tt(t.wait.details);return(n==null?void 0:n.mode)==="approval_required"||(n==null?void 0:n.kind)==="tool_approval"}autoApproveCurrentWait(){const t=this.snapshot.interaction;if(!this.coveredByStandingPermission(this.snapshot,t))return;const n={runId:t.runId,waitKey:kt(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 a=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(c=>{if(this.live(a)){if(this.grantedToolWaits.delete(r),l!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(c,!1)}})}emitEvent(t){return this.sendCommand("emit_event",t)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!kt(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 a=Tt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;a&&this.updateRunState(t,a)}catch(a){if(!this.live(n))return;if(ol(a))throw a;this.fail(a,!1)}if(await this.catchUp(t,n),!this.live(n)||ks(Br(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(a){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw a;if(ol(a)){this.fail(a);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(a,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let a=0;a<100&&this.live(n);a+=1){const l=this.cursors.get(t)||0,c=await this.transport.getLedger(t,l,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const u=Tt(c),f=Array.isArray(c)?c:Nf(u==null?void 0:u.items);for(const m of f)this.ingestItem(t,m);const h=Number(u==null?void 0:u.next_after);if(!f.length||!Number.isFinite(h)||h<=l)break;this.cursors.set(t,h)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var a;let r=0;for(;this.live(n)&&!ks(Br(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let c=!1;const u=()=>{!this.live(n)||c||(c=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,l,h=>{this.live(n)&&(u(),this.ingestItem(t,h))},this.controller.signal,u,h=>{this.live(n)&&(u(),this.ingestDelta(t,h))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const f=Tt(await this.transport.getRun(t,(a=this.controller)==null?void 0:a.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),r+=1}catch(c){if(!this.live(n))return;if(r+=1,this.fail(c,!1),ol(c)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(ks(Br(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 a=Tt(t);if(!a)return;const l=Tt(a.session),c=Nf(l==null?void 0:l.turns).map(Tt).filter(h=>!!h);if(await this.hydrateHistoricalSessionRuns(c,n,r),!this.live(r))return;for(const h of c){const m=kt(h==null?void 0:h.run_id)||n;this.ingestSessionTurn(h,n,m!==n&&this.historicalRuns.get(m)||null)}const u=`turn:${n}:user`;if(!this.seenMessages.has(u)){const h=nv(Tt(a.input_data));h&&this.addMessage({id:u,role:"user",content:h})}const f=Tt(a.ledgers);if(f)for(const[h,m]of Object.entries(f)){const g=Tt(m);for(const y of Nf(g==null?void 0:g.items))this.ingestItem(h,y)}}ingestSessionTurn(t,n,r){if(!t)return;const a=kt(t.run_id)||n,l=Tt(t.input_data)||Tt(t.input)||{},c=kt(t.prompt)||nv(l);c&&this.addMessage({id:`turn:${a}:user`,role:"user",content:c,ts:kt(t.created_at)||void 0});const u=this.historicalRunFailures.get(a);if(u){const g=kt(t.answer)||gg(t.output),y=u.missing?"is unavailable because the run no longer exists":"could not be restored",w=g?` Saved reply (not verified as the final result): ${g}`:"";this.addMessage({id:`history:${a}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${y}.${w}`});return}const h=(r&&ks(Br(r))?yu(r.output):"")||(r?kt(t.answer)||gg(t.output):""),m=this.historicalEvidence.get(a);for(const g of(m==null?void 0:m.tools)||[])this.upsertTool(g);h&&this.addRunAssistantMessage(a,{id:`final:${a}`,role:"assistant",content:h,runId:a,statistics:m==null?void 0:m.statistics,ts:kt(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const a=[...new Set(t.map(f=>kt(f.run_id)).filter(f=>f&&f!==n&&!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)))];if(!a.length||!this.live(r))return;let l=0,c=!1;const u=async()=>{var f,h,m;for(;!c&&this.live(r);){const g=a[l++];if(!g)return;try{const y=Tt(await this.transport.getRun(g,(f=this.controller)==null?void 0:f.signal));if(!this.live(r))return;if(y){this.historicalRuns.set(g,y);try{const w=await this.transport.getHistory(g,(h=this.controller)==null?void 0:h.signal);if(!this.live(r))return;this.historicalEvidence.set(g,pp(n$(w)))}catch(w){if(!this.live(r))return;if(ol(w))throw w;this.fail(new Error(`Earlier turn activity could not be restored: ${w instanceof Error?w.message:String(w)}`),!1)}}else this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(y){if(!this.live(r))return;const w=c$(y)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:w,detail:y instanceof Error?y.message:kt((m=Tt(y))==null?void 0:m.detail)||"request failed"}),ol(y)&&(c=!0,this.fail(y))}}};if(await Promise.all(Array.from({length:Math.min(4,a.length)},()=>u())),c&&this.live(r))for(const f of a)!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)&&(this.historicalRuns.set(f,null),this.historicalRunFailures.set(f,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=Tt(n),a=Tt(r==null?void 0:r.record)||r;if(!a)return;const l=u$(a,t),c=Number(r==null?void 0:r.cursor),u=Number.isFinite(c)&&c>0?c:(this.cursors.get(l)||0)+1,f=`${l}:${u}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,u)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:u,record:a,runId:l}]}),this.foldRecord(l,a,f),this.snapshot.messages.some(h=>h.id===`final:${this.rootRunId}`)){const h=pp(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(m=>m.id===`final:${this.rootRunId}`?{...m,statistics:h}:m)})}for(const h of iv(a))h!==l&&this.catchUpAndWatch(h,this.generation)}}foldRecord(t,n,r){var m,g,y;const a=yg(n),l=kt(a.type).toLowerCase(),c=Tt(n.result),u=kt(n.status).toLowerCase(),f=rv(n);if(this.foldStopEvidence(t,n,l,u),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(u)){const w=Date.parse(f||"");(!Number.isFinite(w)||w>=this.displayStatusAt)&&(Number.isFinite(w)&&(this.displayStatusAt=w),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&u==="completed"){const w=yu(c)||yu(Tt(a.payload));w&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:w,ts:f})}if(l==="emit_event"&&u==="completed"){const w=Tt(a.payload)||{},k=Tt(c),b=kt(w.name)||kt(k==null?void 0:k.name),S=w.payload!==void 0?w.payload:k==null?void 0:k.payload;if(["abstract.message","abstractcode.message"].includes(b)){const N=yu(S);if(N){const R=kt((m=Tt(S))==null?void 0:m.level).toLowerCase(),$=R==="error"?"error":["warn","warning"].includes(R)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:N,level:$,ts:f})}}if(["abstract.status","abstractcode.status"].includes(b)){const N=Tt(S),R=N?N.status??N.text??N.value:S,$=Date.parse(f||"");!ks(this.snapshot.status)&&typeof R=="string"&&(!Number.isFinite($)||$>=this.displayStatusAt)&&(Number.isFinite($)&&(this.displayStatusAt=$),this.set({...this.snapshot,displayStatus:R.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(b)){const N=yu(S);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:f})}}const h=x0(n);if(u==="waiting"&&h&&!ks(this.snapshot.status)&&!ks(Br(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${kt(h.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:h,...kt(n.step_id)?{stepId:kt(n.step_id)}:{}})})),l==="tool_calls")for(const w of w0(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(w);if(l==="resume"&&(c==null?void 0:c.resumed)===!0){const w=kt((g=Tt(a.payload))==null?void 0:g.wait_key);w&&this.resolvedWaits.add(`${t}:${w}`),((y=this.snapshot.interaction)==null?void 0:y.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,a){let l=!1;if(r==="llm_call"){const c=kt(n.step_id);if(c){const u=`${t}:${c}`;a==="started"?(this.openLlmSteps.add(u),l=!0):["completed","failed","cancelled","waiting"].includes(a)&&(l=this.openLlmSteps.delete(u)||l),["completed","failed","cancelled"].includes(a)&&this.closeLiveReply(u)}}if(r==="emit_event"&&a==="completed"){const c=Tt(yg(n).payload)||{},u=Tt(n.result),f=kt(c.name)||kt(u==null?void 0:u.name),h=Tt(c.payload!==void 0?c.payload:u==null?void 0:u.payload);f==="abstract.status"&&kt(h==null?void 0:h.killed_by)==="kill_switch"&&(this.forcedStop=h,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:kt(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,a=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(r),!this.live(t))return;const l=[this.rootRunId,...[...this.watchedRuns].filter(u=>u!==this.rootRunId)];let c=!1;for(const u of l)try{await this.catchUp(u,t)}catch(f){c=!0,this.live(t)&&(this.fail(f,!1),a=this.snapshot.error)}!c&&a&&this.snapshot.error===a&&(this.set({...this.snapshot,error:null}),a=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=kt(t.id)||`${t.role}:${t.content}:${t.ts||""}`;this.seenMessages.has(n)||(this.seenMessages.add(n),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...t,id:n}]}))}toolMessage(t){return{id:`tool:${t.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:t.runId,toolActivity:t,content:JSON.stringify({tool:t.name,status:t.status,arguments:t.arguments,output:t.output,error:t.error},null,2),ts:t.endedAt||t.startedAt}}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(l=>l.id===n.id);if(r<0){this.addMessage(n);return}const a=[...this.snapshot.messages];a[r]=n,this.set({...this.snapshot,messages:a})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,a=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===a||String(l.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=h0(n)}catch(f){this.fail(f,!1);return}const a=`${r.run_id}:${r.call_id}`;if(f0(r)){if(r.reason==="unavailable"){this.noteStreamUnavailable(r);return}if(r.reason==="cancelled"&&r.detail==="reinvoked"){this.closeLiveReply(a,"restarted");return}this.closeLiveReply(a,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(a)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(a)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},c=r.channel==="reasoning"?"reasoning":"text",u=l.seq[r.channel];if(r.snapshot){if(r.seq<u)return;l[c]=r.text}else{if(r.seq<=u)return;l[c]+=r.text}l.seq[r.channel]=r.seq,l.via=t,this.liveReplies.set(a,l),this.liveDirty.add(a),this.scheduleLiveRender()}runEnded(t){return ks(Br(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 a=this.liveMessage(r),l=t.findIndex(c=>c.id===a.id);l<0?t.push(a):t[l]=a,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 a=`live:${r.runId}:${r.callId}`,l=this.snapshot.messages.findIndex(u=>u.id===a);if(l<0)return;const c=[...this.snapshot.messages];if(n==="restarted"){const u=this.restartNote(t);this.seenMessages.add(String(u.id)),c[l]=u}else if(n){const u=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(u),c[l]={id:u,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else c.splice(l,1);this.set({...this.snapshot,messages:c})}restartNote(t){const n=t.slice(0,t.indexOf(":"));return{id:`live-end:${t}`,role:"system",level:"info",title:"Reply",runId:n,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(t){const n=`${t.run_id}:${t.call_id}`;this.closeLiveReply(n),this.addMessage({id:`stream-unavailable:${t.run_id}:${t.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:t.run_id,content:uE(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 a of[...this.liveReplies.values()])this.closeLiveReply(`${a.runId}:${a.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const a of[...this.closedLiveCalls])a.startsWith(`${t}:`)&&this.closedLiveCalls.delete(a);for(const a of[...this.shownLiveCalls])a.startsWith(`${t}:`)&&this.shownLiveCalls.delete(a)}dropLiveRepliesVia(t){const n=new Set;for(const[r,a]of this.liveReplies)a.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${a.runId}:${a.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,a,l;ol(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(a=(r=this.options).onAuthError)==null||a.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:kt((l=Tt(t))==null?void 0:l.detail)||String(t),...ol(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const n=t.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n,a=>a.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),ks(Br(n))&&this.endLiveRepliesOfRun(t,Br(n)),t!==this.rootRunId){ks(Br(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=Br(n),a=ks(r);if(a){const c=yu(n.output);c&&this.upsertFinal(t,c,rv(n))}this.set({...this.snapshot,run:n,status:r,...a?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),a||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const a=`final:${t}`;this.seenMessages.add(a);const l={id:a,role:"assistant",content:n,ts:r,runId:t,statistics:pp(this.snapshot.records).statistics},c=this.snapshot.messages.findIndex(f=>f.id===a||String(f.id||"").startsWith(`answer:${t}:`)&&f.content===n);if(c<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,l]});return}const u=[...this.snapshot.messages];u[c]=l,this.set({...this.snapshot,messages:u})}async refreshRunState(t,n){var r;try{const a=Tt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));a&&this.live(n)&&this.updateRunState(t,a)}catch(a){this.live(n)&&this.fail(a,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!ks(Br(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||ks(Br(this.runStates.get(t)||null)))return;try{const a=Tt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));a&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,a)}catch(a){if(!this.live(n))return;if(ol(a)){this.fail(a);return}this.fail(a,!1)}}}waitForRetry(t){var a;const n=(a=this.controller)==null?void 0:a.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(l=>{const c=setTimeout(f,t),u=()=>{clearTimeout(c),f()};function f(){r.removeEventListener("abort",u),l()}r.addEventListener("abort",u,{once:!0})})}}function f$(e){const t=_.useMemo(()=>new d$(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(a=>t.subscribe(a),()=>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 sc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ur(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function av(e){return["session","workflow","run","global"].includes(e)?e:null}function cl(e){return{scope:ur(e==null?void 0:e.scope).toLowerCase(),name:ur(e==null?void 0:e.name)||ur(e==null?void 0:e.event_name),scopeId:ur(e==null?void 0:e.scope_id)||ur(e==null?void 0:e.scopeId),sessionId:ur(e==null?void 0:e.session_id)||ur(e==null?void 0:e.sessionId),workflowId:ur(e==null?void 0:e.workflow_id)||ur(e==null?void 0:e.workflowId),runId:ur(e==null?void 0:e.run_id)||ur(e==null?void 0:e.runId)}}function h$(e,t){const n=e.wait,r=ur(n.wait_key),a=[cl(n),cl(sc(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const c=l.record,u=sc(c.result),f=sc(u==null?void 0:u.wait),h=sc(c.effect),m=sc(h==null?void 0:h.payload);ur(f==null?void 0:f.wait_key)!==r&&ur(m==null?void 0:m.wait_key)!==r||a.push(cl(c),cl(m),cl(sc(m==null?void 0:m.details)),cl(f),cl(sc(f==null?void 0:f.details)))}return a}function wp(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function b0(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function m$(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const a=e.slice(r.length);return a?b0(t,n,a):null}function _$(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=ur(e.wait.wait_key),a=/^evt:(session|workflow|run|global):/.exec(r);if(!a)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=av(a[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const c=h$(e,Array.isArray(t)?t:[]),u=new Map;for(const y of c){const w=av(y.scope);if(!w||!y.name)continue;if(w!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const k=`evt:${w}:`,b=`:${y.name}`;if(!r.startsWith(k)||!r.endsWith(b)||r.length<=k.length+b.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const S=r.slice(k.length,-b.length),N=wp(w,y);if(N&&N!==S)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const R=b0(w,S,y.name);u.set(`${R.scope}\0${R.scopeId}\0${R.name}`,R)}if(u.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(u.size===1)return{target:[...u.values()][0]};const f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const y of c){const w=wp(l,y);w&&f.add(w)}if(ur(n==null?void 0:n.run_id)===e.runId){const y=cl(n||null),w=wp(l,y);w&&f.add(w)}const m=[...f].map(y=>m$(r,l,y)).filter(y=>!!y),g=new Map(m.map(y=>[`${y.scope}\0${y.scopeId}\0${y.name}`,y]));return g.size===1?{target:[...g.values()][0]}:g.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}function k0(e){return s.jsx(s0,{text:e,images:"link"})}const p$={trigger:"Trigger",answer:"Automation"};function j0(e,t){return s.jsx(dy,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:p$[e.kind],runId:e.runId},images:"link"})}const g$={renderText:k0,renderTurn:j0};function y$(e){const{fetchGateway:t,messageProps:n,...r}=e,a=r.onOpenResource??(t?l=>IE(t,l.url,{name:l.name}):void 0);return s.jsx(A2,{...r,onOpenResource:a,...g$,renderTurn:l=>j0(l,n)})}function w$(e,t,n={}){if(!e)return null;const r=e.wait,a=`${e.runId}:${r.wait_key}:${e.stepId||""}`,l=r.details||{};if(l.mode==="approval_required"||l.kind==="tool_approval"){const u=Array.isArray(l.tool_calls)?l.tool_calls:[],f={runId:e.runId,waitKey:String(r.wait_key||""),stepId:e.stepId},h=[...new Set(u.map(g=>String((g==null?void 0:g.name)||"tool")))],m=n.onPermissionsAll;return{id:a,kind:"tool-approval",title:`${u.length||"Requested"} ${u.length===1?"action needs":"actions need"} permission`,toolName:h.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:s.jsxs("div",{className:"pc-approval-summary",children:[s.jsx(o0,{tools:u.map((g,y)=>({id:String((g==null?void 0:g.call_id)||(g==null?void 0:g.id)||y),runId:e.runId,name:(g==null?void 0:g.name)||"Tool",arguments:g==null?void 0:g.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(Is,{value:u.length?u:l})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:m?"Allow all enabled tools":void 0,approveAllDescription:m?"Sets permissions: all for this Gateway account, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.":void 0,onApproveAll:m?async()=>{await t.approveWithPolicyChange(f,()=>{m()})}:void 0,onApprove:async()=>{await t.approve(!0,f)},onDeny:async()=>{await t.approve(!1,f)}}}if(r.reason==="user"||r.reason==="ask_user")return{id:a,kind:"ask-user",title:"A question for you",prompt:String(r.prompt||l.prompt||"How would you like to continue?"),allowFreeText:r.allow_free_text!==!1,choices:(Array.isArray(r.choices)?r.choices:[]).map(u=>typeof u=="object"&&u!==null?{id:String(u.value??u.id??u.label),label:String(u.label??u.text??u.value??u.id),description:u.description}:{id:String(u),label:String(u)}),onSubmit:async u=>{await t.resume(u)}};const c=String(r.wait_key||"");if(r.reason==="event"||c.startsWith("evt:")){const u=_$(e,n.records||[],n.currentRun??null),f=u.target,h=(f==null?void 0:f.name)||"";return{id:a,kind:"event-wait",title:f?"Waiting for an event":"Event routing unavailable",eventName:h,prompt:String(r.prompt||`This workflow will continue when “${h||"its trigger"}” arrives.`),description:f?"You can also send the expected event here.":`This event cannot be sent safely. ${u.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async m=>{if(!f)throw new Error(u.error);const g=JSON.parse(m||"{}"),y={name:f.name,scope:f.scope,payload:g};f.scope==="session"?y.session_id=f.scopeId:f.scope==="workflow"?y.workflow_id=f.scopeId:f.scope==="run"&&(y.run_id=f.scopeId),await t.emitEvent(y)}}}return null}const v$={app:"observer",name:"AbstractObserver"},x$=["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 b$(e){const t=_.useRef(e.gateway);t.current=e.gateway;const n=(r,a)=>t.current.fetch_gateway(r,a);return s.jsx(ZE,{open:e.open,onClose:e.onClose,source:v$,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:x$})}function k$(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 j$(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 S$(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const N$='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function C$(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function E$(e){const[t,n]=_.useReducer(k$,!1),r=_.useRef(null),a=_.useRef(null),l=_.useRef(!1);return _.useEffect(()=>{n({type:"page_change"})},[e.page]),_.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),_.useEffect(()=>{var c;if(t){l.current=!0;const u=a.current,f=(u==null?void 0:u.querySelector(".shell_nav_item.active"))||(u==null?void 0:u.querySelector(".shell_nav_item"));f==null||f.focus();const h=m=>{if(m.key==="Escape"){n({type:"escape",default_prevented:m.defaultPrevented,other_modal_open:C$(a.current)});return}if(m.key!=="Tab"||!a.current)return;const g=Array.from(a.current.querySelectorAll(N$)).filter(w=>w.offsetParent!==null||w===document.activeElement),y=S$(g.length,g.indexOf(document.activeElement),m.shiftKey);y>=0&&(m.preventDefault(),g[y].focus())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)}l.current&&(l.current=!1,(c=r.current)==null||c.focus())},[t]),{open:t,set_open:c=>n({type:c?"open":"close"}),toggle_ref:r,sidebar_ref:a,attrs:j$(e.is_drawer,t)}}function $$(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function wm(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function A$(e){const t=wm(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=wm(e.replayed_messages),r=wm(e.dropped_tokens),a=wm(e.max_tokens),l=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${r?` (~${r.toLocaleString("en-US")} tokens)`:""}.`,`The model read the newest ${n.toLocaleString("en-US")} message${n===1?"":"s"}`+(a?` (history window: the most recent ${a.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&l.push("Your latest message alone is larger than the window; it was sent whole."),l.join(" ")}function T$(e){const t=A$(e.history);return t?s.jsx(dy,{message:{role:"system",level:"info",title:"History",content:t}}):null}const M$="api/local/reveal",R$="sw.js",wg="#run/";function L$(e){return`${wg}${encodeURIComponent(String(e||"").trim())}`}function S0(e){const t=String(e||"");if(!t.startsWith(wg))return"";const n=t.slice(wg.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function I$(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function O$(e){const t=S0(e.hash);if(t)return t;const n=c=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c),r=c=>{const u=c.split("/").filter(Boolean);return u.length?u[u.length-1].trim():""},a=r(String(e.hash||"").replace(/^#/,""));if(n(a))return a;const l=r(String(e.pathname||""));return n(l)?l:""}const P$={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"},D$=new Set(["wait","resume","memory","model","node"]),F$=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),z$={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 B$(e){const t=String(e||"").trim();return t?P$[t]||"other":"node"}function U$(e,t,n){return n?!1:e==="event"?F$.has(String(t||"").trim()):D$.has(e)}const W$=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 q$(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,a=new Uint8Array(r);a.set(t),a[t.length]=128;const l=new DataView(a.buffer);l.setUint32(r-8,Math.floor(n/4294967296)),l.setUint32(r-4,n>>>0);const c=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),u=new Uint32Array(64);for(let f=0;f<r;f+=64){for(let N=0;N<16;N++)u[N]=l.getUint32(f+N*4);for(let N=16;N<64;N++){const R=u[N-15],$=u[N-2],A=(R>>>7|R<<25)^(R>>>18|R<<14)^R>>>3,W=($>>>17|$<<15)^($>>>19|$<<13)^$>>>10;u[N]=u[N-16]+A+u[N-7]+W>>>0}let[h,m,g,y,w,k,b,S]=c;for(let N=0;N<64;N++){const R=(w>>>6|w<<26)^(w>>>11|w<<21)^(w>>>25|w<<7),$=w&k^~w&b,A=S+R+$+W$[N]+u[N]>>>0,W=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),z=h&m^h&g^m&g,H=W+z>>>0;S=b,b=k,k=w,w=y+A>>>0,y=g,g=m,m=h,h=A+H>>>0}c[0]=c[0]+h>>>0,c[1]=c[1]+m>>>0,c[2]=c[2]+g>>>0,c[3]=c[3]+y>>>0,c[4]=c[4]+w>>>0,c[5]=c[5]+k>>>0,c[6]=c[6]+b>>>0,c[7]=c[7]+S>>>0}return Array.from(c,f=>f.toString(16).padStart(8,"0")).join("")}const vg="$slim";function H$(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[vg]&&typeof e[vg]=="object")}function V$(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||""),a=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&a&&typeof a=="object"&&!t.has(r)&&t.set(r,a)}return t}function G$(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 a of e.messages)a&&typeof a=="object"&&n.push({...a})}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 K$(e,t){const n=e&&e[vg];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 a;if(n.kind==="started_payload_field"){const c=String(n.field||"");if(!(c in r))return{state:"missing",reason:`the started record has no "${c}" field`};a=r[c]}else if(n.kind==="started_messages_layout"){if(a=Array.isArray(n.layout)?G$(r,n.layout.map(String)):null,!a)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(a))return{state:"missing",reason:"appendix on a non-list value"};const c=a.map(f=>f&&typeof f=="object"?{...f}:f),u=[...n.appendix].sort((f,h)=>Number((f==null?void 0:f.at)??-1)-Number((h==null?void 0:h.at)??-1));for(const f of u){const h=Number(f==null?void 0:f.at);if(!Number.isInteger(h)||h<0||h>c.length)return{state:"missing",reason:"appendix position out of range"};c.splice(h,0,f.item)}a=c}return q$(JSON.stringify(a))!==String(n.sha256||"")?{state:"unverified",value:a,reason:"checksum differs from the record"}:{state:"resolved",value:a}}function Y$(e,t){const n=[],r=[],a=(l,c,u)=>{if(u>14)return l;if(H$(l)){const f=K$(l,t);return f.state==="missing"?(n.push({path:c,reason:f.reason}),l):(f.state==="unverified"&&r.push({path:c,reason:f.reason}),f.value)}if(Array.isArray(l)){let f=null;return l.forEach((h,m)=>{const g=a(h,`${c}[${m}]`,u+1);g!==h&&((f??(f=[...l]))[m]=g)}),f??l}if(l&&typeof l=="object"){let f=null;for(const h of Object.keys(l)){const m=a(l[h],c?`${c}.${h}`:h,u+1);m!==l[h]&&((f??(f={...l}))[h]=m)}return f??l}return l};return{value:a(e,"",0),unresolved:n,unverified:r}}function ov(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function N0(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function J$(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&N0(e).some(n=>n&&n.success===!1):!1}function C0(e,t){var h,m,g,y,w,k;const n=String(t||"").trim(),r=(e||[]).filter(b=>b&&b.record&&String(b.run_id||b.record.run_id||"").trim()===n).sort((b,S)=>(b.cursor||0)-(S.cursor||0)),a=V$(r.map(b=>b.record)),l=new Map,c=[];for(const b of r){const S=b.record,R=String(S.step_id||"")||`cursor:${b.cursor}`;let $=l.get(R);$||($={cursor:b.cursor,started:null,latest:S,latest_cursor:b.cursor},l.set(R,$),c.push(R)),String(S.status||"")==="started"&&!$.started&&($.started=S),b.cursor>=$.latest_cursor&&($.latest=S,$.latest_cursor=b.cursor)}let u=0;const f=[];for(const b of c){const S=l.get(b),N=Y$(S.latest,a),R=N.value,$=String(((h=R==null?void 0:R.effect)==null?void 0:h.type)||((g=(m=S.started)==null?void 0:m.effect)==null?void 0:g.type)||"").trim(),A=B$($),W=A==="event"?String(((w=(y=R==null?void 0:R.effect)==null?void 0:y.payload)==null?void 0:w.name)||"").trim():"";A==="llm_call"&&(u+=1);const z=J$(R,A),H=String(((k=S.started)==null?void 0:k.started_at)||(R==null?void 0:R.started_at)||""),G=String((R==null?void 0:R.ended_at)||""),re=ov(H),te=ov(G);f.push({id:`${n}:${b}`,run_id:n,step_id:String((R==null?void 0:R.step_id)||""),node_id:String((R==null?void 0:R.node_id)||""),kind:A,effect_type:$,event_name:W,status:String((R==null?void 0:R.status)||""),cursor:S.cursor,started_at:H,ended_at:G,duration_ms:re!==null&&te!==null?Math.max(0,te-re):null,started:S.started,record:R,failed:z,housekeeping:U$(A,W,z),cycle:u,unresolved:N.unresolved,unverified:N.unverified})}return f}function X$(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 Z$={view:"cycles",only:"all",all_steps:!1,q:""};function Q$(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(a=>!(t.only==="llm"&&a.kind!=="llm_call"||t.only==="tools"&&a.kind!=="tool"||t.only==="failed"&&!a.failed||t.only==="all"&&!t.all_steps&&a.housekeeping||r&&!n(a).includes(r)))}const eA=["all","llm","tools","failed"];function lv(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...Z$};const r=new URLSearchParams(t.slice(n+1)),a=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:eA.includes(a)?a:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function tA(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 a=r.toString();return a?`${n}?${a}`:n}function Ru(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 E0(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function $0(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:E0(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function cv(e){const t={role:String((e==null?void 0:e.role)||"?"),content:Ru(e==null?void 0:e.content)},n=$0(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 uv(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const nA={"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 py(e){var w,k,b,S,N,R;const t=e.record||{},n=((k=(w=e.started)==null?void 0:w.effect)!=null&&k.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(b=t==null?void 0:t.effect)==null?void 0:b.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},a=r.usage||r.token_usage||{},l=[],c=e.unverified.map($=>`${$.path}: ${$.reason}`);for(const $ of e.unresolved){const A=nA[$.path];A&&l.push(`${A}: ${$.reason}`)}const u=(N=(S=r==null?void 0:r.metadata)==null?void 0:S._provider_request)==null?void 0:N.payload;let f="",h=[],m="";if(u&&Array.isArray(u.messages)){m="sent";for(const $ of u.messages)String(($==null?void 0:$.role)||"")==="system"&&!h.length?f+=(f?`
|
|
85
|
-
|
|
86
|
-
`:"")+Ru($.content):h.push(cv($))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(m="payload",h=(Array.isArray(n.messages)?n.messages:[]).map(cv),typeof n.prompt=="string"&&n.prompt.trim()&&h.push({role:"user",content:n.prompt}));!f&&typeof n.system_prompt=="string"&&(f=n.system_prompt);const y=(Array.isArray(n.tools)?n.tools:Array.isArray(u==null?void 0:u.tools)?u.tools:[]).filter($=>$&&typeof $=="object").map($=>{const A=$.function&&typeof $.function=="object"?$.function:$;return{name:String(A.name||"?"),description:String(A.description||""),schema:A.parameters??A.input_schema??null}});return{provider:String(n.provider||r.provider||""),model:String(n.model||r.model||""),tokens_in:uv(a.prompt_tokens??a.input_tokens),tokens_out:uv(a.completion_tokens??a.output_tokens),system:f,messages:h,messages_source:m,tools:y,response:Ru(r.content??r.response??""),tool_calls:$0(r.tool_calls),reasoning:Ru(r.reasoning??((R=r==null?void 0:r.metadata)==null?void 0:R.reasoning)??""),missing:l,unverified:c}}function gy(e){var a,l,c,u;const t=((l=(a=e.record)==null?void 0:a.effect)==null?void 0:l.payload)||((u=(c=e.started)==null?void 0:c.effect)==null?void 0:u.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(f=>{var h,m;return{name:String((f==null?void 0:f.name)||((h=f==null?void 0:f.function)==null?void 0:h.name)||"?"),arguments:E0((f==null?void 0:f.arguments)??((m=f==null?void 0:f.function)==null?void 0:m.arguments)),call_id:String((f==null?void 0:f.call_id)||(f==null?void 0:f.id)||"")}}),r=N0(e.record).map(f=>({name:String((f==null?void 0:f.name)||"?"),success:typeof(f==null?void 0:f.success)=="boolean"?f.success:null,output:(f==null?void 0:f.output)==null?"":Ru(f.output),error:(f==null?void 0:f.error)==null?"":Ru(f.error),call_id:String((f==null?void 0:f.call_id)||""),raw:f}));return{calls:n,results:r}}function sA(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 A0(e){var r,a,l;const t=(r=e==null?void 0:e.result)==null?void 0:r.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((a=t==null?void 0:t.details)==null?void 0:a.sub_run_id)||((l=e==null?void 0:e.result)==null?void 0:l.sub_run_id)||n||"").trim()}function T0(e){var n,r,a,l,c,u,f,h,m,g,y;const t=e.record||{};switch(e.kind){case"llm_call":{const w=py(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=gy(e).calls;if(!w.length)return"";const k=`${w[0].name}(${sA(w[0].arguments)})`;return w.length>1?`${k} +${w.length-1} more`:k}case"event":return e.event_name;case"subflow":{const w=A0(t);return[String(((r=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:r.workflow_id)||""),w].filter(Boolean).join(" · ")}case"wait":case"resume":return String(((l=(a=t==null?void 0:t.result)==null?void 0:a.wait)==null?void 0:l.reason)||((u=(c=t==null?void 0:t.effect)==null?void 0:c.payload)==null?void 0:u.reason)||"");case"ask":return String(((h=(f=t==null?void 0:t.effect)==null?void 0:f.payload)==null?void 0:h.prompt)||"");case"answer":return String(((g=(m=t==null?void 0:t.effect)==null?void 0:m.payload)==null?void 0:g.message)||((y=t==null?void 0:t.result)==null?void 0:y.message)||"");default:return e.effect_type}}function M0(e){return e.kind==="llm_call"?py(e).model:""}function rA(e,t){var r,a;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,T0(e),M0(e)];try{n.push(JSON.stringify(((a=(r=e.started)==null?void 0:r.effect)==null?void 0:a.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
|
|
87
|
-
`).toLowerCase()}function iA(e){var r,a;const t=Array.from(new Set((e||[]).map(l=>{var c;return String(l.run_id||((c=l.record)==null?void 0:c.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0};for(const l of t)for(const c of C0(e,l))if(c.kind==="llm_call"){n.llm_calls+=1;const u=((a=(r=c.record)==null?void 0:r.result)==null?void 0:a.usage)||{};n.tokens+=Number(u.total_tokens??Number(u.prompt_tokens??u.input_tokens??0)+Number(u.completion_tokens??u.output_tokens??0))||0}else if(c.kind==="tool"){const u=gy(c);n.tool_calls+=Math.max(u.calls.length,u.results.length),n.tool_failures+=u.results.filter(f=>f.success===!1).length}return n}function aA(e){const t=[];return e.llm_calls&&t.push(`${e.llm_calls} LLM call${e.llm_calls===1?"":"s"}`),e.tokens&&t.push(`${e.tokens.toLocaleString("en-US")} tokens`),e.tool_calls&&t.push(`${e.tool_calls} tool call${e.tool_calls===1?"":"s"}${e.tool_failures?`, ${e.tool_failures} failed`:""}`),t.join(" · ")}function Rt(){return new Date().toISOString()}function oA(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function dr(e,t){try{const n=JSON.stringify(e);return typeof n!="string"?String(e):n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}catch{const n=String(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}}function At(e,t){const n=typeof(t==null?void 0:t.max_chars)=="number"?t.max_chars:360,r=typeof(t==null?void 0:t.max_lines)=="number"?t.max_lines:2,l=String(e||"").replace(/\r\n/g,`
|
|
88
|
-
`).replace(/\r/g,`
|
|
89
|
-
`).split(`
|
|
90
|
-
`),c=l.slice(0,Math.max(1,r)).join(`
|
|
91
|
-
`),u=l.length>r,f=c.length>n?`${c.slice(0,Math.max(0,n-1))}…`:c;return u&&f===c?`${c}…`:f}function sn(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function dv(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function qn(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;const n=t.replace(/(\.\d{3})\d+/,"$1"),r=Date.parse(n);return Number.isFinite(r)?r:null}function lA(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),a=Math.floor(r/60),l=Math.floor(a/24);return n<60?"just now":r<60?`${r}m ago`:a<24?`${a}h ago`:l<=3?`${l}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function mc(e){const t=qn(e);return t===null?"—":lA(t)}function fv(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),a=Math.floor(r/24),l=t%60,c=n%60,u=r%24;return a>0?`${a}d ${u}h`:r>0?`${r}h ${c}m`:n>0?`${n}m ${l}s`:`${t}s`}function yy(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),a=r%60,l=Math.floor(r/60),c=l%24,u=Math.floor(l/24);return u>0?`${u}d ${c}h`:l>0?`${l}h ${a}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function zu(e){const t=qn(e);return t===null?"—":new Date(t).toLocaleString()}function gn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function cA(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function Oa(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Bu(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Au(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function uA(e){const t=String((e==null?void 0:e.status)||"").trim();return Oa(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function wy(e,t=Date.now()){const n=qn(Au(e));if(n===null)return-1;const r=qn(uA(e));return Math.max(0,(r!==null?r:t)-n)}function yc(e,t=Date.now()){return yy(wy(e,t))}function dA(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 fA(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 Zm(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 wc(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 hA={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function bi(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function La(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 vp(e){return`${e.toLocaleString("en-US")} chars`}function vy(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(La,{title:"Raw JSON",copy:bi(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function mA(e){const t=py(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(La,{title:"System",meta:vp(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(La,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:bi(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,a)=>{var l;return s.jsxs("li",{className:`rs_msg rs_msg_${r.role}`,children:[s.jsxs("span",{className:"rs_role",children:[r.role,r.name?` · ${r.name}`:""]}),r.content?s.jsx("pre",{className:"rs_text",children:r.content}):null,(l=r.tool_calls)==null?void 0:l.map((c,u)=>s.jsx("pre",{className:"rs_text mono",children:`${c.name}(${bi(c.arguments)})`},u))]},a)})})}):null,t.tools.length?s.jsx(La,{title:"Tools offered",meta:String(t.tools.length),copy:bi(t.tools),on_copy:e.on_copy,children:s.jsx("ul",{className:"rs_tools",children:t.tools.map(r=>s.jsxs("li",{children:[s.jsx("strong",{className:"mono",children:r.name}),r.description?s.jsxs("span",{children:[" — ",r.description]}):null]},r.name))})}):null,s.jsxs(La,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?vp(t.response.length):"empty",copy:t.response||bi(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(Si,{text:t.response})}):null,t.tool_calls.map((r,a)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${bi(r.arguments)})`},a)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(La,{title:"Reasoning",meta:vp(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(vy,{step:e.step,on_copy:e.on_copy})]})}function _A(e){const t=gy(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(La,{title:"Calls",meta:String(t.calls.length),copy:bi(t.calls),open:!0,on_copy:e.on_copy,children:t.calls.map((n,r)=>s.jsx("pre",{className:"rs_text mono",children:`${n.name}(${bi(n.arguments)})`},r))}),s.jsxs(La,{title:"Results",meta:String(t.results.length),copy:bi(t.results),open:!0,on_copy:e.on_copy,children:[t.results.length?null:s.jsx("p",{className:"rs_muted",children:"No result recorded yet."}),s.jsx("ol",{className:"rs_messages",children:t.results.map((n,r)=>s.jsxs("li",{className:`rs_msg ${n.success===!1?"rs_msg_failed":""}`,children:[s.jsxs("span",{className:"rs_role",children:[n.name," · ",n.success===!1?"failed":n.success?"ok":"unknown"]}),s.jsx(r0,{sandbox:pg(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(vy,{step:e.step,on_copy:e.on_copy})]})}function pA(e){var a,l,c;const t=e.step.record||{},n=((l=(a=e.step.started)==null?void 0:a.effect)==null?void 0:l.payload)??((c=t==null?void 0:t.effect)==null?void 0:c.payload),r=e.step.kind==="subflow"?A0(t):"";return s.jsxs(s.Fragment,{children:[r&&e.on_open_run?s.jsxs("p",{className:"rs_line_actions",children:[s.jsx("span",{className:"mono",children:r}),s.jsx("button",{type:"button",className:"btn btn_sm",onClick:()=>{var u;return(u=e.on_open_run)==null?void 0:u.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:bi(t.error)}):null,n!=null?s.jsx(La,{title:"Payload",copy:bi(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(La,{title:"Result",copy:bi(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(Is,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(vy,{step:e.step,on_copy:e.on_copy})]})}function gA(e){const t=e.step,n=T0(t),r=M0(t),a=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:z$[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 ${wc(a)}`,children:a||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?yy(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(mA,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(_A,{step:t,on_copy:e.on_copy}):s.jsx(pA,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function yA(e){const{state:t}=e,n=_.useMemo(()=>C0(e.items,e.run_id),[e.items,e.run_id]),[r,a]=_.useState({}),l=k=>e.node_label(k.run_id,k.node_id),c=_.useMemo(()=>new Map,[n]),f=Q$(n,t,k=>{let b=c.get(k.id);return b===void 0&&(b=rA(k,l(k)),c.set(k.id,b)),b}),h=n.some(k=>k.kind==="llm_call"),m=n.reduce((k,b)=>b.kind==="llm_call"?k+1:k,0),g=n.length-f.length,y=k=>e.on_state({...t,...k}),w=k=>s.jsx(gA,{step:k,node_label:l(k),open:r[k.id]===!0,on_toggle:()=>a(b=>({...b,[k.id]:!b[k.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},k.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[f.length," of ",n.length," steps",h?` · ${m} cycle${m===1?"":"s"}`:"",g&&t.only==="all"&&!t.all_steps&&!t.q?` · ${g} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:k=>e.on_select_run(String(k.target.value||"")),"aria-label":"Run",children:e.run_options.map(k=>s.jsxs("option",{value:k,children:[sn(k,14),e.run_llm_counts[k]?` · ${e.run_llm_counts[k]} LLM`:""]},k))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(k=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===k,className:`seg_btn ${t.view===k?"active":""}`,onClick:()=>y({view:k}),children:k==="cycles"?"Cycles":"Steps"},k))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(k=>s.jsx("button",{type:"button",role:"radio","data-filter":k,"aria-checked":t.only===k,className:`seg_btn ${t.only===k?"active":""}`,onClick:()=>y({only:k}),children:hA[k]},k))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:k=>y({q:k.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(Ni,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:k=>y({all_steps:k})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!f.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&h?X$(f).map(k=>s.jsxs("section",{className:"rs_cycle","data-cycle":k.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:k.cycle===0?"Before the first call":`Cycle ${k.cycle}`}),k.steps.map(w)]},k.cycle)):f.map(w)]})}function wA(e){const[t,n]=_.useState(!1),r=e.answer.length>hv,a=t||!r?e.answer:`${e.answer.slice(0,hv).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 ${wc(e.status)}`,children:e.status||"unknown"}),[e.duration,e.facts].filter(Boolean).join(" · ")]}),e.error?s.jsx("p",{className:"rs_text rs_error",children:e.error}):null,!e.error&&e.answer?s.jsxs("div",{className:"rs_markdown rs_outcome_text",children:[s.jsx(Si,{text:a}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(l=>!l),children:t?"Less":"More"}):null]}):null,s.jsxs("div",{className:"rs_outcome_actions",children:[e.waiting_for_user&&e.on_answer_wait?s.jsx("button",{type:"button",className:"btn primary",onClick:e.on_answer_wait,children:"Answer"}):null,e.speak,s.jsx("button",{type:"button",className:"btn",onClick:e.on_open_artifacts,title:"This run's artifacts in System",children:"Artifacts"}),e.workspace_root?s.jsx("button",{type:"button",className:"btn",onClick:e.on_reveal_workspace,title:e.workspace_root,children:"Folder"}):null]})]})}const hv=600,mv="—";function wu(e){return typeof e=="string"&&e?e:void 0}function vA(e){return e.endsWith("+00:00")||e.endsWith("Z")}function xp(e){if(!e||typeof e!="object")return e;const t=e,n={...e},r=wu(t.next_run_at)??wu(t.next_fire_at);let a=wu(t.next_run_local),l=wu(t.time_zone)??"";return!a&&!l&&r&&vA(r)&&(a=r,l="UTC"),r?n.next_run_at=r:delete n.next_run_at,a?n.next_run_local=a:delete n.next_run_local,n.time_zone=l,n.schedule_rule_text=wu(t.schedule_rule_text)??mv,n.schedule_text=wu(t.schedule_text)??mv,n}function xA(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(xp)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:xp(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:xp(n.summary)}:n}}}const bA="@default:",Lu="abstractcode.agent.v1";function _v(e,t){var n;return e?e.kind==="default"?e.interface===Lu?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function kA(e,t){return e==="@default"?{kind:"default",interface:Lu}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function jA(e){return e?e.kind==="default"?`${bA}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function SA(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 NA(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const a=r.trim();a&&(t[n]=a)}else r!==void 0&&(t[n]=r);return t}const CA={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 EA(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 $A="#launch/automate";function AA(e){const t=S0(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 xg={when:"every",calendar:Rb,email:mb,notify_email:!1,email_recipients:$f,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(Rf),tool_approval:"auto",title:"",start_at:"",count:"",until:""},pv={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."},R0=["use_context"],TA="This choice also sets the workflow's Use Context input: the workflow always reads the history the automation gives it.";function xy(e,t,n=!1){const r=e.when==="every",a=e.when==="daily"||e.when==="weekly"||e.when==="monthly";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:a?oy(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||a)&&e.count.trim()?{count:Number(e.count)}:{},...(r||a)&&e.until?{until:e.until}:{}}}function MA(e){if(e.when==="email")return null;const t=xy(e,"preview");return IN(t.when)?Ab(t).trigger:null}function RA(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:[Vt.not_set_up]};const n=NA(t.input_data),r=typeof n.prompt=="string"?n.prompt:"";delete n.prompt;for(const l of R0)delete n[l];delete n.workspace_root;let a;try{a=SA(t.choice,t.bundle_ref_for,n)}catch(l){return{ok:!1,errors:[String((l==null?void 0:l.message)||l)]}}return Tb(xy(e,r,t.email_usable===!0),{target:a,requestId:t.request_id})}function LA(e,t=!1){if(e.when==="email"){if(!t)return"";const n=Tb(xy(e,"preview",!0),{target:{flow_id:"@default",interface:Lu},requestId:"preview"});return n.ok?`Runs ${pb(n.body.trigger.config)}.`:""}return""}class IA{constructor(t){es(this,"key","");es(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 OA(e,t,n){const r=RA(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:a,...l}=r.body,c=n.id_for(JSON.stringify(l));return{ok:!0,body:{...r.body,request_id:c}}}function _o(e){return typeof e=="string"?e:e??null}function PA(e){var t,n,r,a,l,c;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:_o(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:_o(e==null?void 0:e.created_at),updated_at:_o(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:_o(e==null?void 0:e.parent_run_id),session_id:_o(e==null?void 0:e.session_id),actor_id:_o(e==null?void 0:e.actor_id),session_kind:_o(e==null?void 0:e.session_kind),automation_id:_o(e==null?void 0:e.automation_id),role:_o(e==null?void 0:e.role),occurrence_index:typeof(e==null?void 0:e.occurrence_index)=="number"?Number(e.occurrence_index):null,is_scheduled:typeof(e==null?void 0:e.is_scheduled)=="boolean"?!!e.is_scheduled:(e==null?void 0:e.is_scheduled)??null,paused:typeof(e==null?void 0:e.paused)=="boolean"?!!e.paused:(e==null?void 0:e.paused)??null,waiting_reason:typeof((t=e==null?void 0:e.waiting)==null?void 0:t.reason)=="string"?String(e.waiting.reason):((n=e==null?void 0:e.waiting)==null?void 0:n.reason)??null,schedule_interval:typeof((r=e==null?void 0:e.schedule)==null?void 0:r.interval)=="string"?String(e.schedule.interval).trim():((a=e==null?void 0:e.schedule)==null?void 0:a.interval)??null,schedule_target_workflow_id:typeof((l=e==null?void 0:e.schedule)==null?void 0:l.target_workflow_id)=="string"?String(e.schedule.target_workflow_id).trim():((c=e==null?void 0:e.schedule)==null?void 0:c.target_workflow_id)??null,current_node:typeof(e==null?void 0:e.current_node)=="string"?String(e.current_node).trim():(e==null?void 0:e.current_node)??null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?Number(e.llm_calls):(e==null?void 0:e.llm_calls)??null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?Number(e.tool_calls):(e==null?void 0:e.tool_calls)??null,tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?Number(e.tokens_total):(e==null?void 0:e.tokens_total)??null,error:(e==null?void 0:e.error)??null,waiting:(e==null?void 0:e.waiting)??null,archived:(e==null?void 0:e.archived)===!0}}function DA(e,t){const n=new Set(e.map(a=>String((a==null?void 0:a.run_id)||""))),r=[...e];for(const a of t){const l=String((a==null?void 0:a.run_id)||"");!l||n.has(l)||(n.add(l),r.push(a))}return r}function If(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 L0(e){const t=If(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`occurrence #${e.occurrence_index}`:"occurrence":t==="legacy"?"legacy schedule":t||""}function gv(e){return String((e==null?void 0:e.role)||"").trim()==="controller"}function FA(e){var n,r,a;const t=(a=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:a.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 pl(e){return e.legacy===!0||e.capabilities.includes("legacy")}function I0(e,t=Date.now()){const n=pl(e),r=e.last_occurrence,a=r&&r.attempts>1?` after ${r.attempts} attempts`:"",l=e.attention.unread||e.attention.pending_waits>0;return{id:e.automation_id,title:e.title,cadence:ty(e.trigger,e),next_run:vb(e,t),current:wb(e),state:e.status,last:r?r.excerpt:"",last_status:r?`#${r.index} ${r.status}${a}`:"no runs yet",attention:l?xb(e):null,legacy:n}}function O0(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 zA(e,t){const n=Vm(e,[],t),r=O0(e),a=t?{enabled:!1,reason:"Working…"}:pl(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:a}}function BA(e,t){const n=l=>({enabled:!1,reason:l});if(t)return{legacy_pause:n("Working…"),legacy_resume:n("Working…"),legacy_run_now:n("Working…"),open_run:{enabled:!0},recreate:n("Working…")};const r=e.status==="paused",a=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):a?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(a?"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 UA(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 WA=/^([1-9][0-9]*)([smhd])$/;function qA(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 HA(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(),a=String(n.target_host_bundle_id||n.target_bundle_id||(r.includes("@")?r.slice(0,r.lastIndexOf("@")):"")||(t==null?void 0:t.bundle_id)||"").trim(),l=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!a||!l)throw new Error("The legacy schedule does not name its target workflow.");const c=[],u={...xg},f=typeof n.interval=="string"?n.interval.trim():"";if(!f)u.when="once",c.push("The legacy schedule ran once; pick the date and time to run.");else{const y=WA.exec(f);let w=y?Number(y[1]):0,k=y?y[2]:"";k==="s"&&w%60===0&&(w=w/60,k="m"),k==="m"||k==="h"||k==="d"?(u.amount=String(w),u.unit=k):c.push(`The legacy interval "${f}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(u.count=String(n.repeat_count));const h=qA(n.repeat_until);h&&(u.until=h),u.context=n.share_context===!1?"independent":"growing";const m=t&&typeof t.input_data=="object"&&t.input_data&&!Array.isArray(t.input_data)?t.input_data:{},g={};for(const[y,w]of Object.entries(m))y==="workflow_selection"||y.startsWith("_")||(g[y]=w);return{choice:{kind:"bundle",bundle_id:a,flow_id:l},input_data:g,form:u,notes:c}}const VA={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 GA(e,t,n){return{answer_wait:async(r,a,l)=>{await e.submit_command({command_id:t(),run_id:r,type:"resume",payload:{wait_key:a,payload:l},client_id:"web_pwa"})},legacy_command:async(r,a,l)=>{await e.submit_command({command_id:t(),run_id:r,type:a,payload:l,client_id:"web_pwa"})},now_iso:n}}function KA(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 bp(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function yv(e){return e.items.filter(t=>t.status==="archived").length}function by(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 YA=3e4,vm=50;function Yi(e){return ry(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function kp(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,a)=>a.index-r.index)}class JA{constructor(t,n,r=[1500,4e3]){es(this,"state",{...VA});es(this,"listeners",new Set);es(this,"list_seq",0);es(this,"detail_seq",0);es(this,"sources_loaded",!1);es(this,"client");es(this,"preview_schedule",t=>this.client.previewSchedule(t));es(this,"definitions",new Map);this.host=n,this.followups_ms=r,this.client=xA(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 a=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:vm});if(t.push(...a.items),!a.next_cursor)return t;n=a.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 y_(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,a=r?n.find(l=>l.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&a?{detail:{...r,summary:a}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:Yi(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 a;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((a=this.state.detail)==null?void 0:a.automation_id)!==n?{detail:null}:{}});try{const l=this.state.items.find(f=>f.automation_id===n);if(l&&pl(l)){this.set({detail:{automation_id:n,summary:l,definition:null,occurrences:[],next_cursor:null,error:null}});return}const[c,u]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:vm})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:l??c.summary,definition:c.definition,occurrences:kp([],u.items),next_cursor:u.next_cursor,error:null}}),await this.load_trigger_sources()}catch(l){if(r!==this.detail_seq)return;this.set({error:Yi(l)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||pl(n.summary))return;const[r,a]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:vm})]),l=this.state.detail;if(!l||l.automation_id!==t)return;const c=this.state.items.find(u=>u.automation_id===t);this.set({detail:{...l,summary:c??r.summary,definition:r.definition,occurrences:kp(l.occurrences,a.items),next_cursor:l.occurrences.length>a.items.length?l.next_cursor:a.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:vm}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:kp(r.occurrences,n.items),next_cursor:n.next_cursor}})}catch(n){this.set({error:Yi(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,a){this.set({busy:!0});try{const l=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...a?{command_id:a}:{}});return await this.after_change(t),l}catch(l){throw Yi(l)}finally{this.set({busy:!1})}}async revise(t,n,r,a){this.set({busy:!0});try{const l=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...a?{command_id:a}:{}});return await this.after_change(t),l}catch(l){throw Yi(l)}finally{this.set({busy:!1})}}definition(t){if(pl(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 a=this.definitions.get(n);if(a&&a.revision===t.revision)return a.answer;const l=this.client.getAutomation(n).then(c=>c.definition??null);return l.catch(()=>this.definitions.delete(n)),this.definitions.set(n,{revision:t.revision,answer:l}),l}async discuss(t,n,r,a){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:r,...a?{request_id:a}:{}});return this.set({notice:by(n,l)}),l}catch(l){throw Yi(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Yi(r)}}async answer_wait(t,n,r,a){var l;this.set({busy:!0});try{const c=(((l=this.state.detail)==null?void 0:l.occurrences)||[]).flatMap(u=>u.waits).find(u=>u.run_id===n&&u.wait_key===r);if(!c)throw new Error(`No loaded wait ${r} on run ${n}; reload the automation.`);await this.host.answer_wait(n,r,KA(c.kind,a)),await this.after_change(t)}catch(c){throw Yi(c)}finally{this.set({busy:!1})}}async row_action(t,n){const r=`automation.${n}`;this.set({error:null,notice:""});try{await this.command(t.automation_id,r),this.set({notice:n==="run_now"&&t.status==="paused"?`Run now sent to “${t.title}”; it stays paused.`:n==="pause"||n==="resume"?wv(t.title,n==="resume"):`${XA[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(a){this.set({error:Yi(a)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!pl(t))throw new Error("legacy_action on a non-legacy automation");const r=UA(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}”.`:wv(t.title,n==="legacy_resume")}),await this.refresh()}catch(a){this.set({error:Yi(a)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Yi(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 wv(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const XA={run_now:"Run now",archive:"Archive"};function ZA(e){const t=(n,r,a)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:a,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:CA[e.mode]})]})}function QA(e){const t=e.form,n=y_(e.email_status),r=t.when==="email"&&!n?"every":t.when,a=LA(t,n);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:Ln.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"})})," ",Ln.kind_every]}),["daily","weekly","monthly"].map(l=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:l,checked:r===l,disabled:e.disabled,onChange:()=>e.on_change({when:l})})," ",Ln[`kind_${l}`]]},l)),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"})})," ",Ln.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"})})," ",Vt.trigger_label]})]}),n?null:s.jsx(ug,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),r==="email"?s.jsx(h2,{value:t.email,onChange:l=>e.on_change({email:l}),disabled:e.disabled,idBase:"automate"}):r==="daily"||r==="weekly"||r==="monthly"?s.jsx(Lb,{value:oy(r,t.calendar),onChange:l=>e.on_change({calendar:ly(t.calendar,l)}),idBase:"automate",disabled:e.disabled}):r==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:TN.map(l=>l.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":l.label,"aria-pressed":Number(t.amount)===l.when.amount&&t.unit===l.when.unit,disabled:e.disabled,onClick:()=>{l.when.kind==="every"&&e.on_change({amount:String(l.when.amount),unit:l.when.unit})},children:l.label},l.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:Ln.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:l=>e.on_change({amount:l.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:l=>e.on_change({unit:l.target.value}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]})]}):s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:Ln.once_label}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:l=>e.on_change({once_at:l.target.value})})]}),r==="email"?s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:a||"Incomplete email trigger."}):s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Ob,{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) — ",pv.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"})," — ",pv.growing]}),t.context==="growing"?s.jsxs("label",{children:["Max growing context (tokens)",s.jsx("input",{type:"number",min:1,step:1,required:!0,value:t.growing_max_tokens,disabled:e.disabled,onChange:l=>e.on_change({growing_max_tokens:l.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:TA})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(Pb,{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:Vt.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"})})," ",ON,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(ug,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(m2,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:l=>e.on_change({notify_email:l}),recipients:n?t.email_recipients:$f,onRecipientsChange:l=>e.on_change({email_recipients:l}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function eT(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 Rs(){return xo()}const P0=m_("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",tT="Copy failed — select and copy";function D0(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function nT(e){var a;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{(a=r==null?void 0:r.focus)==null||a.call(r)}catch{}}}async function sT(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 nT(t)}const rT=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 iT(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 a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64),c=(u,f)=>u>>>f|u<<32-f;for(let u=0;u<n.length;u+=64){for(let S=0;S<16;S++)l[S]=r.getUint32(u+S*4,!1);for(let S=16;S<64;S++){const N=c(l[S-15],7)^c(l[S-15],18)^l[S-15]>>>3,R=c(l[S-2],17)^c(l[S-2],19)^l[S-2]>>>10;l[S]=l[S-16]+N+l[S-7]+R>>>0}let[f,h,m,g,y,w,k,b]=[a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7]];for(let S=0;S<64;S++){const N=c(y,6)^c(y,11)^c(y,25),R=y&w^~y&k,$=b+N+R+rT[S]+l[S]>>>0,A=c(f,2)^c(f,13)^c(f,22),W=f&h^f&m^h&m,z=A+W>>>0;b=k,k=w,w=y,y=g+$>>>0,g=m,m=h,h=f,f=$+z>>>0}a[0]=a[0]+f>>>0,a[1]=a[1]+h>>>0,a[2]=a[2]+m>>>0,a[3]=a[3]+g>>>0,a[4]=a[4]+y>>>0,a[5]=a[5]+w>>>0,a[6]=a[6]+k>>>0,a[7]=a[7]+b>>>0}return Array.from(a,u=>u.toString(16).padStart(8,"0")).join("")}async function aT(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 a=await n.digest("SHA-256",t);return Array.from(new Uint8Array(a),l=>l.toString(16).padStart(2,"0")).join("")}return iT(t)}const oT=/^[a-zA-Z0-9_-]+$/;function vv(e){return oT.test(String(e||"").trim())}async function lT(e){const t=String(e||"");return aT(t)}async function cT(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(vv(t)){const r=`session_memory_${t}`;if(vv(r))return r}return`session_memory_sha_${(await lT(t)).slice(0,32)}`}const F0="abstractobserver_voice";function uT(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(F0),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const bg=new Set;function dT(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(F0,JSON.stringify(e||{}))}catch{}for(const n of bg)n(e||{})}function z0(){const[e,t]=_.useState(()=>uT());return _.useEffect(()=>(bg.add(t),()=>{bg.delete(t)}),[]),[e,dT]}function B0(e,t){const[n,r]=_.useState({value:null,failed:!1});return _.useEffect(()=>{if(!t||!e){r({value:null,failed:!1});return}let a=!0;return e.voice_defaults().then(l=>a&&r({value:l||{},failed:!1})).catch(()=>a&&r({value:null,failed:!0})),()=>{a=!1}},[e,t]),n}function fT(e){const t=e.gateway;return s.jsx(xC,{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 hT=18e4;function mT(e,t,n,r=()=>{}){return async function*(a,l){r(),yield*T1({path:e.gateway_url(st(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:l,body:{text:a,request_id:Rs(),..._C(n())}})}}function _T(e,t,n,r,a=()=>{},l=hT){return async(c,u)=>{a();const f=String(u||c.type||"").toLowerCase(),h=f.includes("mp4")?"m4a":f.includes("ogg")?"ogg":f.includes("wav")?"wav":"webm",m=new File([c],`recording.${h}`,{type:f||"audio/webm"}),g=await e.attachments_upload(t,m,{filename:m.name,content_type:m.type});a();let y;const w=await Promise.race([e.audio_transcribe(n,{audio_artifact:g,request_id:Rs(),...pC(r())}),new Promise((k,b)=>{y=setTimeout(()=>b(new Error(`the gateway did not answer within ${Math.round(l/1e3)} s`)),l)})]).finally(()=>clearTimeout(y));return a(),{text:String(w.text||""),provider:w.provider,model:w.model}}}function U0(e){const{gateway:t,prefs:n}=e,r=String(e.session_id||"").trim(),[a,l]=_.useState("");_.useEffect(()=>{let w=!0;if(!r){l("");return}return cT(r).then(k=>w&&l(k)).catch(()=>w&&l("")),()=>{w=!1}},[r]);const c=`${r}|${a}`,u=_.useRef(c);u.current=c;const f=_.useRef(n);f.current=n;const h=_.useRef(e);h.current=e;const m=()=>{if(u.current!==c)throw new Error("Voice session changed.")},g=!!(t&&a&&r),y=z1({output_device_id:n.output_device||"",input_device_id:n.input_device||"",input_gain:n.input_gain,volume:n.reply_volume,stop_on_pointerup:!1,tts_stream:g?mT(t,a,()=>f.current,m):void 0,transcribe:g?_T(t,r,a,()=>f.current,m):void 0,on_transcript:w=>{u.current===c&&h.current.on_transcript(w)},on_error:w=>{u.current===c&&h.current.on_error(w)}});return _.useEffect(()=>{var w;return y.stop_tts(),(w=y.cancel_voice_ptt_recording)==null||w.call(y),()=>{var k;y.stop_tts(),(k=y.cancel_voice_ptt_recording)==null||k.call(y)}},[c,y.stop_tts,y.cancel_voice_ptt_recording]),{...y,run_id:a}}function W0(e,t,n){const r=_.useRef(null);_.useEffect(()=>{const a=(n==null?void 0:n.key)||"";if(r.current===null){r.current=a;return}!a||a===r.current||(r.current=a,t&&e.tts_supported&&(n!=null&&n.text.trim())&&e.toggle_tts(a,n.text))},[n==null?void 0:n.key,n==null?void 0:n.text,t,e.tts_supported,e.toggle_tts])}function pT(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 gT=350;function q0(e){const{voice:t}=e,n=_.useRef(!1),r=_.useRef(!1),a=_.useRef(0),l=()=>{if(r.current){r.current=!1,t.stop_voice_ptt_recording();return}n.current=!0,a.current=Date.now(),t.start_voice_ptt_recording().then(()=>{!n.current&&!r.current&&t.stop_voice_ptt_recording()})},c=()=>{if(n.current){if(n.current=!1,Date.now()-a.current<gT){r.current=!0;return}t.stop_voice_ptt_recording()}};_.useEffect(()=>{const w=()=>{n.current=!1,r.current=!1,t.stop_voice_ptt_recording()};return window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),window.removeEventListener("blur",w)}},[t.stop_voice_ptt_recording]),_.useEffect(()=>{t.voice_ptt_recording||(r.current=!1)},[t.voice_ptt_recording]);const u=t.voice_ptt_since||0,f=pT(!!u),h=b1(e.prefs,e.defaults),m=t.voice_ptt_recording?`Recording… ${u?rb(u,f):""}`.trim():t.voice_ptt_busy?k1(u||f,f,h):"",y=!D0()?P0:e.blocked||(t.voice_ptt_supported?null:"Dictation is not available on this gateway connection.");return s.jsxs("span",{className:"voice_tools","data-voice-tools":!0,children:[s.jsx("button",{type:"button",className:`btn btn_icon voice_btn${t.voice_ptt_recording?" danger":""}`,"data-action":"dictate","aria-label":t.voice_ptt_recording?"Recording — tap or release to transcribe":"Hold to dictate","aria-pressed":t.voice_ptt_recording,title:y||"Hold to dictate, or tap to start and tap again to stop (Space or Enter on keyboard)",disabled:!!y||t.voice_ptt_busy,onPointerDown:w=>{w.button===0&&l()},onPointerUp:c,onPointerCancel:c,onKeyDown:w=>{[" ","Enter"].includes(w.key)&&!w.repeat&&(w.preventDefault(),l())},onKeyUp:w=>{[" ","Enter"].includes(w.key)&&(w.preventDefault(),c())},children:s.jsx(ze,{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(ze,{name:"x",size:14})}):null,m?s.jsx("span",{role:"status",className:"voice_status mono","data-voice-status":!0,children:m}):null,e.error?s.jsx("span",{role:"alert",className:"voice_error","data-voice-error":!0,children:e.error}):null]})}function yT(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(ze,{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 wT="abstractobserver";function vT(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,a,l)=>e.stream_ledger(t,{after:n,on_step:r,signal:a,on_open:l}),submitCommand:t=>e.submit_command(t)}}function xT(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 bT=new Set(["completed","failed","cancelled"]);function kT(e){var te;const{gateway:t,discussion:n}=e,r=_.useMemo(()=>vT(t),[t]),[a,l]=_.useState(((te=n.session)==null?void 0:te.run_id)||""),[c,u]=_.useState(""),[f,h]=_.useState(!1),[m,g]=_.useState(""),{controller:y,snapshot:w}=f$({transport:r,runId:a,enabled:e.connected,clientId:wT}),k=n.session,b=!!a&&!bT.has(w.status)&&w.status!=="idle",S=l$(w),[N]=z0(),R=B0(e.connected?t:null,e.connected),[$,A]=_.useState(""),W=U0({gateway:e.connected?t:null,session_id:(k==null?void 0:k.session_id)||e.voice_session_id||"",prefs:N,on_error:A,on_transcript:Q=>u(D=>D.trim()?`${D.trimEnd()}
|
|
92
|
-
${Q}`:Q)}),z=_.useMemo(()=>{for(let Q=w.messages.length-1;Q>=0;Q-=1){const D=w.messages[Q];if(D.role==="assistant")return D.live?null:{key:String(D.id||""),text:String(D.content||"")}}return null},[w.messages]);W0(W,N.read_aloud===!0,z);const H=Q=>W.tts_playback.key&&W.tts_playback.key===String(Q.id||"")?W.tts_playback.status:"idle",G=async Q=>{var T;const D=Q.trim();if(D){h(!0);try{if(k){const E=String(((T=w.run)==null?void 0:T.workflow_id)||""),L=xT(E),M=await t.start_run(L.flow_id,{prompt:D},{bundle_id:L.bundle_id,session_id:k.session_id});l(M)}else{const E=await e.on_fork(n.automation_id,n.occurrence_index,D);l(E.run_id)}u("")}finally{h(!1)}}},re=s.jsxs("div",{className:"discussion_head",children:[s.jsxs("button",{type:"button",className:"btn btn_sm","data-action":"discussion-back",onClick:e.on_close,title:`Back to ${n.automation_title}`,children:[s.jsx(ze,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(ze,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),k?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${m==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>g(m==="own"?"":"own"),title:k.workspace_root,children:[s.jsx(ze,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${m==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>g(m==="mounted"?"":"mounted"),title:k.mounted_workspace,children:[s.jsx(ze,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(k==null?void 0:k.session_id)||void 0,children:[m&&k?s.jsx(p0,{fetchGateway:t.fetch_gateway,runId:m==="own"?k.run_id:n.automation_id,title:m==="own"?"Discussion files":"Automation files",note:m==="own"?"The discussion's own writable folder.":"Mounted read-only for the discussion's file tools; nothing is written back.",onClose:()=>g(""),refreshKey:w.status}):null,s.jsx(o$,{header:re,messages:w.messages,draft:c,onDraftChange:u,onSend:G,busy:b||f,busyLabel:f?k?"Starting…":"Forking the automation…":S?"Waiting for you":"Working…",onCancel:b?()=>y.cancel():void 0,stopState:w.stop??null,disabled:!e.connected,interaction:w$(S,y,{records:w.records,currentRun:w.run}),placeholder:k?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new session that forks this automation at #",n.occurrence_index," with its history (runs 1–",n.occurrence_index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation."]}),composerExtras:s.jsx(q0,{voice:W,defaults:R.value,prefs:N,blocked:e.connected?null:"Connect to the gateway first.",error:$}),messageProps:W.tts_supported?{onSpeakToggle:Q=>{A(""),W.toggle_tts(String(Q.id||""),String(Q.content||""))},getSpeakState:H}:void 0,footer:w.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:w.error}):null})]})}const jT=pn.title;function xv(e){return`${jT}: ${e}`}const ST=["workspace_access_mode","workspace_allowed_paths"];function NT(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function H0(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 NT(t)?t:null}function V0(e,t){const n={...e||{}};for(const r of ST)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 CT(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:V0(n.input_data,t)}}}const ET=3e4,kg=new WeakMap;function $T(e,t,n=Date.now()){let r=kg.get(e);r||kg.set(e,r=new Map);const a=JSON.stringify(t),l=r.get(a);if(l&&n-l.at<ET)return l.answer;const c=Lf(e)(t).then(u=>u.summary);return c.catch(()=>r==null?void 0:r.delete(a)),r.set(a,{at:n,answer:c}),c}function AT(e){kg.delete(e)}function G0(e){const[t,n]=_.useState(null),r=JSON.stringify(e.value);return _.useEffect(()=>{if(!e.connected||!e.request){n(null);return}let a=!0;return $T(e.request,e.value).then(l=>a&&n(xv(l))).catch(l=>a&&n(xv(x_(l)))),()=>{a=!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 TT(e){const{connected:t,request:n,value:r}=e,[a,l]=_.useState(null),[c,u]=_.useState(null),f=JSON.stringify(r);_.useEffect(()=>{if(!t){l(null),u(null);return}let y=!0;return u(null),Lf(n)(r).then(w=>y&&l(w)).catch(w=>y&&u(`Could not read your workspaces: ${x_(w)}`)),()=>{y=!1}},[t,f,n]);const h=e.on_change,m=_.useCallback(async y=>{const w=await Lf(n)(y);await h(y),l(w),AT(n)},[n,h]),g=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(Yb,{level:"run",idPrefix:e.id_prefix,value:r,effective:a,onChange:m,loadError:t?c:g,unavailableReason:g,footer:e.footer})}class MT{constructor(){es(this,"made",new Map);es(this,"current",new Map)}record(t,n,r){if(this.current.set(t,r),n===null)return;let a=this.made.get(t);a||this.made.set(t,a=new Set),a.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 a=n;for(;r&&r.has(a+1);)a+=1;return a}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:V0(n.target.input_data,r)}}}}async function RT(e,t,n,r,a){const l=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,CT(n.definition,r),l,a),t.record(n.automation_id,l,r)}function K0(e){return`abstractobserver_list_open_${e}`}function Y0(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function LT(e,t=Y0()){try{return(t==null?void 0:t.getItem(K0(e)))!=="0"}catch{return!0}}function IT(e,t,n=Y0()){try{n==null||n.setItem(K0(e),t?"1":"0")}catch{}}function Of(e){const[t,n]=_.useState(()=>LT(e)),r=_.useCallback(()=>{n(a=>{const l=!a;return IT(e,l),l})},[e]);return[t,r]}function Pf(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(ze,{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 OT=5e3,PT=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],DT={pause:Ra.pause,resume:Ra.resume,run_now:Ra.run_now,edit:Ra.revise,archive:`${Ra.archive}…`,discuss:Ra.discuss},FT={pause:Xi.pause,resume:Xi.resume,run_now:Xi.run_now,edit:Xi.revise,archive:Xi.archive,discuss:Xi.discuss},zT={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},BT={legacy_pause:Xi.pause,legacy_resume:Xi.resume,legacy_run_now:Xi.run_now,open_run:"list",recreate:"refresh"};function UT(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(qb,{status:e.status})})}function xm(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(ze,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const WT={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},qT="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function bv(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(Ni,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:Ra.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function HT(e){const[t,n]=_.useState(void 0),{summary:r,ws:a}=e;return _.useEffect(()=>{let l=!0;return a.definition(r).then(c=>l&&n(c?H0(c):void 0),()=>l&&n(void 0)),()=>{l=!1}},[r.automation_id,r.revision,a.definition]),t===void 0?null:s.jsx(G0,{request:a.request,connected:a.connected,value:t,refresh_key:r.revision??""})}function VT(e){const t=e.summary,n=I0(t),r=e.state.selected_id===t.automation_id,a=e.state.busy,l=(f,h,m,g,y,w,k,b)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${k?" auto_action_icon":""}${y?` ${y}`:""}`,"data-action":f,disabled:!m.enabled,title:[k?h:null,m.enabled?null:m.reason,b].filter(Boolean).join(`
|
|
93
|
-
`)||void 0,"aria-label":k?h:void 0,"aria-description":b,onClick:g,children:[w?s.jsx(ze,{name:w,size:13}):null,k?null:s.jsx("span",{children:h})]},f);let c;if(n.legacy){const f=BA(t,a),h=t.status==="paused"?"legacy_resume":"legacy_pause",m=["legacy_run_now","open_run","recreate"];c=[s.jsx(bv,{summary:t,busy:a,ctl:f[h],hint:qT,onChange:()=>e.h.on_legacy_action(t,h)},"active"),...m.map(g=>l(g,WT[g],f[g],()=>e.h.on_legacy_action(t,g),void 0,BT[g]))]}else{const f=zA(t,a),h=t.status==="active"?"pause":"resume",m=["run_now","edit","discuss","archive"];c=[s.jsx(bv,{summary:t,busy:a,ctl:f.active,hint:Ym("active",t),onChange:()=>e.h.on_row_action(t,h)},"active"),...m.map(g=>l(g,DT[g],f[g],()=>e.h.on_row_action(t,g),g==="archive"?"danger auto_action_end":void 0,FT[g],g==="archive",Ym(zT[g],t)))]}const u=e.state.confirm_archive_id===t.automation_id;return s.jsxs("li",{className:`auto_row${r?" selected":""}`,"data-automation-id":t.automation_id,"data-legacy":n.legacy?"true":void 0,children:[s.jsxs("button",{type:"button",className:"auto_row_main",onClick:()=>e.h.on_select(t.automation_id),"aria-current":r?"true":void 0,children:[s.jsxs("span",{className:"auto_row_title",children:[n.title,n.legacy?s.jsx("span",{className:"chip scheduled",children:"legacy"}):null,s.jsx(UT,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(ze,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(xm,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(xm,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsxs(xm,{icon:"clock",field:"next",label:"Next run",children:["next: ",n.next_run]}),s.jsx(xm,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),e.ws&&!n.legacy?s.jsx(HT,{summary:t,ws:e.ws}):null,n.last?s.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:k0(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:c}),u?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:a,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(ze,{name:"archive",size:13}),s.jsx("span",{children:"Archive"})]}),s.jsxs("button",{type:"button",className:"btn btn_sm auto_action","data-action":"archive-cancel",onClick:e.h.on_cancel_archive,children:[s.jsx(ze,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function GT(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,a=r?Gm(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(Pf,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:bp(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:bp(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:l=>e.h.on_status_filter(l.target.value),"aria-label":"Filter by status",children:PT.map(([l,c])=>s.jsx("option",{value:l,children:c},l||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(ze,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:$A,"aria-disabled":!e.available.available,title:"New automation: opens Launch in Automate mode","aria-label":"New automation",onClick:l=>{l.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(ze,{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}),a?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":r==null?void 0:r.code,children:[s.jsx(ze,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:a.title})," ",s.jsx("span",{children:a.detail})]}),t.error&&e.h.on_dismiss_error?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:s.jsx(ze,{name:"x",size:12})}):null]}):null,s.jsx("div",{className:`auto_notice${t.notice?" on":""}`,role:"status",children:t.notice?s.jsxs(s.Fragment,{children:[s.jsx(ze,{name:"check",size:13}),s.jsx("span",{className:"auto_list_msg",children:t.notice}),e.h.on_dismiss_notice?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-notice","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_notice,children:s.jsx(ze,{name:"x",size:12})}):null]}):null}),e.available.available&&t.loaded&&!t.items.length?s.jsx("div",{className:"help_text muted",children:"No automations yet. Create one from Launch → Automate."}):null,yv(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(Ni,{variant:"sm",action:"show-archived",label:`Archived (${yv(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:l=>e.h.on_show_archived(l)})}):null,s.jsx("ul",{className:"auto_rows",children:bp(t).map(l=>s.jsx(VT,{summary:l,state:t,h:e.h,ws:e.ws},l.automation_id))})]})]})}function KT(e,t,n,r){const a=e.state,l=a.detail;if(!l||pl(l.summary))return null;const c=l.automation_id;return{summary:l.summary,...l.definition?{definition:l.definition}:{},occurrences:l.occurrences,triggerSources:a.trigger_sources,busy:a.busy,...l.error?{error:l.error}:{},onRevise:async(u,f,h)=>{if(!r)return e.revise(c,u,f,h==null?void 0:h.command_id);const m=r.expected(c,f),g=await e.revise(c,r.changes(c,u),m,h==null?void 0:h.command_id);return r.note(c,m),g},onCommand:(u,f,h)=>e.command(c,u,f,h==null?void 0:h.command_id),onDiscuss:async(u,f,h)=>{const m=await e.discuss(c,u,f,h==null?void 0:h.request_id);return t.on_open_session(m,by(u,m),u),m},onSeen:u=>e.seen(c,u),onLoadMore:()=>void e.load_more(),onOpenRun:u=>t.on_open_run(u),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(u,f,h)=>e.answer_wait(c,u,f,h),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:a.email_status,previewSchedule:e.preview_schedule,...t.on_open_my_email?{onOpenMyEmail:()=>{var u;return(u=t.on_open_my_email)==null?void 0:u.call(t)}}:{}}}function YT(e){var u,f;const t=e.ctl.state.detail;if(!t&&e.ctl.state.selected_id)return s.jsx("section",{className:"pane auto_detail auto_detail_empty","aria-busy":"true",children:s.jsx("div",{className:"help_text muted",children:"Loading…"})});if(!t)return s.jsx("section",{className:"pane auto_detail auto_detail_empty",children:s.jsxs("div",{className:"help_text muted",children:["Select an automation to read its runs as a conversation, change it, or discuss a result (",dg.toLowerCase(),")."]})});if(pl(t.summary)){const h=I0(t.summary);return s.jsxs("section",{className:"pane auto_detail","data-legacy":"true",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:h.title}),s.jsx("span",{className:"chip scheduled",children:"legacy"})]}),s.jsxs("div",{className:"pane_body",children:[s.jsxs("p",{className:"help_text",children:["A schedule created before automations (",h.cadence,"). It keeps working with its existing controls: suspend, resume, run now and edit the interval from its run view. “Recreate as automation” opens Launch → Automate prefilled with its workflow, inputs and interval; the legacy schedule is not changed."]}),s.jsxs("div",{className:"auto_row_actions",children:[s.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open_run",onClick:()=>e.h.on_legacy_action(t.summary,"open_run"),children:"Open run"}),s.jsx("button",{type:"button",className:"btn btn_sm primary","data-action":"recreate",onClick:()=>e.h.on_legacy_action(t.summary,"recreate"),children:"Recreate as automation"})]})]})]})}const n=e.workspaces,r=KT(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),a=e.ctl,l=t.definition,c=H0(l);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n&&l?s.jsx("div",{className:"auto_workspaces","data-section":"workspaces","data-editing":(u=e.edit)!=null&&u.open?"true":void 0,children:(f=e.edit)!=null&&f.open?s.jsx(s.Fragment,{children:s.jsx(TT,{footer:s.jsx("p",{className:"help_text muted auto_workspaces_help",children:"Each change is saved at once as a new revision; it applies from the next run."}),id_prefix:`observer-automation-workspace-${t.automation_id}`,connected:n.connected,request:n.request,value:c,disabled:a.state.busy,on_change:h=>RT(a,n.revisions,{automation_id:t.automation_id,summary:t.summary,definition:l},h,xo())})}):s.jsx(G0,{request:n.request,connected:n.connected,value:c,refresh_key:t.summary.revision??""})}):null,r?s.jsx(y$,{...r,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools}):null]})}function JT(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=O0(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function XT(e){const t=e.ctl,n=_.useRef(null);n.current||(n.current=new MT);const r=e.workspace_request?{request:e.workspace_request,connected:e.active,definition:$=>t.definition($)}:void 0,[a,l]=Of("automations"),[c,u]=_.useState(null),f=$=>u(A=>({...$,opened:((A==null?void 0:A.opened)||0)+1})),[h,m]=_.useState(""),[g,y]=_.useState("");_.useSyncExternalStore($=>t.subscribe($),()=>t.state,()=>t.state);const[w,k]=_.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");_.useEffect(()=>{const $=()=>k(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",$),()=>document.removeEventListener("visibilitychange",$)},[]),_.useEffect(()=>{if(!e.active||!w||!e.available.available)return;t.refresh();const $=window.setInterval(()=>void t.refresh(),YA);return()=>window.clearInterval($)},[t,e.active,w,e.available.available]);const b=t.state.detail,S=t.state.notice;_.useEffect(()=>{if(!S)return;const $=window.setTimeout(()=>t.dismiss_notice(),OT);return()=>window.clearTimeout($)},[t,S]);const N={...e.host,on_open_workspace:$=>m(A=>A===$?"":$),fetch_gateway:e.gateway.fetch_gateway,on_open_session:($,A,W)=>{e.host.on_open_session($,A,W),b&&f({automation_id:b.automation_id,automation_title:b.summary.title,occurrence_index:W,session:$})}},R={...e.h,on_select:$=>{u(null),m(""),$!==g&&y(""),e.h.on_select($)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:($,A)=>{const W=JT($,A);W.kind==="forward"?e.h.on_row_action($,A):W.kind==="edit"?(u(null),m(""),y($.automation_id),e.h.on_select($.automation_id)):W.kind==="discuss"&&(e.h.on_select($.automation_id),f({automation_id:$.automation_id,automation_title:$.title,occurrence_index:W.index}))}};return s.jsxs("div",{className:`page auto_page${a?"":" list_collapsed"}`,children:[s.jsx(GT,{state:t.state,available:e.available,h:R,list:{open:a,on_toggle:l},ws:r}),c?s.jsx(kT,{gateway:e.gateway,discussion:c,connected:e.active,voice_session_id:e.voice_session_id||"",on_fork:async($,A,W)=>{const z=await t.discuss($,A,W);return e.host.on_open_session(z,by(A,z),A),u(H=>H&&{...H,session:z}),z},on_close:()=>u(null)},c.opened):s.jsx(YT,{workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,ctl:t,host:N,h:R,edit:{open:!!b&&g===b.automation_id,on_change:$=>y($&&b?b.automation_id:"")},workspaces:e.workspace_request?{request:e.workspace_request,connected:e.active,revisions:n.current}:void 0,browser:h?s.jsx(p0,{fetchGateway:e.gateway.fetch_gateway,runId:h,title:h===(b==null?void 0:b.automation_id)?"Automation files":"Run files",onClose:()=>m("")}):void 0})]})}function ZT(e){return s.jsx(Ni,{variant:"row",action:"auto-connect",label:"Auto-connect on load",description:"Reuse the browser session automatically when the app opens.",checked:e.checked,onChange:e.onChange})}function QT(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(Ni,{variant:"row",action:"assistant-skill",label:s.jsxs("span",{className:"settings_choice_name",children:[e.name,e.version?s.jsxs("em",{children:[" v",e.version]}):null]}),ariaLabel:e.name,description:e.description||void 0,checked:e.checked,onChange:e.onChange})})}const eM="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function tM(e){return s.jsx(Ni,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:eM,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function nM(e){return s.jsx(Ni,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function sM(e){return s.jsx(Ni,{variant:"row",action:"apply-immediately",label:"Apply immediately",description:"Recompute the next run from now if the schedule is waiting.",checked:e.checked,busy:e.busy,onChange:e.onChange})}const kv={framework:null,gateway:null,gatewayNote:"checking…"};function rM(){const e="0.7.1".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 iM(){return u1("abstractobserver",rM())}async function aM(e){let t;try{t=await e.gateway_about()}catch(n){return ww(null,n instanceof Error?n.message||n.name:String(n))}return ww(t)}class Qm{constructor(t){this._maxSize=Qm._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=Qm._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 oM(e){try{return new URL(String(e)),!0}catch{return!1}}function lM({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return oM(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function cM({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function uM({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function dM(e){if(!e||typeof e!="object")return null;const t=Number(e.utilization_gpu_pct);if(Number.isFinite(t))return t;const n=e.gpus;if(Array.isArray(n)&&n.length){const r=n.map(l=>Number(l&&l.utilization_gpu_pct)).filter(l=>Number.isFinite(l));return r.length?r.reduce((l,c)=>l+c,0)/r.length:null}return null}async function fM({baseUrl:e,endpoint:t,token:n,getToken:r,signal:a,fetchImpl:l}={}){const c=lM({baseUrl:e,endpoint:t}),u=await cM({token:n,getToken:r}),f=l||globalThis.fetch;if(typeof f!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let h;try{h=await f(c,{method:"GET",headers:{Accept:"application/json",...uM({token:u})},signal:a})}catch(g){return{ok:!1,status:0,error:"network_error",detail:g instanceof Error?g.message:String(g),payload:null}}let m=null;try{m=await h.json()}catch{m=null}return{ok:h.ok,status:h.status,error:h.ok?null:"http_error",payload:m}}const lf=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function hM(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function jv(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Sv(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function jp(e,t=1){const n=jv(Number(e)/100,0,1),r=Math.round(140-140*n),a=jv(Number(t),0,1);return a>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${a})`}function Nv(e){const t={...lf,...e||{}};return t.tickMs=Math.max(250,Sv(t.tickMs,lf.tickMs)),t.historySize=Math.max(1,Math.min(200,Sv(t.historySize,lf.historySize))),t.endpoint=String(t.endpoint||lf.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||lf.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function mM(){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 _M{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=Nv(n),this._buffer=new Qm(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=mM();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const a=document.createElement("div");a.className="top";const l=document.createElement("div");l.className="label",l.textContent="GPU";const c=document.createElement("div");c.className="value muted",c.textContent="—",a.appendChild(l),a.appendChild(c);const u=document.createElement("div");u.className="bars",r.appendChild(a),r.appendChild(u),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:c,bars:u},this._mounted=!0,this._rebuildBars(),this._render()}start(){this.mount(),!this._running&&(this._running=!0,this._timer_gen+=1,this._poll_loop(this._timer_gen))}stop(){this._running=!1,this._timer_gen+=1,this._timer&&(clearTimeout(this._timer),this._timer=null),this._resumeTimer&&(clearTimeout(this._resumeTimer),this._resumeTimer=null),this._abort&&(this._abort.abort(),this._abort=null)}destroy(){this.stop(),this._target&&this._mounted&&(this._target.textContent=""),this._mounted=!1,this._els=null}setOptions(t){const n=Nv({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,a=n.tickMs!==this._opts.tickMs,l=n.mode!==this._opts.mode;this._opts=n,l&&this._mounted&&this._els&&this._els.wrap&&(this._els.wrap.className=n.mode==="icon"?"wrap icon":"wrap"),r&&(this._buffer.setMaxSize(n.historySize),this._mounted&&this._rebuildBars()),a&&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:a}=this._els,l=this._buffer.values(),c=this._buffer.last(),u=Number.isFinite(c)?Math.max(0,Math.min(100,c)):null;u==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${u.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=u==null?"GPU —":`GPU ${u.toFixed(0)}%`,u==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",jp(u,.95)),n.style.setProperty("--monitor-gpu-accent-glow",jp(u,.35))));const f=Array.from(a.children),h=Math.max(0,f.length-l.length),m=Math.max(2,a&&typeof a.clientHeight=="number"&&a.clientHeight>0?a.clientHeight:34);for(let g=0;g<f.length;g+=1){const y=f[g],w=g-h,k=w>=0?l[w]:null,b=Number.isFinite(k)?k:null,S=b==null?0:hM(b/100),N=Math.max(2,Math.min(m,Math.round(S*m)));y.style.height=`${N}px`,y.style.background=b==null?"":jp(b),y.className="bar",b==null&&y.classList.add("missing"),t&&y.classList.add("error")}}async _tick(){const t=String(this._token||"").trim(),n=this._getToken,r=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const a=await fM({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),l=a&&a.payload,c=l&&typeof l=="object"?l.supported!==!1:!0,u=dM(l);if(!a.ok){if(this._buffer.push(null),this._render({error:!0}),a.status===401||a.status===403){const f=String(this._token||"").trim(),h=typeof this._getToken=="function";if(!r&&(!!f||h))return;this._stoppedForAuth=!0,this.stop()}else a.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!c||u==null){this._buffer.push(null),this._render();return}this._buffer.push(u),this._render()}async _poll_loop(t){!this._running||t!==this._timer_gen||(await this._tick(),!(!this._running||t!==this._timer_gen)&&(this._timer=setTimeout(()=>{this._timer=null,this._poll_loop(t)},this._opts.tickMs)))}}function pM(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 a=this._shadow||this;this._controller=new _M(a,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(a){if(!Object.prototype.hasOwnProperty.call(this,a))return;const l=this[a];try{delete this[a]}catch{}this[a]=l}connectedCallback(){this._controller.setOptions(this._readAttrs());const a=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(a):Promise.resolve().then(a)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const a=this.getAttribute("tick-ms"),l=this.getAttribute("history-size"),c=this.getAttribute("endpoint"),u=this.getAttribute("base-url"),f=this.getAttribute("mode");return{...a!=null?{tickMs:a}:{},...l!=null?{historySize:l}:{},...c!=null?{endpoint:c}:{},...u!=null?{baseUrl:u}:{},...f!=null?{mode:f}:{}}}set token(a){this._controller.token=a}get token(){return this._controller.token}set getToken(a){this._controller.getToken=a}get getToken(){return this._controller.getToken}set tickMs(a){this._controller.setOptions({tickMs:a})}get tickMs(){return this._controller.options.tickMs}set historySize(a){this._controller.setOptions({historySize:a})}get historySize(){return this._controller.options.historySize}set endpoint(a){this._controller.setOptions({endpoint:a})}get endpoint(){return this._controller.options.endpoint}set baseUrl(a){this._controller.setOptions({baseUrl:a})}get baseUrl(){return this._controller.options.baseUrl}set mode(a){this._controller.setOptions({mode:a})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function Uu(e){return String(e||"").trim().toLowerCase()}function k_(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Af(e,t){return t.some(n=>e.endsWith(n))}function gM(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 yM(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 wM(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 J0(e,t){var c,u,f,h,m;const n=Uu(e==null?void 0:e.content_type),r=k_(e),a=[e==null?void 0:e.semantic_kind,e==null?void 0:e.render_kind,e==null?void 0:e.task,(c=e==null?void 0:e.tags)==null?void 0:c.semantic_kind,(u=e==null?void 0:e.tags)==null?void 0:u.render_kind,(f=e==null?void 0:e.tags)==null?void 0:f.task,(h=e==null?void 0:e.tags)==null?void 0:h.kind,(m=e==null?void 0:e.tags)==null?void 0:m.type].map(g=>String(g||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(a)||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")||Af(r,[".py",".js",".jsx",".ts",".tsx",".mjs",".cjs",".sh",".bash",".zsh",".go",".rs",".java",".c",".cc",".cpp",".h",".hpp",".cs",".php",".rb",".swift",".kt",".sql"]))return!0;const l=String(t||"").replace(/\r\n/g,`
|
|
108
|
-
`).replace(/\r/g,`
|
|
109
|
-
`).split(`
|
|
110
|
-
`);return X0(l)}function vM(e){const n=String(e||"").replace(/\r\n/g,`
|
|
111
|
-
`).replace(/\r/g,`
|
|
112
|
-
`).split(`
|
|
113
|
-
`),r=n.findIndex(c=>/^Markdown Content:\s*$/i.test(c.trim()));if(r===-1)return null;const a=[];for(const c of n.slice(0,r)){const u=c.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);u&&a.push({label:u[1].trim(),value:u[2].trim()})}const l=n.slice(r+1).join(`
|
|
114
|
-
`).trim();return!a.length&&!l?null:{metadata:a,body:l}}function xM(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(a=>a.split(n).length);if(r[0]>=3&&r.every(a=>Math.abs(a-r[0])<=1))return!0}return!1}function bM(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:X0(e)}function X0(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 kM(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 a=t.replace(/\r\n/g,`
|
|
115
|
-
`).replace(/\r/g,`
|
|
116
|
-
`).split(`
|
|
117
|
-
`).map(f=>f.trim()).filter(Boolean).slice(0,80);if(a.length<12)return!1;const l=a.filter(f=>f.length<=28).length,c=a.filter(f=>/^[,.;:()†]+$/.test(f)).length;return a.filter(f=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(f)).length>=2&&(l/a.length>=.45||c>=2)}function jM(e,t){var h;const n=String(t||""),r=gM(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 a=n.replace(/\r\n/g,`
|
|
118
|
-
`).replace(/\r/g,`
|
|
119
|
-
`).split(`
|
|
120
|
-
`),l=a.map(m=>m.trim()).filter(Boolean);if(l.length<2||kM(n)||xM(a)||bM(a))return!1;const c=((h=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:h.length)||0,u=a.filter(m=>!m.trim()).length,f=l.filter(m=>/[A-Za-z]{3,}/.test(m)&&m.length>=12).length;return c>=24&&f>=2&&(u>=1||l[0].length<=140)}function Tf(e){const t=Uu(e==null?void 0:e.modality),n=Uu(e==null?void 0:e.content_type),r=k_(e),a=yM(e);return t==="image"||n.startsWith("image/")||Af(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(a)||Af(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Af(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")||J0(e,"")?"text":"binary"}function e_(e,t){const n=Uu(e==null?void 0:e.content_type),r=k_(e),a=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||wM(t)?"html":J0(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(a.startsWith("{")||a.startsWith("["))&&b_(a)!==null?"json":jM(e,t)?"markdown":"text"}function ky(e,t=""){const n=Tf(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},a=[e==null?void 0:e.semantic_kind,e==null?void 0:e.modality,e==null?void 0:e.task,r.semantic_kind,r.modality,r.kind,r.task,r.source,e==null?void 0:e.filename,e==null?void 0:e.source_path].map(l=>String(l||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(a)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(a)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(a)?"sound":"audio"}if(n==="binary"){const r=Uu(e==null?void 0:e.modality),a=Uu(e==null?void 0:e.content_type),l=k_(e);return r==="document"||a.includes("pdf")||Af(l,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return e_(e,t)}function Sp(e){var h,m;const t=String(e||"").replace(/\r\n/g,`
|
|
121
|
-
`).replace(/\r/g,`
|
|
122
|
-
`).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),r=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],a=[];let l=0,c="";const u=g=>" ".repeat(Math.max(0,g)),f=(g,y)=>{const w=g.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!w||g.length<=120||g.startsWith("</")||g.startsWith("<!"))return[`${u(y)}${g.trim()}`];const k=(w[3]||"").trim();if(!k)return[`${u(y)}${g.trim()}`];const b=k.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[k];return[`${u(y)}${w[1]}${w[2]}`,...b.map(S=>`${u(y+1)}${S.trim()}`),`${u(y)}${w[4]}`]};for(const g of r){const y=String(g||"");if(!y.trim())continue;const w=y.trim().toLowerCase();if(w.startsWith("</")){const b=((h=w.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:h[1])||"";c&&b===c&&(c=""),l=Math.max(0,l-1),a.push(`${u(l)}${y.trim()}`);continue}if(y.trimStart().startsWith("<")){a.push(...f(y,l));const b=((m=w.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:m[1])||"";/\/>\s*$/.test(y)||w.startsWith("<!")||n.has(b)||(l+=1,(b==="script"||b==="style")&&(c=b));continue}if(c){const b=y.trim();b&&a.push(...b.split(`
|
|
123
|
-
`).map(S=>`${u(l)}${S.trimEnd()}`));continue}const k=y.replace(/\s+/g," ").trim();k&&a.push(`${u(l)}${k}`)}return a.join(`
|
|
124
|
-
`)}const SM=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function jy(e){const t=typeof e=="string"?e:String(e??""),n=SM.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const a=JSON.parse(String(n[1]||"").trim());a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function Z0(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,a]of Object.entries(n))a==null||String(a).trim()===""||(t[r]=a);return Object.keys(t).length?t:null}function jg(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>jg(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=jg(t);if(n)return n}}return""}function Q0(e){const t=jy(jg(e));return{text:t.text,runtime_metadata:t.metadata}}function NM(e){var r,a;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const l=jy(t);return{text:l.text,runtime_metadata:l.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const l of n)for(let c=l.length-1;c>=0;c-=1){const u=l[c],f=String((u==null?void 0:u.role)||(u==null?void 0:u.speaker)||"").trim().toLowerCase();if(f&&f!=="user"&&f!=="human")continue;const h=Q0((u==null?void 0:u.content)??(u==null?void 0:u.text)??u);if(h.text)return{text:h.text,runtime_metadata:Z0(h.runtime_metadata,u!=null&&u.runtime_metadata&&typeof u.runtime_metadata=="object"?u.runtime_metadata:null,(a=u==null?void 0:u.metadata)!=null&&a.runtime_metadata&&typeof u.metadata.runtime_metadata=="object"?u.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function CM(e,t=6){var l,c;if(!e)return[];const r=[(l=e.context)==null?void 0:l.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(u=>u.length)||[],a=[];for(const u of r){const f=String((u==null?void 0:u.role)||(u==null?void 0:u.speaker)||(u==null?void 0:u.author)||"").trim().toLowerCase()||"message",h=Q0((u==null?void 0:u.content)??(u==null?void 0:u.text)??(u==null?void 0:u.message)??u),m=h.text;if(!m)continue;const g=String((u==null?void 0:u.ts)||(u==null?void 0:u.timestamp)||(u==null?void 0:u.created_at)||(u==null?void 0:u.time)||"").trim(),y=Z0(h.runtime_metadata,u!=null&&u.runtime_metadata&&typeof u.runtime_metadata=="object"?u.runtime_metadata:null,(c=u==null?void 0:u.metadata)!=null&&c.runtime_metadata&&typeof u.metadata.runtime_metadata=="object"?u.metadata.runtime_metadata:null);a.push({role:f,text:m,ts:g,runtime_metadata:y})}return a.slice(Math.max(0,a.length-Math.max(1,t)))}function ek(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function EM(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 tk="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function nk(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(),a=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&a.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&a.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&a.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&a.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&a.push("Filesystem write"),a.length||a.push("Tool call"),Array.from(new Set(a)).slice(0,4)}function Sy(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=EM(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 sk(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 rk(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=jy(n),a=NM(t);return r.text&&!ek(r.text)?{text:r.text,runtime_metadata:r.metadata}:a.text?a:{text:r.text||n,runtime_metadata:r.metadata}}function $M(e,t){return rk(e,t).text}function AM(e,t){return e||String(t||"").trim()||{}}function Zi(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 vc(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${wc(t)}`,children:t})}function TM(e){var l;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Oa(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(),a=Array.isArray((l=n==null?void 0:n.details)==null?void 0:l.tool_calls)?n.details.tool_calls:[];return a.length?Sy(n,a):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 Df(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?At(t,{max_chars:220,max_lines:2}):At(dr(t,400),{max_chars:220,max_lines:2}):""}function MM(e){const t=TM(e);if(t)return t;const n=Df(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const a=String((e==null?void 0:e.status)||"").trim().toLowerCase();return a==="running"?"Running":Oa(a)?"Terminal":"No current activity reported"}function ik(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 Cv(e){const t=ik(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:{},a=gn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(a)return a;const l=gn(e==null?void 0:e.content_type,e==null?void 0:e.mime_type,e==null?void 0:e.mime,t==null?void 0:t.content_type,t==null?void 0:t.mime_type,t==null?void 0:t.mime,n==null?void 0:n.content_type,r.content_type).toLowerCase();return l.startsWith("image/")?"image":l.startsWith("audio/")?"audio":l.startsWith("video/")?"video":l.includes("pdf")?"document":l.startsWith("text/")||l.includes("json")||l.includes("markdown")||l.includes("csv")?"text":"artifact"}function RM(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 LM(e,t){if(!e||typeof e!="object")return null;const n=RM(e),r=ik(e),a=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},l=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},c=gn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,a.artifact_id,a.$artifact);if(!c)return null;const u={...r.tags&&typeof r.tags=="object"?r.tags:{},...a.tags&&typeof a.tags=="object"?a.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},f={};for(const[A,W]of Object.entries(u)){const z=String(A||"").trim();z&&(f[z]=String(W??""))}const h=gn(n.filename,e.filename,r.filename,a.filename,f.filename,f.name,e.name,r.name),m=gn(n.source_path,e.source_path,r.source_path,a.source_path,e.path,r.path,f.path,f.source_path,f.file_path),g=gn(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,a.content_type,f.content_type),y=gn(n.render_kind,l.render_kind,e.render_kind,f.render_kind),w=gn(n.semantic_kind,l.semantic_kind,e.semantic_kind,f.semantic_kind,f.artifact_type),k=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},b=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:l.producer&&typeof l.producer=="object"?l.producer:{},S=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:l.provenance&&typeof l.provenance=="object"?l.provenance:{},N=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:l.generation&&typeof l.generation=="object"?l.generation:{},R=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:l.media&&typeof l.media=="object"?l.media:{},$=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:l.links&&typeof l.links=="object"?l.links:{};return{artifact_id:c,run_id:gn(n.run_id,e.run_id,r.run_id,a.run_id,f.run_id,S.run_id),content_type:g,modality:gn(n.modality,e.modality,l.modality,f.modality)||Cv({...e,ref:r,metadata:a,tags:f}),semantic_kind:w||Cv({...e,ref:r,metadata:a,tags:f}),render_kind:y||ky({content_type:g,filename:h,source_path:m,modality:gn(n.modality,e.modality,f.modality),tags:f}),task:gn(n.task,l.task,e.task,f.task,f.provider_task),classification_source:gn(n.classification_source,l.classification_source,e.classification_source),session_id:gn(n.session_id,l.session_id,e.session_id,f.session_id),workflow_id:gn(n.workflow_id,l.workflow_id,e.workflow_id,f.workflow_id,f.workflow),node_id:gn(n.node_id,l.node_id,e.node_id,f.node_id,f.node),step_id:gn(n.step_id,l.step_id,e.step_id,f.step_id),effect_id:gn(n.effect_id,l.effect_id,e.effect_id,f.effect_id,f.effect_idempotency_key),turn_id:gn(n.turn_id,l.turn_id,e.turn_id,f.turn_id,f.turn),ledger_cursor:gn(n.ledger_cursor,l.ledger_cursor,e.ledger_cursor,f.ledger_cursor,f.step_cursor),parent_run_id:gn(n.parent_run_id,l.parent_run_id,e.parent_run_id,f.parent_run_id),actor_id:gn(n.actor_id,l.actor_id,e.actor_id,f.actor_id),title:gn(n.title,e.title,f.title,f.label,f.name),created_at:gn(n.created_at,e.created_at,r.created_at,a.created_at,f.created_at),size_bytes:cA(n.size_bytes,e.size_bytes,r.size_bytes,a.size_bytes,f.size_bytes),filename:h,source_path:m,sha256:gn(n.sha256,e.sha256,r.sha256,a.sha256,f.sha256),tags:f,producer:b,provenance:S,generation:N,media:R,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:k,links:$,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(gn(n.classification_source,l.classification_source,e.classification_source))),descriptor:l,source:t,raw:e}}function t_(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||sn(e.artifact_id,16)}function IM(e,t){if(t==="type")return Ou(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return Sg(e);if(t==="node")return Iu(e)||"(node unknown)";if(t==="workflow")return Ny(e)||"(workflow unknown)";if(t==="location"){const a=(e.source_path||e.filename||"").split("/").filter(Boolean);return a.length>1?a.slice(0,-1).join("/"):"(root)"}if(t==="source")return Ff(e)||e.source||"artifact";const n=qn(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ny(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 Iu(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 a=String((e==null?void 0:e.source_path)||t.path||"").trim().match(/(?:^|[._:/-])(node-[A-Za-z0-9_-]+)/);return a!=null&&a[1]?String(a[1]):""}function Sg(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=Iu(e),a=qn(e==null?void 0:e.created_at),l=a===null?"unknown time":new Date(a).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),c=e!=null&&e.run_id?sn(String(e.run_id),10):"unknown run";return r?`${c} · ${r} · ${l}`:`${c} · ${l}`}function Ev(e){if(!e)return"provenance unavailable";const t=[],n=Ny(e),r=Iu(e),a=Ff(e),l=ak(e);return n&&t.push(n),r&&t.push(r),a&&t.push(a),l&&t.push(l),t.length?t.join(" · "):"provenance unavailable"}function cc(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 a=r===0?0:n>=10?1:2;return`${n.toFixed(a)} ${t[r]}`}function Ou(e){const t=String((e==null?void 0:e.semantic_kind)||(e==null?void 0:e.modality)||"").trim().toLowerCase(),n=String((e==null?void 0:e.render_kind)||"").trim().toLowerCase(),r=t||n||"artifact";return{voice:"Voice",music:"Music",sound:"Sound",recording:"Recording",audio:"Unclassified audio",image:"Image",video:"Video",markdown:"Markdown",html:"HTML",json:"JSON",document:"Document",code:"Code",text:"Text",binary:"Other",artifact:"Other"}[r]||r.replace(/[_-]+/g," ").replace(/\b\w/g,l=>l.toUpperCase())}function OM(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function PM(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 DM(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 $v(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 FM(e){const t=zu(e.created_at),n=mc(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function Av(e){var a;const t=e.tags||{},n=String(((a=e.access)==null?void 0:a.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=zu(n);return r==="—"?"—":r}function Tv(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 a=Ff(e),l=Ou(e);return a?`${l} ${a}`:`${l} artifact`}function Ff(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 ak(e){var r,a,l,c,u,f,h,m;if(!e)return"";const t=gn((r=e.producer)==null?void 0:r.provider,(a=e.producer)==null?void 0:a.provider_id,(l=e.provenance)==null?void 0:l.provider,(c=e.generation)==null?void 0:c.provider),n=gn((u=e.producer)==null?void 0:u.model,(f=e.producer)==null?void 0:f.model_id,(h=e.provenance)==null?void 0:h.model,(m=e.generation)==null?void 0:m.model);return t&&n?`${t} / ${n}`:t||n}function zM(e){var t,n,r,a;return e?gn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(a=e.provenance)==null?void 0:a.prompt):""}function Mv(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),a=Number(t.height??t.image_height??t.video_height),l=Number(t.sample_rate??t.sample_rate_hz),c=Number(t.channels);if(Number.isFinite(n)&&n>0){const f=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(l)&&l>0&&f.push(`${Math.round(l/1e3)} kHz`),Number.isFinite(c)&&c>0&&f.push(`${c} ch`),f.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(a)&&r>0&&a>0)return`${Math.round(r)} x ${Math.round(a)}`;const u=Number(t.page_count??t.pages);return Number.isFinite(u)&&u>0?`${Math.round(u)} pages`:""}function Rv(e){return e.source_path||e.filename||""}function n_(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const a=Zi(r,n),l={...e.tags||{}};return a&&!l.workflow&&(l.workflow=a),a&&!l.workflow_id&&(l.workflow_id=a),{...e,workflow_id:e.workflow_id||a,tags:l}}function Ng(e,t,n,r=""){const a=n_(e,t,n),l=ky(a,r);return{json:"JSON",html:"HTML",markdown:"Markdown",code:"Code",voice:"Voice",music:"Music",sound:"Sound",audio:"Unclassified audio",image:"Image",video:"Video",document:"Document",text:"Text",other:"Other"}[l]||Ou(a)}function go(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 bm(e){var l,c,u;const t=e,n=t==null?void 0:t.effect;if(!n||typeof n!="object"||String(n.type||"")!=="emit_event")return null;const r=String(((l=n==null?void 0:n.payload)==null?void 0:l.name)||((c=n==null?void 0:n.payload)==null?void 0:c.event_name)||"").trim();if(!r)return null;const a=(u=n==null?void 0:n.payload)==null?void 0:u.payload;return{name:r,payload:a}}function sh(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(a=>a&&typeof a=="object"&&typeof a.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function BM(e){var a,l;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((a=e==null?void 0:e.effect)==null?void 0:a.type)||"").trim(),r=(l=e==null?void 0:e.effect)!=null&&l.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function ok(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=BM(e),a=go(e);if(a){const l=String(a.reason||"").trim();if(String(a.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(l)return`${t||"node"} is waiting (${l})`}return e.error?`${t||"node"} failed`:n==="completed"?`${t||"node"} completed ${r}`:n==="running"?`${t||"node"} started ${r}`:n==="waiting"?`${t||"node"} is waiting`:[t,n,r].filter(Boolean).join(" · ")||"Ledger record"}function vu(e){if(typeof e=="string")return{text:e,duration:-1};if(e&&typeof e=="object"){const t=typeof e.text=="string"?String(e.text):typeof e.value=="string"?String(e.value):typeof e.message=="string"?String(e.message):dr(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:dr(e,320),duration:-1}}function lk(e){var c,u,f,h,m,g,y,w,k;if(!e||typeof e!="object")return"";const t=String(((c=e==null?void 0:e.effect)==null?void 0:c.type)||"").trim(),n=e==null?void 0:e.result,r=b=>typeof b=="string"?b.trim():b==null?"":typeof b=="number"||typeof b=="boolean"?String(b):"",a=b=>{if(!b||typeof b!="object")return"";const S=b,N=[S.response,S.answer,S.message,S.text,S.content];for(const R of N){const $=r(R);if($)return $}return""};if(t==="answer_user"){const b=r(n==null?void 0:n.message)||r((u=n==null?void 0:n.output)==null?void 0:u.message)||r((f=n==null?void 0:n.output)==null?void 0:f.response)||r((m=(h=e==null?void 0:e.effect)==null?void 0:h.payload)==null?void 0:m.message)||r((y=(g=e==null?void 0:e.effect)==null?void 0:g.payload)==null?void 0:y.text)||r((k=(w=e==null?void 0:e.effect)==null?void 0:w.payload)==null?void 0:k.content);if(b)return b}if(t==="llm_call"){const b=a(n)||r(n==null?void 0:n.output)||a(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(b)return b}return r(n==null?void 0:n.output)||a(n==null?void 0:n.output)||a(n)||r(n==null?void 0:n.response)}function Fm(e){var a;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((a=e==null?void 0:e.effect)==null?void 0:a.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function UM(e){return!!(e&&String(e.status||"")==="waiting")}function WM(e){var n,r;const t=[];for(const a of e||[]){const l=a.record;if(String(((n=l==null?void 0:l.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const u=(r=l==null?void 0:l.effect)!=null&&r.payload&&typeof l.effect.payload=="object"?l.effect.payload:{},f=l!=null&&l.result&&typeof l.result=="object"?l.result:{},h=(f==null?void 0:f.usage)||(f==null?void 0:f.token_usage)||{},m=typeof u.prompt=="string"?u.prompt:Array.isArray(u.messages)?dr(u.messages,1800):"",g=typeof f.content=="string"?f.content:typeof f.response=="string"?f.response:typeof l.result=="string"?String(l.result):"",y=qn(l.started_at),w=qn(l.ended_at),k=Number(h.prompt_tokens??h.input_tokens??0)||0,b=Number(h.completion_tokens??h.output_tokens??0)||0;t.push({id:`${String(a.run_id||l.run_id||"")}:${a.cursor}`,cursor:Number(a.cursor||0),ts:String(l.ended_at||l.started_at||""),run_id:String(a.run_id||l.run_id||"").trim(),node_id:String(l.node_id||"").trim(),provider:String(u.provider||f.provider||f.runtime_provider||"").trim(),model:String(u.model||f.model||f.runtime_model||"").trim(),prompt_preview:At(m,{max_chars:1200,max_lines:10}),response_preview:At(g,{max_chars:1200,max_lines:10}),missing_response:!String(g||"").trim(),tokens:{prompt:k,completion:b,total:Number(h.total_tokens??k+b)||0},duration_ms:y!==null&&w!==null?Math.max(0,w-y):typeof f.gen_time=="number"?Number(f.gen_time)*1e3:null,status:String(l.status||"").trim(),error:l.error?dr(l.error,500):"",raw:l})}return t.sort((a,l)=>(qn(l.ts)??0)-(qn(a.ts)??0))}function Lv(e){const t=e.size||18,n=Tf(e.artifact),r=ky(e.artifact,""),a=`artifact_glyph ${r==="code"?"code":n}`,l={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"};return n==="image"?s.jsx("span",{className:a,children:s.jsxs("svg",{...l,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),s.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?s.jsx("span",{className:a,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M4 12h2"}),s.jsx("path",{d:"M8 8v8"}),s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M16 8v8"}),s.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?s.jsx("span",{className:a,children:s.jsxs("svg",{...l,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):r==="code"?s.jsx("span",{className:a,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M8 8l-4 4 4 4"}),s.jsx("path",{d:"M16 8l4 4-4 4"}),s.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?s.jsx("span",{className:a,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M10 13h7"}),s.jsx("path",{d:"M10 17h5"})]})}):s.jsx("span",{className:a,children:s.jsxs("svg",{...l,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const qM=2,HM=Number.MAX_SAFE_INTEGER;function VM(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 GM(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:Sp(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const a=l=>{if(l.nodeType===Node.TEXT_NODE){const c=String(l.textContent||"").trim();return c?{kind:"text",text:c}:null}if(l.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(l.textContent||"")};if(l.nodeType===Node.ELEMENT_NODE){const c=l,u=Array.from(c.attributes||[]).map(h=>({name:h.name,value:h.value})),f=Array.from(c.childNodes||[]).map(a).filter(Boolean);return{kind:"element",tag:c.tagName.toLowerCase(),attrs:u,children:f}}return null};if(n.documentElement){const l=a(n.documentElement);l&&r.push(l)}return r.length?r:[{kind:"text",text:Sp(t)||t}]}catch{return[{kind:"text",text:Sp(t)||t}]}}function Np(e){return e.closing?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"</"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),s.jsx("span",{className:"runtime_html_punct",children:">"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"runtime_html_punct",children:"<"}),s.jsx("span",{className:"runtime_html_tag",children:e.tag}),e.attrs.map(t=>s.jsxs(xe.Fragment,{children:[" ",s.jsx("span",{className:"runtime_html_attr",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:"="}),s.jsxs("span",{className:"runtime_html_value",children:['"',t.value,'"']})]},`${e.tag}:${t.name}:${t.value}`)),s.jsx("span",{className:"runtime_html_punct",children:e.selfClosing?" />":">"})]})}function ck(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[a,l]=_.useState(r);if(_.useEffect(()=>{l(r)},[r,e.expansionVersion]),t.kind==="doctype")return s.jsxs("div",{className:"html-tree__line",style:{paddingLeft:n},children:[s.jsx("span",{className:"runtime_html_punct",children:"<!DOCTYPE "}),s.jsx("span",{className:"runtime_html_tag",children:t.name}),s.jsx("span",{className:"runtime_html_punct",children:">"})]});if(t.kind==="comment")return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx("span",{className:"runtime_html_comment",children:`<!-- ${t.text.trim()} -->`})});if(t.kind==="text")return s.jsx("div",{className:"html-tree__line html-tree__text",style:{paddingLeft:n},children:t.text});if(!t.children.length)return s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(Np,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const c=t.children.find(u=>u.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:a,onToggle:u=>l(u.currentTarget.open),children:[s.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[s.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:a?"▾":"▸"}),s.jsx(Np,{tag:t.tag,attrs:t.attrs}),!a&&c?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",VM(c.text)]}):null]}),a?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((u,f)=>s.jsx(ck,{node:u,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${f}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(Np,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function KM(e){const t=_.useMemo(()=>GM(e.text),[e.text]),[n,r]=_.useState({mode:"folded",version:0}),a=n.mode==="unfolded"?HM:qM;_.useEffect(()=>{r(c=>({mode:"folded",version:c.version+1}))},[e.text]);const l=()=>{r(c=>({mode:c.mode==="unfolded"?"folded":"unfolded",version:c.version+1}))};return s.jsxs("div",{className:`${e.className} structured html_source_preview`,children:[s.jsx("div",{className:"html-tree__toolbar",children:s.jsx("button",{type:"button",className:"btn html-tree__toggle",onClick:l,"aria-expanded":n.mode==="unfolded",children:n.mode==="unfolded"?"Fold all":"Unfold all"})}),s.jsx("div",{className:"html-tree__tree",role:"tree","aria-label":"HTML source tree",children:t.map((c,u)=>s.jsx(ck,{node:c,depth:0,collapseAfterDepth:a,expansionMode:n.mode,expansionVersion:n.version},`root:${u}`))})]})}function YM(e){var r;const t=vM(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Si,{text:e.text})});const n=((r=t.metadata.find(a=>a.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(a=>{const l=/^https?:\/\//i.test(a.value);return s.jsxs("div",{children:[s.jsx("dt",{children:a.label}),s.jsx("dd",{children:l?s.jsx("a",{href:a.value,target:"_blank",rel:"noreferrer",children:a.value}):a.value})]},`${a.label}:${a.value}`)})}):null,s.jsx(Si,{text:t.body||e.text})]})}function uk(e){const t=String(e.text||""),n=e_(e.artifact,t);if(n==="json"){const r=b_(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(Is,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(YM,{text:t,className:e.className}):n==="html"?s.jsx(KM,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function JM(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:t_(n)}):t.kind==="audio"&&t.url?s.jsx(v_,{className:"runtime_inline_preview audio",src:t.url,name:t_(n)}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(uk,{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 Cy(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function dk(e){const t=Cy(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function Iv(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 XM(e){const t=e.map(n=>String((n==null?void 0:n.name)||"tool").trim()).filter(Boolean);return t.length?`${t.slice(0,3).join(", ")}${t.length>3?` +${t.length-3}`:""}`:""}function Ku(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Oa(t)||t!=="waiting")return"none";const n=Cy(e),r=dk(e);return sh(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?Iv(n)?"user_response":"external_event":r==="user"||Iv(n)?"user_response":"unknown_wait"}function fk(e){const t=Cy(e),n=sh(t),r=Ku(e);return r==="tool_approval"?`Tool approval: ${XM(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 ZM(e){const t=Ku(e);if(t==="tool_approval")return"Review the tool request, then approve, reject, or cancel the whole run.";if(t==="user_response")return"Answer the workflow request. Submit resumes only this wait.";if(t==="scheduled")return"No response is needed. The run resumes when the scheduled time arrives or it is manually resumed.";if(t==="subworkflow")return"No direct response is needed. Inspect the child workflow or cancel the parent run.";if(t==="external_event")return"No direct response is available here. Inspect the ledger or the event source.";if(t==="unknown_wait")return"No clear prompt was provided. Review the input and recent ledger before taking action.";const n=String((e==null?void 0:e.status)||"").trim().toLowerCase();return n==="failed"?"Open the ledger, artifacts, or logs to inspect the failure.":n==="running"?"Watch the ledger/provider traces or cancel the workflow if it should stop.":Oa(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function Ov(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 QM(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",a=String(e.status||"unknown").trim().toLowerCase()||"unknown",l=Ku(e),c=Oa(a),u=wy(e,n),f=qn(e.updated_at||e.created_at)??0,h=a==="running"&&u>=14400*1e3,m=fk(e)||Ov(e)||(e.current_node?`Current node: ${e.current_node}`:a==="running"?"Running":c?"Terminal":"No current activity reported");let g="all";l==="tool_approval"?g="tool_approval":l==="user_response"?g="user_wait":l==="scheduled"?g="scheduled":l==="subworkflow"||l==="external_event"?g="subflows":a==="failed"?g="failed":a==="running"?g="running":c&&(g="finished");const y=l==="tool_approval"?0:l==="user_response"?1:l==="unknown_wait"?2:a==="failed"?3:h?4:a==="running"?5:l!=="none"?6:c?8:7,w=l==="tool_approval"||l==="user_response",k=l==="tool_approval"?"Open approval":l==="user_response"?"Open wait":"Open Observe",b=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,dk(e),m,Ov(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:a,wait_kind:l,queue:g,attention_rank:y,reason:m,expected_action:ZM(e),action_label:k,search_text:b,is_terminal:c,needs_user_action:w,is_stale:h,duration_ms:u,updated_ms:f}}function eR(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(a=>QM(a,{now_ms:n,workflow_label:r[String(a.workflow_id||"")]||String(a.workflow_id||"")}))}function tR(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 nR(e,t){const n=t.queue,a=(t.query??"").trim().toLowerCase();return e.filter(l=>{if(n==="attention"){if(!(l.needs_user_action||l.status==="failed"||l.is_stale||l.wait_kind==="unknown_wait"))return!1}else if(n!=="all"&&l.queue!==n)return!1;return!a||l.search_text.includes(a)})}function sR(e,t){const n=[...e];return n.sort((r,a)=>{if(t==="recent")return a.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-a.updated_ms;if(t==="duration")return a.duration_ms-r.duration_ms;if(t==="tokens")return(Number(a.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(a.run.workflow_id||""));const l=r.attention_rank-a.attention_rank;return l!==0?l:a.updated_ms-r.updated_ms}),n}function rR(e){const[t,n]=_.useState("attention"),[r,a]=Of("system_queues"),[l,c]=Of("system_runs"),[u,f]=_.useState(""),[h,m]=_.useState("attention"),[g,y]=_.useState(""),w=_.useMemo(()=>{const M={};for(const ee of e.artifacts){const F=String(ee.run_id||"").trim();F&&(M[F]=(M[F]||0)+1)}return M},[e.artifacts]),k=_.useMemo(()=>eR(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),b=_.useMemo(()=>tR(k),[k]),S=_.useMemo(()=>{const M=nR(k,{queue:t,query:u});return sR(M,h)},[k,t,u,h]),N=S.find(M=>String(M.run_id||"")===g)||S.find(M=>String(M.run_id||"")===e.selected_run_id)||S[0]||null,R=(N==null?void 0:N.run)||null,$=String((R==null?void 0:R.run_id)||"").trim(),A=String((R==null?void 0:R.session_id)||"").trim(),W=_.useMemo(()=>A?new Set(e.runs.filter(M=>String(M.session_id||"").trim()===A).map(M=>String(M.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,A]),z=A?W.size:0,H=_.useMemo(()=>A?e.artifacts.filter(M=>String(M.session_id||"").trim()===A||W.has(String(M.run_id||"").trim())).length:0,[e.artifacts,A,W]),G=R!=null&&R.waiting&&typeof R.waiting=="object"?R.waiting:null,re=G?sh(G):[],te=(N==null?void 0:N.reason)||(G?Sy(G,re):""),Q=(N==null?void 0:N.expected_action)||(G?sk(G,re):""),D=G?$M(G,null):"",T=$&&w[$]||0,E=Oa(R==null?void 0:R.status),L=[{key:"attention",label:"Needs attention",count:b.attention},{key:"user_wait",label:"Needs my response",count:b.user_wait},{key:"tool_approval",label:"Tool approvals",count:b.tool_approval},{key:"running",label:"Running",count:b.running},{key:"failed",label:"Failed",count:b.failed},{key:"scheduled",label:"Scheduled",count:b.scheduled},{key:"subflows",label:"Subflows / external events",count:b.subflows},{key:"finished",label:"Finished",count:b.finished},{key:"all",label:"All loaded",count:b.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${l?"":" runs_collapsed"}`,children:[s.jsxs("aside",{className:`pane runtime_ops_filters${r?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_filter_header",children:[s.jsx(Pf,{open:r,on_toggle:a,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(ze,{name:"refresh",size:14}),e.gateway_connected?"Refresh":"Reconnect"]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_queue_list",id:"runtime_ops_queues",hidden:!r,children:[L.map(M=>s.jsxs("button",{className:`runtime_ops_filter ${t===M.key?"selected":""}`,"aria-pressed":t===M.key,onClick:()=>n(M.key),children:[s.jsx("span",{children:M.label}),s.jsx("strong",{children:M.count.toLocaleString()})]},M.key)),s.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),s.jsxs("section",{className:`pane runtime_ops_table_panel${l?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(Pf,{open:l,on_toggle:c,controls:"runtime_ops_runs",title:"Runs",count:S.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:u,onChange:M=>f(M.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:h,onChange:M=>m(M.target.value),children:[s.jsx("option",{value:"attention",children:"Attention order"}),s.jsx("option",{value:"recent",children:"Latest event"}),s.jsx("option",{value:"oldest",children:"Oldest event"}),s.jsx("option",{value:"duration",children:"Longest duration"}),s.jsx("option",{value:"tokens",children:"Most tokens"}),s.jsx("option",{value:"workflow",children:"Workflow"})]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_rows",id:"runtime_ops_runs",hidden:!l,children:[S.length?null:s.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}),S.map(M=>{const ee=M.run,F=String(ee.run_id||"").trim(),U=w[F]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${F===$?"selected":""}`,"aria-current":F===$?"true":void 0,tabIndex:0,onClick:()=>{y(F),e.on_select_run(F)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),y(F),e.on_select_run(F))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Zi(ee,e.workflow_label_by_id)}),M.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(vc,{status:ee.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:sn(F,18)}),s.jsx("span",{children:mc(ee.updated_at||ee.created_at)}),s.jsx("span",{children:yc(ee)}),s.jsx("span",{className:"runtime_ops_row_reason",title:M.reason,children:M.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(ee.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(ee.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(ee.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[U.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[M.needs_user_action?s.jsx("button",{className:"btn primary",onClick:K=>{K.stopPropagation(),e.on_open_run(F)},children:M.action_label}):s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_open_run(F)},children:"Open"}),s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_open_ledger(F)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_select_run(F),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:K=>{K.stopPropagation(),e.on_filter_artifacts(F)},children:"Artifacts"})]})]})]},F)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),R?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(vc,{status:R.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:R?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Zi(R,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:sn($,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(N==null?void 0:N.reason)||MM(R)}),s.jsx("span",{children:(N==null?void 0:N.expected_action)||(String(R.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":E?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Started"}),s.jsx("strong",{children:zu(Au(R))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:yc(R)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:zu(R.updated_at||R.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:R.session_id?sn(String(R.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:R.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:T.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number(R.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number(R.tokens_total||0).toLocaleString()})]})]}),A?s.jsxs("section",{className:"runtime_ops_session_context",children:[s.jsxs("div",{children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Session context"}),s.jsx("strong",{className:"mono",children:sn(A,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[z.toLocaleString()," loaded run",z===1?"":"s"]}),s.jsxs("span",{children:[H.toLocaleString()," visible artifact",H===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(A),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void yl(A),children:"Copy session id"})]})]}):null,G?s.jsxs("div",{className:"runtime_ops_wait_summary",children:[s.jsxs("div",{className:"runtime_ops_wait_header",children:[s.jsx("span",{className:"run_hero_eyebrow",children:"Blocked on"}),s.jsx("strong",{children:te})]}),s.jsx("p",{children:Q}),D?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Si,{text:D})]}):s.jsx("div",{className:"runtime_ops_wait_request muted",children:"No explicit prompt is attached to this wait. Open Observe or the ledger for full run context before responding."}),re.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:re.map((M,ee)=>s.jsxs(xe.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((M==null?void 0:M.name)||"tool")}),nk(M).map(F=>s.jsxs("span",{className:"chip muted",title:tk,children:[F,"~"]},`${ee}:${F}`))]},`${String((M==null?void 0:M.name)||"tool")}:${ee}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(Is,{value:G,collapseAfterDepth:3,showCopy:!0})]})]}):null,Df(R)?s.jsx("div",{className:"warn_callout",children:Df(R)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run($),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger($),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts($),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void yl($),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function iR(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"}],a=_.useMemo(()=>new Set(e.type_filters),[e.type_filters]),l=Math.max(0,Number(e.artifact_total_count||0)),c=!!e.query.trim()||e.type_filters.length>0||e.date_filter!=="all"||e.scope!=="all"||!!e.artifact_run_filter.trim(),u=Math.max(1,Number(e.artifact_page_size||500)),f=Math.max(1,Math.ceil(l/u)),h=Math.min(Math.max(0,Number(e.artifact_page||0)),f-1),m=l?h*u+1:0,g=Math.min(l,h*u+e.artifacts.length),y=_.useMemo(()=>{const T={},E=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,L=(E==null?void 0:E.semantic_kind)||{},M=(E==null?void 0:E.render_kind)||{};for(const ee of n)T[ee]=Number(L[ee]||M[ee]||0);return T.audio=Number(L.audio||0),T.other=Number(L.other||0)+Number(L.artifact||0)+Number(L.binary||0)+Number(L["(none)"]||0),T},[e.artifact_facets,e.artifact_type_facets]),w=T=>{const E=new Set(a);E.has(T)?E.delete(T):E.add(T),e.on_type_filters_change(Array.from(E.values()))},k=_.useMemo(()=>{const T={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const E of e.runs){const L=String(E.status||"").trim().toLowerCase();L==="waiting"?T.waiting.push(E):L==="running"?T.running.push(E):L==="failed"?T.failed.push(E):L==="cancelled"?T.cancelled.push(E):L==="completed"?T.completed.push(E):T.other.push(E)}return T},[e.runs]),b=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,S=e.artifact_run_filter?Zi(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",N=_.useMemo(()=>{var L;const T=new Set,E=((L=e.artifact_facets)==null?void 0:L.run_id)||{};for(const M of Object.keys(E))M&&M!=="(none)"&&T.add(M);for(const M of e.artifacts)M.run_id&&T.add(M.run_id);for(const M of e.active_runs)M.run_id&&T.add(String(M.run_id));return Array.from(T).map(M=>e.run_by_id[M]||{run_id:M,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((M,ee)=>{const F=Bu(M.status)?0:1,U=Bu(ee.status)?0:1;if(F!==U)return F-U;const K=qn(M.updated_at||M.created_at)??0;return(qn(ee.updated_at||ee.created_at)??0)-K}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),R=T=>{e.on_artifact_run_filter_change(T),e.on_session_filter_change(""),e.on_scope_change(T?"run":"all")},$=T=>e.gateway_connected?Math.max(0,Number(T||0)).toLocaleString():"—",A=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,W=_.useMemo(()=>{const T=e.runtime_log_query.trim().toLowerCase(),E=e.runtime_ledger_log_items||[];return T?E.filter(L=>{var F,U;const M=L.record||{};return[L.cursor,M.run_id,M.node_id,M.status,(F=M.effect)==null?void 0:F.type,M.started_at,M.ended_at,dr(((U=M.effect)==null?void 0:U.payload)??{},900),dr(M.result??{},900)].join(" ").toLowerCase().includes(T)}):E},[e.runtime_ledger_log_items,e.runtime_log_query]),z=_.useMemo(()=>{const T=e.runtime_log_query.trim().toLowerCase(),E=WM(e.runtime_ledger_log_items);return T?E.filter(L=>[L.provider,L.model,L.run_id,L.node_id,L.status,L.error,L.prompt_preview,L.response_preview,L.tokens.prompt,L.tokens.completion,L.tokens.total].join(" ").toLowerCase().includes(T)):E},[e.runtime_ledger_log_items,e.runtime_log_query]),H=z.reduce((T,E)=>T+(Number(E.tokens.total)||0),0),G=z.filter(T=>T.missing_response||T.error).length,re=_.useMemo(()=>{const T=e.runtime_log_query.trim().toLowerCase(),E=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
126
|
-
`).replace(/\r/g,`
|
|
127
|
-
`).split(`
|
|
128
|
-
`).filter(Boolean);return T?E.filter(L=>L.toLowerCase().includes(T)):E},[e.audit_log_text,e.runtime_log_query]),te=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",Q=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",D=e.runtime_log_source==="run_ledger"?"Runtime execution records for the selected workflow run.":e.runtime_log_source==="provider_calls"?"Model/provider call records extracted from the selected run ledger.":"Global Gateway HTTP/audit tail. This is system activity, not artifact provenance.";return s.jsxs("div",{className:"page runtime_page",children:[s.jsxs("section",{className:"runtime_header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"run_hero_eyebrow",children:"System"}),s.jsx("h2",{children:e.tab==="activity"?"Activity monitor":e.tab==="artifacts"?"Artifact explorer":e.tab==="memory"?"Active memory":"Logs"}),s.jsxs("div",{className:"run_hero_meta",children:[s.jsx("span",{className:`status_pill ${e.gateway_connected?"ok":"warn"}`,children:e.gateway_connected?"gateway connected":"gateway offline"}),e.tab==="artifacts"&&e.artifact_run_filter?s.jsxs("span",{className:"chip muted",children:["filtered run ",s.jsx("span",{className:"mono",children:sn(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:sn(e.session_id,18)})]}):null]})]}),s.jsxs("div",{className:"metric_grid compact runtime_header_metrics",children:[s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Waiting"}),s.jsx("strong",{children:$(k.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:$(k.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:$(k.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",c?" (filtered)":""]}),s.jsx("strong",{children:$(l)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(T=>s.jsxs("button",{role:"tab","aria-selected":e.tab===T,className:`runtime_mode_tab ${e.tab===T?"active":""}`,onClick:()=>e.on_tab_change(T),children:[s.jsx(ze,{name:T==="activity"?"history":T==="artifacts"?"download":T==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:T==="activity"?"Activity":T==="artifacts"?"Artifacts":T==="memory"?"Memory":"Logs"})]},T))}),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(rR,{gateway_connected:e.gateway_connected,runs:e.runs,artifacts:e.artifacts,selected_run_id:e.selected_run_id,workflow_label_by_id:e.workflow_label_by_id,on_select_run:e.on_select_run,on_open_run:e.on_open_run,on_open_ledger:e.on_open_ledger,on_refresh_runs:e.on_refresh_runs,on_reconnect:e.on_reconnect,on_open_logs:()=>e.on_tab_change("logs"),on_filter_artifacts:T=>{R(T),e.on_select_run(T),e.on_tab_change("artifacts")},on_filter_session_artifacts:T=>{T&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(T),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:T=>e.on_query_change(T.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:T=>{const E=T.target.value;E!=="run"&&e.on_artifact_run_filter_change(""),E==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(E)},children:[s.jsx("option",{value:"all",children:"All runtime"}),s.jsx("option",{value:"session",children:"This session"}),s.jsx("option",{value:"run",children:"Selected run"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Group"}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:T=>e.on_group_by_change(T.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:T=>e.on_sort_by_change(T.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(ze,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(T=>{const E=a.has(T),L=y[T]||0,M=OM(T);return s.jsxs("button",{type:"button","aria-pressed":E,"aria-label":`${M} artifact type filter. Type filters combine with OR.`,title:`${M}: ${E?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${E?"active":""}`,onClick:()=>w(T),children:[s.jsx("span",{children:M}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?L.toLocaleString():"—"})]},T)}),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(T=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===T.value,className:`artifact_filter_chip ${e.date_filter===T.value?"active":""}`,onClick:()=>e.on_date_filter_change(T.value),children:T.label},T.value))})]})]}),s.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?s.jsxs(s.Fragment,{children:["Showing artifacts for ",s.jsx("strong",{children:S||sn(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>R(""),children:"Show all"})]}):s.jsxs(s.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?s.jsxs("span",{className:"mono muted",children:["Total size ",cc(e.artifact_total_bytes)]}):null]})}),s.jsxs("div",{className:"runtime_artifacts_layout",children:[s.jsxs("aside",{className:"pane artifact_filter_rail",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsx("span",{className:"pane_count",children:N.length.toLocaleString()})]}),s.jsxs("div",{className:"pane_body scroll artifact_filter_rail_list",children:[s.jsxs("button",{className:`artifact_filter_run ${e.artifact_run_filter?"":"selected"}`,onClick:()=>R(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${l.toLocaleString()} match${l===1?"":"es"}`:"counts unavailable"})]}),N.map(T=>{const E=String(T.run_id||"").trim(),L=E===e.artifact_run_filter||E===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${L?"selected":""}`,onClick:()=>R(E),title:E,children:[s.jsx("strong",{children:Zi(T,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:sn(E,15)}),s.jsx("span",{children:yc(T)})]},E)})]})]}),s.jsxs("section",{className:"pane runtime_artifact_browser",children:[s.jsxs("div",{className:"pane_header artifact_browser_header",children:[s.jsx("span",{className:"pane_title",children:"Artifacts"}),s.jsx("span",{className:"pane_count",children:l?`${m.toLocaleString()}-${g.toLocaleString()} of ${l.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),f>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled:h<=0,children:"First"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h-1),disabled:h<=0,children:"Prev"}),s.jsxs("span",{className:"muted artifact_page_label",children:["Page ",(h+1).toLocaleString()," / ",f.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h+1),disabled:h>=f-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(f-1),disabled:h>=f-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[e.artifact_groups.length?null:s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}),s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(T=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:T.key}),s.jsx("span",{className:"artifact_group_count",children:T.items.length})]}),T.items.map(E=>{var U;const L=E.run_id&&e.run_by_id[E.run_id]||null,M=L?Zi(L,e.workflow_label_by_id):Ny(E),ee=Mv(E),F=Number(((U=E.access)==null?void 0:U.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===E.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(E.artifact_id),E.run_id&&e.on_select_run(E.run_id)},title:E.artifact_id,children:[s.jsx(Lv,{artifact:E,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:Tv(n_(E,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:Ou(E)}),E.render_kind&&E.render_kind!==E.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:E.render_kind}):null,E.legacy_inferred?s.jsx("span",{className:"artifact_type_badge inferred",children:"legacy inferred"}):null]}),s.jsxs("div",{className:"artifact_row_facts",children:[s.jsxs("span",{children:[s.jsx("b",{children:"Created"})," ",FM(E)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",cc(E.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",Av(E)]}),F?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",F.toLocaleString()]}):null,ee?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",ee]}):null,E.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",E.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[M?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",M]}):null,E.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",sn(E.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",Sg(E)]}),Iu(E)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Iu(E)]}):null,Ff(E)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",Ff(E)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",sn(E.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",Ev(E)]})]}),Rv(E)?s.jsx("div",{className:"artifact_row_path mono",children:Rv(E)}):null]})]},E.artifact_id)})]},T.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?Ng(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):Ng(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var U,K,O,V,J,le,ie;const T=zM(t),E=ak(t),L=Mv(t),M=Number(((U=t.access)==null?void 0:U.access_count)||0)||0,ee=gn((K=t.links)==null?void 0:K.provider_trace,(O=t.links)==null?void 0:O.provider_trace_url,(V=t.links)==null?void 0:V.provider_trace_id),F=gn((J=t.links)==null?void 0:J.audit,(le=t.links)==null?void 0:le.audit_tail,(ie=t.links)==null?void 0:ie.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(Lv,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:Tv(n_(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[Ou(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",cc(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(JM,{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:Ou(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:zu(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:cc(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:Av(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:M?M.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?sn(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:b?Zi(b,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:Sg(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Iu(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:E||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:L||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Trace"}),s.jsx("strong",{children:t.provider_trace_available?"available":"not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provenance"}),s.jsx("strong",{children:Ev(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:sn(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:sn(t.sha256,30)})]}):null]}),T?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:T})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(Is,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>R(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),s.jsx("button",{className:"btn",onClick:()=>{ee&&window.open(ee,"_blank","noopener,noreferrer")},disabled:!ee,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{F?window.open(F,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!F&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void yl(t.artifact_id),disabled:!t.artifact_id,children:"Copy artifact id"})]})]})})(),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw metadata"}),s.jsx(Is,{value:t.raw,collapseAfterDepth:3,showCopy:!0})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select an artifact to inspect metadata, preview, or download content."})]})})]})]}):null,e.tab==="logs"?s.jsxs("section",{className:"overview_panel runtime_logs_panel",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsxs("div",{children:[s.jsx("h3",{children:Q}),s.jsx("div",{className:"mono muted",children:D})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[te&&e.runtime_ledger_log_meta?s.jsx("span",{className:"mono muted",children:e.runtime_ledger_log_meta}):null,e.runtime_log_source==="gateway_audit"&&e.audit_log_meta?s.jsx("span",{className:"mono muted",children:e.audit_log_meta}):null,s.jsxs("button",{className:"btn btn_icon",onClick:()=>{te?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:te?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(ze,{name:"refresh",size:14}),te?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),s.jsxs("div",{className:"runtime_log_toolbar",children:[s.jsxs("div",{className:"seg_toggle mono",children:[s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),s.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:T=>e.on_runtime_log_query_change(T.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:A?Zi(A,e.workflow_label_by_id):e.selected_run_id?sn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:sn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:A!=null&&A.session_id?sn(String(A.session_id),28):e.session_id?sn(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>R(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!W.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No ledger records match the current search."}):null,s.jsx("div",{className:"runtime_log_event_list","aria-label":"Selected run ledger records",children:W.map(T=>{var J,le;const E=T.record||{},L=String(((J=E==null?void 0:E.effect)==null?void 0:J.type)||"").trim(),M=String((E==null?void 0:E.status)||"").trim(),ee=String((E==null?void 0:E.node_id)||"").trim(),F=gn(E==null?void 0:E.ended_at,E==null?void 0:E.started_at,E==null?void 0:E.ts),U=go(E),K=ok(E),O=L?At(dr(((le=E==null?void 0:E.effect)==null?void 0:le.payload)??{},1200),{max_chars:1200,max_lines:6}):"",V=lk(E)||(U?`Waiting for ${String(U.reason||"input")}`:"")||((E==null?void 0:E.result)!==void 0?dr(E.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${wc(M)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",T.cursor]}),s.jsx(vc,{status:M||"record"}),L?s.jsx("span",{className:"chip mono muted",children:L}):null,ee?s.jsx("strong",{className:"mono",children:ee}):null,F?s.jsx("span",{className:"mono muted",children:zu(F)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[K||Fm(E),O&&O!=="{}"?O:""].filter(Boolean).join(`
|
|
129
|
-
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:At(V||"—",{max_chars:1200,max_lines:6})})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw ledger record"}),s.jsx(Is,{value:E,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${T.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:A?Zi(A,e.workflow_label_by_id):e.selected_run_id?sn(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:sn(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:z.length.toLocaleString()}),s.jsx("em",{className:"mono",children:H?`${H.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:G.toLocaleString()})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_runtime_log_source_change("run_ledger"),disabled:!e.selected_run_id,children:"Run ledger"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect provider calls."}),e.selected_run_id&&!z.length&&!e.runtime_ledger_log_loading?s.jsx("div",{className:"empty_state_inline",children:"No provider calls are present in the selected run ledger, or none match the current search."}):null,s.jsx("div",{className:"provider_activity_list runtime_provider_log_list",children:z.map(T=>s.jsxs("article",{className:`provider_activity ${T.error||T.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[T.provider||"provider unknown",T.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[T.node_id?s.jsx("span",{className:"mono",children:T.node_id}):null,T.run_id?s.jsx("span",{className:"mono",children:sn(T.run_id,16)}):null,s.jsx("span",{children:yy(T.duration_ms)}),T.status?s.jsx(vc,{status:T.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[T.tokens.total?T.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:T.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:T.response_preview||T.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(Is,{value:T.raw,collapseAfterDepth:3,showCopy:!0})]})]},T.id))})]}):s.jsxs(s.Fragment,{children:[e.audit_log_error?s.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,s.jsx("pre",{className:"mono audit_log_tail",children:re.length?re.join(`
|
|
130
|
-
`):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function aR(e){const[t,n]=_.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],a=e.wait.allow_free_text!==!1,l=e.disabled===!0,c=String(e.wait.prompt||"").trim();return s.jsxs(s.Fragment,{children:[r.length?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Expected response"}),s.jsxs("select",{className:"mono",value:t,onChange:u=>n(u.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((u,f)=>s.jsx("option",{value:String(u),children:String(u)},f))]})]}):null,a?s.jsxs("div",{className:"field",children:[s.jsx("label",{children:r.length?"Or type a response":c?"Your answer":"Response to resume this wait"}),s.jsx("textarea",{className:"mono wait_response_input",value:t,onChange:u=>n(u.target.value),placeholder:c?"Type your answer to the request above…":"Type the response the workflow is waiting for…",rows:4})]}):null,s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn primary",disabled:l||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function Pv(e,t,n){if(If(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Zi(e,t)}function Dv(e){const t=If(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:L0(e.run)}):null}function oR(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,a=e.sections.reduce((l,c)=>l+c.rows.reduce((u,f)=>{const h=[f.run,...f.children];return u+h.filter(m=>Bu(m.status)).length},0),0);return s.jsxs("aside",{className:`observatory_sidebar pane${n?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"run_nav_header pane_header",children:[e.list?s.jsx(Pf,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${a.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 • ",a.toLocaleString()," active"]})]}),s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[s.jsx(ze,{name:"refresh",size:14}),e.loading?"…":""]})]}),s.jsxs("div",{className:"run_nav_controls",id:"run_nav_controls",hidden:!n,children:[s.jsx("input",{value:e.search,onChange:l=>e.on_search(l.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(l=>s.jsx("button",{className:`seg_btn ${e.filter===l?"active":""}`,onClick:()=>e.on_filter(l),children:l},l))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:l=>e.on_group_by(l.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",id:"run_nav_tree",hidden:!n,children:[e.sections.length?null:e.connected?s.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):s.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",s.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(l=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:l.label}),s.jsx("span",{className:"mono",children:l.rows.length})]}),l.rows.map(c=>{const u=c.run,f=String(u.run_id||"").trim(),h=f===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${h?"selected":""} ${f===r?"root_context":""}`,onClick:()=>e.on_select(f,f),title:f,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:Pv(u,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Dv,{run:u}),u.status?s.jsx(vc,{status:Zm(u)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:sn(f,13)}),s.jsx("span",{children:Au(u)?mc(Au(u)):"no start"}),s.jsx("span",{children:yc(u)})]})]}),c.children.length?s.jsx("div",{className:"run_tree_children",children:c.children.map(m=>{const g=String(m.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${g===t?"selected":""}`,onClick:()=>e.on_select(g,f),title:g,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:Pv(m,e.workflow_label_by_id,e.automation_titles)}),s.jsx(Dv,{run:m}),s.jsx(vc,{status:Zm(m)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:sn(g,13)}),s.jsx("span",{children:Au(m)?mc(Au(m)):"child"}),s.jsx("span",{children:yc(m)})]})]},g)})}):null]},f)})]},l.key))]})]})}class lR{constructor(){es(this,"_buffer","");es(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
|
|
131
|
-
`);if(r===-1)return;const a=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const l=a.endsWith("\r")?a.slice(0,-1):a;if(l.startsWith(":"))continue;if(l===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const h={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
|
|
132
|
-
`)};n(h)}this._current={data_lines:[]};continue}const c=l.indexOf(":"),u=c===-1?l:l.slice(0,c),f=c===-1?"":l.slice(c+1).trimStart();if(u==="id"){this._current.id=f;continue}if(u==="event"){this._current.event=f;continue}if(u==="data"){this._current.data_lines.push(f);continue}}}}const Lt=Xg;function xr(e,t=3e4){const n=AbortSignal.timeout(t);if(!e)return n;const r=AbortSignal.any;return typeof r=="function"?r([e,n]):e}function Cg(){var t;const e={};try{const n=(t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("abstractobserver_gateway_csrf=")))==null?void 0:t.slice(30);n&&(e["X-AbstractObserver-CSRF"]=decodeURIComponent(n))}catch{}return e}function $t(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...Cg()}}async function Gn(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class cR extends Error{constructor(n,r){super(r);es(this,"status");this.name="GatewayRequestError",this.status=n}}async function rc(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const a=JSON.parse(n),l=a&&typeof a=="object"?a.detail:void 0;typeof l=="string"&&l.trim()?r=l.trim():l&&typeof l=="object"&&typeof l.message=="string"&&l.message.trim()&&(r=l.message.trim())}catch{}return new cR(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}async function uR(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 Cp{constructor(t){es(this,"_cfg");es(this,"fetch_gateway",(t,n)=>fetch(Lt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...$t(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const a=String((r==null?void 0:r.bundle_id)||"").trim(),l=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),c=String(t||"").trim(),u=String((r==null?void 0:r.interface)||"").trim();if(c==="@default"&&(!u||a))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const f={input_data:n||{}};a&&(f.bundle_id=a),c&&(f.flow_id=c),c==="@default"&&(f.interface=u),l&&(f.session_id=l),r!=null&&r.workspace&&(f.workspace=r.workspace);const h=await fetch(Lt(this._cfg.base_url,st("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(f)});if(!h.ok)throw new Error(await uR(h)||`start_run failed: ${h.status}`);const m=await h.json(),g=m==null?void 0:m.run_id;if(typeof g!="string"||!g)throw new Error("start_run: missing run_id");return g}async list_mcp_servers(){for(const t of[st("mcp/servers"),st("mcp"),st("discovery/mcp")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(n.status===404||!n.ok)continue;const r=await n.json(),a=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(!a)continue;return a.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),url:typeof(l==null?void 0:l.url)=="string"?l.url:void 0,description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,auth_required:typeof(l==null?void 0:l.auth_required)=="boolean"?l.auth_required:void 0})).filter(l=>l.name)}catch{return null}return null}async list_skills(){for(const t of[st("skills"),st("skills/registry")])try{const n=await fetch(Lt(this._cfg.base_url,t),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(n.status===404||!n.ok)continue;const r=await n.json(),a=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(!a)continue;return a.map(l=>({name:String((l==null?void 0:l.name)||(l==null?void 0:l.id)||"").trim(),description:typeof(l==null?void 0:l.description)=="string"?l.description:void 0,version:typeof(l==null?void 0:l.version)=="string"?l.version:void 0,trust_level:typeof(l==null?void 0:l.trust_level)=="string"?l.trust_level:void 0,blocked:typeof(l==null?void 0:l.blocked)=="boolean"?l.blocked:void 0,requires_review:typeof(l==null?void 0:l.requires_review)=="boolean"?l.requires_review:void 0,tree_hash:typeof(l==null?void 0:l.tree_hash)=="string"?l.tree_hash:void 0,reasons:Array.isArray(l==null?void 0:l.reasons)?l.reasons.map(c=>String(c||"")).filter(Boolean):void 0})).filter(l=>l.name)}catch{return null}return null}async get_run(t){const n=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(t)}`)),{headers:{...$t(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await Gn(n)}`);return await n.json()}async find_run(t){const n=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(t)}`)),{headers:{...$t(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await rc(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 a=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&a.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&a.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&a.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&a.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&a.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const l=Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/history_bundle?${a.toString()}`)),c=await fetch(l,{headers:{...$t(this._cfg.auth_token)}});if(!c.ok)throw new Error(`get_run_history_bundle failed: ${await Gn(c)}`);return await c.json()}async list_runs(t){const n=typeof(t==null?void 0:t.limit)=="number"?t.limit:50,r=String((t==null?void 0:t.status)||"").trim(),a=String((t==null?void 0:t.workflow_id)||"").trim(),l=String((t==null?void 0:t.session_id)||"").trim(),c=(t==null?void 0:t.root_only)===!0,u=new URLSearchParams;u.set("limit",String(n)),r&&u.set("status",r),a&&u.set("workflow_id",a),l&&u.set("session_id",l),c&&u.set("root_only","true"),(t==null?void 0:t.archived_only)===!0&&u.set("archived_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&u.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&u.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&u.set("include_drafts",String(t.include_drafts));const f=Lt(this._cfg.base_url,st(`runs?${u.toString()}`)),h=await fetch(f,{headers:{...$t(this._cfg.auth_token)},signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`list_runs failed: ${await Gn(h)}`);return await h.json()}async audit_log_tail(t){const n=typeof(t==null?void 0:t.max_bytes)=="number"?Math.max(1024,Math.min(4e5,Math.floor(t.max_bytes))):8e4,r=Lt(this._cfg.base_url,st(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),a=await fetch(r,{headers:{...$t(this._cfg.auth_token)}});if(!a.ok)throw new Error(`audit_log_tail failed: ${await Gn(a)}`);return await a.json()}async gateway_about(){const t=await fetch(Lt(this._cfg.base_url,st("about")),{headers:{...$t(this._cfg.auth_token)},signal:xr(void 0,1e4)});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}async get_run_input_data(t){const n=String(t||"").trim();if(!n)throw new Error("get_run_input_data: run_id is required");const r=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await Gn(r)}`);return await r.json()}async list_run_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_run_artifacts: run_id is required");const a=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,c=Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(a))}&offset=${encodeURIComponent(String(l))}`)),u=await fetch(c,{headers:{...$t(this._cfg.auth_token)}});if(!u.ok)throw new Error(`list_run_artifacts failed: ${await Gn(u)}`);return await u.json()}async list_session_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_session_artifacts: session_id is required");const a=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,c=Lt(this._cfg.base_url,st(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(a))}&offset=${encodeURIComponent(String(l))}`)),u=await fetch(c,{headers:{...$t(this._cfg.auth_token)}});if(!u.ok)throw new Error(`list_session_artifacts failed: ${await Gn(u)}`);return await u.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const r=String((t==null?void 0:t.session_id)||"").trim(),a=String((t==null?void 0:t.run_id)||"").trim(),l=String((t==null?void 0:t.modality)||"").trim(),c=String((t==null?void 0:t.artifact_kind)||"").trim(),u=String((t==null?void 0:t.semantic_kind)||"").trim(),f=String((t==null?void 0:t.render_kind)||"").trim(),h=String((t==null?void 0:t.workflow_id)||"").trim(),m=String((t==null?void 0:t.node_id)||"").trim(),g=String((t==null?void 0:t.content_type)||"").trim(),y=String((t==null?void 0:t.query)||"").trim(),w=String((t==null?void 0:t.tags)||"").trim(),k=String((t==null?void 0:t.cursor)||"").trim(),b=String((t==null?void 0:t.order_by)||"").trim(),S=String((t==null?void 0:t.order)||"").trim(),N=String((t==null?void 0:t.created_after)||"").trim(),R=String((t==null?void 0:t.created_before)||"").trim(),$=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,A=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),a&&n.set("run_id",a),l&&n.set("modality",l),c&&n.set("artifact_kind",c),u&&n.set("semantic_kind",u),f&&n.set("render_kind",f),h&&n.set("workflow_id",h),m&&n.set("node_id",m),g&&n.set("content_type",g),y&&n.set("query",y),w&&n.set("tags",w),k&&n.set("cursor",k),b&&n.set("order_by",b),S&&n.set("order",S),N&&n.set("created_after",N),R&&n.set("created_before",R),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String($)),n.set("offset",String(A));const W=await fetch(Lt(this._cfg.base_url,st(`artifacts/search?${n.toString()}`)),{headers:{...$t(this._cfg.auth_token)}});if(!W.ok)throw new Error(`search_artifacts failed: ${await Gn(W)}`);return await W.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const a of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const l=String((t==null?void 0:t[a])||"").trim();l&&n.set(a,l)}const r=await fetch(Lt(this._cfg.base_url,st(`artifacts/stats?${n.toString()}`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await Gn(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const a=String(t||"").trim(),l=String(n||"").trim();if(!a)throw new Error("download_run_artifact_content: run_id is required");if(!l)throw new Error("download_run_artifact_content: artifact_id is required");const c=String((r==null?void 0:r.access)||"").trim(),u=c?`?access=${encodeURIComponent(c)}`:"",f=Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(a)}/artifacts/${encodeURIComponent(l)}/content${u}`)),h=await fetch(f,{headers:{...$t(this._cfg.auth_token)}});if(!h.ok)throw new Error(`download_run_artifact_content failed: ${await Gn(h)}`);return await h.blob()}async list_entities(){const t=await fetch(Lt(this._cfg.base_url,st("entities")),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!t.ok)throw new Error(`list_entities failed: ${await Gn(t)}`);const n=await t.json();return{entities:Array.isArray(n==null?void 0:n.entities)?n.entities:[]}}async get_entity_phases_spec(){const t=await fetch(Lt(this._cfg.base_url,st("entities/spec/phases")),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await Gn(t)}`);return await t.json()}async get_entity_cognition(t){const n=await fetch(Lt(this._cfg.base_url,st(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await Gn(n)}`);return await n.json()}async get_entity_card(t){const n=String(t||"").trim();if(!n)throw new Error("get_entity_card: name is required");const r=await fetch(Lt(this._cfg.base_url,st(`entities/${encodeURIComponent(n)}/card`)),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!r.ok)throw new Error(`get_entity_card failed: ${await Gn(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),a=String(n||"").trim();if(!r||!a)throw new Error("read_entity_diary_entry: name and entry_id are required");const l=Lt(this._cfg.base_url,st(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(a)}?reason=${encodeURIComponent("observer board hint chip")}`)),c=await fetch(l,{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!c.ok)throw new Error(`read_entity_diary_entry failed: ${await Gn(c)}`);return await c.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),a=Number((n==null?void 0:n.limit)||0),l=Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(a))}`)),c=await fetch(l,{headers:{...$t(this._cfg.auth_token)},signal:xr(n==null?void 0:n.signal)});if(!c.ok)throw new Error(`get_ledger failed: ${c.status}`);const u=await c.json(),f=Array.isArray(u==null?void 0:u.items)?u.items:[],h=typeof(u==null?void 0:u.next_after)=="number"?u.next_after:r;return{items:f,next_after:h}}async get_ledger_batch(t){const n=Array.isArray(t==null?void 0:t.runs)?t.runs:[],r=Number((t==null?void 0:t.limit)||0),a=await fetch(Lt(this._cfg.base_url,st("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:xr()});if(!a.ok)throw new Error(`get_ledger_batch failed: ${a.status}`);const l=await a.json(),u=(l&&typeof l=="object"?l:{}).runs;return{runs:u&&typeof u=="object"?u:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const a={include_subruns:(n==null?void 0:n.include_subruns)!==!1},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(a.provider=l);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(a.model=c);const u=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(a)});if(!u.ok)throw await rc(u,"The gateway could not summarize this run");return await u.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const a={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[],persist:!!(n!=null&&n.persist)},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(a.provider=l);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(a.model=c);const u=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(a)});if(!u.ok)throw await rc(u,"The gateway could not answer");return await u.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const a=n==null?void 0:n.audio_artifact;if(!a||typeof a!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(a.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const c={audio_artifact:a};for(const m of["language","provider","model","request_id"]){const g=String((n==null?void 0:n[m])||"").trim();g&&(c[m]=g)}const u=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(c)});if(!u.ok)throw await rc(u,"The gateway refused the transcription");const f=await u.json(),h=String((f==null?void 0:f.text)||"");return{ok:!!(f!=null&&f.ok),run_id:String((f==null?void 0:f.run_id)||""),request_id:String((f==null?void 0:f.request_id)||""),text:h,transcript_artifact:f==null?void 0:f.transcript_artifact,provider:f!=null&&f.provider?String(f.provider):null,model:f!=null&&f.model?String(f.model):null,duration_ms:Number.isFinite(Number(f==null?void 0:f.duration_ms))?Number(f.duration_ms):null}}async voice_defaults(){const t=await fetch(Lt(this._cfg.base_url,st("voice/defaults")),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!t.ok)throw await rc(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 a=await fetch(Lt(this._cfg.base_url,st(`voice/voices?${r.toString()}`)),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!a.ok)throw await rc(a,"The gateway could not list its voices");return await a.json()}gateway_url(t){return Lt(this._cfg.base_url,t)}auth_headers(){return $t(this._cfg.auth_token)}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const a=String((n==null?void 0:n.text)||"").trim();if(!a)throw new Error("voice_tts: text is required");const l={text:a},c=String((n==null?void 0:n.voice)||"").trim();c&&(l.voice=c);const u=String((n==null?void 0:n.format)||"").trim();u&&(l.format=u);const f=String((n==null?void 0:n.request_id)||"").trim();f&&(l.request_id=f);const h=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(l)});if(!h.ok)throw new Error(`voice_tts failed: ${await Gn(h)}`);const m=await h.json();return{ok:!!(m!=null&&m.ok),run_id:String((m==null?void 0:m.run_id)||""),request_id:String((m==null?void 0:m.request_id)||""),audio_artifact:m==null?void 0:m.audio_artifact}}async save_chat_thread(t,n){const r=String(t||"").trim();if(!r)throw new Error("save_chat_thread: run_id is required");const a={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},l=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";l&&(a.provider=l);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(a.model=c);const u=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";u&&(a.title=u);const f=await fetch(Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(a)});if(!f.ok)throw new Error(`save_chat_thread failed: ${await Gn(f)}`);return await f.json()}async list_bundles(){const t=await fetch(Lt(this._cfg.base_url,st("bundles")),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async get_gateway_json(t,n){const r=await fetch(Lt(this._cfg.base_url,st(t)),{headers:{...$t(this._cfg.auth_token)},signal:n??xr()});if(!r.ok)throw new Error(await Gn(r));return await r.json()}async reload_bundles(){const t=await fetch(Lt(this._cfg.base_url,st("bundles/reload")),{method:"POST",headers:{...$t(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const r=(n==null?void 0:n.overwrite)===!0,a=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",r?"true":"false"),l.set("reload",a?"true":"false"),l.set("file",t,t.name||"upload.flow");const c=await fetch(Lt(this._cfg.base_url,st("bundles/upload")),{method:"POST",headers:{...$t(this._cfg.auth_token)},body:l});if(!c.ok)throw new Error(`upload_bundle failed: ${await Gn(c)}`);return await c.json()}async attachments_upload(t,n,r){const a=String(t||"").trim();if(!a)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const l=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",c=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),u=new FormData;u.append("session_id",a),u.append("file",n,l),u.append("filename",l),c&&u.append("content_type",c);const f=await fetch(Lt(this._cfg.base_url,st("attachments/upload")),{method:"POST",headers:{...$t(this._cfg.auth_token)},body:u});if(!f.ok)throw new Error(`attachments_upload failed: ${await Gn(f)}`);const h=await f.json(),m=h==null?void 0:h.attachment;if(!m||typeof m!="object")throw new Error("attachments_upload: missing attachment");if(!String(m.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return m}async remove_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("remove_bundle: bundle_id is required");const a=new URLSearchParams,l=String((n==null?void 0:n.bundle_version)||"").trim();l&&a.set("bundle_version",l),a.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const c=Lt(this._cfg.base_url,st(`bundles/${encodeURIComponent(r)}?${a.toString()}`)),u=await fetch(c,{method:"DELETE",headers:{...$t(this._cfg.auth_token)}});if(!u.ok)throw new Error(`remove_bundle failed: ${await Gn(u)}`);return await u.json()}async discovery_tools(){const t=await fetch(Lt(this._cfg.base_url,st("discovery/tools")),{headers:{...$t(this._cfg.auth_token)}});if(!t.ok)throw new Error(`discovery_tools failed: ${t.status}`);return await t.json()}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,r=Lt(this._cfg.base_url,st(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),a=await fetch(r,{headers:{...$t(this._cfg.auth_token)}});if(!a.ok)throw new Error(`discovery_providers failed: ${a.status}`);return await a.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await fetch(Lt(this._cfg.base_url,st(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`discovery_provider_models failed: ${r.status}`);return await r.json()}async get_bundle(t){const n=String(t||"").trim();if(!n)throw new Error("get_bundle: bundle_id is required");const r=await fetch(Lt(this._cfg.base_url,st(`bundles/${encodeURIComponent(n)}`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_bundle failed: ${r.status}`);return await r.json()}async get_bundle_flow(t,n){const r=String(t||"").trim(),a=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!a)throw new Error("get_bundle_flow: flow_id is required");const l=await fetch(Lt(this._cfg.base_url,st(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(a)}`)),{headers:{...$t(this._cfg.auth_token)}});if(!l.ok)throw new Error(`get_bundle_flow failed: ${l.status}`);return await l.json()}async get_workflow_flow(t){const n=String(t||"").trim();if(!n)throw new Error("get_workflow_flow: workflow_id is required");const r=await fetch(Lt(this._cfg.base_url,st(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...$t(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_workflow_flow failed: ${r.status}`);return await r.json()}async discovery_capabilities(){const t=await fetch(Lt(this._cfg.base_url,st("discovery/capabilities")),{headers:{...$t(this._cfg.auth_token)},signal:xr()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await Gn(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return K1({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>$t(t)})}async submit_command(t){const n=await fetch(Lt(this._cfg.base_url,st("commands")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),r=String((t==null?void 0:t.order)||"desc").trim().toLowerCase(),a=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,l={scope:n,order:r,limit:a},c=String((t==null?void 0:t.run_id)||"").trim();c&&(l.run_id=c);const u=String((t==null?void 0:t.session_id)||"").trim();u&&(l.session_id=u);const f=String((t==null?void 0:t.owner_id)||"").trim();f&&(l.owner_id=f),t!=null&&t.all_owners&&(l.all_owners=!0);const h=String((t==null?void 0:t.subject)||"").trim();h&&(l.subject=h);const m=String((t==null?void 0:t.predicate)||"").trim();m&&(l.predicate=m);const g=String((t==null?void 0:t.object)||"").trim();g&&(l.object=g);const y=String((t==null?void 0:t.since)||"").trim();y&&(l.since=y);const w=String((t==null?void 0:t.until)||"").trim();w&&(l.until=w);const k=String((t==null?void 0:t.active_at)||"").trim();k&&(l.active_at=k);const b=String((t==null?void 0:t.query_text)||"").trim();b&&(l.query_text=b),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(l.min_score=Number(t.min_score));const S=await fetch(Lt(this._cfg.base_url,st("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...$t(this._cfg.auth_token)},body:JSON.stringify(l)});if(!S.ok)throw new Error(`kg_query failed: ${await Gn(S)}`);return await S.json()}async stream_ledger(t,n){var g;const r=Number((n==null?void 0:n.after)||0),a=n.on_step,l=n.signal,c=Lt(this._cfg.base_url,st(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),u=await fetch(c,{headers:{Accept:"text/event-stream",...$t(this._cfg.auth_token)},signal:l});if(!u.ok)throw await rc(u,"The ledger stream was refused");if(!u.body)throw new Error("stream_ledger: response body is missing");(g=n.on_open)==null||g.call(n);const f=u.body.getReader(),h=new TextDecoder("utf-8"),m=new lR;for(;;){const{value:y,done:w}=await f.read();if(w)return;const k=h.decode(y,{stream:!0});m.push(k,b=>{if(!(b.event!=="step"||!b.data))try{const S=JSON.parse(b.data);S&&typeof S.cursor=="number"&&S.record&&a(S)}catch{}})}}}function dR(e,t=()=>({})){return async(n,r)=>{var u;const a=await e(n,{method:r.method,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{},...t()},...r.body!==void 0?{body:JSON.stringify(r.body)}:{}}),l=await a.text();let c=null;try{c=l?JSON.parse(l):null}catch{c=null}if(!a.ok)throw new Error(typeof(c==null?void 0:c.detail)=="string"?c.detail:typeof((u=c==null?void 0:c.detail)==null?void 0:u.message)=="string"?c.detail.message:l||`Gateway request failed (${a.status})`);return c}}function fR({connected:e,request:t,value:n,onChange:r,disabled:a}){const[l,c]=_.useState(null),[u,f]=_.useState(null),h=JSON.stringify(n);_.useEffect(()=>{if(!e){c(null),f(null);return}let y=!0;return f(null),Lf(t)(n).then(w=>y&&c(w)).catch(w=>y&&f(`Could not read your workspaces: ${x_(w)}`)),()=>{y=!1}},[e,h,t]);const m=_.useCallback(async y=>{const w=await Lf(t)(y);c(w),r(y)},[t,r]),g=e?a?"The run is starting.":null:"Connect to your gateway to choose workspaces.";return s.jsx(Yb,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:l,onChange:m,loadError:e?u:g,unavailableReason:g})}function hR(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class mR{constructor(t){es(this,"_cfg");this._cfg={...t,url:(t.url||"").trim()}}async call_tool(t){const n=String((t==null?void 0:t.name)||"").trim(),r=String((t==null?void 0:t.call_id)||(t==null?void 0:t.id)||Rs()),a=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:r,name:"",success:!1,output:null,error:"Missing tool name"};const l={jsonrpc:"2.0",id:Rs(),method:"tools/call",params:{name:n,arguments:a}},c=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...hR(this._cfg.auth_token)},body:JSON.stringify(l)});if(!c.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${c.status}`};const u=await c.json().catch(()=>null),f=u==null?void 0:u.result,h=!!(f!=null&&f.isError),g=(Array.isArray(f==null?void 0:f.content)?f.content:[]).find(w=>w&&w.type==="text"&&typeof w.text=="string"),y=(g==null?void 0:g.text)??"";return h?{call_id:r,name:n,success:!1,output:null,error:y||"Tool failed"}:{call_id:r,name:n,success:!0,output:y,error:null}}}class Fv{constructor(t,n){es(this,"pending",[]);es(this,"scheduled",!1);es(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 zv(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 _R(e,t){const n=qn(e.updated_at||e.created_at)??0;return(qn(t.updated_at||t.created_at)??0)-n}function pR(e,t){const n=t.query.trim().toLowerCase(),r=[...e],a={};for(const y of r){const w=String(y.run_id||"").trim();w&&(a[w]=y)}for(const y of e){const w=zv(y);if(String(y.role||"")==="occurrence"&&w&&!a[w]){const k={run_id:w,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:w,updated_at:y.updated_at??null,created_at:y.created_at??null};a[w]=k,r.push(k)}}const l={},c={};for(const y of r){const w=String(y.run_id||"").trim();if(!w)continue;const k=zv(y,t.parent_hint?t.parent_hint(w):"");c[w]=k,k&&(l[k]||(l[k]=[])).push(y)}const u=y=>{const w=String(y.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Bu(w):t.filter==="waiting"?w==="waiting":t.filter==="terminal"?Oa(w):t.filter==="failed"?w==="failed":!0},f=y=>{if(!n)return!0;const w=String(y.workflow_id||y.schedule_target_workflow_id||"").trim(),k=w?t.workflow_label_by_id[w]||w:"";return[y.run_id,w,k,y.session_id,y.status,y.session_kind,y.automation_id].join(" ").toLowerCase().includes(n)},h=[];for(const y of r){const w=String(y.run_id||"").trim();if(!w)continue;const k=c[w];(!k||!a[k])&&h.push(w)}const m={},g=y=>{if(t.group_by==="workflow"){const k=String(y.schedule_target_workflow_id||y.workflow_id||"").trim()||"(unknown workflow)";return{key:k,label:t.workflow_label_by_id[k]||k}}if(t.group_by==="session"){const k=String(y.session_id||"").trim()||"(no session)";return{key:k,label:k}}const w=String(y.status||"").trim().toLowerCase()||"unknown";return Bu(w)?{key:"active",label:"Active"}:w==="failed"?{key:"failed",label:"Failed"}:Oa(w)?{key:"finished",label:"Finished"}:{key:w,label:w}};for(const y of h){const w=a[y];if(!w)continue;const k=[...l[y]||[]].sort(_R),b=k.some(N=>u(N)&&f(N));if(!(u(w)&&f(w))&&!b)continue;const S=g(w);m[S.key]||(m[S.key]={key:S.key,label:S.label,rows:[]}),m[S.key].rows.push({run:w,children:k})}return Object.values(m).sort((y,w)=>{const k={active:0,waiting:1,failed:2,finished:3},b=k[y.key]??10,S=k[w.key]??10;return b!==S?b-S:y.label.localeCompare(w.label)})}const gR={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"},yR=[{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 wR(){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:[yR.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:gR[n.type]},children:n.shape}),s.jsx("span",{className:"pin-legend-label mono",children:n.label}),s.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),s.jsxs("div",{className:"pin-legend-rules mono",children:[s.jsx("strong",{children:"Connection Rules:"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Execution connects to Execution only"}),s.jsx("li",{children:'"Any" type accepts all data types'}),s.jsx("li",{children:"Same types always compatible"}),s.jsx("li",{children:"Array and Object are interchangeable"}),s.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}function hn(e){return typeof e=="string"?e:e==null?"":String(e)}function Bv(e,t){const n=hn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function hk(e){const t=hn(e==null?void 0:e.targetHandle),n=hn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function mk(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return hn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function _k(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=hn(n).trim();if(!r)return"";if(r.includes(":")){const a=r.split(":",2);if(a.length===2&&a[1])return a[1].trim()}return r}function vR(e){const t=hn(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(mk(r)==="on_flow_start"){const a=hn(r==null?void 0:r.id).trim();if(a)return a}return""}function Ep(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 cf(e,t){const n=hn(e).trim(),r=hn(t).trim();return r?n?`${n}::${r}`:r:""}function xR(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],a=new Set,l=(c,u,f,h)=>{if(!c||typeof c!="object"||n.length>=e.max_nodes||r.length>=e.max_edges)return;const m=Array.isArray(c.nodes)?c.nodes:[],g=Array.isArray(c.edges)?c.edges:[];for(const y of m){const w=hn(y==null?void 0:y.id).trim();if(!w)continue;const k=cf(u,w);if(!k||a.has(k))continue;const b=Ep(y),S={...y,id:k,position:{x:b.x+f.x,y:b.y+f.y}};if(n.push(S),a.add(k),n.length>=e.max_nodes)break}for(const y of g){if(!hk(y))continue;const w=hn(y==null?void 0:y.source).trim(),k=hn(y==null?void 0:y.target).trim();if(!w||!k)continue;const b=cf(u,w),S=cf(u,k);if(!b||!S)continue;const N=hn(y==null?void 0:y.id).trim(),R=N?`${b}->${S}::${N}`:`${b}->${S}`;if(r.push({...y,id:R,source:b,target:S}),r.length>=e.max_edges)break}if(!(h>=e.max_depth))for(const y of m){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(mk(y)!=="subflow")continue;const w=_k(y);if(!w)continue;const k=e.flow_by_id[w];if(!k||typeof k!="object")continue;const b=cf(u,hn(y==null?void 0:y.id));if(!b)continue;const S=vR(k);if(!S)continue;const R=(Array.isArray(k.nodes)?k.nodes:[]).find(re=>hn(re==null?void 0:re.id).trim()===S)||null;if(!R)continue;const $=Ep(y),A=Ep(R),H={x:$.x+f.x+240-A.x,y:$.y+f.y+0-A.y},G=cf(b,S);r.push({id:`${b}=>${G}`,source:b,target:G,sourceHandle:"exec-out",targetHandle:"exec-in"}),l(k,b,H,h+1)}};return l(t,"",{x:0,y:0},0),{...t,id:hn(t.id),nodes:n,edges:r}}function bR(e){const t=hn(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 kR(e){const t=e.nodes.filter(l=>e.keep_id(l.id)),n=new Set(t.map(l=>l.id)),r={};for(const l of e.edges)r[l.source]||(r[l.source]=[]),r[l.source].push(l.target);const a=new Map;for(const l of t){const c=new Set,u=(r[l.id]||[]).slice();for(;u.length;){const f=u.pop();if(!f||c.has(f))continue;if(c.add(f),n.has(f)){const m=`${l.id}->${f}`;a.has(m)||a.set(m,{id:m,source:l.id,target:f});continue}const h=r[f]||[];for(const m of h)c.has(m)||u.push(m);if(a.size>=e.max_edges)break}if(a.size>=e.max_edges)break}return{nodes:t,edges:Array.from(a.values())}}function Uv(e,t){const a=Math.max(t.w*8,160),l=Math.max(t.h*8,120),c=Math.max(160,Math.min(a,e.w)),u=Math.max(120,Math.min(l,e.h));return{x:e.x,y:e.y,w:c,h:u}}function jR(e){const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=hn(e.active_node_id),a=e.recent_nodes||{},l=e.visited_nodes||{},c=e.highlight_path===!0,u=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:f,edges:h,bounds:m}=_.useMemo(()=>{const F=xR({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),U=Array.isArray(F.nodes)?F.nodes:[],K=Array.isArray(F.edges)?F.edges:[];let O=[];for(const ce of U){const oe=hn(ce==null?void 0:ce.id).trim();if(!oe)continue;const Ae=ce!=null&&ce.position&&typeof ce.position=="object"?ce.position:{},he=typeof Ae.x=="number"?Ae.x:0,Ce=typeof Ae.y=="number"?Ae.y:0,Te=ce!=null&&ce.data&&typeof ce.data=="object"?ce.data:{},Ye=hn((Te==null?void 0:Te.label)||(ce==null?void 0:ce.label)||oe)||oe,rt=hn((Te==null?void 0:Te.nodeType)||(ce==null?void 0:ce.type)||"unknown")||"unknown",ht=hn((Te==null?void 0:Te.headerColor)||(ce==null?void 0:ce.headerColor)||"")||"",lt=Te!=null&&Te.eventConfig&&typeof Te.eventConfig=="object"?Te.eventConfig:null,St=lt&&typeof lt.schedule=="string"?hn(lt.schedule).trim():"",Zt=lt&&typeof lt.recurrent=="boolean"?!!lt.recurrent:void 0,On=rt==="subflow"?_k(ce):"",Bt=St||Zt!==void 0||On?{schedule:St||void 0,recurrent:Zt,subflow_id:On||void 0}:void 0;O.push({id:oe,x:he,y:Ce,label:Ye,type:rt,color:ht,meta:Bt})}const V={};for(const ce of O)V[ce.id]=ce;let J=[];for(const ce of K){if(!hk(ce))continue;const oe=hn(ce==null?void 0:ce.source).trim(),Ae=hn(ce==null?void 0:ce.target).trim();!oe||!Ae||J.push({id:hn((ce==null?void 0:ce.id)||`${oe}->${Ae}`),source:oe,target:Ae})}const le=new Set(O.map(ce=>ce.id));if(J=J.filter(ce=>le.has(ce.source)&&le.has(ce.target)),e.simplify===!0){const oe=kR({nodes:O,edges:J,keep_id:Ae=>{if(r&&Ae===r)return!0;const he=V[Ae];if(!he)return!1;const Ce=hn(he.type).trim().toLowerCase();return Ce==="on_flow_start"||Ce==="on_flow_end"||Ce==="subflow"?!0:!bR(Ce)},max_edges:900});O=oe.nodes,J=oe.edges}if(e.prefer_vertical===!0&&O.length>=2){const ce=O.map(Te=>Te.x),oe=O.map(Te=>Te.y),Ae=Math.max(...ce)-Math.min(...ce),he=Math.max(...oe)-Math.min(...oe);Ae>=he&&(O=O.map(Te=>({...Te,x:Te.y,y:Te.x})));const Ce=Math.min(...O.map(Te=>Te.y));O=O.map(Te=>({...Te,y:Ce+(Te.y-Ce)*u}))}const ie={};for(const ce of O)ie[ce.id]=ce;const _e=160,pe=56,ye=_e/2,Ne=pe/2;let Be=0,Ue=0,ut=0,De=0;O.length&&(Be=Math.min(...O.map(ce=>ce.x)),Ue=Math.min(...O.map(ce=>ce.y)),ut=Math.max(...O.map(ce=>ce.x+_e)),De=Math.max(...O.map(ce=>ce.y+pe)));let Qe=0;if(J.length){const ce=new Set(J.map(oe=>`${oe.source}->${oe.target}`));for(const oe of J){if(!ce.has(`${oe.target}->${oe.source}`))continue;const Ae=ie[oe.source],he=ie[oe.target];if(!Ae||!he)continue;const Ce=Ae.x+ye,Te=Ae.y+Ne,Ye=he.x+ye,rt=he.y+Ne,ht=Math.max(1,Math.hypot(Ye-Ce,rt-Te)),lt=Math.max(28,Math.min(72,ht*.14)),St=Math.min(200,lt*3.5);St>Qe&&(Qe=St)}}const at=60+Qe,Ke={x:Be-at,y:Ue-at,w:ut-Be+at*2,h:De-Ue+at*2,node_w:_e,node_h:pe};return{nodes:O,edges:J,bounds:Ke}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,u]);if(!n)return s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const g=_.useRef(null),[y,w]=_.useState(()=>({x:m.x,y:m.y,w:m.w,h:m.h})),k=_.useRef(y);k.current=y,_.useEffect(()=>{w({x:m.x,y:m.y,w:m.w,h:m.h})},[m.x,m.y,m.w,m.h]);const b=_.useRef(new Map),S=_.useRef(null),N=`${y.x} ${y.y} ${y.w} ${y.h}`,R={};for(const F of f)R[F.id]=F;const $=F=>{let U=hn(F).trim();if(!U)return"";if(R[U])return U;for(;U.includes("::");)if(U=U.slice(0,Math.max(0,U.lastIndexOf("::"))),R[U])return U;return""},A=$(r),W={};for(const[F,U]of Object.entries(a)){if(typeof U!="number")continue;const K=$(F);K&&(W[K]=Math.max(W[K]||0,U))}const z={};if(c)for(const[F,U]of Object.entries(l)){if(typeof U!="number")continue;const K=$(F);K&&(z[K]=typeof z[K]=="number"?Math.min(z[K],U):U)}const H=hn(e.schedule_next_in).trim(),G=hn(e.schedule_interval).trim(),re=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},te=F=>{try{const U=new Date(F),K=String(U.getHours()).padStart(2,"0"),O=String(U.getMinutes()).padStart(2,"0");return`${K}:${O}`}catch{return""}},Q=(F,U)=>{var J,le;const K=hn((J=F.meta)==null?void 0:J.schedule).trim();if(!(((le=F.meta)==null?void 0:le.recurrent)===!0))return U&&H?`next ${H}`:K&&K.length<=12&&!K.includes("T")?`in ${K}`:"scheduled";const V=K||G;return V?U&&H?`${V} • next ${H}`:`every ${V}`:U&&H?`next ${H}`:"scheduled"},D=F=>{var _e;const U=hn((_e=F.meta)==null?void 0:_e.subflow_id).trim(),K=U&&e.flow_by_id?e.flow_by_id[U]:null,V=hn(K==null?void 0:K.name).trim()||U||F.label||F.id,J=typeof re[F.id]=="number"?Number(re[F.id]):null,le=J!==null?te(J):"",ie=le?`last ${le}`:"subflow";return{label:V,sub:ie}},T=(F,U,K)=>{const O=K||k.current,V=g.current;if(!V)return{x:F,y:U};const J=V.getBoundingClientRect(),le=J.width>0?(F-J.left)/J.width:0,ie=J.height>0?(U-J.top)/J.height:0;return{x:O.x+le*O.w,y:O.y+ie*O.h}},E=(F,U,K)=>{const O=K||k.current,V=Math.max(.12,Math.min(8,U)),J=O.w*V,le=O.h*V,ie=O.w>0?(F.x-O.x)/O.w:.5,_e=O.h>0?(F.y-O.y)/O.h:.5,pe=F.x-ie*J,ye=F.y-_e*le;w(Uv({x:pe,y:ye,w:J,h:le},m))},L=(F,U,K)=>{const O=K||k.current,V=g.current;if(!V)return;const J=V.getBoundingClientRect(),le=.88,ie=J.width>0?F/J.width*O.w*le:0,_e=J.height>0?U/J.height*O.h*le:0;w(pe=>Uv({x:(K||pe).x-ie,y:(K||pe).y-_e,w:(K||pe).w,h:(K||pe).h},m))},M=_.useMemo(()=>{const F=new Set;for(const U of h)F.add(`${U.source}->${U.target}`);return F},[h]),ee=(F,U,K,O)=>{const V=m.node_w,J=m.node_h,le=Math.abs(K),ie=Math.abs(O);if(le<1e-6&&ie<1e-6)return{x:F,y:U};const _e=le>1e-6?V/2/le:Number.POSITIVE_INFINITY,pe=ie>1e-6?J/2/ie:Number.POSITIVE_INFINITY,ye=Math.min(_e,pe);return{x:F+K*ye,y:U+O*ye}};return s.jsxs("div",{className:"graph_wrap",children:[s.jsxs("div",{className:"graph_corner",children:[s.jsxs("div",{className:"graph_corner_buttons",children:[s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>w({x:m.x,y:m.y,w:m.w,h:m.h}),title:"Recenter",children:"⤢"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const F=g.current;if(!F)return;const U=F.getBoundingClientRect(),K=T(U.left+U.width/2,U.top+U.height/2);E(K,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const F=g.current;if(!F)return;const U=F.getBoundingClientRect(),K=T(U.left+U.width/2,U.top+U.height/2);E(K,1.18)},title:"Zoom out",children:"−"})]}),s.jsx(wR,{})]}),s.jsxs("svg",{ref:g,className:"graph_svg",viewBox:N,role:"img","aria-label":"Workflow execution graph",onWheel:F=>{F.preventDefault();const U=T(F.clientX,F.clientY),K=typeof F.deltaY=="number"?F.deltaY:0,O=typeof F.deltaMode=="number"?Number(F.deltaMode):0,V=O===1?K*24:O===2?K*800:K,J=45e-5*1.15*1.1;let le=Math.exp(V*J);le=Math.max(.86,Math.min(1.16,le)),E(U,le)},onPointerDown:F=>{var K,O;(O=(K=F.currentTarget).setPointerCapture)==null||O.call(K,F.pointerId),b.current.set(F.pointerId,{x:F.clientX,y:F.clientY});const U=Array.from(b.current.values());if(U.length===1)S.current={mode:"pan",start_view:k.current,start_client:{x:F.clientX,y:F.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(U.length>=2){const V=U[0],J=U[1],le=V.x-J.x,ie=V.y-J.y,_e=Math.max(1,Math.hypot(le,ie)),pe={x:(V.x+J.x)/2,y:(V.y+J.y)/2},ye=k.current;S.current={mode:"pinch",start_view:ye,start_client:pe,start_dist:_e,anchor_svg:T(pe.x,pe.y,ye)}}},onPointerMove:F=>{if(!b.current.has(F.pointerId))return;b.current.set(F.pointerId,{x:F.clientX,y:F.clientY});const U=S.current;if(!U)return;const K=Array.from(b.current.values());if(U.mode==="pan"&&K.length===1){const O=F.clientX-U.start_client.x,V=F.clientY-U.start_client.y;L(O,V,U.start_view)}else if(U.mode==="pinch"&&K.length>=2){const O=K[0],V=K[1],J=O.x-V.x,le=O.y-V.y,ie=Math.max(1,Math.hypot(J,le)),_e=U.start_dist/ie;E(U.anchor_svg,_e,U.start_view)}},onPointerUp:F=>{b.current.delete(F.pointerId),b.current.size===0&&(S.current=null)},onPointerCancel:F=>{b.current.delete(F.pointerId),b.current.size===0&&(S.current=null)},children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrow",viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"8",markerHeight:"8",orient:"auto-start-reverse",children:s.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(148,163,184,0.55)"})}),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),h.map(F=>{const U=R[F.source],K=R[F.target];if(!U||!K)return null;const O=U.x+m.node_w/2,V=U.y+m.node_h/2,J=K.x+m.node_w/2,le=K.y+m.node_h/2,ie=J-O,_e=le-V,pe=ee(O,V,ie,_e),ye=ee(J,le,-ie,-_e),Ne=F.source!==F.target&&M.has(`${F.target}->${F.source}`),Be=Math.max(1,Math.hypot(ie,_e)),Ue=-_e/Be,ut=ie/Be,De=String(F.source)<String(F.target)?1:-1,at=Math.abs(ie)>=Math.abs(_e)?ie>=0:_e>=0,Ke=!Ne||at,ce=Math.max(28,Math.min(72,Be*.14)),oe=Math.min(200,ce*3.5),Ae=Ne&&!Ke?oe*De:0,he=(pe.x+ye.x)/2+Ue*Ae,Ce=(pe.y+ye.y)/2+ut*Ae,Te=Ne&&!Ke?`M ${pe.x} ${pe.y} Q ${he} ${Ce} ${ye.x} ${ye.y}`:`M ${pe.x} ${pe.y} L ${ye.x} ${ye.y}`,Ye=c&&z&&z[F.source]!==void 0&&z[F.target]!==void 0;return s.jsx("path",{d:Te,className:`graph_edge ${Ye?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},F.id)}),f.map(F=>{const K=(typeof W[F.id]=="number"?W[F.id]:0)>t,O=A&&F.id===A,V=c&&z&&z[F.id]!==void 0,J=`graph_node ${O?"active":K?"recent":""} ${V?"visited":""}`,le=F.color||"rgba(255,255,255,0.16)";let ie=F.label||F.id,_e=F.type;if(F.type==="on_schedule")_e=Q(F,!!O);else if(F.type==="subflow"){const Ne=D(F);ie=Ne.label,_e=Ne.sub}const pe=Bv(ie,22),ye=Bv(_e,22);return s.jsxs("g",{className:J,transform:`translate(${F.x}, ${F.y})`,children:[s.jsx("rect",{className:"graph_node_bg",width:m.node_w,height:m.node_h,rx:12,ry:12}),s.jsx("rect",{className:"graph_node_bar",width:m.node_w,height:6,rx:12,ry:12,fill:le}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:pe}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:ye}),F.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:m.node_w-18,y:18,children:"⏰"}):null]},F.id)})]})]})}function Vs(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Vs(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var $p={exports:{}},Ap={},Tp={exports:{}},Mp={};/**
|
|
133
|
-
* @license React
|
|
134
|
-
* use-sync-external-store-shim.production.js
|
|
135
|
-
*
|
|
136
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
137
|
-
*
|
|
138
|
-
* This source code is licensed under the MIT license found in the
|
|
139
|
-
* LICENSE file in the root directory of this source tree.
|
|
140
|
-
*/var Wv;function SR(){if(Wv)return Mp;Wv=1;var e=Xf();function t(g,y){return g===y&&(g!==0||1/g===1/y)||g!==g&&y!==y}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,a=e.useEffect,l=e.useLayoutEffect,c=e.useDebugValue;function u(g,y){var w=y(),k=r({inst:{value:w,getSnapshot:y}}),b=k[0].inst,S=k[1];return l(function(){b.value=w,b.getSnapshot=y,f(b)&&S({inst:b})},[g,w,y]),a(function(){return f(b)&&S({inst:b}),g(function(){f(b)&&S({inst:b})})},[g]),c(w),w}function f(g){var y=g.getSnapshot;g=g.value;try{var w=y();return!n(g,w)}catch{return!0}}function h(g,y){return y()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:u;return Mp.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:m,Mp}var qv;function NR(){return qv||(qv=1,Tp.exports=SR()),Tp.exports}/**
|
|
141
|
-
* @license React
|
|
142
|
-
* use-sync-external-store-shim/with-selector.production.js
|
|
143
|
-
*
|
|
144
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
145
|
-
*
|
|
146
|
-
* This source code is licensed under the MIT license found in the
|
|
147
|
-
* LICENSE file in the root directory of this source tree.
|
|
148
|
-
*/var Hv;function CR(){if(Hv)return Ap;Hv=1;var e=Xf(),t=NR();function n(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var r=typeof Object.is=="function"?Object.is:n,a=t.useSyncExternalStore,l=e.useRef,c=e.useEffect,u=e.useMemo,f=e.useDebugValue;return Ap.useSyncExternalStoreWithSelector=function(h,m,g,y,w){var k=l(null);if(k.current===null){var b={hasValue:!1,value:null};k.current=b}else b=k.current;k=u(function(){function N(z){if(!R){if(R=!0,$=z,z=y(z),w!==void 0&&b.hasValue){var H=b.value;if(w(H,z))return A=H}return A=z}if(H=A,r($,z))return H;var G=y(z);return w!==void 0&&w(H,G)?($=z,H):($=z,A=G)}var R=!1,$,A,W=g===void 0?null:g;return[function(){return N(m())},W===null?void 0:function(){return N(W())}]},[m,g,y,w]);var S=a(h,k[0],k[1]);return c(function(){b.hasValue=!0,b.value=S},[S]),f(S),S},Ap}var Vv;function ER(){return Vv||(Vv=1,$p.exports=CR()),$p.exports}var $R=ER();const AR=Jg($R),TR={},Gv=e=>{let t;const n=new Set,r=(m,g)=>{const y=typeof m=="function"?m(t):m;if(!Object.is(y,t)){const w=t;t=g??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(k=>k(t,w))}},a=()=>t,f={setState:r,getState:a,getInitialState:()=>h,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(TR?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},h=t=e(r,a,f);return f},MR=e=>e?Gv(e):Gv,{useDebugValue:RR}=xe,{useSyncExternalStoreWithSelector:LR}=AR,IR=e=>e;function pk(e,t=IR,n){const r=LR(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return RR(r),r}const Kv=(e,t)=>{const n=MR(e),r=(a,l=t)=>pk(n,a,l);return Object.assign(r,n),r},OR=(e,t)=>e?Kv(e,t):Kv;function Os(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,a]of e)if(!Object.is(a,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 PR={value:()=>{}};function j_(){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 zm(n)}function zm(e){this._=e}function DR(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",a=n.indexOf(".");if(a>=0&&(r=n.slice(a+1),n=n.slice(0,a)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}zm.prototype=j_.prototype={constructor:zm,on:function(e,t){var n=this._,r=DR(e+"",n),a,l=-1,c=r.length;if(arguments.length<2){for(;++l<c;)if((a=(e=r[l]).type)&&(a=FR(n[a],e.name)))return a;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++l<c;)if(a=(e=r[l]).type)n[a]=Yv(n[a],e.name,t);else if(t==null)for(a in n)n[a]=Yv(n[a],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new zm(e)},call:function(e,t){if((a=arguments.length-2)>0)for(var n=new Array(a),r=0,a,l;r<a;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(l=this._[e],r=0,a=l.length;r<a;++r)l[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],a=0,l=r.length;a<l;++a)r[a].value.apply(t,n)}};function FR(e,t){for(var n=0,r=e.length,a;n<r;++n)if((a=e[n]).name===t)return a.value}function Yv(e,t,n){for(var r=0,a=e.length;r<a;++r)if(e[r].name===t){e[r]=PR,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Eg="http://www.w3.org/1999/xhtml";const Jv={svg:"http://www.w3.org/2000/svg",xhtml:Eg,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function S_(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Jv.hasOwnProperty(t)?{space:Jv[t],local:e}:e}function zR(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Eg&&t.documentElement.namespaceURI===Eg?t.createElement(e):t.createElementNS(n,e)}}function BR(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function gk(e){var t=S_(e);return(t.local?BR:zR)(t)}function UR(){}function Ey(e){return e==null?UR:function(){return this.querySelector(e)}}function WR(e){typeof e!="function"&&(e=Ey(e));for(var t=this._groups,n=t.length,r=new Array(n),a=0;a<n;++a)for(var l=t[a],c=l.length,u=r[a]=new Array(c),f,h,m=0;m<c;++m)(f=l[m])&&(h=e.call(f,f.__data__,m,l))&&("__data__"in f&&(h.__data__=f.__data__),u[m]=h);return new ti(r,this._parents)}function qR(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function HR(){return[]}function yk(e){return e==null?HR:function(){return this.querySelectorAll(e)}}function VR(e){return function(){return qR(e.apply(this,arguments))}}function GR(e){typeof e=="function"?e=VR(e):e=yk(e);for(var t=this._groups,n=t.length,r=[],a=[],l=0;l<n;++l)for(var c=t[l],u=c.length,f,h=0;h<u;++h)(f=c[h])&&(r.push(e.call(f,f.__data__,h,c)),a.push(f));return new ti(r,a)}function wk(e){return function(){return this.matches(e)}}function vk(e){return function(t){return t.matches(e)}}var KR=Array.prototype.find;function YR(e){return function(){return KR.call(this.children,e)}}function JR(){return this.firstElementChild}function XR(e){return this.select(e==null?JR:YR(typeof e=="function"?e:vk(e)))}var ZR=Array.prototype.filter;function QR(){return Array.from(this.children)}function eL(e){return function(){return ZR.call(this.children,e)}}function tL(e){return this.selectAll(e==null?QR:eL(typeof e=="function"?e:vk(e)))}function nL(e){typeof e!="function"&&(e=wk(e));for(var t=this._groups,n=t.length,r=new Array(n),a=0;a<n;++a)for(var l=t[a],c=l.length,u=r[a]=[],f,h=0;h<c;++h)(f=l[h])&&e.call(f,f.__data__,h,l)&&u.push(f);return new ti(r,this._parents)}function xk(e){return new Array(e.length)}function sL(){return new ti(this._enter||this._groups.map(xk),this._parents)}function s_(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}s_.prototype={constructor:s_,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 rL(e){return function(){return e}}function iL(e,t,n,r,a,l){for(var c=0,u,f=t.length,h=l.length;c<h;++c)(u=t[c])?(u.__data__=l[c],r[c]=u):n[c]=new s_(e,l[c]);for(;c<f;++c)(u=t[c])&&(a[c]=u)}function aL(e,t,n,r,a,l,c){var u,f,h=new Map,m=t.length,g=l.length,y=new Array(m),w;for(u=0;u<m;++u)(f=t[u])&&(y[u]=w=c.call(f,f.__data__,u,t)+"",h.has(w)?a[u]=f:h.set(w,f));for(u=0;u<g;++u)w=c.call(e,l[u],u,l)+"",(f=h.get(w))?(r[u]=f,f.__data__=l[u],h.delete(w)):n[u]=new s_(e,l[u]);for(u=0;u<m;++u)(f=t[u])&&h.get(y[u])===f&&(a[u]=f)}function oL(e){return e.__data__}function lL(e,t){if(!arguments.length)return Array.from(this,oL);var n=t?aL:iL,r=this._parents,a=this._groups;typeof e!="function"&&(e=rL(e));for(var l=a.length,c=new Array(l),u=new Array(l),f=new Array(l),h=0;h<l;++h){var m=r[h],g=a[h],y=g.length,w=cL(e.call(m,m&&m.__data__,h,r)),k=w.length,b=u[h]=new Array(k),S=c[h]=new Array(k),N=f[h]=new Array(y);n(m,g,b,S,N,w,t);for(var R=0,$=0,A,W;R<k;++R)if(A=b[R]){for(R>=$&&($=R+1);!(W=S[$])&&++$<k;);A._next=W||null}}return c=new ti(c,r),c._enter=u,c._exit=f,c}function cL(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function uL(){return new ti(this._exit||this._groups.map(xk),this._parents)}function dL(e,t,n){var r=this.enter(),a=this,l=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(a=t(a),a&&(a=a.selection())),n==null?l.remove():n(l),r&&a?r.merge(a).order():a}function fL(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,a=n.length,l=r.length,c=Math.min(a,l),u=new Array(a),f=0;f<c;++f)for(var h=n[f],m=r[f],g=h.length,y=u[f]=new Array(g),w,k=0;k<g;++k)(w=h[k]||m[k])&&(y[k]=w);for(;f<a;++f)u[f]=n[f];return new ti(u,this._parents)}function hL(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],a=r.length-1,l=r[a],c;--a>=0;)(c=r[a])&&(l&&c.compareDocumentPosition(l)^4&&l.parentNode.insertBefore(c,l),l=c);return this}function mL(e){e||(e=_L);function t(g,y){return g&&y?e(g.__data__,y.__data__):!g-!y}for(var n=this._groups,r=n.length,a=new Array(r),l=0;l<r;++l){for(var c=n[l],u=c.length,f=a[l]=new Array(u),h,m=0;m<u;++m)(h=c[m])&&(f[m]=h);f.sort(t)}return new ti(a,this._parents).order()}function _L(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function pL(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function gL(){return Array.from(this)}function yL(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],a=0,l=r.length;a<l;++a){var c=r[a];if(c)return c}return null}function wL(){let e=0;for(const t of this)++e;return e}function vL(){return!this.node()}function xL(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var a=t[n],l=0,c=a.length,u;l<c;++l)(u=a[l])&&e.call(u,u.__data__,l,a);return this}function bL(e){return function(){this.removeAttribute(e)}}function kL(e){return function(){this.removeAttributeNS(e.space,e.local)}}function jL(e,t){return function(){this.setAttribute(e,t)}}function SL(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function NL(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function CL(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 EL(e,t){var n=S_(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?kL:bL:typeof t=="function"?n.local?CL:NL:n.local?SL:jL)(n,t))}function bk(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function $L(e){return function(){this.style.removeProperty(e)}}function AL(e,t,n){return function(){this.style.setProperty(e,t,n)}}function TL(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function ML(e,t,n){return arguments.length>1?this.each((t==null?$L:typeof t=="function"?TL:AL)(e,t,n??"")):Wu(this.node(),e)}function Wu(e,t){return e.style.getPropertyValue(t)||bk(e).getComputedStyle(e,null).getPropertyValue(t)}function RL(e){return function(){delete this[e]}}function LL(e,t){return function(){this[e]=t}}function IL(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function OL(e,t){return arguments.length>1?this.each((t==null?RL:typeof t=="function"?IL:LL)(e,t)):this.node()[e]}function kk(e){return e.trim().split(/^|\s+/)}function $y(e){return e.classList||new jk(e)}function jk(e){this._node=e,this._names=kk(e.getAttribute("class")||"")}jk.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 Sk(e,t){for(var n=$y(e),r=-1,a=t.length;++r<a;)n.add(t[r])}function Nk(e,t){for(var n=$y(e),r=-1,a=t.length;++r<a;)n.remove(t[r])}function PL(e){return function(){Sk(this,e)}}function DL(e){return function(){Nk(this,e)}}function FL(e,t){return function(){(t.apply(this,arguments)?Sk:Nk)(this,e)}}function zL(e,t){var n=kk(e+"");if(arguments.length<2){for(var r=$y(this.node()),a=-1,l=n.length;++a<l;)if(!r.contains(n[a]))return!1;return!0}return this.each((typeof t=="function"?FL:t?PL:DL)(n,t))}function BL(){this.textContent=""}function UL(e){return function(){this.textContent=e}}function WL(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function qL(e){return arguments.length?this.each(e==null?BL:(typeof e=="function"?WL:UL)(e)):this.node().textContent}function HL(){this.innerHTML=""}function VL(e){return function(){this.innerHTML=e}}function GL(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function KL(e){return arguments.length?this.each(e==null?HL:(typeof e=="function"?GL:VL)(e)):this.node().innerHTML}function YL(){this.nextSibling&&this.parentNode.appendChild(this)}function JL(){return this.each(YL)}function XL(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function ZL(){return this.each(XL)}function QL(e){var t=typeof e=="function"?e:gk(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function e3(){return null}function t3(e,t){var n=typeof e=="function"?e:gk(e),r=t==null?e3:typeof t=="function"?t:Ey(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function n3(){var e=this.parentNode;e&&e.removeChild(this)}function s3(){return this.each(n3)}function r3(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function i3(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function a3(e){return this.select(e?i3:r3)}function o3(e){return arguments.length?this.property("__data__",e):this.node().__data__}function l3(e){return function(t){e.call(this,t,this.__data__)}}function c3(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 u3(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,a=t.length,l;n<a;++n)l=t[n],(!e.type||l.type===e.type)&&l.name===e.name?this.removeEventListener(l.type,l.listener,l.options):t[++r]=l;++r?t.length=r:delete this.__on}}}function d3(e,t,n){return function(){var r=this.__on,a,l=l3(t);if(r){for(var c=0,u=r.length;c<u;++c)if((a=r[c]).type===e.type&&a.name===e.name){this.removeEventListener(a.type,a.listener,a.options),this.addEventListener(a.type,a.listener=l,a.options=n),a.value=t;return}}this.addEventListener(e.type,l,n),a={type:e.type,name:e.name,value:t,listener:l,options:n},r?r.push(a):this.__on=[a]}}function f3(e,t,n){var r=c3(e+""),a,l=r.length,c;if(arguments.length<2){var u=this.node().__on;if(u){for(var f=0,h=u.length,m;f<h;++f)for(a=0,m=u[f];a<l;++a)if((c=r[a]).type===m.type&&c.name===m.name)return m.value}return}for(u=t?d3:u3,a=0;a<l;++a)this.each(u(r[a],t,n));return this}function Ck(e,t,n){var r=bk(e),a=r.CustomEvent;typeof a=="function"?a=new a(t,n):(a=r.document.createEvent("Event"),n?(a.initEvent(t,n.bubbles,n.cancelable),a.detail=n.detail):a.initEvent(t,!1,!1)),e.dispatchEvent(a)}function h3(e,t){return function(){return Ck(this,e,t)}}function m3(e,t){return function(){return Ck(this,e,t.apply(this,arguments))}}function _3(e,t){return this.each((typeof t=="function"?m3:h3)(e,t))}function*p3(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],a=0,l=r.length,c;a<l;++a)(c=r[a])&&(yield c)}var Ek=[null];function ti(e,t){this._groups=e,this._parents=t}function rh(){return new ti([[document.documentElement]],Ek)}function g3(){return this}ti.prototype=rh.prototype={constructor:ti,select:WR,selectAll:GR,selectChild:XR,selectChildren:tL,filter:nL,data:lL,enter:sL,exit:uL,join:dL,merge:fL,selection:g3,order:hL,sort:mL,call:pL,nodes:gL,node:yL,size:wL,empty:vL,each:xL,attr:EL,style:ML,property:OL,classed:zL,text:qL,html:KL,raise:JL,lower:ZL,append:QL,insert:t3,remove:s3,clone:a3,datum:o3,on:f3,dispatch:_3,[Symbol.iterator]:p3};function ki(e){return typeof e=="string"?new ti([[document.querySelector(e)]],[document.documentElement]):new ti([[e]],Ek)}function y3(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Ji(e,t){if(e=y3(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 a=t.getBoundingClientRect();return[e.clientX-a.left-t.clientLeft,e.clientY-a.top-t.clientTop]}}return[e.pageX,e.pageY]}const w3={passive:!1},zf={capture:!0,passive:!1};function Rp(e){e.stopImmediatePropagation()}function Pu(e){e.preventDefault(),e.stopImmediatePropagation()}function $k(e){var t=e.document.documentElement,n=ki(e).on("dragstart.drag",Pu,zf);"onselectstart"in t?n.on("selectstart.drag",Pu,zf):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Ak(e,t){var n=e.document.documentElement,r=ki(e).on("dragstart.drag",null);t&&(r.on("click.drag",Pu,zf),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 km=e=>()=>e;function $g(e,{sourceEvent:t,subject:n,target:r,identifier:a,active:l,x:c,y:u,dx:f,dy:h,dispatch:m}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:a,enumerable:!0,configurable:!0},active:{value:l,enumerable:!0,configurable:!0},x:{value:c,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:f,enumerable:!0,configurable:!0},dy:{value:h,enumerable:!0,configurable:!0},_:{value:m}})}$g.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function v3(e){return!e.ctrlKey&&!e.button}function x3(){return this.parentNode}function b3(e,t){return t??{x:e.x,y:e.y}}function k3(){return navigator.maxTouchPoints||"ontouchstart"in this}function j3(){var e=v3,t=x3,n=b3,r=k3,a={},l=j_("start","drag","end"),c=0,u,f,h,m,g=0;function y(A){A.on("mousedown.drag",w).filter(r).on("touchstart.drag",S).on("touchmove.drag",N,w3).on("touchend.drag touchcancel.drag",R).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function w(A,W){if(!(m||!e.call(this,A,W))){var z=$(this,t.call(this,A,W),A,W,"mouse");z&&(ki(A.view).on("mousemove.drag",k,zf).on("mouseup.drag",b,zf),$k(A.view),Rp(A),h=!1,u=A.clientX,f=A.clientY,z("start",A))}}function k(A){if(Pu(A),!h){var W=A.clientX-u,z=A.clientY-f;h=W*W+z*z>g}a.mouse("drag",A)}function b(A){ki(A.view).on("mousemove.drag mouseup.drag",null),Ak(A.view,h),Pu(A),a.mouse("end",A)}function S(A,W){if(e.call(this,A,W)){var z=A.changedTouches,H=t.call(this,A,W),G=z.length,re,te;for(re=0;re<G;++re)(te=$(this,H,A,W,z[re].identifier,z[re]))&&(Rp(A),te("start",A,z[re]))}}function N(A){var W=A.changedTouches,z=W.length,H,G;for(H=0;H<z;++H)(G=a[W[H].identifier])&&(Pu(A),G("drag",A,W[H]))}function R(A){var W=A.changedTouches,z=W.length,H,G;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),H=0;H<z;++H)(G=a[W[H].identifier])&&(Rp(A),G("end",A,W[H]))}function $(A,W,z,H,G,re){var te=l.copy(),Q=Ji(re||z,W),D,T,E;if((E=n.call(A,new $g("beforestart",{sourceEvent:z,target:y,identifier:G,active:c,x:Q[0],y:Q[1],dx:0,dy:0,dispatch:te}),H))!=null)return D=E.x-Q[0]||0,T=E.y-Q[1]||0,function L(M,ee,F){var U=Q,K;switch(M){case"start":a[G]=L,K=c++;break;case"end":delete a[G],--c;case"drag":Q=Ji(F||ee,W),K=c;break}te.call(M,A,new $g(M,{sourceEvent:ee,subject:E,target:y,identifier:G,active:K,x:Q[0]+D,y:Q[1]+T,dx:Q[0]-U[0],dy:Q[1]-U[1],dispatch:te}),H)}}return y.filter=function(A){return arguments.length?(e=typeof A=="function"?A:km(!!A),y):e},y.container=function(A){return arguments.length?(t=typeof A=="function"?A:km(A),y):t},y.subject=function(A){return arguments.length?(n=typeof A=="function"?A:km(A),y):n},y.touchable=function(A){return arguments.length?(r=typeof A=="function"?A:km(!!A),y):r},y.on=function(){var A=l.on.apply(l,arguments);return A===l?y:A},y.clickDistance=function(A){return arguments.length?(g=(A=+A)*A,y):Math.sqrt(g)},y}function Ay(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Tk(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function ih(){}var Bf=.7,r_=1/Bf,Du="\\s*([+-]?\\d+)\\s*",Uf="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ia="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",S3=/^#([0-9a-f]{3,8})$/,N3=new RegExp(`^rgb\\(${Du},${Du},${Du}\\)$`),C3=new RegExp(`^rgb\\(${Ia},${Ia},${Ia}\\)$`),E3=new RegExp(`^rgba\\(${Du},${Du},${Du},${Uf}\\)$`),$3=new RegExp(`^rgba\\(${Ia},${Ia},${Ia},${Uf}\\)$`),A3=new RegExp(`^hsl\\(${Uf},${Ia},${Ia}\\)$`),T3=new RegExp(`^hsla\\(${Uf},${Ia},${Ia},${Uf}\\)$`),Xv={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};Ay(ih,Wf,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Zv,formatHex:Zv,formatHex8:M3,formatHsl:R3,formatRgb:Qv,toString:Qv});function Zv(){return this.rgb().formatHex()}function M3(){return this.rgb().formatHex8()}function R3(){return Mk(this).formatHsl()}function Qv(){return this.rgb().formatRgb()}function Wf(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=S3.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?ex(t):n===3?new Wr(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?jm(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?jm(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=N3.exec(e))?new Wr(t[1],t[2],t[3],1):(t=C3.exec(e))?new Wr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=E3.exec(e))?jm(t[1],t[2],t[3],t[4]):(t=$3.exec(e))?jm(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=A3.exec(e))?sx(t[1],t[2]/100,t[3]/100,1):(t=T3.exec(e))?sx(t[1],t[2]/100,t[3]/100,t[4]):Xv.hasOwnProperty(e)?ex(Xv[e]):e==="transparent"?new Wr(NaN,NaN,NaN,0):null}function ex(e){return new Wr(e>>16&255,e>>8&255,e&255,1)}function jm(e,t,n,r){return r<=0&&(e=t=n=NaN),new Wr(e,t,n,r)}function L3(e){return e instanceof ih||(e=Wf(e)),e?(e=e.rgb(),new Wr(e.r,e.g,e.b,e.opacity)):new Wr}function Ag(e,t,n,r){return arguments.length===1?L3(e):new Wr(e,t,n,r??1)}function Wr(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Ay(Wr,Ag,Tk(ih,{brighter(e){return e=e==null?r_:Math.pow(r_,e),new Wr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Bf:Math.pow(Bf,e),new Wr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Wr(_c(this.r),_c(this.g),_c(this.b),i_(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:tx,formatHex:tx,formatHex8:I3,formatRgb:nx,toString:nx}));function tx(){return`#${uc(this.r)}${uc(this.g)}${uc(this.b)}`}function I3(){return`#${uc(this.r)}${uc(this.g)}${uc(this.b)}${uc((isNaN(this.opacity)?1:this.opacity)*255)}`}function nx(){const e=i_(this.opacity);return`${e===1?"rgb(":"rgba("}${_c(this.r)}, ${_c(this.g)}, ${_c(this.b)}${e===1?")":`, ${e})`}`}function i_(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function _c(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function uc(e){return e=_c(e),(e<16?"0":"")+e.toString(16)}function sx(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Qi(e,t,n,r)}function Mk(e){if(e instanceof Qi)return new Qi(e.h,e.s,e.l,e.opacity);if(e instanceof ih||(e=Wf(e)),!e)return new Qi;if(e instanceof Qi)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,a=Math.min(t,n,r),l=Math.max(t,n,r),c=NaN,u=l-a,f=(l+a)/2;return u?(t===l?c=(n-r)/u+(n<r)*6:n===l?c=(r-t)/u+2:c=(t-n)/u+4,u/=f<.5?l+a:2-l-a,c*=60):u=f>0&&f<1?0:c,new Qi(c,u,f,e.opacity)}function O3(e,t,n,r){return arguments.length===1?Mk(e):new Qi(e,t,n,r??1)}function Qi(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Ay(Qi,O3,Tk(ih,{brighter(e){return e=e==null?r_:Math.pow(r_,e),new Qi(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Bf:Math.pow(Bf,e),new Qi(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,a=2*n-r;return new Wr(Lp(e>=240?e-240:e+120,a,r),Lp(e,a,r),Lp(e<120?e+240:e-120,a,r),this.opacity)},clamp(){return new Qi(rx(this.h),Sm(this.s),Sm(this.l),i_(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=i_(this.opacity);return`${e===1?"hsl(":"hsla("}${rx(this.h)}, ${Sm(this.s)*100}%, ${Sm(this.l)*100}%${e===1?")":`, ${e})`}`}}));function rx(e){return e=(e||0)%360,e<0?e+360:e}function Sm(e){return Math.max(0,Math.min(1,e||0))}function Lp(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 Rk=e=>()=>e;function P3(e,t){return function(n){return e+n*t}}function D3(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 F3(e){return(e=+e)==1?Lk:function(t,n){return n-t?D3(t,n,e):Rk(isNaN(t)?n:t)}}function Lk(e,t){var n=t-e;return n?P3(e,n):Rk(isNaN(e)?t:e)}const ix=(function e(t){var n=F3(t);function r(a,l){var c=n((a=Ag(a)).r,(l=Ag(l)).r),u=n(a.g,l.g),f=n(a.b,l.b),h=Lk(a.opacity,l.opacity);return function(m){return a.r=c(m),a.g=u(m),a.b=f(m),a.opacity=h(m),a+""}}return r.gamma=e,r})(1);function fl(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var Tg=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ip=new RegExp(Tg.source,"g");function z3(e){return function(){return e}}function B3(e){return function(t){return e(t)+""}}function U3(e,t){var n=Tg.lastIndex=Ip.lastIndex=0,r,a,l,c=-1,u=[],f=[];for(e=e+"",t=t+"";(r=Tg.exec(e))&&(a=Ip.exec(t));)(l=a.index)>n&&(l=t.slice(n,l),u[c]?u[c]+=l:u[++c]=l),(r=r[0])===(a=a[0])?u[c]?u[c]+=a:u[++c]=a:(u[++c]=null,f.push({i:c,x:fl(r,a)})),n=Ip.lastIndex;return n<t.length&&(l=t.slice(n),u[c]?u[c]+=l:u[++c]=l),u.length<2?f[0]?B3(f[0].x):z3(t):(t=f.length,function(h){for(var m=0,g;m<t;++m)u[(g=f[m]).i]=g.x(h);return u.join("")})}var ax=180/Math.PI,Mg={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Ik(e,t,n,r,a,l){var c,u,f;return(c=Math.sqrt(e*e+t*t))&&(e/=c,t/=c),(f=e*n+t*r)&&(n-=e*f,r-=t*f),(u=Math.sqrt(n*n+r*r))&&(n/=u,r/=u,f/=u),e*r<t*n&&(e=-e,t=-t,f=-f,c=-c),{translateX:a,translateY:l,rotate:Math.atan2(t,e)*ax,skewX:Math.atan(f)*ax,scaleX:c,scaleY:u}}var Nm;function W3(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Mg:Ik(t.a,t.b,t.c,t.d,t.e,t.f)}function q3(e){return e==null||(Nm||(Nm=document.createElementNS("http://www.w3.org/2000/svg","g")),Nm.setAttribute("transform",e),!(e=Nm.transform.baseVal.consolidate()))?Mg:(e=e.matrix,Ik(e.a,e.b,e.c,e.d,e.e,e.f))}function Ok(e,t,n,r){function a(h){return h.length?h.pop()+" ":""}function l(h,m,g,y,w,k){if(h!==g||m!==y){var b=w.push("translate(",null,t,null,n);k.push({i:b-4,x:fl(h,g)},{i:b-2,x:fl(m,y)})}else(g||y)&&w.push("translate("+g+t+y+n)}function c(h,m,g,y){h!==m?(h-m>180?m+=360:m-h>180&&(h+=360),y.push({i:g.push(a(g)+"rotate(",null,r)-2,x:fl(h,m)})):m&&g.push(a(g)+"rotate("+m+r)}function u(h,m,g,y){h!==m?y.push({i:g.push(a(g)+"skewX(",null,r)-2,x:fl(h,m)}):m&&g.push(a(g)+"skewX("+m+r)}function f(h,m,g,y,w,k){if(h!==g||m!==y){var b=w.push(a(w)+"scale(",null,",",null,")");k.push({i:b-4,x:fl(h,g)},{i:b-2,x:fl(m,y)})}else(g!==1||y!==1)&&w.push(a(w)+"scale("+g+","+y+")")}return function(h,m){var g=[],y=[];return h=e(h),m=e(m),l(h.translateX,h.translateY,m.translateX,m.translateY,g,y),c(h.rotate,m.rotate,g,y),u(h.skewX,m.skewX,g,y),f(h.scaleX,h.scaleY,m.scaleX,m.scaleY,g,y),h=m=null,function(w){for(var k=-1,b=y.length,S;++k<b;)g[(S=y[k]).i]=S.x(w);return g.join("")}}}var H3=Ok(W3,"px, ","px)","deg)"),V3=Ok(q3,", ",")",")"),G3=1e-12;function ox(e){return((e=Math.exp(e))+1/e)/2}function K3(e){return((e=Math.exp(e))-1/e)/2}function Y3(e){return((e=Math.exp(2*e))-1)/(e+1)}const J3=(function e(t,n,r){function a(l,c){var u=l[0],f=l[1],h=l[2],m=c[0],g=c[1],y=c[2],w=m-u,k=g-f,b=w*w+k*k,S,N;if(b<G3)N=Math.log(y/h)/t,S=function(H){return[u+H*w,f+H*k,h*Math.exp(t*H*N)]};else{var R=Math.sqrt(b),$=(y*y-h*h+r*b)/(2*h*n*R),A=(y*y-h*h-r*b)/(2*y*n*R),W=Math.log(Math.sqrt($*$+1)-$),z=Math.log(Math.sqrt(A*A+1)-A);N=(z-W)/t,S=function(H){var G=H*N,re=ox(W),te=h/(n*R)*(re*Y3(t*G+W)-K3(W));return[u+te*w,f+te*k,h*re/ox(t*G+W)]}}return S.duration=N*1e3*t/Math.SQRT2,S}return a.rho=function(l){var c=Math.max(.001,+l),u=c*c,f=u*u;return e(c,u,f)},a})(Math.SQRT2,2,4);var qu=0,Cf=0,uf=0,Pk=1e3,a_,Ef,o_=0,xc=0,N_=0,qf=typeof performance=="object"&&performance.now?performance:Date,Dk=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ty(){return xc||(Dk(X3),xc=qf.now()+N_)}function X3(){xc=0}function l_(){this._call=this._time=this._next=null}l_.prototype=Fk.prototype={constructor:l_,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Ty():+n)+(t==null?0:+t),!this._next&&Ef!==this&&(Ef?Ef._next=this:a_=this,Ef=this),this._call=e,this._time=n,Rg()},stop:function(){this._call&&(this._call=null,this._time=1/0,Rg())}};function Fk(e,t,n){var r=new l_;return r.restart(e,t,n),r}function Z3(){Ty(),++qu;for(var e=a_,t;e;)(t=xc-e._time)>=0&&e._call.call(void 0,t),e=e._next;--qu}function lx(){xc=(o_=qf.now())+N_,qu=Cf=0;try{Z3()}finally{qu=0,e4(),xc=0}}function Q3(){var e=qf.now(),t=e-o_;t>Pk&&(N_-=t,o_=e)}function e4(){for(var e,t=a_,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:a_=n);Ef=e,Rg(r)}function Rg(e){if(!qu){Cf&&(Cf=clearTimeout(Cf));var t=e-xc;t>24?(e<1/0&&(Cf=setTimeout(lx,e-qf.now()-N_)),uf&&(uf=clearInterval(uf))):(uf||(o_=qf.now(),uf=setInterval(Q3,Pk)),qu=1,Dk(lx))}}function cx(e,t,n){var r=new l_;return t=t==null?0:+t,r.restart(a=>{r.stop(),e(a+t)},t,n),r}var t4=j_("start","end","cancel","interrupt"),n4=[],zk=0,ux=1,Lg=2,Bm=3,dx=4,Ig=5,Um=6;function C_(e,t,n,r,a,l){var c=e.__transition;if(!c)e.__transition={};else if(n in c)return;s4(e,n,{name:t,index:r,group:a,on:t4,tween:n4,time:l.time,delay:l.delay,duration:l.duration,ease:l.ease,timer:null,state:zk})}function My(e,t){var n=ta(e,t);if(n.state>zk)throw new Error("too late; already scheduled");return n}function Pa(e,t){var n=ta(e,t);if(n.state>Bm)throw new Error("too late; already running");return n}function ta(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function s4(e,t,n){var r=e.__transition,a;r[t]=n,n.timer=Fk(l,0,n.time);function l(h){n.state=ux,n.timer.restart(c,n.delay,n.time),n.delay<=h&&c(h-n.delay)}function c(h){var m,g,y,w;if(n.state!==ux)return f();for(m in r)if(w=r[m],w.name===n.name){if(w.state===Bm)return cx(c);w.state===dx?(w.state=Um,w.timer.stop(),w.on.call("interrupt",e,e.__data__,w.index,w.group),delete r[m]):+m<t&&(w.state=Um,w.timer.stop(),w.on.call("cancel",e,e.__data__,w.index,w.group),delete r[m])}if(cx(function(){n.state===Bm&&(n.state=dx,n.timer.restart(u,n.delay,n.time),u(h))}),n.state=Lg,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Lg){for(n.state=Bm,a=new Array(y=n.tween.length),m=0,g=-1;m<y;++m)(w=n.tween[m].value.call(e,e.__data__,n.index,n.group))&&(a[++g]=w);a.length=g+1}}function u(h){for(var m=h<n.duration?n.ease.call(null,h/n.duration):(n.timer.restart(f),n.state=Ig,1),g=-1,y=a.length;++g<y;)a[g].call(e,m);n.state===Ig&&(n.on.call("end",e,e.__data__,n.index,n.group),f())}function f(){n.state=Um,n.timer.stop(),delete r[t];for(var h in r)return;delete e.__transition}}function Wm(e,t){var n=e.__transition,r,a,l=!0,c;if(n){t=t==null?null:t+"";for(c in n){if((r=n[c]).name!==t){l=!1;continue}a=r.state>Lg&&r.state<Ig,r.state=Um,r.timer.stop(),r.on.call(a?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[c]}l&&delete e.__transition}}function r4(e){return this.each(function(){Wm(this,e)})}function i4(e,t){var n,r;return function(){var a=Pa(this,e),l=a.tween;if(l!==n){r=n=l;for(var c=0,u=r.length;c<u;++c)if(r[c].name===t){r=r.slice(),r.splice(c,1);break}}a.tween=r}}function a4(e,t,n){var r,a;if(typeof n!="function")throw new Error;return function(){var l=Pa(this,e),c=l.tween;if(c!==r){a=(r=c).slice();for(var u={name:t,value:n},f=0,h=a.length;f<h;++f)if(a[f].name===t){a[f]=u;break}f===h&&a.push(u)}l.tween=a}}function o4(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=ta(this.node(),n).tween,a=0,l=r.length,c;a<l;++a)if((c=r[a]).name===e)return c.value;return null}return this.each((t==null?i4:a4)(n,e,t))}function Ry(e,t,n){var r=e._id;return e.each(function(){var a=Pa(this,r);(a.value||(a.value={}))[t]=n.apply(this,arguments)}),function(a){return ta(a,r).value[t]}}function Bk(e,t){var n;return(typeof t=="number"?fl:t instanceof Wf?ix:(n=Wf(t))?(t=n,ix):U3)(e,t)}function l4(e){return function(){this.removeAttribute(e)}}function c4(e){return function(){this.removeAttributeNS(e.space,e.local)}}function u4(e,t,n){var r,a=n+"",l;return function(){var c=this.getAttribute(e);return c===a?null:c===r?l:l=t(r=c,n)}}function d4(e,t,n){var r,a=n+"",l;return function(){var c=this.getAttributeNS(e.space,e.local);return c===a?null:c===r?l:l=t(r=c,n)}}function f4(e,t,n){var r,a,l;return function(){var c,u=n(this),f;return u==null?void this.removeAttribute(e):(c=this.getAttribute(e),f=u+"",c===f?null:c===r&&f===a?l:(a=f,l=t(r=c,u)))}}function h4(e,t,n){var r,a,l;return function(){var c,u=n(this),f;return u==null?void this.removeAttributeNS(e.space,e.local):(c=this.getAttributeNS(e.space,e.local),f=u+"",c===f?null:c===r&&f===a?l:(a=f,l=t(r=c,u)))}}function m4(e,t){var n=S_(e),r=n==="transform"?V3:Bk;return this.attrTween(e,typeof t=="function"?(n.local?h4:f4)(n,r,Ry(this,"attr."+e,t)):t==null?(n.local?c4:l4)(n):(n.local?d4:u4)(n,r,t))}function _4(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function p4(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function g4(e,t){var n,r;function a(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&p4(e,l)),n}return a._value=t,a}function y4(e,t){var n,r;function a(){var l=t.apply(this,arguments);return l!==r&&(n=(r=l)&&_4(e,l)),n}return a._value=t,a}function w4(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=S_(e);return this.tween(n,(r.local?g4:y4)(r,t))}function v4(e,t){return function(){My(this,e).delay=+t.apply(this,arguments)}}function x4(e,t){return t=+t,function(){My(this,e).delay=t}}function b4(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?v4:x4)(t,e)):ta(this.node(),t).delay}function k4(e,t){return function(){Pa(this,e).duration=+t.apply(this,arguments)}}function j4(e,t){return t=+t,function(){Pa(this,e).duration=t}}function S4(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?k4:j4)(t,e)):ta(this.node(),t).duration}function N4(e,t){if(typeof t!="function")throw new Error;return function(){Pa(this,e).ease=t}}function C4(e){var t=this._id;return arguments.length?this.each(N4(t,e)):ta(this.node(),t).ease}function E4(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Pa(this,e).ease=n}}function $4(e){if(typeof e!="function")throw new Error;return this.each(E4(this._id,e))}function A4(e){typeof e!="function"&&(e=wk(e));for(var t=this._groups,n=t.length,r=new Array(n),a=0;a<n;++a)for(var l=t[a],c=l.length,u=r[a]=[],f,h=0;h<c;++h)(f=l[h])&&e.call(f,f.__data__,h,l)&&u.push(f);return new ko(r,this._parents,this._name,this._id)}function T4(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,a=n.length,l=Math.min(r,a),c=new Array(r),u=0;u<l;++u)for(var f=t[u],h=n[u],m=f.length,g=c[u]=new Array(m),y,w=0;w<m;++w)(y=f[w]||h[w])&&(g[w]=y);for(;u<r;++u)c[u]=t[u];return new ko(c,this._parents,this._name,this._id)}function M4(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 R4(e,t,n){var r,a,l=M4(t)?My:Pa;return function(){var c=l(this,e),u=c.on;u!==r&&(a=(r=u).copy()).on(t,n),c.on=a}}function L4(e,t){var n=this._id;return arguments.length<2?ta(this.node(),n).on.on(e):this.each(R4(n,e,t))}function I4(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function O4(){return this.on("end.remove",I4(this._id))}function P4(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Ey(e));for(var r=this._groups,a=r.length,l=new Array(a),c=0;c<a;++c)for(var u=r[c],f=u.length,h=l[c]=new Array(f),m,g,y=0;y<f;++y)(m=u[y])&&(g=e.call(m,m.__data__,y,u))&&("__data__"in m&&(g.__data__=m.__data__),h[y]=g,C_(h[y],t,n,y,h,ta(m,n)));return new ko(l,this._parents,t,n)}function D4(e){var t=this._name,n=this._id;typeof e!="function"&&(e=yk(e));for(var r=this._groups,a=r.length,l=[],c=[],u=0;u<a;++u)for(var f=r[u],h=f.length,m,g=0;g<h;++g)if(m=f[g]){for(var y=e.call(m,m.__data__,g,f),w,k=ta(m,n),b=0,S=y.length;b<S;++b)(w=y[b])&&C_(w,t,n,b,y,k);l.push(y),c.push(m)}return new ko(l,c,t,n)}var F4=rh.prototype.constructor;function z4(){return new F4(this._groups,this._parents)}function B4(e,t){var n,r,a;return function(){var l=Wu(this,e),c=(this.style.removeProperty(e),Wu(this,e));return l===c?null:l===n&&c===r?a:a=t(n=l,r=c)}}function Uk(e){return function(){this.style.removeProperty(e)}}function U4(e,t,n){var r,a=n+"",l;return function(){var c=Wu(this,e);return c===a?null:c===r?l:l=t(r=c,n)}}function W4(e,t,n){var r,a,l;return function(){var c=Wu(this,e),u=n(this),f=u+"";return u==null&&(f=u=(this.style.removeProperty(e),Wu(this,e))),c===f?null:c===r&&f===a?l:(a=f,l=t(r=c,u))}}function q4(e,t){var n,r,a,l="style."+t,c="end."+l,u;return function(){var f=Pa(this,e),h=f.on,m=f.value[l]==null?u||(u=Uk(t)):void 0;(h!==n||a!==m)&&(r=(n=h).copy()).on(c,a=m),f.on=r}}function H4(e,t,n){var r=(e+="")=="transform"?H3:Bk;return t==null?this.styleTween(e,B4(e,r)).on("end.style."+e,Uk(e)):typeof t=="function"?this.styleTween(e,W4(e,r,Ry(this,"style."+e,t))).each(q4(this._id,e)):this.styleTween(e,U4(e,r,t),n).on("end.style."+e,null)}function V4(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function G4(e,t,n){var r,a;function l(){var c=t.apply(this,arguments);return c!==a&&(r=(a=c)&&V4(e,c,n)),r}return l._value=t,l}function K4(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,G4(e,t,n??""))}function Y4(e){return function(){this.textContent=e}}function J4(e){return function(){var t=e(this);this.textContent=t??""}}function X4(e){return this.tween("text",typeof e=="function"?J4(Ry(this,"text",e)):Y4(e==null?"":e+""))}function Z4(e){return function(t){this.textContent=e.call(this,t)}}function Q4(e){var t,n;function r(){var a=e.apply(this,arguments);return a!==n&&(t=(n=a)&&Z4(a)),t}return r._value=e,r}function eI(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,Q4(e))}function tI(){for(var e=this._name,t=this._id,n=Wk(),r=this._groups,a=r.length,l=0;l<a;++l)for(var c=r[l],u=c.length,f,h=0;h<u;++h)if(f=c[h]){var m=ta(f,t);C_(f,e,n,h,c,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new ko(r,this._parents,e,n)}function nI(){var e,t,n=this,r=n._id,a=n.size();return new Promise(function(l,c){var u={value:c},f={value:function(){--a===0&&l()}};n.each(function(){var h=Pa(this,r),m=h.on;m!==e&&(t=(e=m).copy(),t._.cancel.push(u),t._.interrupt.push(u),t._.end.push(f)),h.on=t}),a===0&&l()})}var sI=0;function ko(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Wk(){return++sI}var po=rh.prototype;ko.prototype={constructor:ko,select:P4,selectAll:D4,selectChild:po.selectChild,selectChildren:po.selectChildren,filter:A4,merge:T4,selection:z4,transition:tI,call:po.call,nodes:po.nodes,node:po.node,size:po.size,empty:po.empty,each:po.each,on:L4,attr:m4,attrTween:w4,style:H4,styleTween:K4,text:X4,textTween:eI,remove:O4,tween:o4,delay:b4,duration:S4,ease:C4,easeVarying:$4,end:nI,[Symbol.iterator]:po[Symbol.iterator]};function rI(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var iI={time:null,delay:0,duration:250,ease:rI};function aI(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 oI(e){var t,n;e instanceof ko?(t=e._id,e=e._name):(t=Wk(),(n=iI).time=Ty(),e=e==null?null:e+"");for(var r=this._groups,a=r.length,l=0;l<a;++l)for(var c=r[l],u=c.length,f,h=0;h<u;++h)(f=c[h])&&C_(f,e,t,h,c,n||aI(f,t));return new ko(r,this._parents,e,t)}rh.prototype.interrupt=r4;rh.prototype.transition=oI;const Cm=e=>()=>e;function lI(e,{sourceEvent:t,target:n,transform:r,dispatch:a}){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:a}})}function vo(e,t,n){this.k=e,this.x=t,this.y=n}vo.prototype={constructor:vo,scale:function(e){return e===1?this:new vo(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new vo(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 bo=new vo(1,0,0);vo.prototype;function Op(e){e.stopImmediatePropagation()}function df(e){e.preventDefault(),e.stopImmediatePropagation()}function cI(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function uI(){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 fx(){return this.__zoom||bo}function dI(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function fI(){return navigator.maxTouchPoints||"ontouchstart"in this}function hI(e,t,n){var r=e.invertX(t[0][0])-n[0][0],a=e.invertX(t[1][0])-n[1][0],l=e.invertY(t[0][1])-n[0][1],c=e.invertY(t[1][1])-n[1][1];return e.translate(a>r?(r+a)/2:Math.min(0,r)||Math.max(0,a),c>l?(l+c)/2:Math.min(0,l)||Math.max(0,c))}function qk(){var e=cI,t=uI,n=hI,r=dI,a=fI,l=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],u=250,f=J3,h=j_("start","zoom","end"),m,g,y,w=500,k=150,b=0,S=10;function N(E){E.property("__zoom",fx).on("wheel.zoom",G,{passive:!1}).on("mousedown.zoom",re).on("dblclick.zoom",te).filter(a).on("touchstart.zoom",Q).on("touchmove.zoom",D).on("touchend.zoom touchcancel.zoom",T).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function(E,L,M,ee){var F=E.selection?E.selection():E;F.property("__zoom",fx),E!==F?W(E,L,M,ee):F.interrupt().each(function(){z(this,arguments).event(ee).start().zoom(null,typeof L=="function"?L.apply(this,arguments):L).end()})},N.scaleBy=function(E,L,M,ee){N.scaleTo(E,function(){var F=this.__zoom.k,U=typeof L=="function"?L.apply(this,arguments):L;return F*U},M,ee)},N.scaleTo=function(E,L,M,ee){N.transform(E,function(){var F=t.apply(this,arguments),U=this.__zoom,K=M==null?A(F):typeof M=="function"?M.apply(this,arguments):M,O=U.invert(K),V=typeof L=="function"?L.apply(this,arguments):L;return n($(R(U,V),K,O),F,c)},M,ee)},N.translateBy=function(E,L,M,ee){N.transform(E,function(){return n(this.__zoom.translate(typeof L=="function"?L.apply(this,arguments):L,typeof M=="function"?M.apply(this,arguments):M),t.apply(this,arguments),c)},null,ee)},N.translateTo=function(E,L,M,ee,F){N.transform(E,function(){var U=t.apply(this,arguments),K=this.__zoom,O=ee==null?A(U):typeof ee=="function"?ee.apply(this,arguments):ee;return n(bo.translate(O[0],O[1]).scale(K.k).translate(typeof L=="function"?-L.apply(this,arguments):-L,typeof M=="function"?-M.apply(this,arguments):-M),U,c)},ee,F)};function R(E,L){return L=Math.max(l[0],Math.min(l[1],L)),L===E.k?E:new vo(L,E.x,E.y)}function $(E,L,M){var ee=L[0]-M[0]*E.k,F=L[1]-M[1]*E.k;return ee===E.x&&F===E.y?E:new vo(E.k,ee,F)}function A(E){return[(+E[0][0]+ +E[1][0])/2,(+E[0][1]+ +E[1][1])/2]}function W(E,L,M,ee){E.on("start.zoom",function(){z(this,arguments).event(ee).start()}).on("interrupt.zoom end.zoom",function(){z(this,arguments).event(ee).end()}).tween("zoom",function(){var F=this,U=arguments,K=z(F,U).event(ee),O=t.apply(F,U),V=M==null?A(O):typeof M=="function"?M.apply(F,U):M,J=Math.max(O[1][0]-O[0][0],O[1][1]-O[0][1]),le=F.__zoom,ie=typeof L=="function"?L.apply(F,U):L,_e=f(le.invert(V).concat(J/le.k),ie.invert(V).concat(J/ie.k));return function(pe){if(pe===1)pe=ie;else{var ye=_e(pe),Ne=J/ye[2];pe=new vo(Ne,V[0]-ye[0]*Ne,V[1]-ye[1]*Ne)}K.zoom(null,pe)}})}function z(E,L,M){return!M&&E.__zooming||new H(E,L)}function H(E,L){this.that=E,this.args=L,this.active=0,this.sourceEvent=null,this.extent=t.apply(E,L),this.taps=0}H.prototype={event:function(E){return E&&(this.sourceEvent=E),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(E,L){return this.mouse&&E!=="mouse"&&(this.mouse[1]=L.invert(this.mouse[0])),this.touch0&&E!=="touch"&&(this.touch0[1]=L.invert(this.touch0[0])),this.touch1&&E!=="touch"&&(this.touch1[1]=L.invert(this.touch1[0])),this.that.__zoom=L,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(E){var L=ki(this.that).datum();h.call(E,this.that,new lI(E,{sourceEvent:this.sourceEvent,target:N,transform:this.that.__zoom,dispatch:h}),L)}};function G(E,...L){if(!e.apply(this,arguments))return;var M=z(this,L).event(E),ee=this.__zoom,F=Math.max(l[0],Math.min(l[1],ee.k*Math.pow(2,r.apply(this,arguments)))),U=Ji(E);if(M.wheel)(M.mouse[0][0]!==U[0]||M.mouse[0][1]!==U[1])&&(M.mouse[1]=ee.invert(M.mouse[0]=U)),clearTimeout(M.wheel);else{if(ee.k===F)return;M.mouse=[U,ee.invert(U)],Wm(this),M.start()}df(E),M.wheel=setTimeout(K,k),M.zoom("mouse",n($(R(ee,F),M.mouse[0],M.mouse[1]),M.extent,c));function K(){M.wheel=null,M.end()}}function re(E,...L){if(y||!e.apply(this,arguments))return;var M=E.currentTarget,ee=z(this,L,!0).event(E),F=ki(E.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",J,!0),U=Ji(E,M),K=E.clientX,O=E.clientY;$k(E.view),Op(E),ee.mouse=[U,this.__zoom.invert(U)],Wm(this),ee.start();function V(le){if(df(le),!ee.moved){var ie=le.clientX-K,_e=le.clientY-O;ee.moved=ie*ie+_e*_e>b}ee.event(le).zoom("mouse",n($(ee.that.__zoom,ee.mouse[0]=Ji(le,M),ee.mouse[1]),ee.extent,c))}function J(le){F.on("mousemove.zoom mouseup.zoom",null),Ak(le.view,ee.moved),df(le),ee.event(le).end()}}function te(E,...L){if(e.apply(this,arguments)){var M=this.__zoom,ee=Ji(E.changedTouches?E.changedTouches[0]:E,this),F=M.invert(ee),U=M.k*(E.shiftKey?.5:2),K=n($(R(M,U),ee,F),t.apply(this,L),c);df(E),u>0?ki(this).transition().duration(u).call(W,K,ee,E):ki(this).call(N.transform,K,ee,E)}}function Q(E,...L){if(e.apply(this,arguments)){var M=E.touches,ee=M.length,F=z(this,L,E.changedTouches.length===ee).event(E),U,K,O,V;for(Op(E),K=0;K<ee;++K)O=M[K],V=Ji(O,this),V=[V,this.__zoom.invert(V),O.identifier],F.touch0?!F.touch1&&F.touch0[2]!==V[2]&&(F.touch1=V,F.taps=0):(F.touch0=V,U=!0,F.taps=1+!!m);m&&(m=clearTimeout(m)),U&&(F.taps<2&&(g=V[0],m=setTimeout(function(){m=null},w)),Wm(this),F.start())}}function D(E,...L){if(this.__zooming){var M=z(this,L).event(E),ee=E.changedTouches,F=ee.length,U,K,O,V;for(df(E),U=0;U<F;++U)K=ee[U],O=Ji(K,this),M.touch0&&M.touch0[2]===K.identifier?M.touch0[0]=O:M.touch1&&M.touch1[2]===K.identifier&&(M.touch1[0]=O);if(K=M.that.__zoom,M.touch1){var J=M.touch0[0],le=M.touch0[1],ie=M.touch1[0],_e=M.touch1[1],pe=(pe=ie[0]-J[0])*pe+(pe=ie[1]-J[1])*pe,ye=(ye=_e[0]-le[0])*ye+(ye=_e[1]-le[1])*ye;K=R(K,Math.sqrt(pe/ye)),O=[(J[0]+ie[0])/2,(J[1]+ie[1])/2],V=[(le[0]+_e[0])/2,(le[1]+_e[1])/2]}else if(M.touch0)O=M.touch0[0],V=M.touch0[1];else return;M.zoom("touch",n($(K,O,V),M.extent,c))}}function T(E,...L){if(this.__zooming){var M=z(this,L).event(E),ee=E.changedTouches,F=ee.length,U,K;for(Op(E),y&&clearTimeout(y),y=setTimeout(function(){y=null},w),U=0;U<F;++U)K=ee[U],M.touch0&&M.touch0[2]===K.identifier?delete M.touch0:M.touch1&&M.touch1[2]===K.identifier&&delete M.touch1;if(M.touch1&&!M.touch0&&(M.touch0=M.touch1,delete M.touch1),M.touch0)M.touch0[1]=this.__zoom.invert(M.touch0[0]);else if(M.end(),M.taps===2&&(K=Ji(K,this),Math.hypot(g[0]-K[0],g[1]-K[1])<S)){var O=ki(this).on("dblclick.zoom");O&&O.apply(this,arguments)}}}return N.wheelDelta=function(E){return arguments.length?(r=typeof E=="function"?E:Cm(+E),N):r},N.filter=function(E){return arguments.length?(e=typeof E=="function"?E:Cm(!!E),N):e},N.touchable=function(E){return arguments.length?(a=typeof E=="function"?E:Cm(!!E),N):a},N.extent=function(E){return arguments.length?(t=typeof E=="function"?E:Cm([[+E[0][0],+E[0][1]],[+E[1][0],+E[1][1]]]),N):t},N.scaleExtent=function(E){return arguments.length?(l[0]=+E[0],l[1]=+E[1],N):[l[0],l[1]]},N.translateExtent=function(E){return arguments.length?(c[0][0]=+E[0][0],c[1][0]=+E[1][0],c[0][1]=+E[0][1],c[1][1]=+E[1][1],N):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},N.constrain=function(E){return arguments.length?(n=E,N):n},N.duration=function(E){return arguments.length?(u=+E,N):u},N.interpolate=function(E){return arguments.length?(f=E,N):f},N.on=function(){var E=h.on.apply(h,arguments);return E===h?N:E},N.clickDistance=function(E){return arguments.length?(b=(E=+E)*E,N):Math.sqrt(b)},N.tapDistance=function(E){return arguments.length?(S=+E,N):S},N}const E_=_.createContext(null),mI=E_.Provider,jo={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.`},Hk=jo.error001();function In(e,t){const n=_.useContext(E_);if(n===null)throw new Error(Hk);return pk(n,e,t)}const js=()=>{const e=_.useContext(E_);if(e===null)throw new Error(Hk);return _.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},_I=e=>e.userSelectionActive?"none":"all";function Hf({position:e,children:t,className:n,style:r,...a}){const l=In(_I),c=`${e}`.split("-");return xe.createElement("div",{className:Vs(["react-flow__panel",n,...c]),style:{...r,pointerEvents:l},...a},t)}function pI({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:xe.createElement(Hf,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://reactflow.dev/pro"},xe.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const gI=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:a=!0,labelBgStyle:l={},labelBgPadding:c=[2,4],labelBgBorderRadius:u=2,children:f,className:h,...m})=>{const g=_.useRef(null),[y,w]=_.useState({x:0,y:0,width:0,height:0}),k=Vs(["react-flow__edge-textwrapper",h]);return _.useEffect(()=>{if(g.current){const b=g.current.getBBox();w({x:b.x,y:b.y,width:b.width,height:b.height})}},[n]),typeof n>"u"||!n?null:xe.createElement("g",{transform:`translate(${e-y.width/2} ${t-y.height/2})`,className:k,visibility:y.width?"visible":"hidden",...m},a&&xe.createElement("rect",{width:y.width+2*c[0],x:-c[0],y:-c[1],height:y.height+2*c[1],className:"react-flow__edge-textbg",style:l,rx:u,ry:u}),xe.createElement("text",{className:"react-flow__edge-text",y:y.height/2,dy:"0.3em",ref:g,style:r},n),f)};var yI=_.memo(gI);const Ly=e=>({width:e.offsetWidth,height:e.offsetHeight}),Hu=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Iy=(e={x:0,y:0},t)=>({x:Hu(e.x,t[0][0],t[1][0]),y:Hu(e.y,t[0][1],t[1][1])}),hx=(e,t,n)=>e<t?Hu(Math.abs(e-t),1,50)/50:e>n?-Hu(Math.abs(e-n),1,50)/50:0,Vk=(e,t)=>{const n=hx(e.x,35,t.width-35)*20,r=hx(e.y,35,t.height-35)*20;return[n,r]},Gk=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Kk=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Vf=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Yk=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),mx=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),wI=(e,t)=>Yk(Kk(Vf(e),Vf(t))),Og=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},vI=e=>ji(e.width)&&ji(e.height)&&ji(e.x)&&ji(e.y),ji=e=>!isNaN(e)&&isFinite(e),_s=Symbol.for("internals"),Jk=["Enter"," ","Escape"],xI=(e,t)=>{},bI=e=>"nativeEvent"in e;function Pg(e){var a,l;const t=bI(e)?e.nativeEvent:e,n=((l=(a=t.composedPath)==null?void 0:a.call(t))==null?void 0:l[0])||e.target;return["INPUT","SELECT","TEXTAREA"].includes(n==null?void 0:n.nodeName)||(n==null?void 0:n.hasAttribute("contenteditable"))||!!(n!=null&&n.closest(".nokey"))}const Xk=e=>"clientX"in e,gl=(e,t)=>{var l,c;const n=Xk(e),r=n?e.clientX:(l=e.touches)==null?void 0:l[0].clientX,a=n?e.clientY:(c=e.touches)==null?void 0:c[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:a-((t==null?void 0:t.top)??0)}},c_=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},ah=({id:e,path:t,labelX:n,labelY:r,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:w=20})=>xe.createElement(xe.Fragment,null,xe.createElement("path",{id:e,style:m,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:g,markerStart:y}),w&&xe.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:w,className:"react-flow__edge-interaction"}),a&&ji(n)&&ji(r)?xe.createElement(yI,{x:n,y:r,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h}):null);ah.displayName="BaseEdge";function ff(e,t,n){return n===void 0?n:r=>{const a=t().edges.find(l=>l.id===e);a&&n(r,{...a})}}function Zk({sourceX:e,sourceY:t,targetX:n,targetY:r}){const a=Math.abs(n-e)/2,l=n<e?n+a:n-a,c=Math.abs(r-t)/2,u=r<t?r+c:r-c;return[l,u,a,c]}function Qk({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:u}){const f=e*.125+a*.375+c*.375+n*.125,h=t*.125+l*.375+u*.375+r*.125,m=Math.abs(f-e),g=Math.abs(h-t);return[f,h,m,g]}var bc;(function(e){e.Strict="strict",e.Loose="loose"})(bc||(bc={}));var dc;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(dc||(dc={}));var Gf;(function(e){e.Partial="partial",e.Full="full"})(Gf||(Gf={}));var ml;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(ml||(ml={}));var Kf;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Kf||(Kf={}));var wt;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(wt||(wt={}));function _x({pos:e,x1:t,y1:n,x2:r,y2:a}){return e===wt.Left||e===wt.Right?[.5*(t+r),n]:[t,.5*(n+a)]}function ej({sourceX:e,sourceY:t,sourcePosition:n=wt.Bottom,targetX:r,targetY:a,targetPosition:l=wt.Top}){const[c,u]=_x({pos:n,x1:e,y1:t,x2:r,y2:a}),[f,h]=_x({pos:l,x1:r,y1:a,x2:e,y2:t}),[m,g,y,w]=Qk({sourceX:e,sourceY:t,targetX:r,targetY:a,sourceControlX:c,sourceControlY:u,targetControlX:f,targetControlY:h});return[`M${e},${t} C${c},${u} ${f},${h} ${r},${a}`,m,g,y,w]}const Oy=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:a=wt.Bottom,targetPosition:l=wt.Top,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,interactionWidth:b})=>{const[S,N,R]=ej({sourceX:e,sourceY:t,sourcePosition:a,targetX:n,targetY:r,targetPosition:l});return xe.createElement(ah,{path:S,labelX:N,labelY:R,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,interactionWidth:b})});Oy.displayName="SimpleBezierEdge";const px={[wt.Left]:{x:-1,y:0},[wt.Right]:{x:1,y:0},[wt.Top]:{x:0,y:-1},[wt.Bottom]:{x:0,y:1}},kI=({source:e,sourcePosition:t=wt.Bottom,target:n})=>t===wt.Left||t===wt.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},gx=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function jI({source:e,sourcePosition:t=wt.Bottom,target:n,targetPosition:r=wt.Top,center:a,offset:l}){const c=px[t],u=px[r],f={x:e.x+c.x*l,y:e.y+c.y*l},h={x:n.x+u.x*l,y:n.y+u.y*l},m=kI({source:f,sourcePosition:t,target:h}),g=m.x!==0?"x":"y",y=m[g];let w=[],k,b;const S={x:0,y:0},N={x:0,y:0},[R,$,A,W]=Zk({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(c[g]*u[g]===-1){k=a.x||R,b=a.y||$;const H=[{x:k,y:f.y},{x:k,y:h.y}],G=[{x:f.x,y:b},{x:h.x,y:b}];c[g]===y?w=g==="x"?H:G:w=g==="x"?G:H}else{const H=[{x:f.x,y:h.y}],G=[{x:h.x,y:f.y}];if(g==="x"?w=c.x===y?G:H:w=c.y===y?H:G,t===r){const T=Math.abs(e[g]-n[g]);if(T<=l){const E=Math.min(l-1,l-T);c[g]===y?S[g]=(f[g]>e[g]?-1:1)*E:N[g]=(h[g]>n[g]?-1:1)*E}}if(t!==r){const T=g==="x"?"y":"x",E=c[g]===u[T],L=f[T]>h[T],M=f[T]<h[T];(c[g]===1&&(!E&&L||E&&M)||c[g]!==1&&(!E&&M||E&&L))&&(w=g==="x"?H:G)}const re={x:f.x+S.x,y:f.y+S.y},te={x:h.x+N.x,y:h.y+N.y},Q=Math.max(Math.abs(re.x-w[0].x),Math.abs(te.x-w[0].x)),D=Math.max(Math.abs(re.y-w[0].y),Math.abs(te.y-w[0].y));Q>=D?(k=(re.x+te.x)/2,b=w[0].y):(k=w[0].x,b=(re.y+te.y)/2)}return[[e,{x:f.x+S.x,y:f.y+S.y},...w,{x:h.x+N.x,y:h.y+N.y},n],k,b,A,W]}function SI(e,t,n,r){const a=Math.min(gx(e,t)/2,gx(t,n)/2,r),{x:l,y:c}=t;if(e.x===l&&l===n.x||e.y===c&&c===n.y)return`L${l} ${c}`;if(e.y===c){const h=e.x<n.x?-1:1,m=e.y<n.y?1:-1;return`L ${l+a*h},${c}Q ${l},${c} ${l},${c+a*m}`}const u=e.x<n.x?1:-1,f=e.y<n.y?-1:1;return`L ${l},${c+a*f}Q ${l},${c} ${l+a*u},${c}`}function Dg({sourceX:e,sourceY:t,sourcePosition:n=wt.Bottom,targetX:r,targetY:a,targetPosition:l=wt.Top,borderRadius:c=5,centerX:u,centerY:f,offset:h=20}){const[m,g,y,w,k]=jI({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:a},targetPosition:l,center:{x:u,y:f},offset:h});return[m.reduce((S,N,R)=>{let $="";return R>0&&R<m.length-1?$=SI(m[R-1],N,m[R+1],c):$=`${R===0?"M":"L"}${N.x} ${N.y}`,S+=$,S},""),g,y,w,k]}const $_=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,sourcePosition:g=wt.Bottom,targetPosition:y=wt.Top,markerEnd:w,markerStart:k,pathOptions:b,interactionWidth:S})=>{const[N,R,$]=Dg({sourceX:e,sourceY:t,sourcePosition:g,targetX:n,targetY:r,targetPosition:y,borderRadius:b==null?void 0:b.borderRadius,offset:b==null?void 0:b.offset});return xe.createElement(ah,{path:N,labelX:R,labelY:$,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:w,markerStart:k,interactionWidth:S})});$_.displayName="SmoothStepEdge";const Py=_.memo(e=>{var t;return xe.createElement($_,{...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])})});Py.displayName="StepEdge";function NI({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[a,l,c,u]=Zk({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,a,l,c,u]}const Dy=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:w})=>{const[k,b,S]=NI({sourceX:e,sourceY:t,targetX:n,targetY:r});return xe.createElement(ah,{path:k,labelX:b,labelY:S,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:u,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:w})});Dy.displayName="StraightEdge";function Em(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function yx({pos:e,x1:t,y1:n,x2:r,y2:a,c:l}){switch(e){case wt.Left:return[t-Em(t-r,l),n];case wt.Right:return[t+Em(r-t,l),n];case wt.Top:return[t,n-Em(n-a,l)];case wt.Bottom:return[t,n+Em(a-n,l)]}}function tj({sourceX:e,sourceY:t,sourcePosition:n=wt.Bottom,targetX:r,targetY:a,targetPosition:l=wt.Top,curvature:c=.25}){const[u,f]=yx({pos:n,x1:e,y1:t,x2:r,y2:a,c}),[h,m]=yx({pos:l,x1:r,y1:a,x2:e,y2:t,c}),[g,y,w,k]=Qk({sourceX:e,sourceY:t,targetX:r,targetY:a,sourceControlX:u,sourceControlY:f,targetControlX:h,targetControlY:m});return[`M${e},${t} C${u},${f} ${h},${m} ${r},${a}`,g,y,w,k]}const u_=_.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:a=wt.Bottom,targetPosition:l=wt.Top,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,pathOptions:b,interactionWidth:S})=>{const[N,R,$]=tj({sourceX:e,sourceY:t,sourcePosition:a,targetX:n,targetY:r,targetPosition:l,curvature:b==null?void 0:b.curvature});return xe.createElement(ah,{path:N,labelX:R,labelY:$,label:c,labelStyle:u,labelShowBg:f,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:g,style:y,markerEnd:w,markerStart:k,interactionWidth:S})});u_.displayName="BezierEdge";const Fy=_.createContext(null),CI=Fy.Provider;Fy.Consumer;const EI=()=>_.useContext(Fy),$I=e=>"id"in e&&"source"in e&&"target"in e,AI=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,Fg=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,TI=(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)),MI=(e,t)=>{if(!e.source||!e.target)return t;let n;return $I(e)?n={...e}:n={...e,id:AI(e)},TI(n,t)?t:t.concat(n)},zg=({x:e,y:t},[n,r,a],l,[c,u])=>{const f={x:(e-n)/a,y:(t-r)/a};return l?{x:c*Math.round(f.x/c),y:u*Math.round(f.y/u)}:f},nj=({x:e,y:t},[n,r,a])=>({x:e*a+n,y:t*a+r}),pc=(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],a={x:e.position.x-n,y:e.position.y-r};return{...a,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:a}},A_=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,a)=>{const{x:l,y:c}=pc(a,t).positionAbsolute;return Kk(r,Vf({x:l,y:c,width:a.width||0,height:a.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Yk(n)},sj=(e,t,[n,r,a]=[0,0,1],l=!1,c=!1,u=[0,0])=>{const f={x:(t.x-n)/a,y:(t.y-r)/a,width:t.width/a,height:t.height/a},h=[];return e.forEach(m=>{const{width:g,height:y,selectable:w=!0,hidden:k=!1}=m;if(c&&!w||k)return!1;const{positionAbsolute:b}=pc(m,u),S={x:b.x,y:b.y,width:g||0,height:y||0},N=Og(f,S),R=typeof g>"u"||typeof y>"u"||g===null||y===null,$=l&&N>0,A=(g||0)*(y||0);(R||$||N>=A||m.dragging)&&h.push(m)}),h},rj=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},ij=(e,t,n,r,a,l=.1)=>{const c=t/(e.width*(1+l)),u=n/(e.height*(1+l)),f=Math.min(c,u),h=Hu(f,r,a),m=e.x+e.width/2,g=e.y+e.height/2,y=t/2-m*h,w=n/2-g*h;return{x:y,y:w,zoom:h}},ac=(e,t=0)=>e.transition().duration(t);function wx(e,t,n,r){return(t[n]||[]).reduce((a,l)=>{var c,u;return`${e.id}-${l.id}-${n}`!==r&&a.push({id:l.id||null,type:n,nodeId:e.id,x:(((c=e.positionAbsolute)==null?void 0:c.x)??0)+l.x+l.width/2,y:(((u=e.positionAbsolute)==null?void 0:u.y)??0)+l.y+l.height/2}),a},[])}function RI(e,t,n,r,a,l){const{x:c,y:u}=gl(e),h=t.elementsFromPoint(c,u).find(k=>k.classList.contains("react-flow__handle"));if(h){const k=h.getAttribute("data-nodeid");if(k){const b=zy(void 0,h),S=h.getAttribute("data-handleid"),N=l({nodeId:k,id:S,type:b});if(N){const R=a.find($=>$.nodeId===k&&$.type===b&&$.id===S);return{handle:{id:S,type:b,nodeId:k,x:(R==null?void 0:R.x)||n.x,y:(R==null?void 0:R.y)||n.y},validHandleResult:N}}}}let m=[],g=1/0;if(a.forEach(k=>{const b=Math.sqrt((k.x-n.x)**2+(k.y-n.y)**2);if(b<=r){const S=l(k);b<=g&&(b<g?m=[{handle:k,validHandleResult:S}]:b===g&&m.push({handle:k,validHandleResult:S}),g=b)}}),!m.length)return{handle:null,validHandleResult:aj()};if(m.length===1)return m[0];const y=m.some(({validHandleResult:k})=>k.isValid),w=m.some(({handle:k})=>k.type==="target");return m.find(({handle:k,validHandleResult:b})=>w?k.type==="target":y?b.isValid:!0)||m[0]}const LI={source:null,target:null,sourceHandle:null,targetHandle:null},aj=()=>({handleDomNode:null,isValid:!1,connection:LI,endHandle:null});function oj(e,t,n,r,a,l,c){const u=a==="target",f=c.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),h={...aj(),handleDomNode:f};if(f){const m=zy(void 0,f),g=f.getAttribute("data-nodeid"),y=f.getAttribute("data-handleid"),w=f.classList.contains("connectable"),k=f.classList.contains("connectableend"),b={source:u?g:n,sourceHandle:u?y:r,target:u?n:g,targetHandle:u?r:y};h.connection=b,w&&k&&(t===bc.Strict?u&&m==="source"||!u&&m==="target":g!==n||y!==r)&&(h.endHandle={nodeId:g,handleId:y,type:m},h.isValid=l(b))}return h}function II({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((a,l)=>{if(l[_s]){const{handleBounds:c}=l[_s];let u=[],f=[];c&&(u=wx(l,c,"source",`${t}-${n}-${r}`),f=wx(l,c,"target",`${t}-${n}-${r}`)),a.push(...u,...f)}return a},[])}function zy(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function Pp(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function OI(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function lj({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:a,getState:l,setState:c,isValidConnection:u,edgeUpdaterType:f,onEdgeUpdateEnd:h}){const m=Gk(e.target),{connectionMode:g,domNode:y,autoPanOnConnect:w,connectionRadius:k,onConnectStart:b,panBy:S,getNodes:N,cancelConnection:R}=l();let $=0,A;const{x:W,y:z}=gl(e),H=m==null?void 0:m.elementFromPoint(W,z),G=zy(f,H),re=y==null?void 0:y.getBoundingClientRect();if(!re||!G)return;let te,Q=gl(e,re),D=!1,T=null,E=!1,L=null;const M=II({nodes:N(),nodeId:n,handleId:t,handleType:G}),ee=()=>{if(!w)return;const[K,O]=Vk(Q,re);S({x:K,y:O}),$=requestAnimationFrame(ee)};c({connectionPosition:Q,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:G,connectionStartHandle:{nodeId:n,handleId:t,type:G},connectionEndHandle:null}),b==null||b(e,{nodeId:n,handleId:t,handleType:G});function F(K){const{transform:O}=l();Q=gl(K,re);const{handle:V,validHandleResult:J}=RI(K,m,zg(Q,O,!1,[1,1]),k,M,le=>oj(le,g,n,t,a?"target":"source",u,m));if(A=V,D||(ee(),D=!0),L=J.handleDomNode,T=J.connection,E=J.isValid,c({connectionPosition:A&&E?nj({x:A.x,y:A.y},O):Q,connectionStatus:OI(!!A,E),connectionEndHandle:J.endHandle}),!A&&!E&&!L)return Pp(te);T.source!==T.target&&L&&(Pp(te),te=L,L.classList.add("connecting","react-flow__handle-connecting"),L.classList.toggle("valid",E),L.classList.toggle("react-flow__handle-valid",E))}function U(K){var O,V;(A||L)&&T&&E&&(r==null||r(T)),(V=(O=l()).onConnectEnd)==null||V.call(O,K),f&&(h==null||h(K)),Pp(te),R(),cancelAnimationFrame($),D=!1,E=!1,T=null,L=null,m.removeEventListener("mousemove",F),m.removeEventListener("mouseup",U),m.removeEventListener("touchmove",F),m.removeEventListener("touchend",U)}m.addEventListener("mousemove",F),m.addEventListener("mouseup",U),m.addEventListener("touchmove",F),m.addEventListener("touchend",U)}const vx=()=>!0,PI=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),DI=(e,t,n)=>r=>{const{connectionStartHandle:a,connectionEndHandle:l,connectionClickStartHandle:c}=r;return{connecting:(a==null?void 0:a.nodeId)===e&&(a==null?void 0:a.handleId)===t&&(a==null?void 0:a.type)===n||(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.handleId)===t&&(l==null?void 0:l.type)===n,clickConnecting:(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.handleId)===t&&(c==null?void 0:c.type)===n}},cj=_.forwardRef(({type:e="source",position:t=wt.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:a=!0,isConnectableEnd:l=!0,id:c,onConnect:u,children:f,className:h,onMouseDown:m,onTouchStart:g,...y},w)=>{var re,te;const k=c||null,b=e==="target",S=js(),N=EI(),{connectOnClick:R,noPanClassName:$}=In(PI,Os),{connecting:A,clickConnecting:W}=In(DI(N,k,e),Os);N||(te=(re=S.getState()).onError)==null||te.call(re,"010",jo.error010());const z=Q=>{const{defaultEdgeOptions:D,onConnect:T,hasDefaultEdges:E}=S.getState(),L={...D,...Q};if(E){const{edges:M,setEdges:ee}=S.getState();ee(MI(L,M))}T==null||T(L),u==null||u(L)},H=Q=>{if(!N)return;const D=Xk(Q);a&&(D&&Q.button===0||!D)&&lj({event:Q,handleId:k,nodeId:N,onConnect:z,isTarget:b,getState:S.getState,setState:S.setState,isValidConnection:n||S.getState().isValidConnection||vx}),D?m==null||m(Q):g==null||g(Q)},G=Q=>{const{onClickConnectStart:D,onClickConnectEnd:T,connectionClickStartHandle:E,connectionMode:L,isValidConnection:M}=S.getState();if(!N||!E&&!a)return;if(!E){D==null||D(Q,{nodeId:N,handleId:k,handleType:e}),S.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:k}});return}const ee=Gk(Q.target),F=n||M||vx,{connection:U,isValid:K}=oj({nodeId:N,id:k,type:e},L,E.nodeId,E.handleId||null,E.type,F,ee);K&&z(U),T==null||T(Q),S.setState({connectionClickStartHandle:null})};return xe.createElement("div",{"data-handleid":k,"data-nodeid":N,"data-handlepos":t,"data-id":`${N}-${k}-${e}`,className:Vs(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",$,h,{source:!b,target:b,connectable:r,connectablestart:a,connectableend:l,connecting:W,connectionindicator:r&&(a&&!A||l&&A)}]),onMouseDown:H,onTouchStart:H,onClick:R?G:void 0,ref:w,...y},f)});cj.displayName="Handle";var d_=_.memo(cj);const uj=({data:e,isConnectable:t,targetPosition:n=wt.Top,sourcePosition:r=wt.Bottom})=>xe.createElement(xe.Fragment,null,xe.createElement(d_,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,xe.createElement(d_,{type:"source",position:r,isConnectable:t}));uj.displayName="DefaultNode";var Bg=_.memo(uj);const dj=({data:e,isConnectable:t,sourcePosition:n=wt.Bottom})=>xe.createElement(xe.Fragment,null,e==null?void 0:e.label,xe.createElement(d_,{type:"source",position:n,isConnectable:t}));dj.displayName="InputNode";var fj=_.memo(dj);const hj=({data:e,isConnectable:t,targetPosition:n=wt.Top})=>xe.createElement(xe.Fragment,null,xe.createElement(d_,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);hj.displayName="OutputNode";var mj=_.memo(hj);const By=()=>null;By.displayName="GroupNode";const FI=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),$m=e=>e.id;function zI(e,t){return Os(e.selectedNodes.map($m),t.selectedNodes.map($m))&&Os(e.selectedEdges.map($m),t.selectedEdges.map($m))}const _j=_.memo(({onSelectionChange:e})=>{const t=js(),{selectedNodes:n,selectedEdges:r}=In(FI,zI);return _.useEffect(()=>{const a={nodes:n,edges:r};e==null||e(a),t.getState().onSelectionChange.forEach(l=>l(a))},[n,r,e]),null});_j.displayName="SelectionListener";const BI=e=>!!e.onSelectionChange;function UI({onSelectionChange:e}){const t=In(BI);return e||t?xe.createElement(_j,{onSelectionChange:e}):null}const WI=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 xu(e,t){_.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Xt(e,t,n){_.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const qI=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:a,onConnectStart:l,onConnectEnd:c,onClickConnectStart:u,onClickConnectEnd:f,nodesDraggable:h,nodesConnectable:m,nodesFocusable:g,edgesFocusable:y,edgesUpdatable:w,elevateNodesOnSelect:k,minZoom:b,maxZoom:S,nodeExtent:N,onNodesChange:R,onEdgesChange:$,elementsSelectable:A,connectionMode:W,snapGrid:z,snapToGrid:H,translateExtent:G,connectOnClick:re,defaultEdgeOptions:te,fitView:Q,fitViewOptions:D,onNodesDelete:T,onEdgesDelete:E,onNodeDrag:L,onNodeDragStart:M,onNodeDragStop:ee,onSelectionDrag:F,onSelectionDragStart:U,onSelectionDragStop:K,noPanClassName:O,nodeOrigin:V,rfId:J,autoPanOnConnect:le,autoPanOnNodeDrag:ie,onError:_e,connectionRadius:pe,isValidConnection:ye,nodeDragThreshold:Ne})=>{const{setNodes:Be,setEdges:Ue,setDefaultNodesAndEdges:ut,setMinZoom:De,setMaxZoom:Qe,setTranslateExtent:at,setNodeExtent:Ke,reset:ce}=In(WI,Os),oe=js();return _.useEffect(()=>{const Ae=r==null?void 0:r.map(he=>({...he,...te}));return ut(n,Ae),()=>{ce()}},[]),Xt("defaultEdgeOptions",te,oe.setState),Xt("connectionMode",W,oe.setState),Xt("onConnect",a,oe.setState),Xt("onConnectStart",l,oe.setState),Xt("onConnectEnd",c,oe.setState),Xt("onClickConnectStart",u,oe.setState),Xt("onClickConnectEnd",f,oe.setState),Xt("nodesDraggable",h,oe.setState),Xt("nodesConnectable",m,oe.setState),Xt("nodesFocusable",g,oe.setState),Xt("edgesFocusable",y,oe.setState),Xt("edgesUpdatable",w,oe.setState),Xt("elementsSelectable",A,oe.setState),Xt("elevateNodesOnSelect",k,oe.setState),Xt("snapToGrid",H,oe.setState),Xt("snapGrid",z,oe.setState),Xt("onNodesChange",R,oe.setState),Xt("onEdgesChange",$,oe.setState),Xt("connectOnClick",re,oe.setState),Xt("fitViewOnInit",Q,oe.setState),Xt("fitViewOnInitOptions",D,oe.setState),Xt("onNodesDelete",T,oe.setState),Xt("onEdgesDelete",E,oe.setState),Xt("onNodeDrag",L,oe.setState),Xt("onNodeDragStart",M,oe.setState),Xt("onNodeDragStop",ee,oe.setState),Xt("onSelectionDrag",F,oe.setState),Xt("onSelectionDragStart",U,oe.setState),Xt("onSelectionDragStop",K,oe.setState),Xt("noPanClassName",O,oe.setState),Xt("nodeOrigin",V,oe.setState),Xt("rfId",J,oe.setState),Xt("autoPanOnConnect",le,oe.setState),Xt("autoPanOnNodeDrag",ie,oe.setState),Xt("onError",_e,oe.setState),Xt("connectionRadius",pe,oe.setState),Xt("isValidConnection",ye,oe.setState),Xt("nodeDragThreshold",Ne,oe.setState),xu(e,Be),xu(t,Ue),xu(b,De),xu(S,Qe),xu(G,at),xu(N,Ke),null},xx={display:"none"},HI={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},pj="react-flow__node-desc",gj="react-flow__edge-desc",VI="react-flow__aria-live",GI=e=>e.ariaLiveMessage;function KI({rfId:e}){const t=In(GI);return xe.createElement("div",{id:`${VI}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:HI},t)}function YI({rfId:e,disableKeyboardA11y:t}){return xe.createElement(xe.Fragment,null,xe.createElement("div",{id:`${pj}-${e}`,style:xx},"Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "),xe.createElement("div",{id:`${gj}-${e}`,style:xx},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&xe.createElement(KI,{rfId:e}))}var Yf=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=_.useState(!1),a=_.useRef(!1),l=_.useRef(new Set([])),[c,u]=_.useMemo(()=>{if(e!==null){const h=(Array.isArray(e)?e:[e]).filter(g=>typeof g=="string").map(g=>g.split("+")),m=h.reduce((g,y)=>g.concat(...y),[]);return[h,m]}return[[],[]]},[e]);return _.useEffect(()=>{const f=typeof document<"u"?document:null,h=(t==null?void 0:t.target)||f;if(e!==null){const m=w=>{if(a.current=w.ctrlKey||w.metaKey||w.shiftKey,(!a.current||a.current&&!t.actInsideInputWithModifier)&&Pg(w))return!1;const b=kx(w.code,u);l.current.add(w[b]),bx(c,l.current,!1)&&(w.preventDefault(),r(!0))},g=w=>{if((!a.current||a.current&&!t.actInsideInputWithModifier)&&Pg(w))return!1;const b=kx(w.code,u);bx(c,l.current,!0)?(r(!1),l.current.clear()):l.current.delete(w[b]),w.key==="Meta"&&l.current.clear(),a.current=!1},y=()=>{l.current.clear(),r(!1)};return h==null||h.addEventListener("keydown",m),h==null||h.addEventListener("keyup",g),window.addEventListener("blur",y),()=>{h==null||h.removeEventListener("keydown",m),h==null||h.removeEventListener("keyup",g),window.removeEventListener("blur",y)}}},[e,r]),n};function bx(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(a=>t.has(a)))}function kx(e,t){return t.includes(e)?"code":"key"}function yj(e,t,n,r){var c,u;if(!e.parentNode)return n;const a=t.get(e.parentNode),l=pc(a,r);return yj(a,t,{x:(n.x??0)+l.x,y:(n.y??0)+l.y,z:(((c=a[_s])==null?void 0:c.z)??0)>(n.z??0)?((u=a[_s])==null?void 0:u.z)??0:n.z??0},r)}function wj(e,t,n){e.forEach(r=>{var a;if(r.parentNode&&!e.has(r.parentNode))throw new Error(`Parent node ${r.parentNode} not found`);if(r.parentNode||n!=null&&n[r.id]){const{x:l,y:c,z:u}=yj(r,e,{...r.position,z:((a=r[_s])==null?void 0:a.z)??0},t);r.positionAbsolute={x:l,y:c},r[_s].z=u,n!=null&&n[r.id]&&(r[_s].isParent=!0)}})}function Dp(e,t,n,r){const a=new Map,l={},c=r?1e3:0;return e.forEach(u=>{var y;const f=(ji(u.zIndex)?u.zIndex:0)+(u.selected?c:0),h=t.get(u.id),m={...u,positionAbsolute:{x:u.position.x,y:u.position.y}};u.parentNode&&(l[u.parentNode]=!0);const g=(h==null?void 0:h.type)&&(h==null?void 0:h.type)!==u.type;Object.defineProperty(m,_s,{enumerable:!1,value:{handleBounds:g||(y=h==null?void 0:h[_s])==null?void 0:y.handleBounds,z:f}}),a.set(u.id,m)}),wj(a,n,l),a}function vj(e,t={}){const{getNodes:n,width:r,height:a,minZoom:l,maxZoom:c,d3Zoom:u,d3Selection:f,fitViewOnInitDone:h,fitViewOnInit:m,nodeOrigin:g}=e(),y=t.initial&&!h&&m;if(u&&f&&(y||!t.initial)){const k=n().filter(S=>{var R;const N=t.includeHiddenNodes?S.width&&S.height:!S.hidden;return(R=t.nodes)!=null&&R.length?N&&t.nodes.some($=>$.id===S.id):N}),b=k.every(S=>S.width&&S.height);if(k.length>0&&b){const S=A_(k,g),{x:N,y:R,zoom:$}=ij(S,r,a,t.minZoom??l,t.maxZoom??c,t.padding??.1),A=bo.translate(N,R).scale($);return typeof t.duration=="number"&&t.duration>0?u.transform(ac(f,t.duration),A):u.transform(f,A),!0}}return!1}function JI(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[_s]:r[_s],selected:n.selected})}),new Map(t)}function XI(e,t){return t.map(n=>{const r=e.find(a=>a.id===n.id);return r&&(n.selected=r.selected),n})}function Am({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:a,edges:l,onNodesChange:c,onEdgesChange:u,hasDefaultNodes:f,hasDefaultEdges:h}=n();e!=null&&e.length&&(f&&r({nodeInternals:JI(e,a)}),c==null||c(e)),t!=null&&t.length&&(h&&r({edges:XI(t,l)}),u==null||u(t))}const bu=()=>{},ZI={zoomIn:bu,zoomOut:bu,zoomTo:bu,getZoom:()=>1,setViewport:bu,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:bu,fitBounds:bu,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},QI=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),e5=()=>{const e=js(),{d3Zoom:t,d3Selection:n}=In(QI,Os);return _.useMemo(()=>n&&t?{zoomIn:a=>t.scaleBy(ac(n,a==null?void 0:a.duration),1.2),zoomOut:a=>t.scaleBy(ac(n,a==null?void 0:a.duration),1/1.2),zoomTo:(a,l)=>t.scaleTo(ac(n,l==null?void 0:l.duration),a),getZoom:()=>e.getState().transform[2],setViewport:(a,l)=>{const[c,u,f]=e.getState().transform,h=bo.translate(a.x??c,a.y??u).scale(a.zoom??f);t.transform(ac(n,l==null?void 0:l.duration),h)},getViewport:()=>{const[a,l,c]=e.getState().transform;return{x:a,y:l,zoom:c}},fitView:a=>vj(e.getState,a),setCenter:(a,l,c)=>{const{width:u,height:f,maxZoom:h}=e.getState(),m=typeof(c==null?void 0:c.zoom)<"u"?c.zoom:h,g=u/2-a*m,y=f/2-l*m,w=bo.translate(g,y).scale(m);t.transform(ac(n,c==null?void 0:c.duration),w)},fitBounds:(a,l)=>{const{width:c,height:u,minZoom:f,maxZoom:h}=e.getState(),{x:m,y:g,zoom:y}=ij(a,c,u,f,h,(l==null?void 0:l.padding)??.1),w=bo.translate(m,g).scale(y);t.transform(ac(n,l==null?void 0:l.duration),w)},project:a=>{const{transform:l,snapToGrid:c,snapGrid:u}=e.getState();return console.warn("[DEPRECATED] `project` is deprecated. Instead use `screenToFlowPosition`. There is no need to subtract the react flow bounds anymore! https://reactflow.dev/api-reference/types/react-flow-instance#screen-to-flow-position"),zg(a,l,c,u)},screenToFlowPosition:a=>{const{transform:l,snapToGrid:c,snapGrid:u,domNode:f}=e.getState();if(!f)return a;const{x:h,y:m}=f.getBoundingClientRect(),g={x:a.x-h,y:a.y-m};return zg(g,l,c,u)},flowToScreenPosition:a=>{const{transform:l,domNode:c}=e.getState();if(!c)return a;const{x:u,y:f}=c.getBoundingClientRect(),h=nj(a,l);return{x:h.x+u,y:h.y+f}},viewportInitialized:!0}:ZI,[t,n])};function Uy(){const e=e5(),t=js(),n=_.useCallback(()=>t.getState().getNodes().map(b=>({...b})),[]),r=_.useCallback(b=>t.getState().nodeInternals.get(b),[]),a=_.useCallback(()=>{const{edges:b=[]}=t.getState();return b.map(S=>({...S}))},[]),l=_.useCallback(b=>{const{edges:S=[]}=t.getState();return S.find(N=>N.id===b)},[]),c=_.useCallback(b=>{const{getNodes:S,setNodes:N,hasDefaultNodes:R,onNodesChange:$}=t.getState(),A=S(),W=typeof b=="function"?b(A):b;if(R)N(W);else if($){const z=W.length===0?A.map(H=>({type:"remove",id:H.id})):W.map(H=>({item:H,type:"reset"}));$(z)}},[]),u=_.useCallback(b=>{const{edges:S=[],setEdges:N,hasDefaultEdges:R,onEdgesChange:$}=t.getState(),A=typeof b=="function"?b(S):b;if(R)N(A);else if($){const W=A.length===0?S.map(z=>({type:"remove",id:z.id})):A.map(z=>({item:z,type:"reset"}));$(W)}},[]),f=_.useCallback(b=>{const S=Array.isArray(b)?b:[b],{getNodes:N,setNodes:R,hasDefaultNodes:$,onNodesChange:A}=t.getState();if($){const z=[...N(),...S];R(z)}else if(A){const W=S.map(z=>({item:z,type:"add"}));A(W)}},[]),h=_.useCallback(b=>{const S=Array.isArray(b)?b:[b],{edges:N=[],setEdges:R,hasDefaultEdges:$,onEdgesChange:A}=t.getState();if($)R([...N,...S]);else if(A){const W=S.map(z=>({item:z,type:"add"}));A(W)}},[]),m=_.useCallback(()=>{const{getNodes:b,edges:S=[],transform:N}=t.getState(),[R,$,A]=N;return{nodes:b().map(W=>({...W})),edges:S.map(W=>({...W})),viewport:{x:R,y:$,zoom:A}}},[]),g=_.useCallback(({nodes:b,edges:S})=>{const{nodeInternals:N,getNodes:R,edges:$,hasDefaultNodes:A,hasDefaultEdges:W,onNodesDelete:z,onEdgesDelete:H,onNodesChange:G,onEdgesChange:re}=t.getState(),te=(b||[]).map(L=>L.id),Q=(S||[]).map(L=>L.id),D=R().reduce((L,M)=>{const ee=!te.includes(M.id)&&M.parentNode&&L.find(U=>U.id===M.parentNode);return(typeof M.deletable=="boolean"?M.deletable:!0)&&(te.includes(M.id)||ee)&&L.push(M),L},[]),T=$.filter(L=>typeof L.deletable=="boolean"?L.deletable:!0),E=T.filter(L=>Q.includes(L.id));if(D||E){const L=rj(D,T),M=[...E,...L],ee=M.reduce((F,U)=>(F.includes(U.id)||F.push(U.id),F),[]);if((W||A)&&(W&&t.setState({edges:$.filter(F=>!ee.includes(F.id))}),A&&(D.forEach(F=>{N.delete(F.id)}),t.setState({nodeInternals:new Map(N)}))),ee.length>0&&(H==null||H(M),re&&re(ee.map(F=>({id:F,type:"remove"})))),D.length>0&&(z==null||z(D),G)){const F=D.map(U=>({id:U.id,type:"remove"}));G(F)}}},[]),y=_.useCallback(b=>{const S=vI(b),N=S?null:t.getState().nodeInternals.get(b.id);return!S&&!N?[null,null,S]:[S?b:mx(N),N,S]},[]),w=_.useCallback((b,S=!0,N)=>{const[R,$,A]=y(b);return R?(N||t.getState().getNodes()).filter(W=>{if(!A&&(W.id===$.id||!W.positionAbsolute))return!1;const z=mx(W),H=Og(z,R);return S&&H>0||H>=R.width*R.height}):[]},[]),k=_.useCallback((b,S,N=!0)=>{const[R]=y(b);if(!R)return!1;const $=Og(R,S);return N&&$>0||$>=R.width*R.height},[]);return _.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:a,getEdge:l,setNodes:c,setEdges:u,addNodes:f,addEdges:h,toObject:m,deleteElements:g,getIntersectingNodes:w,isNodeIntersecting:k}),[e,n,r,a,l,c,u,f,h,m,g,w,k])}const t5={actInsideInputWithModifier:!1};var n5=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=js(),{deleteElements:r}=Uy(),a=Yf(e,t5),l=Yf(t);_.useEffect(()=>{if(a){const{edges:c,getNodes:u}=n.getState(),f=u().filter(m=>m.selected),h=c.filter(m=>m.selected);r({nodes:f,edges:h}),n.setState({nodesSelectionActive:!1})}},[a]),_.useEffect(()=>{n.setState({multiSelectionActive:l})},[l])};function s5(e){const t=js();_.useEffect(()=>{let n;const r=()=>{var l,c;if(!e.current)return;const a=Ly(e.current);(a.height===0||a.width===0)&&((c=(l=t.getState()).onError)==null||c.call(l,"004",jo.error004())),t.setState({width:a.width||500,height:a.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 Wy={position:"absolute",width:"100%",height:"100%",top:0,left:0},r5=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Tm=e=>({x:e.x,y:e.y,zoom:e.k}),ku=(e,t)=>e.target.closest(`.${t}`),jx=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Sx=e=>{const t=e.ctrlKey&&c_()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},i5=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),a5=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:a=!0,zoomOnPinch:l=!0,panOnScroll:c=!1,panOnScrollSpeed:u=.5,panOnScrollMode:f=dc.Free,zoomOnDoubleClick:h=!0,elementsSelectable:m,panOnDrag:g=!0,defaultViewport:y,translateExtent:w,minZoom:k,maxZoom:b,zoomActivationKeyCode:S,preventScrolling:N=!0,children:R,noWheelClassName:$,noPanClassName:A})=>{const W=_.useRef(),z=js(),H=_.useRef(!1),G=_.useRef(!1),re=_.useRef(null),te=_.useRef({x:0,y:0,zoom:0}),{d3Zoom:Q,d3Selection:D,d3ZoomHandler:T,userSelectionActive:E}=In(i5,Os),L=Yf(S),M=_.useRef(0),ee=_.useRef(!1),F=_.useRef();return s5(re),_.useEffect(()=>{if(re.current){const U=re.current.getBoundingClientRect(),K=qk().scaleExtent([k,b]).translateExtent(w),O=ki(re.current).call(K),V=bo.translate(y.x,y.y).scale(Hu(y.zoom,k,b)),J=[[0,0],[U.width,U.height]],le=K.constrain()(V,J,w);K.transform(O,le),K.wheelDelta(Sx),z.setState({d3Zoom:K,d3Selection:O,d3ZoomHandler:O.on("wheel.zoom"),transform:[le.x,le.y,le.k],domNode:re.current.closest(".react-flow")})}},[]),_.useEffect(()=>{D&&Q&&(c&&!L&&!E?D.on("wheel.zoom",U=>{if(ku(U,$))return!1;U.preventDefault(),U.stopImmediatePropagation();const K=D.property("__zoom").k||1,O=c_();if(U.ctrlKey&&l&&O){const Ne=Ji(U),Be=Sx(U),Ue=K*Math.pow(2,Be);Q.scaleTo(D,Ue,Ne,U);return}const V=U.deltaMode===1?20:1;let J=f===dc.Vertical?0:U.deltaX*V,le=f===dc.Horizontal?0:U.deltaY*V;!O&&U.shiftKey&&f!==dc.Vertical&&(J=U.deltaY*V,le=0),Q.translateBy(D,-(J/K)*u,-(le/K)*u,{internal:!0});const ie=Tm(D.property("__zoom")),{onViewportChangeStart:_e,onViewportChange:pe,onViewportChangeEnd:ye}=z.getState();clearTimeout(F.current),ee.current||(ee.current=!0,t==null||t(U,ie),_e==null||_e(ie)),ee.current&&(e==null||e(U,ie),pe==null||pe(ie),F.current=setTimeout(()=>{n==null||n(U,ie),ye==null||ye(ie),ee.current=!1},150))},{passive:!1}):typeof T<"u"&&D.on("wheel.zoom",function(U,K){if(!N||ku(U,$))return null;U.preventDefault(),T.call(this,U,K)},{passive:!1}))},[E,c,f,D,Q,T,L,l,N,$,t,e,n]),_.useEffect(()=>{Q&&Q.on("start",U=>{var V,J;if(!U.sourceEvent||U.sourceEvent.internal)return null;M.current=(V=U.sourceEvent)==null?void 0:V.button;const{onViewportChangeStart:K}=z.getState(),O=Tm(U.transform);H.current=!0,te.current=O,((J=U.sourceEvent)==null?void 0:J.type)==="mousedown"&&z.setState({paneDragging:!0}),K==null||K(O),t==null||t(U.sourceEvent,O)})},[Q,t]),_.useEffect(()=>{Q&&(E&&!H.current?Q.on("zoom",null):E||Q.on("zoom",U=>{var O;const{onViewportChange:K}=z.getState();if(z.setState({transform:[U.transform.x,U.transform.y,U.transform.k]}),G.current=!!(r&&jx(g,M.current??0)),(e||K)&&!((O=U.sourceEvent)!=null&&O.internal)){const V=Tm(U.transform);K==null||K(V),e==null||e(U.sourceEvent,V)}}))},[E,Q,e,g,r]),_.useEffect(()=>{Q&&Q.on("end",U=>{if(!U.sourceEvent||U.sourceEvent.internal)return null;const{onViewportChangeEnd:K}=z.getState();if(H.current=!1,z.setState({paneDragging:!1}),r&&jx(g,M.current??0)&&!G.current&&r(U.sourceEvent),G.current=!1,(n||K)&&r5(te.current,U.transform)){const O=Tm(U.transform);te.current=O,clearTimeout(W.current),W.current=setTimeout(()=>{K==null||K(O),n==null||n(U.sourceEvent,O)},c?150:0)}})},[Q,c,g,n,r]),_.useEffect(()=>{Q&&Q.filter(U=>{const K=L||a,O=l&&U.ctrlKey;if((g===!0||Array.isArray(g)&&g.includes(1))&&U.button===1&&U.type==="mousedown"&&(ku(U,"react-flow__node")||ku(U,"react-flow__edge")))return!0;if(!g&&!K&&!c&&!h&&!l||E||!h&&U.type==="dblclick"||ku(U,$)&&U.type==="wheel"||ku(U,A)&&(U.type!=="wheel"||c&&U.type==="wheel"&&!L)||!l&&U.ctrlKey&&U.type==="wheel"||!K&&!c&&!O&&U.type==="wheel"||!g&&(U.type==="mousedown"||U.type==="touchstart")||Array.isArray(g)&&!g.includes(U.button)&&(U.type==="mousedown"||U.type==="touchstart"))return!1;const V=Array.isArray(g)&&g.includes(U.button)||!U.button||U.button<=1;return(!U.ctrlKey||U.type==="wheel")&&V})},[E,Q,a,l,c,h,g,m,L]),xe.createElement("div",{className:"react-flow__renderer",ref:re,style:Wy},R)},o5=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function l5(){const{userSelectionActive:e,userSelectionRect:t}=In(o5,Os);return e&&t?xe.createElement("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}function Nx(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,a=t.position.y+t.height-n.height;if(r>0||a>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),a>0&&(n.style.height+=a),t.position.x<0){const l=Math.abs(t.position.x);n.position.x=n.position.x-l,n.style.width+=l,t.position.x=0}if(t.position.y<0){const l=Math.abs(t.position.y);n.position.y=n.position.y-l,n.style.height+=l,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function c5(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,a)=>{const l=e.filter(u=>u.id===a.id);if(l.length===0)return r.push(a),r;const c={...a};for(const u of l)if(u)switch(u.type){case"select":{c.selected=u.selected;break}case"position":{typeof u.position<"u"&&(c.position=u.position),typeof u.positionAbsolute<"u"&&(c.positionAbsolute=u.positionAbsolute),typeof u.dragging<"u"&&(c.dragging=u.dragging),c.expandParent&&Nx(r,c);break}case"dimensions":{typeof u.dimensions<"u"&&(c.width=u.dimensions.width,c.height=u.dimensions.height),typeof u.updateStyle<"u"&&(c.style={...c.style||{},...u.dimensions}),typeof u.resizing=="boolean"&&(c.resizing=u.resizing),c.expandParent&&Nx(r,c);break}case"remove":return r}return r.push(c),r},n)}function u5(e,t){return c5(e,t)}const hl=(e,t)=>({id:e,type:"select",selected:t});function Tu(e,t){return e.reduce((n,r)=>{const a=t.includes(r.id);return!r.selected&&a?(r.selected=!0,n.push(hl(r.id,!0))):r.selected&&!a&&(r.selected=!1,n.push(hl(r.id,!1))),n},[])}const Fp=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},d5=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),xj=_.memo(({isSelecting:e,selectionMode:t=Gf.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:a,onPaneClick:l,onPaneContextMenu:c,onPaneScroll:u,onPaneMouseEnter:f,onPaneMouseMove:h,onPaneMouseLeave:m,children:g})=>{const y=_.useRef(null),w=js(),k=_.useRef(0),b=_.useRef(0),S=_.useRef(),{userSelectionActive:N,elementsSelectable:R,dragging:$}=In(d5,Os),A=()=>{w.setState({userSelectionActive:!1,userSelectionRect:null}),k.current=0,b.current=0},W=T=>{l==null||l(T),w.getState().resetSelectedElements(),w.setState({nodesSelectionActive:!1})},z=T=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){T.preventDefault();return}c==null||c(T)},H=u?T=>u(T):void 0,G=T=>{const{resetSelectedElements:E,domNode:L}=w.getState();if(S.current=L==null?void 0:L.getBoundingClientRect(),!R||!e||T.button!==0||T.target!==y.current||!S.current)return;const{x:M,y:ee}=gl(T,S.current);E(),w.setState({userSelectionRect:{width:0,height:0,startX:M,startY:ee,x:M,y:ee}}),r==null||r(T)},re=T=>{const{userSelectionRect:E,nodeInternals:L,edges:M,transform:ee,onNodesChange:F,onEdgesChange:U,nodeOrigin:K,getNodes:O}=w.getState();if(!e||!S.current||!E)return;w.setState({userSelectionActive:!0,nodesSelectionActive:!1});const V=gl(T,S.current),J=E.startX??0,le=E.startY??0,ie={...E,x:V.x<J?V.x:J,y:V.y<le?V.y:le,width:Math.abs(V.x-J),height:Math.abs(V.y-le)},_e=O(),pe=sj(L,ie,ee,t===Gf.Partial,!0,K),ye=rj(pe,M).map(Be=>Be.id),Ne=pe.map(Be=>Be.id);if(k.current!==Ne.length){k.current=Ne.length;const Be=Tu(_e,Ne);Be.length&&(F==null||F(Be))}if(b.current!==ye.length){b.current=ye.length;const Be=Tu(M,ye);Be.length&&(U==null||U(Be))}w.setState({userSelectionRect:ie})},te=T=>{if(T.button!==0)return;const{userSelectionRect:E}=w.getState();!N&&E&&T.target===y.current&&(W==null||W(T)),w.setState({nodesSelectionActive:k.current>0}),A(),a==null||a(T)},Q=T=>{N&&(w.setState({nodesSelectionActive:k.current>0}),a==null||a(T)),A()},D=R&&(e||N);return xe.createElement("div",{className:Vs(["react-flow__pane",{dragging:$,selection:e}]),onClick:D?void 0:Fp(W,y),onContextMenu:Fp(z,y),onWheel:Fp(H,y),onMouseEnter:D?void 0:f,onMouseDown:D?G:void 0,onMouseMove:D?re:h,onMouseUp:D?te:void 0,onMouseLeave:D?Q:m,ref:y,style:Wy},g,xe.createElement(l5,null))});xj.displayName="Pane";function bj(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:bj(n,t):!1}function Cx(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 f5(e,t,n,r){return Array.from(e.values()).filter(a=>(a.selected||a.id===r)&&(!a.parentNode||!bj(a,e))&&(a.draggable||t&&typeof a.draggable>"u")).map(a=>{var l,c;return{id:a.id,position:a.position||{x:0,y:0},positionAbsolute:a.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((l=a.positionAbsolute)==null?void 0:l.x)??0),y:n.y-(((c=a.positionAbsolute)==null?void 0:c.y)??0)},delta:{x:0,y:0},extent:a.extent,parentNode:a.parentNode,width:a.width,height:a.height,expandParent:a.expandParent}})}function h5(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function kj(e,t,n,r,a=[0,0],l){const c=h5(e,e.extent||r);let u=c;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const m=n.get(e.parentNode),{x:g,y}=pc(m,a).positionAbsolute;u=m&&ji(g)&&ji(y)&&ji(m.width)&&ji(m.height)?[[g+e.width*a[0],y+e.height*a[1]],[g+m.width-e.width+e.width*a[0],y+m.height-e.height+e.height*a[1]]]:u}else l==null||l("005",jo.error005()),u=c;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const m=n.get(e.parentNode),{x:g,y}=pc(m,a).positionAbsolute;u=[[e.extent[0][0]+g,e.extent[0][1]+y],[e.extent[1][0]+g,e.extent[1][1]+y]]}let f={x:0,y:0};if(e.parentNode){const m=n.get(e.parentNode);f=pc(m,a).positionAbsolute}const h=u&&u!=="parent"?Iy(t,u):t;return{position:{x:h.x-f.x,y:h.y-f.y},positionAbsolute:h}}function zp({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(a=>({...n.get(a.id),position:a.position,positionAbsolute:a.positionAbsolute}));return[e?r.find(a=>a.id===e):r[0],r]}const Ex=(e,t,n,r)=>{const a=t.querySelectorAll(e);if(!a||!a.length)return null;const l=Array.from(a),c=t.getBoundingClientRect(),u={x:c.width*r[0],y:c.height*r[1]};return l.map(f=>{const h=f.getBoundingClientRect();return{id:f.getAttribute("data-handleid"),position:f.getAttribute("data-handlepos"),x:(h.left-c.left-u.x)/n,y:(h.top-c.top-u.y)/n,...Ly(f)}})};function hf(e,t,n){return n===void 0?n:r=>{const a=t().nodeInternals.get(e);a&&n(r,{...a})}}function Ug({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:a,unselectNodesAndEdges:l,multiSelectionActive:c,nodeInternals:u,onError:f}=t.getState(),h=u.get(e);if(!h){f==null||f("012",jo.error012(e));return}t.setState({nodesSelectionActive:!1}),h.selected?(n||h.selected&&c)&&(l({nodes:[h],edges:[]}),requestAnimationFrame(()=>{var m;return(m=r==null?void 0:r.current)==null?void 0:m.blur()})):a([e])}function m5(){const e=js();return _.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:a,snapToGrid:l}=e.getState(),c=n.touches?n.touches[0].clientX:n.clientX,u=n.touches?n.touches[0].clientY:n.clientY,f={x:(c-r[0])/r[2],y:(u-r[1])/r[2]};return{xSnapped:l?a[0]*Math.round(f.x/a[0]):f.x,ySnapped:l?a[1]*Math.round(f.y/a[1]):f.y,...f}},[])}function Bp(e){return(t,n,r)=>e==null?void 0:e(t,r)}function jj({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:a,isSelectable:l,selectNodesOnDrag:c}){const u=js(),[f,h]=_.useState(!1),m=_.useRef([]),g=_.useRef({x:null,y:null}),y=_.useRef(0),w=_.useRef(null),k=_.useRef({x:0,y:0}),b=_.useRef(null),S=_.useRef(!1),N=_.useRef(!1),R=m5();return _.useEffect(()=>{if(e!=null&&e.current){const $=ki(e.current),A=({x:H,y:G})=>{const{nodeInternals:re,onNodeDrag:te,onSelectionDrag:Q,updateNodePositions:D,nodeExtent:T,snapGrid:E,snapToGrid:L,nodeOrigin:M,onError:ee}=u.getState();g.current={x:H,y:G};let F=!1,U={x:0,y:0,x2:0,y2:0};if(m.current.length>1&&T){const O=A_(m.current,M);U=Vf(O)}if(m.current=m.current.map(O=>{const V={x:H-O.distance.x,y:G-O.distance.y};L&&(V.x=E[0]*Math.round(V.x/E[0]),V.y=E[1]*Math.round(V.y/E[1]));const J=[[T[0][0],T[0][1]],[T[1][0],T[1][1]]];m.current.length>1&&T&&!O.extent&&(J[0][0]=O.positionAbsolute.x-U.x+T[0][0],J[1][0]=O.positionAbsolute.x+(O.width??0)-U.x2+T[1][0],J[0][1]=O.positionAbsolute.y-U.y+T[0][1],J[1][1]=O.positionAbsolute.y+(O.height??0)-U.y2+T[1][1]);const le=kj(O,V,re,J,M,ee);return F=F||O.position.x!==le.position.x||O.position.y!==le.position.y,O.position=le.position,O.positionAbsolute=le.positionAbsolute,O}),!F)return;D(m.current,!0,!0),h(!0);const K=a?te:Bp(Q);if(K&&b.current){const[O,V]=zp({nodeId:a,dragItems:m.current,nodeInternals:re});K(b.current,O,V)}},W=()=>{if(!w.current)return;const[H,G]=Vk(k.current,w.current);if(H!==0||G!==0){const{transform:re,panBy:te}=u.getState();g.current.x=(g.current.x??0)-H/re[2],g.current.y=(g.current.y??0)-G/re[2],te({x:H,y:G})&&A(g.current)}y.current=requestAnimationFrame(W)},z=H=>{var M;const{nodeInternals:G,multiSelectionActive:re,nodesDraggable:te,unselectNodesAndEdges:Q,onNodeDragStart:D,onSelectionDragStart:T}=u.getState();N.current=!0;const E=a?D:Bp(T);(!c||!l)&&!re&&a&&((M=G.get(a))!=null&&M.selected||Q()),a&&l&&c&&Ug({id:a,store:u,nodeRef:e});const L=R(H);if(g.current=L,m.current=f5(G,te,L,a),E&&m.current){const[ee,F]=zp({nodeId:a,dragItems:m.current,nodeInternals:G});E(H.sourceEvent,ee,F)}};if(t)$.on(".drag",null);else{const H=j3().on("start",G=>{const{domNode:re,nodeDragThreshold:te}=u.getState();te===0&&z(G);const Q=R(G);g.current=Q,w.current=(re==null?void 0:re.getBoundingClientRect())||null,k.current=gl(G.sourceEvent,w.current)}).on("drag",G=>{var D,T;const re=R(G),{autoPanOnNodeDrag:te,nodeDragThreshold:Q}=u.getState();if(!S.current&&N.current&&te&&(S.current=!0,W()),!N.current){const E=re.xSnapped-(((D=g==null?void 0:g.current)==null?void 0:D.x)??0),L=re.ySnapped-(((T=g==null?void 0:g.current)==null?void 0:T.y)??0);Math.sqrt(E*E+L*L)>Q&&z(G)}(g.current.x!==re.xSnapped||g.current.y!==re.ySnapped)&&m.current&&N.current&&(b.current=G.sourceEvent,k.current=gl(G.sourceEvent,w.current),A(re))}).on("end",G=>{if(N.current&&(h(!1),S.current=!1,N.current=!1,cancelAnimationFrame(y.current),m.current)){const{updateNodePositions:re,nodeInternals:te,onNodeDragStop:Q,onSelectionDragStop:D}=u.getState(),T=a?Q:Bp(D);if(re(m.current,!1,!1),T){const[E,L]=zp({nodeId:a,dragItems:m.current,nodeInternals:te});T(G.sourceEvent,E,L)}}}).filter(G=>{const re=G.target;return!G.button&&(!n||!Cx(re,`.${n}`,e))&&(!r||Cx(re,r,e))});return $.call(H),()=>{$.on(".drag",null)}}}},[e,t,n,r,l,u,a,c,R]),f}function Sj(){const e=js();return _.useCallback(n=>{const{nodeInternals:r,nodeExtent:a,updateNodePositions:l,getNodes:c,snapToGrid:u,snapGrid:f,onError:h,nodesDraggable:m}=e.getState(),g=c().filter(R=>R.selected&&(R.draggable||m&&typeof R.draggable>"u")),y=u?f[0]:5,w=u?f[1]:5,k=n.isShiftPressed?4:1,b=n.x*y*k,S=n.y*w*k,N=g.map(R=>{if(R.positionAbsolute){const $={x:R.positionAbsolute.x+b,y:R.positionAbsolute.y+S};u&&($.x=f[0]*Math.round($.x/f[0]),$.y=f[1]*Math.round($.y/f[1]));const{positionAbsolute:A,position:W}=kj(R,$,r,a,void 0,h);R.position=W,R.positionAbsolute=A}return R});l(N,!0,!1)},[])}const Fu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var mf=e=>{const t=({id:n,type:r,data:a,xPos:l,yPos:c,xPosOrigin:u,yPosOrigin:f,selected:h,onClick:m,onMouseEnter:g,onMouseMove:y,onMouseLeave:w,onContextMenu:k,onDoubleClick:b,style:S,className:N,isDraggable:R,isSelectable:$,isConnectable:A,isFocusable:W,selectNodesOnDrag:z,sourcePosition:H,targetPosition:G,hidden:re,resizeObserver:te,dragHandle:Q,zIndex:D,isParent:T,noDragClassName:E,noPanClassName:L,initialized:M,disableKeyboardA11y:ee,ariaLabel:F,rfId:U,hasHandleBounds:K})=>{const O=js(),V=_.useRef(null),J=_.useRef(H),le=_.useRef(G),ie=_.useRef(r),_e=$||R||m||g||y||w,pe=Sj(),ye=hf(n,O.getState,g),Ne=hf(n,O.getState,y),Be=hf(n,O.getState,w),Ue=hf(n,O.getState,k),ut=hf(n,O.getState,b),De=Ke=>{const{nodeDragThreshold:ce}=O.getState();if($&&(!z||!R||ce>0)&&Ug({id:n,store:O,nodeRef:V}),m){const oe=O.getState().nodeInternals.get(n);oe&&m(Ke,{...oe})}},Qe=Ke=>{if(!Pg(Ke))if(Jk.includes(Ke.key)&&$){const ce=Ke.key==="Escape";Ug({id:n,store:O,unselect:ce,nodeRef:V})}else!ee&&R&&h&&Object.prototype.hasOwnProperty.call(Fu,Ke.key)&&(O.setState({ariaLiveMessage:`Moved selected node ${Ke.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~l}, y: ${~~c}`}),pe({x:Fu[Ke.key].x,y:Fu[Ke.key].y,isShiftPressed:Ke.shiftKey}))};_.useEffect(()=>()=>{V.current&&(te==null||te.unobserve(V.current))},[]),_.useEffect(()=>{if(V.current&&!re){const Ke=V.current;(!M||!K)&&(te==null||te.unobserve(Ke),te==null||te.observe(Ke))}},[re,M,K]),_.useEffect(()=>{const Ke=ie.current!==r,ce=J.current!==H,oe=le.current!==G;V.current&&(Ke||ce||oe)&&(Ke&&(ie.current=r),ce&&(J.current=H),oe&&(le.current=G),O.getState().updateNodeDimensions([{id:n,nodeElement:V.current,forceUpdate:!0}]))},[n,r,H,G]);const at=jj({nodeRef:V,disabled:re||!R,noDragClassName:E,handleSelector:Q,nodeId:n,isSelectable:$,selectNodesOnDrag:z});return re?null:xe.createElement("div",{className:Vs(["react-flow__node",`react-flow__node-${r}`,{[L]:R},N,{selected:h,selectable:$,parent:T,dragging:at}]),ref:V,style:{zIndex:D,transform:`translate(${u}px,${f}px)`,pointerEvents:_e?"all":"none",visibility:M?"visible":"hidden",...S},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ye,onMouseMove:Ne,onMouseLeave:Be,onContextMenu:Ue,onClick:De,onDoubleClick:ut,onKeyDown:W?Qe:void 0,tabIndex:W?0:void 0,role:W?"button":void 0,"aria-describedby":ee?void 0:`${pj}-${U}`,"aria-label":F},xe.createElement(CI,{value:n},xe.createElement(e,{id:n,data:a,type:r,xPos:l,yPos:c,selected:h,isConnectable:A,sourcePosition:H,targetPosition:G,dragging:at,dragHandle:Q,zIndex:D})))};return t.displayName="NodeWrapper",_.memo(t)};const _5=e=>{const t=e.getNodes().filter(n=>n.selected);return{...A_(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function p5({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=js(),{width:a,height:l,x:c,y:u,transformString:f,userSelectionActive:h}=In(_5,Os),m=Sj(),g=_.useRef(null);if(_.useEffect(()=>{var k;n||(k=g.current)==null||k.focus({preventScroll:!0})},[n]),jj({nodeRef:g}),h||!a||!l)return null;const y=e?k=>{const b=r.getState().getNodes().filter(S=>S.selected);e(k,b)}:void 0,w=k=>{Object.prototype.hasOwnProperty.call(Fu,k.key)&&m({x:Fu[k.key].x,y:Fu[k.key].y,isShiftPressed:k.shiftKey})};return xe.createElement("div",{className:Vs(["react-flow__nodesselection","react-flow__container",t]),style:{transform:f}},xe.createElement("div",{ref:g,className:"react-flow__nodesselection-rect",onContextMenu:y,tabIndex:n?void 0:-1,onKeyDown:n?void 0:w,style:{width:a,height:l,top:u,left:c}}))}var g5=_.memo(p5);const y5=e=>e.nodesSelectionActive,Nj=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:a,onPaneContextMenu:l,onPaneScroll:c,deleteKeyCode:u,onMove:f,onMoveStart:h,onMoveEnd:m,selectionKeyCode:g,selectionOnDrag:y,selectionMode:w,onSelectionStart:k,onSelectionEnd:b,multiSelectionKeyCode:S,panActivationKeyCode:N,zoomActivationKeyCode:R,elementsSelectable:$,zoomOnScroll:A,zoomOnPinch:W,panOnScroll:z,panOnScrollSpeed:H,panOnScrollMode:G,zoomOnDoubleClick:re,panOnDrag:te,defaultViewport:Q,translateExtent:D,minZoom:T,maxZoom:E,preventScrolling:L,onSelectionContextMenu:M,noWheelClassName:ee,noPanClassName:F,disableKeyboardA11y:U})=>{const K=In(y5),O=Yf(g),V=Yf(N),J=V||te,le=V||z,ie=O||y&&J!==!0;return n5({deleteKeyCode:u,multiSelectionKeyCode:S}),xe.createElement(a5,{onMove:f,onMoveStart:h,onMoveEnd:m,onPaneContextMenu:l,elementsSelectable:$,zoomOnScroll:A,zoomOnPinch:W,panOnScroll:le,panOnScrollSpeed:H,panOnScrollMode:G,zoomOnDoubleClick:re,panOnDrag:!O&&J,defaultViewport:Q,translateExtent:D,minZoom:T,maxZoom:E,zoomActivationKeyCode:R,preventScrolling:L,noWheelClassName:ee,noPanClassName:F},xe.createElement(xj,{onSelectionStart:k,onSelectionEnd:b,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:a,onPaneContextMenu:l,onPaneScroll:c,panOnDrag:J,isSelecting:!!ie,selectionMode:w},e,K&&xe.createElement(g5,{onSelectionContextMenu:M,noPanClassName:F,disableKeyboardA11y:U})))};Nj.displayName="FlowRenderer";var w5=_.memo(Nj);function v5(e){return In(_.useCallback(n=>e?sj(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function x5(e){const t={input:mf(e.input||fj),default:mf(e.default||Bg),output:mf(e.output||mj),group:mf(e.group||By)},n={},r=Object.keys(e).filter(a=>!["input","default","output","group"].includes(a)).reduce((a,l)=>(a[l]=mf(e[l]||Bg),a),n);return{...t,...r}}const b5=({x:e,y:t,width:n,height:r,origin:a})=>!n||!r?{x:e,y:t}:a[0]<0||a[1]<0||a[0]>1||a[1]>1?{x:e,y:t}:{x:e-n*a[0],y:t-r*a[1]},k5=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),Cj=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:a,updateNodeDimensions:l,onError:c}=In(k5,Os),u=v5(e.onlyRenderVisibleElements),f=_.useRef(),h=_.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const m=new ResizeObserver(g=>{const y=g.map(w=>({id:w.target.getAttribute("data-id"),nodeElement:w.target,forceUpdate:!0}));l(y)});return f.current=m,m},[]);return _.useEffect(()=>()=>{var m;(m=f==null?void 0:f.current)==null||m.disconnect()},[]),xe.createElement("div",{className:"react-flow__nodes",style:Wy},u.map(m=>{var W,z,H;let g=m.type||"default";e.nodeTypes[g]||(c==null||c("003",jo.error003(g)),g="default");const y=e.nodeTypes[g]||e.nodeTypes.default,w=!!(m.draggable||t&&typeof m.draggable>"u"),k=!!(m.selectable||a&&typeof m.selectable>"u"),b=!!(m.connectable||n&&typeof m.connectable>"u"),S=!!(m.focusable||r&&typeof m.focusable>"u"),N=e.nodeExtent?Iy(m.positionAbsolute,e.nodeExtent):m.positionAbsolute,R=(N==null?void 0:N.x)??0,$=(N==null?void 0:N.y)??0,A=b5({x:R,y:$,width:m.width??0,height:m.height??0,origin:e.nodeOrigin});return xe.createElement(y,{key:m.id,id:m.id,className:m.className,style:m.style,type:g,data:m.data,sourcePosition:m.sourcePosition||wt.Bottom,targetPosition:m.targetPosition||wt.Top,hidden:m.hidden,xPos:R,yPos:$,xPosOrigin:A.x,yPosOrigin:A.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!m.selected,isDraggable:w,isSelectable:k,isConnectable:b,isFocusable:S,resizeObserver:h,dragHandle:m.dragHandle,zIndex:((W=m[_s])==null?void 0:W.z)??0,isParent:!!((z=m[_s])!=null&&z.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!m.width&&!!m.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:m.ariaLabel,hasHandleBounds:!!((H=m[_s])!=null&&H.handleBounds)})}))};Cj.displayName="NodeRenderer";var j5=_.memo(Cj);const S5=(e,t,n)=>n===wt.Left?e-t:n===wt.Right?e+t:e,N5=(e,t,n)=>n===wt.Top?e-t:n===wt.Bottom?e+t:e,$x="react-flow__edgeupdater",Ax=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:a,onMouseEnter:l,onMouseOut:c,type:u})=>xe.createElement("circle",{onMouseDown:a,onMouseEnter:l,onMouseOut:c,className:Vs([$x,`${$x}-${u}`]),cx:S5(t,r,e),cy:N5(n,r,e),r,stroke:"transparent",fill:"transparent"}),C5=()=>!0;var ju=e=>{const t=({id:n,className:r,type:a,data:l,onClick:c,onEdgeDoubleClick:u,selected:f,animated:h,label:m,labelStyle:g,labelShowBg:y,labelBgStyle:w,labelBgPadding:k,labelBgBorderRadius:b,style:S,source:N,target:R,sourceX:$,sourceY:A,targetX:W,targetY:z,sourcePosition:H,targetPosition:G,elementsSelectable:re,hidden:te,sourceHandleId:Q,targetHandleId:D,onContextMenu:T,onMouseEnter:E,onMouseMove:L,onMouseLeave:M,edgeUpdaterRadius:ee,onEdgeUpdate:F,onEdgeUpdateStart:U,onEdgeUpdateEnd:K,markerEnd:O,markerStart:V,rfId:J,ariaLabel:le,isFocusable:ie,isUpdatable:_e,pathOptions:pe,interactionWidth:ye})=>{const Ne=_.useRef(null),[Be,Ue]=_.useState(!1),[ut,De]=_.useState(!1),Qe=js(),at=_.useMemo(()=>`url('#${Fg(V,J)}')`,[V,J]),Ke=_.useMemo(()=>`url('#${Fg(O,J)}')`,[O,J]);if(te)return null;const ce=Bt=>{var xn;const{edges:yn,addSelectedEdges:zn,unselectNodesAndEdges:Tn,multiSelectionActive:wn}=Qe.getState(),Pn=yn.find(Ss=>Ss.id===n);Pn&&(re&&(Qe.setState({nodesSelectionActive:!1}),Pn.selected&&wn?(Tn({nodes:[],edges:[Pn]}),(xn=Ne.current)==null||xn.blur()):zn([n])),c&&c(Bt,Pn))},oe=ff(n,Qe.getState,u),Ae=ff(n,Qe.getState,T),he=ff(n,Qe.getState,E),Ce=ff(n,Qe.getState,L),Te=ff(n,Qe.getState,M),Ye=(Bt,yn)=>{if(Bt.button!==0)return;const{edges:zn,isValidConnection:Tn}=Qe.getState(),wn=yn?R:N,Pn=(yn?D:Q)||null,xn=yn?"target":"source",Ss=Tn||C5,Kn=yn,Ns=zn.find(fe=>fe.id===n);De(!0),U==null||U(Bt,Ns,xn);const jr=fe=>{De(!1),K==null||K(fe,Ns,xn)};lj({event:Bt,handleId:Pn,nodeId:wn,onConnect:fe=>F==null?void 0:F(Ns,fe),isTarget:Kn,getState:Qe.getState,setState:Qe.setState,isValidConnection:Ss,edgeUpdaterType:xn,onEdgeUpdateEnd:jr})},rt=Bt=>Ye(Bt,!0),ht=Bt=>Ye(Bt,!1),lt=()=>Ue(!0),St=()=>Ue(!1),Zt=!re&&!c,On=Bt=>{var yn;if(Jk.includes(Bt.key)&&re){const{unselectNodesAndEdges:zn,addSelectedEdges:Tn,edges:wn}=Qe.getState();Bt.key==="Escape"?((yn=Ne.current)==null||yn.blur(),zn({edges:[wn.find(xn=>xn.id===n)]})):Tn([n])}};return xe.createElement("g",{className:Vs(["react-flow__edge",`react-flow__edge-${a}`,r,{selected:f,animated:h,inactive:Zt,updating:Be}]),onClick:ce,onDoubleClick:oe,onContextMenu:Ae,onMouseEnter:he,onMouseMove:Ce,onMouseLeave:Te,onKeyDown:ie?On:void 0,tabIndex:ie?0:void 0,role:ie?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":le===null?void 0:le||`Edge from ${N} to ${R}`,"aria-describedby":ie?`${gj}-${J}`:void 0,ref:Ne},!ut&&xe.createElement(e,{id:n,source:N,target:R,selected:f,animated:h,label:m,labelStyle:g,labelShowBg:y,labelBgStyle:w,labelBgPadding:k,labelBgBorderRadius:b,data:l,style:S,sourceX:$,sourceY:A,targetX:W,targetY:z,sourcePosition:H,targetPosition:G,sourceHandleId:Q,targetHandleId:D,markerStart:at,markerEnd:Ke,pathOptions:pe,interactionWidth:ye}),_e&&xe.createElement(xe.Fragment,null,(_e==="source"||_e===!0)&&xe.createElement(Ax,{position:H,centerX:$,centerY:A,radius:ee,onMouseDown:rt,onMouseEnter:lt,onMouseOut:St,type:"source"}),(_e==="target"||_e===!0)&&xe.createElement(Ax,{position:G,centerX:W,centerY:z,radius:ee,onMouseDown:ht,onMouseEnter:lt,onMouseOut:St,type:"target"})))};return t.displayName="EdgeWrapper",_.memo(t)};function E5(e){const t={default:ju(e.default||u_),straight:ju(e.bezier||Dy),step:ju(e.step||Py),smoothstep:ju(e.step||$_),simplebezier:ju(e.simplebezier||Oy)},n={},r=Object.keys(e).filter(a=>!["default","bezier"].includes(a)).reduce((a,l)=>(a[l]=ju(e[l]||u_),a),n);return{...t,...r}}function Tx(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,a=((n==null?void 0:n.y)||0)+t.y,l=(n==null?void 0:n.width)||t.width,c=(n==null?void 0:n.height)||t.height;switch(e){case wt.Top:return{x:r+l/2,y:a};case wt.Right:return{x:r+l,y:a+c/2};case wt.Bottom:return{x:r+l/2,y:a+c};case wt.Left:return{x:r,y:a+c/2}}}function Mx(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const $5=(e,t,n,r,a,l)=>{const c=Tx(n,e,t),u=Tx(l,r,a);return{sourceX:c.x,sourceY:c.y,targetX:u.x,targetY:u.y}};function A5({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:a,targetHeight:l,width:c,height:u,transform:f}){const h={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+a),y2:Math.max(e.y+r,t.y+l)};h.x===h.x2&&(h.x2+=1),h.y===h.y2&&(h.y2+=1);const m=Vf({x:(0-f[0])/f[2],y:(0-f[1])/f[2],width:c/f[2],height:u/f[2]}),g=Math.max(0,Math.min(m.x2,h.x2)-Math.max(m.x,h.x)),y=Math.max(0,Math.min(m.y2,h.y2)-Math.max(m.y,h.y));return Math.ceil(g*y)>0}function Rx(e){var r,a,l,c,u;const t=((r=e==null?void 0:e[_s])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((a=e==null?void 0:e.positionAbsolute)==null?void 0:a.x)<"u"&&typeof((l=e==null?void 0:e.positionAbsolute)==null?void 0:l.y)<"u";return[{x:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.x)||0,y:((u=e==null?void 0:e.positionAbsolute)==null?void 0:u.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const T5=[{level:0,isMaxLevel:!0,edges:[]}];function M5(e,t,n=!1){let r=-1;const a=e.reduce((c,u)=>{var m,g;const f=ji(u.zIndex);let h=f?u.zIndex:0;if(n){const y=t.get(u.target),w=t.get(u.source),k=u.selected||(y==null?void 0:y.selected)||(w==null?void 0:w.selected),b=Math.max(((m=w==null?void 0:w[_s])==null?void 0:m.z)||0,((g=y==null?void 0:y[_s])==null?void 0:g.z)||0,1e3);h=(f?u.zIndex:0)+(k?b:0)}return c[h]?c[h].push(u):c[h]=[u],r=h>r?h:r,c},{}),l=Object.entries(a).map(([c,u])=>{const f=+c;return{edges:u,level:f,isMaxLevel:f===r}});return l.length===0?T5:l}function R5(e,t,n){const r=In(_.useCallback(a=>e?a.edges.filter(l=>{const c=t.get(l.source),u=t.get(l.target);return(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&(u==null?void 0:u.width)&&(u==null?void 0:u.height)&&A5({sourcePos:c.positionAbsolute||{x:0,y:0},targetPos:u.positionAbsolute||{x:0,y:0},sourceWidth:c.width,sourceHeight:c.height,targetWidth:u.width,targetHeight:u.height,width:a.width,height:a.height,transform:a.transform})}):a.edges,[e,t]));return M5(r,t,n)}const L5=({color:e="none",strokeWidth:t=1})=>xe.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),I5=({color:e="none",strokeWidth:t=1})=>xe.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"}),Lx={[Kf.Arrow]:L5,[Kf.ArrowClosed]:I5};function O5(e){const t=js();return _.useMemo(()=>{var a,l;return Object.prototype.hasOwnProperty.call(Lx,e)?Lx[e]:((l=(a=t.getState()).onError)==null||l.call(a,"009",jo.error009(e)),null)},[e])}const P5=({id:e,type:t,color:n,width:r=12.5,height:a=12.5,markerUnits:l="strokeWidth",strokeWidth:c,orient:u="auto-start-reverse"})=>{const f=O5(t);return f?xe.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${a}`,viewBox:"-10 -10 20 20",markerUnits:l,orient:u,refX:"0",refY:"0"},xe.createElement(f,{color:n,strokeWidth:c})):null},D5=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((a,l)=>([l.markerStart,l.markerEnd].forEach(c=>{if(c&&typeof c=="object"){const u=Fg(c,t);r.includes(u)||(a.push({id:u,color:c.color||e,...c}),r.push(u))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))},Ej=({defaultColor:e,rfId:t})=>{const n=In(_.useCallback(D5({defaultColor:e,rfId:t}),[e,t]),(r,a)=>!(r.length!==a.length||r.some((l,c)=>l.id!==a[c].id)));return xe.createElement("defs",null,n.map(r=>xe.createElement(P5,{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})))};Ej.displayName="MarkerDefinitions";var F5=_.memo(Ej);const z5=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}),$j=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:a,noPanClassName:l,onEdgeUpdate:c,onEdgeContextMenu:u,onEdgeMouseEnter:f,onEdgeMouseMove:h,onEdgeMouseLeave:m,onEdgeClick:g,edgeUpdaterRadius:y,onEdgeDoubleClick:w,onEdgeUpdateStart:k,onEdgeUpdateEnd:b,children:S})=>{const{edgesFocusable:N,edgesUpdatable:R,elementsSelectable:$,width:A,height:W,connectionMode:z,nodeInternals:H,onError:G}=In(z5,Os),re=R5(t,H,n);return A?xe.createElement(xe.Fragment,null,re.map(({level:te,edges:Q,isMaxLevel:D})=>xe.createElement("svg",{key:te,style:{zIndex:te},width:A,height:W,className:"react-flow__edges react-flow__container"},D&&xe.createElement(F5,{defaultColor:e,rfId:r}),xe.createElement("g",null,Q.map(T=>{const[E,L,M]=Rx(H.get(T.source)),[ee,F,U]=Rx(H.get(T.target));if(!M||!U)return null;let K=T.type||"default";a[K]||(G==null||G("011",jo.error011(K)),K="default");const O=a[K]||a.default,V=z===bc.Strict?F.target:(F.target??[]).concat(F.source??[]),J=Mx(L.source,T.sourceHandle),le=Mx(V,T.targetHandle),ie=(J==null?void 0:J.position)||wt.Bottom,_e=(le==null?void 0:le.position)||wt.Top,pe=!!(T.focusable||N&&typeof T.focusable>"u"),ye=typeof c<"u"&&(T.updatable||R&&typeof T.updatable>"u");if(!J||!le)return G==null||G("008",jo.error008(J,T)),null;const{sourceX:Ne,sourceY:Be,targetX:Ue,targetY:ut}=$5(E,J,ie,ee,le,_e);return xe.createElement(O,{key:T.id,id:T.id,className:Vs([T.className,l]),type:K,data:T.data,selected:!!T.selected,animated:!!T.animated,hidden:!!T.hidden,label:T.label,labelStyle:T.labelStyle,labelShowBg:T.labelShowBg,labelBgStyle:T.labelBgStyle,labelBgPadding:T.labelBgPadding,labelBgBorderRadius:T.labelBgBorderRadius,style:T.style,source:T.source,target:T.target,sourceHandleId:T.sourceHandle,targetHandleId:T.targetHandle,markerEnd:T.markerEnd,markerStart:T.markerStart,sourceX:Ne,sourceY:Be,targetX:Ue,targetY:ut,sourcePosition:ie,targetPosition:_e,elementsSelectable:$,onEdgeUpdate:c,onContextMenu:u,onMouseEnter:f,onMouseMove:h,onMouseLeave:m,onClick:g,edgeUpdaterRadius:y,onEdgeDoubleClick:w,onEdgeUpdateStart:k,onEdgeUpdateEnd:b,rfId:r,ariaLabel:T.ariaLabel,isFocusable:pe,isUpdatable:ye,pathOptions:"pathOptions"in T?T.pathOptions:void 0,interactionWidth:T.interactionWidth})})))),S):null};$j.displayName="EdgeRenderer";var B5=_.memo($j);const U5=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function W5({children:e}){const t=In(U5);return xe.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function q5(e){const t=Uy(),n=_.useRef(!1);_.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const H5={[wt.Left]:wt.Right,[wt.Right]:wt.Left,[wt.Top]:wt.Bottom,[wt.Bottom]:wt.Top},Aj=({nodeId:e,handleType:t,style:n,type:r=ml.Bezier,CustomComponent:a,connectionStatus:l})=>{var z,H,G;const{fromNode:c,handleId:u,toX:f,toY:h,connectionMode:m}=In(_.useCallback(re=>({fromNode:re.nodeInternals.get(e),handleId:re.connectionHandleId,toX:(re.connectionPosition.x-re.transform[0])/re.transform[2],toY:(re.connectionPosition.y-re.transform[1])/re.transform[2],connectionMode:re.connectionMode}),[e]),Os),g=(z=c==null?void 0:c[_s])==null?void 0:z.handleBounds;let y=g==null?void 0:g[t];if(m===bc.Loose&&(y=y||(g==null?void 0:g[t==="source"?"target":"source"])),!c||!y)return null;const w=u?y.find(re=>re.id===u):y[0],k=w?w.x+w.width/2:(c.width??0)/2,b=w?w.y+w.height/2:c.height??0,S=(((H=c.positionAbsolute)==null?void 0:H.x)??0)+k,N=(((G=c.positionAbsolute)==null?void 0:G.y)??0)+b,R=w==null?void 0:w.position,$=R?H5[R]:null;if(!R||!$)return null;if(a)return xe.createElement(a,{connectionLineType:r,connectionLineStyle:n,fromNode:c,fromHandle:w,fromX:S,fromY:N,toX:f,toY:h,fromPosition:R,toPosition:$,connectionStatus:l});let A="";const W={sourceX:S,sourceY:N,sourcePosition:R,targetX:f,targetY:h,targetPosition:$};return r===ml.Bezier?[A]=tj(W):r===ml.Step?[A]=Dg({...W,borderRadius:0}):r===ml.SmoothStep?[A]=Dg(W):r===ml.SimpleBezier?[A]=ej(W):A=`M${S},${N} ${f},${h}`,xe.createElement("path",{d:A,fill:"none",className:"react-flow__connection-path",style:n})};Aj.displayName="ConnectionLine";const V5=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function G5({containerStyle:e,style:t,type:n,component:r}){const{nodeId:a,handleType:l,nodesConnectable:c,width:u,height:f,connectionStatus:h}=In(V5,Os);return!(a&&l&&u&&c)?null:xe.createElement("svg",{style:e,width:u,height:f,className:"react-flow__edges react-flow__connectionline react-flow__container"},xe.createElement("g",{className:Vs(["react-flow__connection",h])},xe.createElement(Aj,{nodeId:a,handleType:l,style:t,type:n,CustomComponent:r,connectionStatus:h})))}function Ix(e,t){return _.useRef(null),js(),_.useMemo(()=>t(e),[e])}const Tj=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:a,onInit:l,onNodeClick:c,onEdgeClick:u,onNodeDoubleClick:f,onEdgeDoubleClick:h,onNodeMouseEnter:m,onNodeMouseMove:g,onNodeMouseLeave:y,onNodeContextMenu:w,onSelectionContextMenu:k,onSelectionStart:b,onSelectionEnd:S,connectionLineType:N,connectionLineStyle:R,connectionLineComponent:$,connectionLineContainerStyle:A,selectionKeyCode:W,selectionOnDrag:z,selectionMode:H,multiSelectionKeyCode:G,panActivationKeyCode:re,zoomActivationKeyCode:te,deleteKeyCode:Q,onlyRenderVisibleElements:D,elementsSelectable:T,selectNodesOnDrag:E,defaultViewport:L,translateExtent:M,minZoom:ee,maxZoom:F,preventScrolling:U,defaultMarkerColor:K,zoomOnScroll:O,zoomOnPinch:V,panOnScroll:J,panOnScrollSpeed:le,panOnScrollMode:ie,zoomOnDoubleClick:_e,panOnDrag:pe,onPaneClick:ye,onPaneMouseEnter:Ne,onPaneMouseMove:Be,onPaneMouseLeave:Ue,onPaneScroll:ut,onPaneContextMenu:De,onEdgeUpdate:Qe,onEdgeContextMenu:at,onEdgeMouseEnter:Ke,onEdgeMouseMove:ce,onEdgeMouseLeave:oe,edgeUpdaterRadius:Ae,onEdgeUpdateStart:he,onEdgeUpdateEnd:Ce,noDragClassName:Te,noWheelClassName:Ye,noPanClassName:rt,elevateEdgesOnSelect:ht,disableKeyboardA11y:lt,nodeOrigin:St,nodeExtent:Zt,rfId:On})=>{const Bt=Ix(e,x5),yn=Ix(t,E5);return q5(l),xe.createElement(w5,{onPaneClick:ye,onPaneMouseEnter:Ne,onPaneMouseMove:Be,onPaneMouseLeave:Ue,onPaneContextMenu:De,onPaneScroll:ut,deleteKeyCode:Q,selectionKeyCode:W,selectionOnDrag:z,selectionMode:H,onSelectionStart:b,onSelectionEnd:S,multiSelectionKeyCode:G,panActivationKeyCode:re,zoomActivationKeyCode:te,elementsSelectable:T,onMove:n,onMoveStart:r,onMoveEnd:a,zoomOnScroll:O,zoomOnPinch:V,zoomOnDoubleClick:_e,panOnScroll:J,panOnScrollSpeed:le,panOnScrollMode:ie,panOnDrag:pe,defaultViewport:L,translateExtent:M,minZoom:ee,maxZoom:F,onSelectionContextMenu:k,preventScrolling:U,noDragClassName:Te,noWheelClassName:Ye,noPanClassName:rt,disableKeyboardA11y:lt},xe.createElement(W5,null,xe.createElement(B5,{edgeTypes:yn,onEdgeClick:u,onEdgeDoubleClick:h,onEdgeUpdate:Qe,onlyRenderVisibleElements:D,onEdgeContextMenu:at,onEdgeMouseEnter:Ke,onEdgeMouseMove:ce,onEdgeMouseLeave:oe,onEdgeUpdateStart:he,onEdgeUpdateEnd:Ce,edgeUpdaterRadius:Ae,defaultMarkerColor:K,noPanClassName:rt,elevateEdgesOnSelect:!!ht,disableKeyboardA11y:lt,rfId:On},xe.createElement(G5,{style:R,type:N,component:$,containerStyle:A})),xe.createElement("div",{className:"react-flow__edgelabel-renderer"}),xe.createElement(j5,{nodeTypes:Bt,onNodeClick:c,onNodeDoubleClick:f,onNodeMouseEnter:m,onNodeMouseMove:g,onNodeMouseLeave:y,onNodeContextMenu:w,selectNodesOnDrag:E,onlyRenderVisibleElements:D,noPanClassName:rt,noDragClassName:Te,disableKeyboardA11y:lt,nodeOrigin:St,nodeExtent:Zt,rfId:On})))};Tj.displayName="GraphView";var K5=_.memo(Tj);const Wg=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],ll={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:Wg,nodeExtent:Wg,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:bc.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:xI,isValidConnection:void 0},Y5=()=>OR((e,t)=>({...ll,setNodes:n=>{const{nodeInternals:r,nodeOrigin:a,elevateNodesOnSelect:l}=t();e({nodeInternals:Dp(n,r,a,l)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(a=>({...r,...a}))})},setDefaultNodesAndEdges:(n,r)=>{const a=typeof n<"u",l=typeof r<"u",c=a?Dp(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:c,edges:l?r:[],hasDefaultNodes:a,hasDefaultEdges:l})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:a,fitViewOnInit:l,fitViewOnInitDone:c,fitViewOnInitOptions:u,domNode:f,nodeOrigin:h}=t(),m=f==null?void 0:f.querySelector(".react-flow__viewport");if(!m)return;const g=window.getComputedStyle(m),{m22:y}=new window.DOMMatrixReadOnly(g.transform),w=n.reduce((b,S)=>{const N=a.get(S.id);if(N){const R=Ly(S.nodeElement);!!(R.width&&R.height&&(N.width!==R.width||N.height!==R.height||S.forceUpdate))&&(a.set(N.id,{...N,[_s]:{...N[_s],handleBounds:{source:Ex(".source",S.nodeElement,y,h),target:Ex(".target",S.nodeElement,y,h)}},...R}),b.push({id:N.id,type:"dimensions",dimensions:R}))}return b},[]);wj(a,h);const k=c||l&&!c&&vj(t,{initial:!0,...u});e({nodeInternals:new Map(a),fitViewOnInitDone:k}),(w==null?void 0:w.length)>0&&(r==null||r(w))},updateNodePositions:(n,r=!0,a=!1)=>{const{triggerNodeChanges:l}=t(),c=n.map(u=>{const f={id:u.id,type:"position",dragging:a};return r&&(f.positionAbsolute=u.positionAbsolute,f.position=u.position),f});l(c)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:a,hasDefaultNodes:l,nodeOrigin:c,getNodes:u,elevateNodesOnSelect:f}=t();if(n!=null&&n.length){if(l){const h=u5(n,u()),m=Dp(h,a,c,f);e({nodeInternals:m})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:a,getNodes:l}=t();let c,u=null;r?c=n.map(f=>hl(f,!0)):(c=Tu(l(),n),u=Tu(a,[])),Am({changedNodes:c,changedEdges:u,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:a,getNodes:l}=t();let c,u=null;r?c=n.map(f=>hl(f,!0)):(c=Tu(a,n),u=Tu(l(),[])),Am({changedNodes:u,changedEdges:c,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:a,getNodes:l}=t(),c=n||l(),u=r||a,f=c.map(m=>(m.selected=!1,hl(m.id,!1))),h=u.map(m=>hl(m.id,!1));Am({changedNodes:f,changedEdges:h,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:a}=t();r==null||r.scaleExtent([n,a]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:a}=t();r==null||r.scaleExtent([a,n]),e({maxZoom:n})},setTranslateExtent:n=>{var r;(r=t().d3Zoom)==null||r.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:r}=t(),l=r().filter(u=>u.selected).map(u=>hl(u.id,!1)),c=n.filter(u=>u.selected).map(u=>hl(u.id,!1));Am({changedNodes:l,changedEdges:c,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(a=>{a.positionAbsolute=Iy(a.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:a,height:l,d3Zoom:c,d3Selection:u,translateExtent:f}=t();if(!c||!u||!n.x&&!n.y)return!1;const h=bo.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),m=[[0,0],[a,l]],g=c==null?void 0:c.constrain()(h,m,f);return c.transform(u,g),r[0]!==g.x||r[1]!==g.y||r[2]!==g.k},cancelConnection:()=>e({connectionNodeId:ll.connectionNodeId,connectionHandleId:ll.connectionHandleId,connectionHandleType:ll.connectionHandleType,connectionStatus:ll.connectionStatus,connectionStartHandle:ll.connectionStartHandle,connectionEndHandle:ll.connectionEndHandle}),reset:()=>e({...ll})}),Object.is),qy=({children:e})=>{const t=_.useRef(null);return t.current||(t.current=Y5()),xe.createElement(mI,{value:t.current},e)};qy.displayName="ReactFlowProvider";const Mj=({children:e})=>_.useContext(E_)?xe.createElement(xe.Fragment,null,e):xe.createElement(qy,null,e);Mj.displayName="ReactFlowWrapper";const J5={input:fj,default:Bg,output:mj,group:By},X5={default:u_,straight:Dy,step:Py,smoothstep:$_,simplebezier:Oy},Z5=[0,0],Q5=[15,15],eO={x:0,y:0,zoom:1},tO={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},Rj=_.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:a,nodeTypes:l=J5,edgeTypes:c=X5,onNodeClick:u,onEdgeClick:f,onInit:h,onMove:m,onMoveStart:g,onMoveEnd:y,onConnect:w,onConnectStart:k,onConnectEnd:b,onClickConnectStart:S,onClickConnectEnd:N,onNodeMouseEnter:R,onNodeMouseMove:$,onNodeMouseLeave:A,onNodeContextMenu:W,onNodeDoubleClick:z,onNodeDragStart:H,onNodeDrag:G,onNodeDragStop:re,onNodesDelete:te,onEdgesDelete:Q,onSelectionChange:D,onSelectionDragStart:T,onSelectionDrag:E,onSelectionDragStop:L,onSelectionContextMenu:M,onSelectionStart:ee,onSelectionEnd:F,connectionMode:U=bc.Strict,connectionLineType:K=ml.Bezier,connectionLineStyle:O,connectionLineComponent:V,connectionLineContainerStyle:J,deleteKeyCode:le="Backspace",selectionKeyCode:ie="Shift",selectionOnDrag:_e=!1,selectionMode:pe=Gf.Full,panActivationKeyCode:ye="Space",multiSelectionKeyCode:Ne=c_()?"Meta":"Control",zoomActivationKeyCode:Be=c_()?"Meta":"Control",snapToGrid:Ue=!1,snapGrid:ut=Q5,onlyRenderVisibleElements:De=!1,selectNodesOnDrag:Qe=!0,nodesDraggable:at,nodesConnectable:Ke,nodesFocusable:ce,nodeOrigin:oe=Z5,edgesFocusable:Ae,edgesUpdatable:he,elementsSelectable:Ce,defaultViewport:Te=eO,minZoom:Ye=.5,maxZoom:rt=2,translateExtent:ht=Wg,preventScrolling:lt=!0,nodeExtent:St,defaultMarkerColor:Zt="#b1b1b7",zoomOnScroll:On=!0,zoomOnPinch:Bt=!0,panOnScroll:yn=!1,panOnScrollSpeed:zn=.5,panOnScrollMode:Tn=dc.Free,zoomOnDoubleClick:wn=!0,panOnDrag:Pn=!0,onPaneClick:xn,onPaneMouseEnter:Ss,onPaneMouseMove:Kn,onPaneMouseLeave:Ns,onPaneScroll:jr,onPaneContextMenu:Dn,children:fe,onEdgeUpdate:Se,onEdgeContextMenu:et,onEdgeDoubleClick:Ze,onEdgeMouseEnter:ct,onEdgeMouseMove:mt,onEdgeMouseLeave:It,onEdgeUpdateStart:Ct,onEdgeUpdateEnd:Qt,edgeUpdaterRadius:jt=10,onNodesChange:en,onEdgesChange:Gt,noDragClassName:Ut="nodrag",noWheelClassName:Pt="nowheel",noPanClassName:Dt="nopan",fitView:We=!1,fitViewOptions:ln,connectOnClick:pt=!0,attributionPosition:rn,proOptions:gt,defaultEdgeOptions:Bn,elevateNodesOnSelect:cn=!0,elevateEdgesOnSelect:Gs=!1,disableKeyboardA11y:ls=!1,autoPanOnConnect:qr=!0,autoPanOnNodeDrag:hr=!0,connectionRadius:ni=20,isValidConnection:si,onError:Ps,style:me,id:mr,nodeDragThreshold:na,..._r},Sr)=>{const Hr=mr||"1";return xe.createElement("div",{..._r,style:{...me,...tO},ref:Sr,className:Vs(["react-flow",a]),"data-testid":"rf__wrapper",id:mr},xe.createElement(Mj,null,xe.createElement(K5,{onInit:h,onMove:m,onMoveStart:g,onMoveEnd:y,onNodeClick:u,onEdgeClick:f,onNodeMouseEnter:R,onNodeMouseMove:$,onNodeMouseLeave:A,onNodeContextMenu:W,onNodeDoubleClick:z,nodeTypes:l,edgeTypes:c,connectionLineType:K,connectionLineStyle:O,connectionLineComponent:V,connectionLineContainerStyle:J,selectionKeyCode:ie,selectionOnDrag:_e,selectionMode:pe,deleteKeyCode:le,multiSelectionKeyCode:Ne,panActivationKeyCode:ye,zoomActivationKeyCode:Be,onlyRenderVisibleElements:De,selectNodesOnDrag:Qe,defaultViewport:Te,translateExtent:ht,minZoom:Ye,maxZoom:rt,preventScrolling:lt,zoomOnScroll:On,zoomOnPinch:Bt,zoomOnDoubleClick:wn,panOnScroll:yn,panOnScrollSpeed:zn,panOnScrollMode:Tn,panOnDrag:Pn,onPaneClick:xn,onPaneMouseEnter:Ss,onPaneMouseMove:Kn,onPaneMouseLeave:Ns,onPaneScroll:jr,onPaneContextMenu:Dn,onSelectionContextMenu:M,onSelectionStart:ee,onSelectionEnd:F,onEdgeUpdate:Se,onEdgeContextMenu:et,onEdgeDoubleClick:Ze,onEdgeMouseEnter:ct,onEdgeMouseMove:mt,onEdgeMouseLeave:It,onEdgeUpdateStart:Ct,onEdgeUpdateEnd:Qt,edgeUpdaterRadius:jt,defaultMarkerColor:Zt,noDragClassName:Ut,noWheelClassName:Pt,noPanClassName:Dt,elevateEdgesOnSelect:Gs,rfId:Hr,disableKeyboardA11y:ls,nodeOrigin:oe,nodeExtent:St}),xe.createElement(qI,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:w,onConnectStart:k,onConnectEnd:b,onClickConnectStart:S,onClickConnectEnd:N,nodesDraggable:at,nodesConnectable:Ke,nodesFocusable:ce,edgesFocusable:Ae,edgesUpdatable:he,elementsSelectable:Ce,elevateNodesOnSelect:cn,minZoom:Ye,maxZoom:rt,nodeExtent:St,onNodesChange:en,onEdgesChange:Gt,snapToGrid:Ue,snapGrid:ut,connectionMode:U,translateExtent:ht,connectOnClick:pt,defaultEdgeOptions:Bn,fitView:We,fitViewOptions:ln,onNodesDelete:te,onEdgesDelete:Q,onNodeDragStart:H,onNodeDrag:G,onNodeDragStop:re,onSelectionDrag:E,onSelectionDragStart:T,onSelectionDragStop:L,noPanClassName:Dt,nodeOrigin:oe,rfId:Hr,autoPanOnConnect:qr,autoPanOnNodeDrag:hr,onError:Ps,connectionRadius:ni,isValidConnection:si,nodeDragThreshold:na}),xe.createElement(UI,{onSelectionChange:D}),fe,xe.createElement(pI,{proOptions:gt,position:rn}),xe.createElement(YI,{rfId:Hr,disableKeyboardA11y:ls})))});Rj.displayName="ReactFlow";const Lj=({id:e,x:t,y:n,width:r,height:a,style:l,color:c,strokeColor:u,strokeWidth:f,className:h,borderRadius:m,shapeRendering:g,onClick:y,selected:w})=>{const{background:k,backgroundColor:b}=l||{},S=c||k||b;return xe.createElement("rect",{className:Vs(["react-flow__minimap-node",{selected:w},h]),x:t,y:n,rx:m,ry:m,width:r,height:a,fill:S,stroke:u,strokeWidth:f,shapeRendering:g,onClick:y?N=>y(N,e):void 0})};Lj.displayName="MiniMapNode";var nO=_.memo(Lj);const sO=e=>e.nodeOrigin,rO=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),Up=e=>e instanceof Function?e:()=>e;function iO({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:a=2,nodeComponent:l=nO,onClick:c}){const u=In(rO,Os),f=In(sO),h=Up(t),m=Up(e),g=Up(n),y=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return xe.createElement(xe.Fragment,null,u.map(w=>{const{x:k,y:b}=pc(w,f).positionAbsolute;return xe.createElement(l,{key:w.id,x:k,y:b,width:w.width,height:w.height,style:w.style,selected:w.selected,className:g(w),color:h(w),borderRadius:r,strokeColor:m(w),strokeWidth:a,shapeRendering:y,onClick:c,id:w.id})}))}var aO=_.memo(iO);const oO=200,lO=150,cO=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?wI(A_(t,e.nodeOrigin),n):n,rfId:e.rfId}},uO="react-flow__minimap-desc";function Ij({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:a="",nodeBorderRadius:l=5,nodeStrokeWidth:c=2,nodeComponent:u,maskColor:f="rgb(240, 240, 240, 0.6)",maskStrokeColor:h="none",maskStrokeWidth:m=1,position:g="bottom-right",onClick:y,onNodeClick:w,pannable:k=!1,zoomable:b=!1,ariaLabel:S="React Flow mini map",inversePan:N=!1,zoomStep:R=10,offsetScale:$=5}){const A=js(),W=_.useRef(null),{boundingRect:z,viewBB:H,rfId:G}=In(cO,Os),re=(e==null?void 0:e.width)??oO,te=(e==null?void 0:e.height)??lO,Q=z.width/re,D=z.height/te,T=Math.max(Q,D),E=T*re,L=T*te,M=$*T,ee=z.x-(E-z.width)/2-M,F=z.y-(L-z.height)/2-M,U=E+M*2,K=L+M*2,O=`${uO}-${G}`,V=_.useRef(0);V.current=T,_.useEffect(()=>{if(W.current){const ie=ki(W.current),_e=Ne=>{const{transform:Be,d3Selection:Ue,d3Zoom:ut}=A.getState();if(Ne.sourceEvent.type!=="wheel"||!Ue||!ut)return;const De=-Ne.sourceEvent.deltaY*(Ne.sourceEvent.deltaMode===1?.05:Ne.sourceEvent.deltaMode?1:.002)*R,Qe=Be[2]*Math.pow(2,De);ut.scaleTo(Ue,Qe)},pe=Ne=>{const{transform:Be,d3Selection:Ue,d3Zoom:ut,translateExtent:De,width:Qe,height:at}=A.getState();if(Ne.sourceEvent.type!=="mousemove"||!Ue||!ut)return;const Ke=V.current*Math.max(1,Be[2])*(N?-1:1),ce={x:Be[0]-Ne.sourceEvent.movementX*Ke,y:Be[1]-Ne.sourceEvent.movementY*Ke},oe=[[0,0],[Qe,at]],Ae=bo.translate(ce.x,ce.y).scale(Be[2]),he=ut.constrain()(Ae,oe,De);ut.transform(Ue,he)},ye=qk().on("zoom",k?pe:null).on("zoom.wheel",b?_e:null);return ie.call(ye),()=>{ie.on("zoom",null)}}},[k,b,N,R]);const J=y?ie=>{const _e=Ji(ie);y(ie,{x:_e[0],y:_e[1]})}:void 0,le=w?(ie,_e)=>{const pe=A.getState().nodeInternals.get(_e);w(ie,pe)}:void 0;return xe.createElement(Hf,{position:g,style:e,className:Vs(["react-flow__minimap",t]),"data-testid":"rf__minimap"},xe.createElement("svg",{width:re,height:te,viewBox:`${ee} ${F} ${U} ${K}`,role:"img","aria-labelledby":O,ref:W,onClick:J},S&&xe.createElement("title",{id:O},S),xe.createElement(aO,{onClick:le,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:l,nodeClassName:a,nodeStrokeWidth:c,nodeComponent:u}),xe.createElement("path",{className:"react-flow__minimap-mask",d:`M${ee-M},${F-M}h${U+M*2}v${K+M*2}h${-U-M*2}z
|
|
149
|
-
M${H.x},${H.y}h${H.width}v${H.height}h${-H.width}z`,fill:f,fillRule:"evenodd",stroke:h,strokeWidth:m,pointerEvents:"none"})))}Ij.displayName="MiniMap";var dO=_.memo(Ij);function fO(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},xe.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function hO(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},xe.createElement("path",{d:"M0 0h32v4.2H0z"}))}function mO(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},xe.createElement("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"}))}function _O(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},xe.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"}))}function pO(){return xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},xe.createElement("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"}))}const Mu=({children:e,className:t,...n})=>xe.createElement("button",{type:"button",className:Vs(["react-flow__controls-button",t]),...n},e);Mu.displayName="ControlButton";const gO=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),Oj=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:a,onZoomIn:l,onZoomOut:c,onFitView:u,onInteractiveChange:f,className:h,children:m,position:g="bottom-left"})=>{const y=js(),[w,k]=_.useState(!1),{isInteractive:b,minZoomReached:S,maxZoomReached:N}=In(gO,Os),{zoomIn:R,zoomOut:$,fitView:A}=Uy();if(_.useEffect(()=>{k(!0)},[]),!w)return null;const W=()=>{R(),l==null||l()},z=()=>{$(),c==null||c()},H=()=>{A(a),u==null||u()},G=()=>{y.setState({nodesDraggable:!b,nodesConnectable:!b,elementsSelectable:!b}),f==null||f(!b)};return xe.createElement(Hf,{className:Vs(["react-flow__controls",h]),position:g,style:e,"data-testid":"rf__controls"},t&&xe.createElement(xe.Fragment,null,xe.createElement(Mu,{onClick:W,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},xe.createElement(fO,null)),xe.createElement(Mu,{onClick:z,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:S},xe.createElement(hO,null))),n&&xe.createElement(Mu,{className:"react-flow__controls-fitview",onClick:H,title:"fit view","aria-label":"fit view"},xe.createElement(mO,null)),r&&xe.createElement(Mu,{className:"react-flow__controls-interactive",onClick:G,title:"toggle interactivity","aria-label":"toggle interactivity"},b?xe.createElement(pO,null):xe.createElement(_O,null)),m)};Oj.displayName="Controls";var yO=_.memo(Oj),ea;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(ea||(ea={}));function wO({color:e,dimensions:t,lineWidth:n}){return xe.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function vO({color:e,radius:t}){return xe.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const xO={[ea.Dots]:"#91919a",[ea.Lines]:"#eee",[ea.Cross]:"#e2e2e2"},bO={[ea.Dots]:1,[ea.Lines]:1,[ea.Cross]:6},kO=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Pj({id:e,variant:t=ea.Dots,gap:n=20,size:r,lineWidth:a=1,offset:l=2,color:c,style:u,className:f}){const h=_.useRef(null),{transform:m,patternId:g}=In(kO,Os),y=c||xO[t],w=r||bO[t],k=t===ea.Dots,b=t===ea.Cross,S=Array.isArray(n)?n:[n,n],N=[S[0]*m[2]||1,S[1]*m[2]||1],R=w*m[2],$=b?[R,R]:N,A=k?[R/l,R/l]:[$[0]/l,$[1]/l];return xe.createElement("svg",{className:Vs(["react-flow__background",f]),style:{...u,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:h,"data-testid":"rf__background"},xe.createElement("pattern",{id:g+e,x:m[0]%N[0],y:m[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${A[0]},-${A[1]})`},k?xe.createElement(vO,{color:y,radius:R/l}):xe.createElement(wO,{dimensions:$,color:y,lineWidth:a})),xe.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g+e})`}))}Pj.displayName="Background";var jO=_.memo(Pj);function Dj(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,a=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,l=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||a===null||l===null)return null;const c=typeof t.maxAbsTranslate=="number"&&Number.isFinite(t.maxAbsTranslate)?Math.abs(t.maxAbsTranslate):1e6;if(Math.abs(r)>c||Math.abs(a)>c)return null;const u=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,f=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,h=Math.min(u,f),m=Math.max(u,f);return{x:r,y:a,zoom:Math.min(m,Math.max(h,l))}}function f_(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 SO(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(),a=t.slice(n+1).toLowerCase();if(r==="ex"){const l=a.indexOf("-"),c=l>0?a.slice(0,l):a;return c==="person"?"person":c==="org"?"org":c==="concept"?"concept":c==="claim"?"claim":c==="event"?"event":c==="doc"?"doc":c==="thing"?"thing":"entity"}return r==="schema"||r==="skos"||r==="dcterms"||r==="rdf"||r==="cito"?"vocab":"entity"}function NO(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return f_(t);const r=t.slice(0,n).toLowerCase(),a=t.slice(n+1);if(r==="ex"){const l=a.indexOf("-");if(l>0&&l<a.length-1)return a.slice(l+1)}return f_(t)}function qg(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),a={};for(let l=0;l<e.length;l++){const c=Math.floor(l/r),u=l%r;a[e[l]]={x:u*240,y:c*120}}return a}function Hg(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 Fj(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 CO(e,t){const n={},r=e.length;if(!r)return n;const a=Math.max(260,Math.sqrt(r)*150),l=t%360*Math.PI/180;for(let c=0;c<r;c++){const u=l+2*Math.PI*c/r;n[e[c]]={x:a*Math.cos(u),y:a*Math.sin(u)}}return n}function Ox(e,t,n){var k;const r={};if(!e.length)return r;const a=new Map;for(const b of e)a.set(b,new Set);for(const b of t){const S=String((b==null?void 0:b.source)||"").trim(),N=String((b==null?void 0:b.target)||"").trim();if(!S||!N||S===N)continue;const R=a.get(S),$=a.get(N);R&&R.add(N),$&&$.add(S)}let l=e[0],c=-1;for(const b of e){const S=((k=a.get(b))==null?void 0:k.size)??0;(S>c||S===c&&b.localeCompare(l)<0)&&(l=b,c=S)}const u=new Map,f=[];for(u.set(l,0),f.push(l);f.length;){const b=f.shift(),S=u.get(b)??0,N=Array.from(a.get(b)??[]);N.sort((R,$)=>R.localeCompare($));for(const R of N)u.has(R)||(u.set(R,S+1),f.push(R))}let h=0;for(const b of u.values())h=Math.max(h,b);for(const b of e)u.has(b)||u.set(b,h+1);const m=new Map;for(const b of e){const S=u.get(b)??0,N=m.get(S);N?N.push(b):m.set(S,[b])}const g=Array.from(m.keys()).sort((b,S)=>b-S),y=260,w=n%360*Math.PI/180;for(const b of g){const S=m.get(b)||[];if(S.sort((A,W)=>A.localeCompare(W)),b===0){if(S.length===1)r[S[0]]={x:0,y:0};else for(let W=0;W<S.length;W++){const z=w+2*Math.PI*W/S.length;r[S[W]]={x:80*Math.cos(z),y:80*Math.sin(z)}}continue}const N=y*b,R=S.length;if(R===1){r[S[0]]={x:N,y:0};continue}const $=w+b*.35;for(let A=0;A<R;A++){const W=$+2*Math.PI*A/R;r[S[A]]={x:N*Math.cos(W),y:N*Math.sin(W)}}}return r}function Cu(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,a=e.nodes.map(l=>l.id);if(n==="grid")return qg(a);if(n==="circle")return CO(a,r);if(n==="radial")return Ox(a,e.edges,r);if(n==="force"){const l=Ox(a,e.edges,r),c=Fj(r||1),u=Math.max(10,Math.min(42,Math.sqrt(a.length)*2.75)),f={};for(const h of a){const m=l[h]||{x:0,y:0};f[h]={x:m.x+(c()-.5)*u,y:m.y+(c()-.5)*u}}return f}return qg(a)}function EO(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 $O(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),a=EO(e),l=new Set;for(const y of a){const w=String(y.subject||"").trim(),k=String(y.object||"").trim();w&&l.add(w),k&&l.add(k)}const c=Array.from(l);c.sort((y,w)=>y.localeCompare(w));const u=qg(c),f=c.map(y=>({id:y,type:"default",data:{label:NO(y),kind:SO(y)},position:u[y]||{x:0,y:0}})),h=new Map,m=(y,w)=>{const k=String(y.subject||"").trim(),b=String(y.object||"").trim(),S=String(y.predicate||"").trim();return n?`edge:${k}:${b}`:`edge:${w}:${k}:${S}:${b}`};for(let y=0;y<a.length;y++){const w=a[y],k=m(w,y),b=h.get(k);b?b.push(w):h.set(k,[w])}const g=[];for(const[y,w]of h.entries()){const k=w[0],b=String(k.subject||"").trim(),S=String(k.object||"").trim();if(!b||!S)continue;const N=new Map;for(const H of w){const G=String(H.predicate||"").trim();G&&N.set(G,(N.get(G)||0)+1)}const R=Array.from(N.entries());R.sort((H,G)=>G[1]-H[1]||H[0].localeCompare(G[0]));const A=R.slice(0,r).map(([H,G])=>G>1?`${f_(H)}×${G}`:f_(H)).join(" | "),W=R.length>r?` +${R.length-r}`:"",z=`${A}${W}`.trim();g.push({id:y,source:b,target:S,label:z,animated:!1,data:{assertions:w,predicateSummary:z}})}return{nodes:f,edges:g}}function AO(e,t,n,r={}){const a=r.directed!==!1,l=String(t||"").trim(),c=String(n||"").trim();if(!l||!c)return null;if(l===c)return{nodeIds:[l],edgeIds:[]};const u=new Map,f=(b,S,N)=>{const R=u.get(b);R?R.push({to:S,edgeId:N}):u.set(b,[{to:S,edgeId:N}])};for(const b of e.edges)f(b.source,b.target,b.id),a||f(b.target,b.source,b.id);const h=[l],m=new Map,g=new Map;for(m.set(l,null),g.set(l,null);h.length;){const b=h.shift(),S=u.get(b)||[];for(const N of S)if(!m.has(N.to)){if(m.set(N.to,b),g.set(N.to,N.edgeId),N.to===c){h.length=0;break}h.push(N.to)}}if(!m.has(c))return null;const y=[],w=[];let k=c;for(;k;){y.push(k);const b=g.get(k);b&&w.push(b),k=m.get(k)||null}return y.reverse(),w.reverse(),{nodeIds:y,edgeIds:w}}const Px={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function Mm(e,t={}){const n={...Px,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):Px.seed},r=e.nodes.map(w=>w.id),a=r.length,l=new Float64Array(2*a),c=new Float64Array(2*a),u=new Float64Array(2*a),f=new Map;for(let w=0;w<a;w++)f.set(r[w],w);const h=t.positions??Cu(e,{kind:"force",seed:n.seed}),m=Fj(n.seed||1),g=Math.max(8,Math.min(38,Math.sqrt(a)*2.25));for(let w=0;w<a;w++){const k=r[w],b=h[k],S=typeof(b==null?void 0:b.x)=="number"&&Number.isFinite(b.x)?b.x:(m()-.5)*500,N=typeof(b==null?void 0:b.y)=="number"&&Number.isFinite(b.y)?b.y:(m()-.5)*500;l[2*w]=S+(m()-.5)*g,l[2*w+1]=N+(m()-.5)*g,c[2*w]=0,c[2*w+1]=0}const y=[];for(const w of e.edges){const k=f.get(String((w==null?void 0:w.source)||"").trim()),b=f.get(String((w==null?void 0:w.target)||"").trim());typeof k!="number"||typeof b!="number"||k===b||y.push(k,b)}return{nodeIds:r,pos:l,vel:c,acc:u,edges:new Uint32Array(y),options:n,tick:0}}function TO(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,a=r.dt;for(let l=0;l<Math.max(1,Math.trunc(t));l++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const w=r.repulsionStrength;for(let k=0;k<n;k++){const b=e.pos[2*k],S=e.pos[2*k+1];for(let N=k+1;N<n;N++){const R=e.pos[2*N]-b,$=e.pos[2*N+1]-S,A=R*R+$*$+1e-6,W=1/Math.sqrt(A),z=w/A,H=z*R*W,G=z*$*W;e.acc[2*k]-=H,e.acc[2*k+1]-=G,e.acc[2*N]+=H,e.acc[2*N+1]+=G}}}const u=r.springLength,f=r.springStrength,h=e.edges;for(let w=0;w<h.length;w+=2){const k=h[w],b=h[w+1],S=e.pos[2*k],N=e.pos[2*k+1],R=e.pos[2*b],$=e.pos[2*b+1],A=R-S,W=$-N,z=A*A+W*W+1e-6,H=Math.sqrt(z),G=f*(H-u),re=G*A/H,te=G*W/H;e.acc[2*k]+=re,e.acc[2*k+1]+=te,e.acc[2*b]-=re,e.acc[2*b+1]-=te}const m=r.centeringStrength;for(let w=0;w<n;w++)e.acc[2*w]+=-m*e.pos[2*w],e.acc[2*w+1]+=-m*e.pos[2*w+1];const g=r.damping,y=r.maxSpeed;for(let w=0;w<n;w++){let k=(e.vel[2*w]+e.acc[2*w]*a)*g,b=(e.vel[2*w+1]+e.acc[2*w+1]*a)*g;const S=Math.sqrt(k*k+b*b);if(S>y){const N=y/S;k*=N,b*=N}e.vel[2*w]=k,e.vel[2*w+1]=b,e.pos[2*w]+=k*a,e.pos[2*w+1]+=b*a}e.tick+=1}}function MO(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const a=e.vel[2*r],l=e.vel[2*r+1];n+=Math.sqrt(a*a+l*l)}return n/t}function RO(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 Dx(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function LO(){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 IO(){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 zj(e,t,n,r){const a=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,a))}function _f(e){const t=zj(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const Jf="abstractuic_amx_saved_layouts_v1",Vg=.025,Gg=6,Bj=1e6;function Hy(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Kg(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function OO(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 Fx(e){const t=Hy();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(Jf);if(!r)return null;const a=JSON.parse(r),l=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!l)return null;const c=l[n],u=c&&typeof c=="object"&&!Array.isArray(c)?c:null;if(!u)return null;const f=u.version===1?1:null;if(f===null)return null;const h=Kg(u.kind,"grid"),m=typeof u.seed=="number"&&Number.isFinite(u.seed)?Math.trunc(u.seed):Hg(n),g=u.positions&&typeof u.positions=="object"&&!Array.isArray(u.positions)?u.positions:null,y={};if(g)for(const[b,S]of Object.entries(g)){const N=OO(S);N&&(y[String(b)]=N)}const w=Dj(u.viewport,{minZoom:Vg,maxZoom:Gg,maxAbsTranslate:Bj})??void 0,k=typeof u.saved_at=="string"&&u.saved_at.trim()?u.saved_at.trim():"";return{version:f,kind:h,seed:m,positions:y,viewport:w,saved_at:k}}catch{return null}}function PO(e,t){const n=Hy();if(!n)return;const r=String(e??"").trim();if(r)try{const a=n.getItem(Jf),l=a?JSON.parse(a):null,c=l&&typeof l=="object"&&!Array.isArray(l)?{...l}:{};c[r]=t,n.setItem(Jf,JSON.stringify(c))}catch{}}function DO(e){const t=Hy();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(Jf);if(!r)return;const a=JSON.parse(r),l=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:null;if(!l||!(n in l))return;delete l[n],t.setItem(Jf,JSON.stringify(l))}catch{}}function FO(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function Wp(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),a=String(e??"").trim();if(!a)return;const l=Number(a);if(!Number.isFinite(l))return;const c=Math.trunc(l);if(r&&c===-1)return-1;if(!(!n&&c<=0)&&!(n&&c<0))return c}function zO(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,a=[];return n&&a.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&a.push(`limit=${r.limit}`),typeof r.min_score=="number"&&a.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&a.push(`max_input_tokens=${r.max_input_tokens}`)),a.length?a.join(" · "):null}function BO(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 a=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;a!==null&&t.push(`confidence=${a.toFixed(3)}`);const l=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(l){const h=typeof l.writer_run_id=="string"?l.writer_run_id.trim():"",m=typeof l.writer_workflow_id=="string"?l.writer_workflow_id.trim():"";h&&t.push(`writer_run_id=${h}`),m&&t.push(`writer_workflow_id=${m}`)}const c=e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)?e.attributes:null,u=c&&c._retrieval&&typeof c._retrieval=="object"&&!Array.isArray(c._retrieval)?c._retrieval:null,f=u&&typeof u.score=="number"&&Number.isFinite(u.score)?u.score:null;return f!==null&&t.push(`score=${f.toFixed(3)}`),t.length?t.join(" · "):null}function UO(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const a=n.toLowerCase().indexOf(r.toLowerCase());if(a<0)return n;const l=n.slice(0,a),c=n.slice(a,a+r.length),u=n.slice(a+r.length);return s.jsxs(s.Fragment,{children:[l,s.jsx("span",{className:"amx-hl",children:c}),u]})}function pf(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 WO(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 gf(e){const t=WO(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),a=String(n.getUTCMonth()+1).padStart(2,"0"),l=String(n.getUTCDate()).padStart(2,"0"),c=String(n.getUTCHours()).padStart(2,"0"),u=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${a}/${l} ${c}:${u}`}function Uj(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 qp(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function qO(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const f of e){const h=String((f==null?void 0:f.predicate)||"").trim();h&&r.set(h,(r.get(h)||0)+1)}const a=Array.from(r.entries());a.sort((f,h)=>h[1]-f[1]||f[0].localeCompare(h[0]));const c=a.slice(0,n).map(([f,h])=>{const m=Uj(f);return h>1?`${m}×${h}`:m}).join(" | "),u=a.length>n?` +${a.length-n}`:"";return`${c}${u}`.trim()}function HO({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:a,packetsVersion:l,packedCount:c,dropped:u,estimatedTokens:f,effort:h,warnings:m,onQuery:g,onItemsReplace:y,onOpenSpan:w,onOpenTranscript:k}){var ai;const b=_.useRef(null),S=_.useMemo(()=>{const q=n==null?void 0:n[0],ue=n==null?void 0:n[n.length-1],je=q?`${q.subject}|${q.predicate}|${q.object}`:"",$e=ue?`${ue.subject}|${ue.predicate}|${ue.object}`:"";return`${(n==null?void 0:n.length)||0}:${je}:${$e}`},[n]),N=String(e??S),R=t==="replace"?"replace":"override",[$,A]=_.useState(null),[W,z]=_.useState(null),[H,G]=_.useState(!1),[re,te]=_.useState(""),[Q,D]=_.useState(!1),[T,E]=_.useState("");_.useEffect(()=>{A(null),z(null),te(""),G(!1),E(""),D(!1)},[N]);const[L,M]=_.useState(""),[ee,F]=_.useState(!0),[U,K]=_.useState(!1),[O,V]=_.useState(!0),[J]=_.useState(()=>({compact:LO(),show:!1})),le=J.compact,[ie,_e]=_.useState(J.show),[pe,ye]=_.useState(!1),Ne=N,Be=_.useMemo(()=>Hg(Ne),[Ne]),[Ue,ut]=_.useState("grid"),[De,Qe]=_.useState(Be),[at,Ke]=_.useState(!1),[ce,oe]=_.useState(1),Ae=_.useRef(null),he=_.useRef(null),Ce=_.useRef(!1),[Te,Ye]=_.useState(0),rt=_.useRef(null),ht=_.useRef(0),lt=_.useRef(0),St=_.useRef(0),Zt=_.useRef(0),[On,Bt]=_.useState(!1),[yn,zn]=_.useState(""),[Tn,wn]=_.useState({}),Pn=_.useRef({});_.useEffect(()=>{Pn.current=Tn},[Tn]);const[xn,Ss]=_.useState(""),[Kn,Ns]=_.useState(""),jr=_.useMemo(()=>{var ue;const q=(ue=n==null?void 0:n[0])==null?void 0:ue.scope;return Dx(q,"session")},[n]),[Dn,fe]=_.useState(jr),[Se,et]=_.useState("standard"),[Ze,ct]=_.useState(""),[mt,It]=_.useState(""),[Ct,Qt]=_.useState(""),[jt,en]=_.useState(""),[Gt,Ut]=_.useState(""),[Pt,Dt]=_.useState(""),[We,ln]=_.useState(""),[pt,rn]=_.useState("qwen/qwen3-next-80b");_.useEffect(()=>{fe(jr)},[N]);const gt=Array.isArray(n)?n:[],Bn=typeof r=="string"?r:"",cn=Array.isArray(a)?a:[],Gs=typeof l=="number"?l:void 0,ls=typeof c=="number"?c:void 0,qr=typeof u=="number"?u:void 0,hr=typeof f=="number"?f:void 0,ni=h,si=m,Ps=R==="override"&&($!=null&&$.items)&&Array.isArray($.items)?$.items:gt,me=typeof($==null?void 0:$.active_memory_text)=="string"&&$.active_memory_text.trim()?$.active_memory_text:Bn,mr=($==null?void 0:$.effort)??ni,na=($==null?void 0:$.warnings)??si,_r=_.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),Sr=_.useMemo(()=>O?Ps:(Ps||[]).filter(q=>!qp(q==null?void 0:q.predicate,_r)),[Ps,O,_r]),Hr=_.useMemo(()=>$O(Ps,{groupEdges:ee}),[Ps,ee]),dt=_.useMemo(()=>{if(O)return Hr;const q=[];for(const ue of Hr.edges){const $e=(ue&&ue.data&&Array.isArray(ue.data.assertions)?ue.data.assertions:[]).filter(Ve=>!qp(Ve==null?void 0:Ve.predicate,_r));if(!$e.length)continue;const Ee=qO($e);q.push({...ue,label:Ee,data:{...ue.data,assertions:$e,predicateSummary:Ee}})}return{nodes:Hr.nodes,edges:q}},[Hr,O,_r]),fn=_.useMemo(()=>dt.nodes.map(q=>q.id),[dt.nodes]),Ds=_.useMemo(()=>{const q=fn[0]||"",ue=fn[fn.length-1]||"";return`${fn.length}:${q}:${ue}`},[fn]),Vr=_.useMemo(()=>{var ue;const q=new Map;for(const je of dt.nodes)q.set(je.id,String(((ue=je.data)==null?void 0:ue.label)||je.id));return q},[dt.nodes]),cs=_.useMemo(()=>{var ue;const q=new Map;for(const je of dt.nodes)q.set(je.id,String(((ue=je.data)==null?void 0:ue.kind)||""));return q},[dt.nodes]),Da=L.trim().toLowerCase(),Fa=_.useMemo(()=>{var ue;if(!Da)return new Set;const q=new Set;for(const je of dt.nodes){const $e=String(je.id||"").toLowerCase(),Ee=String(((ue=je.data)==null?void 0:ue.label)||"").toLowerCase();($e.includes(Da)||Ee.includes(Da))&&q.add(je.id)}return q},[dt.nodes,Da]),za=_.useCallback((q,ue)=>{const je={};for(const $e of fn){const Ee=q[$e]||ue[$e];je[$e]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return je},[fn]);_.useEffect(()=>{wn(q=>{const ue=Cu(dt,{kind:Ue,seed:De}),je={};for(const $e of fn){const Ee=q[$e]||ue[$e];je[$e]=Ee?{x:Ee.x,y:Ee.y}:{x:0,y:0}}return je})},[dt,Ue,De,fn,Ds]),_.useEffect(()=>{if(!Ce.current)return;const q=b.current;if(!(!q||typeof q.fitView!="function")&&fn.length){Ce.current=!1;try{q.fitView({padding:.2,duration:0})}catch{try{q.fitView({padding:.2})}catch{}}}},[fn.length,Ds,Tn]),_.useEffect(()=>{Ke(!1),Ae.current=null,he.current=null,Ce.current=!1,ht.current=0,lt.current=0,St.current=0;const q=Fx(Ne);if(q&&Object.keys(q.positions||{}).length){if(ut(q.kind),Qe(q.seed),Bt(!0),zn(q.saved_at||""),q.viewport){he.current=q.viewport;const Ee=b.current;if(Ee&&typeof Ee.setViewport=="function"){try{Ee.setViewport(q.viewport,{duration:0})}catch{try{Ee.setViewport(q.viewport)}catch{}}he.current=null}}else Ce.current=!0;const $e=Cu(dt,{kind:q.kind,seed:q.seed});wn(za(q.positions,$e));return}Bt(!1),zn("");const ue=Hg(Ne);Qe(ue);const je=Cu(dt,{kind:Ue,seed:ue});wn(je),Ue==="force"&&dt.nodes.length>0&&dt.nodes.length<=320&&(Ae.current=Mm(dt,{seed:ue,positions:je,..._f(ce)}),Ke(!0))},[Ne]);const Fn=_.useMemo(()=>{const q=String(xn||"").trim(),ue=String(Kn||"").trim();return!q||!ue?null:AO(dt,q,ue,{directed:U})},[dt,xn,Kn,U]),pr=!!(Fn&&String(xn||"").trim()&&String(Kn||"").trim()),Hn=_.useMemo(()=>{const q=String(xn||"").trim(),ue=String(Kn||"").trim();if(!q||!ue)return null;const je=U,$e=new Map,Ee=(_t,vt)=>{const qt=$e.get(_t);qt?qt.push(vt):$e.set(_t,[vt])};for(const _t of dt.edges)Ee(_t.source,_t.target),je||Ee(_t.target,_t.source);const Ve=new Set,yt=[];for(Ve.add(q),yt.push(q);yt.length;){const _t=yt.shift(),vt=$e.get(_t)||[];for(const qt of vt)Ve.has(qt)||(Ve.add(qt),yt.push(qt))}return{reachableFromStart:Ve.size,endReachable:Ve.has(ue),nodes:dt.nodes.length,edges:dt.edges.length,assertions:Sr.length}},[U,dt.edges,dt.nodes.length,Kn,xn,Sr.length]),sa=_.useMemo(()=>new Set((Fn==null?void 0:Fn.nodeIds)||[]),[Fn]),ri=_.useMemo(()=>new Set((Fn==null?void 0:Fn.edgeIds)||[]),[Fn]),[Mn,Fs]=_.useState(""),[ps,Ks]=_.useState(""),gs=!!(String(Mn||"").trim()||String(ps||"").trim()),So=_.useMemo(()=>{const q=new Set,ue=new Set,je=String(Mn||"").trim(),$e=String(ps||"").trim();if(je){q.add(je);for(const Ee of dt.edges)(Ee.source===je||Ee.target===je)&&(ue.add(Ee.id),q.add(Ee.source),q.add(Ee.target));return{nodes:q,edges:ue}}if($e){const Ee=dt.edges.find(Ve=>Ve.id===$e);Ee&&(ue.add(Ee.id),q.add(Ee.source),q.add(Ee.target))}return{nodes:q,edges:ue}},[dt.edges,ps,Mn]);_.useEffect(()=>{Fs(""),Ks(""),Ss(""),Ns("")},[N]);const[ra,un]=_.useState(!1);_.useEffect(()=>{un(!1)},[N]),_.useEffect(()=>{at||(Ae.current=null)},[at]),_.useEffect(()=>{if(Ue!=="force")return;const q=Ae.current;if(!q)return;const ue=_f(ce);q.options.springLength=ue.springLength,q.options.repulsionStrength=ue.repulsionStrength},[Ue,ce]),_.useEffect(()=>{Ue!=="force"&&at&&Ke(!1)},[Ue,at]),_.useEffect(()=>{if(!at||Ue!=="force"||dt.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Ae.current||(Ae.current=Mm(dt,{seed:De,positions:Pn.current,..._f(ce)}));let q=0,ue=0,je=0;const $e=dt.nodes.length<=140?2:1,Ee=1600,Ve=.08,yt=_t=>{if(q=window.requestAnimationFrame(yt),_t-ue<33)return;ue=_t;const vt=Ae.current;if(!vt){Ke(!1);return}TO(vt,$e),je+=$e,wn(RO(vt)),(MO(vt)<=Ve||je>=Ee)&&Ke(!1)};return q=window.requestAnimationFrame(yt),()=>{window.cancelAnimationFrame(q)}},[dt,Ue,at,De]);const No=_.useMemo(()=>dt.nodes.map(q=>{var dn;const ue=sa.has(q.id),je=Fa.has(q.id),$e=Mn===q.id,Ee=gs&&So.nodes.has(q.id),Ve=pf((dn=q.data)==null?void 0:dn.kind),yt="rgba(34, 211, 238, 0.88)",_t=je?"0 0 0 1px rgba(34, 211, 238, 0.34), 0 0 16px rgba(34, 211, 238, 0.26), 0 0 44px rgba(34, 211, 238, 0.14)":"",vt=ue?"rgba(168, 85, 247, 0.9)":je?yt:Ve.stroke,qt=$e?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ee?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,Yt=_t&&qt?`${_t}, ${qt}`:qt||_t||void 0,ws=ue?"rgba(168, 85, 247, 0.10)":je?"rgba(34, 211, 238, 0.08)":Ve.bg,Ft=pr?ue||$e?1:.16:gs?Ee||$e?1:.1:1;return{...q,position:Tn[q.id]?{x:Tn[q.id].x,y:Tn[q.id].y}:q.position,style:{...q.style||{},border:`1px solid ${vt}`,borderRadius:10,background:ws,color:"rgba(255,255,255,0.92)",opacity:Ft,padding:8,fontSize:12,boxShadow:Yt,width:180,cursor:"pointer"}}}),[dt.nodes,pr,Fa,Tn,Mn,sa,gs,So.nodes]),kc=_.useMemo(()=>dt.edges.map(q=>{const ue=ri.has(q.id),je=ps===q.id,$e=gs&&So.edges.has(q.id),Ee=ue?"rgba(168, 85, 247, 0.9)":gs?$e||je?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",Ve=ue?2.75:gs?$e||je?2.25:1.25:1.5,yt=je?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,_t=ue?"rgba(168, 85, 247, 0.9)":pr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",vt=pr?ue||je?1:.1:gs?$e||je?1:.08:1,qt=pr?ue||je?1:0:gs?$e||je?1:0:1,Yt=pr?ue||je?String(q.label||""):"":String(q.label||"");return{...q,label:Yt,style:{...q.style||{},stroke:Ee,strokeWidth:Ve,filter:yt,opacity:vt},animated:!1,markerEnd:{type:Kf.ArrowClosed,color:_t,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*qt})`,stroke:`rgba(255, 255, 255, ${.14*qt})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*qt})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[dt.edges,pr,ps,ri,gs,So.edges]),Ba=_.useMemo(()=>{if(!ps)return[];const q=dt.edges.find(je=>je.id===ps),ue=q&&q.data&&Array.isArray(q.data.assertions)?q.data.assertions:[];return Array.isArray(ue)?ue:[]},[dt.edges,ps]),ys=_.useMemo(()=>ps&&dt.edges.find(q=>q.id===ps)||null,[dt.edges,ps]),Nr=_.useMemo(()=>{const q=String(Mn||"").trim();return q?Ps.filter(ue=>!ue||typeof ue!="object"||!(ue.subject===q||ue.object===q)?!1:O?!0:!qp(ue.predicate,_r)):[]},[Ps,Mn,O,_r]),Cr=_.useMemo(()=>ps?Ba:Nr,[Ba,ps,Nr]),ia=_.useMemo(()=>{const q=new Map;for(const ue of Cr){if(!ue||typeof ue!="object")continue;const je=ue.provenance&&typeof ue.provenance=="object"&&!Array.isArray(ue.provenance)?ue.provenance:null,$e=je&&typeof je.span_id=="string"?je.span_id.trim():"",Ee=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"",Ve=typeof ue.owner_id=="string"?ue.owner_id.trim():"",yt=Ee||Ve;if(!yt||!$e)continue;const _t=`${yt}|${$e}`,vt=q.get(_t),qt=typeof ue.observed_at=="string"?ue.observed_at.trim():"";vt?(vt.count+=1,qt&&(!vt.last_observed_at||qt>vt.last_observed_at)&&(vt.last_observed_at=qt,vt.last_observed_at_fmt=gf(qt),vt.assertion=ue)):q.set(_t,{span_run_id:yt,span_id:$e,writer_run_id:Ee,count:1,last_observed_at:qt,last_observed_at_fmt:gf(qt),assertion:ue})}return Array.from(q.values()).sort((ue,je)=>String(je.last_observed_at||"").localeCompare(String(ue.last_observed_at||"")))},[Cr]),gr=_.useMemo(()=>{const q=new Map;for(const ue of Cr){if(!ue||typeof ue!="object")continue;const je=ue.provenance&&typeof ue.provenance=="object"&&!Array.isArray(ue.provenance)?ue.provenance:null,$e=je&&typeof je.span_id=="string"?je.span_id.trim():"",Ee=je&&typeof je.writer_run_id=="string"?je.writer_run_id.trim():"";if(!Ee||$e)continue;const Ve=q.get(Ee),yt=typeof ue.observed_at=="string"?ue.observed_at.trim():"";Ve?(Ve.count+=1,yt&&(!Ve.last_observed_at||yt>Ve.last_observed_at)&&(Ve.last_observed_at=yt,Ve.last_observed_at_fmt=gf(yt),Ve.assertion=ue)):q.set(Ee,{run_id:Ee,count:1,last_observed_at:yt,last_observed_at_fmt:gf(yt),assertion:ue})}return Array.from(q.values()).sort((ue,je)=>String(je.last_observed_at||"").localeCompare(String(ue.last_observed_at||"")))},[Cr]),Cs=_.useCallback(q=>{const ue=String(q.run_id||"").trim(),je=typeof q.span_id=="string"?String(q.span_id).trim():"";if(ue){if(k){try{k({run_id:ue,span_id:je||void 0,assertion:q.assertion})}catch{}return}if(w&&je)try{w({run_id:ue,span_id:je,assertion:q.assertion})}catch{}}},[w,k]),yr=_.useCallback(async q=>{var je;const ue=String(q??"");if(ue){try{if(typeof((je=navigator.clipboard)==null?void 0:je.writeText)=="function"){await navigator.clipboard.writeText(ue);return}}catch{}try{const $e=document.createElement("textarea");$e.value=ue,$e.style.position="fixed",$e.style.left="-9999px",document.body.appendChild($e),$e.select(),document.execCommand("copy"),document.body.removeChild($e)}catch{}}},[]),Er=_.useCallback(()=>{const q=b.current;if(!(!q||typeof q.fitView!="function")){if(Mn&&typeof q.getNode=="function"){const ue=q.getNode(Mn);if(ue){q.fitView({nodes:[ue],padding:.55,duration:350});return}}q.fitView({padding:.2,duration:350})}},[Mn]),Ys=_.useCallback(q=>{const ue=q.kind,je=Math.trunc(q.seed);Ke(!1),Ae.current=null,he.current=null,ut(ue),Qe(je);const $e=Cu(dt,{kind:ue,seed:je});wn($e),ue==="force"&&(q.autoPlay??!0)&&dt.nodes.length>0&&dt.nodes.length<=320&&(Ae.current=Mm(dt,{seed:je,positions:$e,..._f(ce)}),Ke(!0))},[dt,ce]),Ci=_.useCallback(()=>{if(Ue==="force"){if(at){Ke(!1);return}Ae.current=Mm(dt,{seed:De,positions:Pn.current,..._f(ce)}),Ke(!0)}},[dt,Ue,at,De,ce]);_.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&Zt.current&&window.cancelAnimationFrame(Zt.current)},[]);const us=_.useCallback(()=>{const q=b.current;if(!q||typeof q.getViewport!="function"||!fn.length)return null;const ue=rt.current;if(!ue)return null;const je=ue.getBoundingClientRect();if(!Number.isFinite(je.width)||!Number.isFinite(je.height)||je.width<64||je.height<64)return null;const $e=q.getViewport(),Ee=typeof($e==null?void 0:$e.zoom)=="number"&&Number.isFinite($e.zoom)?$e.zoom:null,Ve=typeof($e==null?void 0:$e.x)=="number"&&Number.isFinite($e.x)?$e.x:null,yt=typeof($e==null?void 0:$e.y)=="number"&&Number.isFinite($e.y)?$e.y:null;if(Ee===null||Ve===null||yt===null||Ee<=0)return null;const _t=140,vt=Math.min(fn.length,180),qt=Pn.current;let Yt=0,ws=0;for(const Ft of fn){const dn=qt[Ft];if(!dn||!Number.isFinite(dn.x)||!Number.isFinite(dn.y))continue;ws+=1;const En=[{x:dn.x,y:dn.y},{x:dn.x+90,y:dn.y+24}];for(const vn of En){const ts=vn.x*Ee+Ve,Qs=vn.y*Ee+yt;if(ts>-_t&&ts<je.width+_t&&Qs>-_t&&Qs<je.height+_t)return!1}if(Yt++,Yt>=vt)break}return ws?!0:null},[fn]),$r=_.useCallback(q=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||Zt.current||(Zt.current=window.requestAnimationFrame(()=>{Zt.current=0;const ue=us();if(ue===null){if(St.current>=12)return;St.current+=1,window.setTimeout(()=>$r(`${q}:probe`),120);return}if(ue!==!0){St.current=0,lt.current=0;return}St.current=0;const je=b.current;if(je&&typeof je.fitView=="function")try{je.fitView({padding:.2,duration:0})}catch{try{je.fitView({padding:.2})}catch{}}if(lt.current+=1,lt.current>=4&&ht.current<1){lt.current=0,ht.current+=1,Ye($e=>$e+1);return}lt.current<8&&window.setTimeout(()=>$r(`${q}:retry`),220)}))},[us]);_.useEffect(()=>{lt.current=0,ht.current=0,St.current=0,$r("mount")},[N,$r]),_.useEffect(()=>{$r("graph change")},[Ds,$r]),_.useEffect(()=>{const q=rt.current;if(!q||typeof window>"u"||typeof ResizeObserver!="function")return;const ue=new ResizeObserver(()=>$r("resize"));return ue.observe(q),()=>ue.disconnect()},[$r]);const Co=_.useCallback(()=>{const q=new Date().toISOString(),ue={};for(const yt of fn){const _t=Pn.current[yt];_t&&typeof _t.x=="number"&&typeof _t.y=="number"&&(ue[yt]={x:_t.x,y:_t.y})}const je=b.current,$e=je&&typeof je.toObject=="function"?je.toObject():null,Ee=$e&&$e.viewport?$e.viewport:je&&typeof je.getViewport=="function"?je.getViewport():null,Ve=Dj(Ee,{minZoom:Vg,maxZoom:Gg,maxAbsTranslate:Bj})??void 0;PO(Ne,{version:1,kind:Ue,seed:De,positions:ue,viewport:Ve,saved_at:q}),Bt(!0),zn(q),Ke(!1)},[Ne,Ue,De,fn]),wr=_.useCallback(()=>{const q=Fx(Ne);if(!q)return;Ke(!1),Ae.current=null,ut(q.kind),Qe(q.seed),Bt(!0),zn(q.saved_at||""),he.current=q.viewport||null,Ce.current=!q.viewport;const ue=Cu(dt,{kind:q.kind,seed:q.seed});if(wn(za(q.positions,ue)),q.viewport){const je=b.current;if(je&&typeof je.setViewport=="function"){try{je.setViewport(q.viewport,{duration:0})}catch{try{je.setViewport(q.viewport)}catch{}}he.current=null}}},[za,dt,Ne]),aa=_.useCallback(()=>{DO(Ne),Bt(!1),zn("")},[Ne]),jc=_.useCallback(q=>{if(!Array.isArray(q)||q.length===0)return;let ue=!1;wn(je=>{let $e=je,Ee=!1;for(const Ve of q){const yt=Ve&&typeof Ve=="object"&&"id"in Ve&&typeof Ve.id=="string"?String(Ve.id):"",_t=(Ve==null?void 0:Ve.type)==="position"?Ve==null?void 0:Ve.position:null;yt&&_t&&typeof _t.x=="number"&&typeof _t.y=="number"&&(Ee||($e={...je},Ee=!0),$e[yt]={x:_t.x,y:_t.y},Ve!=null&&Ve.dragging&&(ue=!0))}return Ee?$e:je}),ue&&at&&Ke(!1)},[at]),Ei=_.useMemo(()=>{const q=new Map;for(const ue of dt.edges)q.set(ue.id,ue);return q},[dt.edges]),Js=_.useMemo(()=>{var $e;if(!Fn)return[];const q=Fn.nodeIds||[],ue=Fn.edgeIds||[],je=[];for(let Ee=0;Ee<Math.min(q.length-1,ue.length);Ee++){const Ve=q[Ee],yt=q[Ee+1],_t=ue[Ee],vt=Ei.get(_t),qt=String((($e=vt==null?void 0:vt.data)==null?void 0:$e.predicateSummary)||(vt==null?void 0:vt.label)||"").trim(),Yt=vt&&vt.source===Ve&&vt.target===yt?"forward":vt&&vt.source===yt&&vt.target===Ve?"reverse":"unknown";je.push({from:Ve,to:yt,edgeId:_t,predicate:qt,dir:Yt})}return je},[Ei,Fn]),Yu=_.useCallback(async()=>{if(g){te(""),E(""),G(!0);try{const q=FO(Gt),ue=Wp(Pt,{allowZero:!0,allowNegativeOne:!0}),je=Wp(We,{allowZero:!0}),$e=await g({scope:Dn,owner_id:void 0,recall_level:Se,query_text:Ze||void 0,subject:mt||void 0,predicate:Ct||void 0,object:jt||void 0,min_score:q,limit:ue,max_input_tokens:je,model:pt||void 0});A($e),z("live query"),R==="replace"&&y&&$e&&Array.isArray($e.items)&&y($e.items,{kind:"live query",result:$e})}catch(q){const ue=q instanceof Error?q.message:String(q);te(ue||"Query failed")}finally{G(!1)}}},[Pt,We,Gt,pt,jt,y,g,Ct,R,Ze,Se,Dn,mt]),Xs=_.useCallback(async()=>{if(!g)return;const q=String(xn||"").trim(),ue=String(Kn||"").trim();if(!q||!ue)return;const je=Math.max(200,Wp(Pt)??80),$e=60;E(""),te(""),D(!0);try{const Ee=[],Ve=new Set,yt=Ft=>{if(!Ft||typeof Ft!="object"||typeof Ft.subject!="string"||typeof Ft.predicate!="string"||typeof Ft.object!="string")return;const dn=`${Ft.subject}|${Ft.predicate}|${Ft.object}|${String(Ft.observed_at||"")}|${String(Ft.scope||"")}|${String(Ft.owner_id||"")}`;Ve.has(dn)||(Ve.add(dn),Ee.push(Ft))};for(const Ft of Ps)yt(Ft);const _t=U,vt=new Set,qt=[q],Yt=new Set([q]),ws=async Ft=>{const dn=await g({scope:Dn,recall_level:Se,min_score:0,limit:je,subject:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(dn&&Array.isArray(dn.items)){for(const En of dn.items)if(yt(En),typeof En.subject=="string"&&En.subject.trim()===Ft&&typeof En.object=="string"){const vn=En.object.trim();vn&&!Yt.has(vn)&&(Yt.add(vn),qt.push(vn))}}if(!_t){const En=await g({scope:Dn,recall_level:Se,min_score:0,limit:je,object:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(En&&Array.isArray(En.items)){for(const vn of En.items)if(yt(vn),typeof vn.object=="string"&&vn.object.trim()===Ft&&typeof vn.subject=="string"){const ts=vn.subject.trim();ts&&!Yt.has(ts)&&(Yt.add(ts),qt.push(ts))}}}};for(;qt.length&&vt.size<$e&&!Yt.has(ue);){const Ft=qt.shift();!Ft||vt.has(Ft)||(vt.add(Ft),await ws(Ft))}A({ok:!0,count:Ee.length,items:Ee,active_memory_text:me,raw:{expanded_for_path:!0,expanded_nodes:vt.size,discovered_nodes:Yt.size,merged:Ee.length,directed:_t}}),z("expanded neighborhood"),R==="replace"&&y&&y(Ee,{kind:"expanded neighborhood",result:{ok:!0,count:Ee.length,items:Ee,active_memory_text:me,raw:{expanded_for_path:!0,expanded_nodes:vt.size,discovered_nodes:Yt.size,merged:Ee.length,directed:_t}}})}catch(Ee){const Ve=Ee instanceof Error?Ee.message:String(Ee);E(Ve||"Expand neighborhood failed")}finally{D(!1)}},[U,me,Ps,Pt,y,g,Kn,xn,R,Se,Dn]),oa=_.useCallback(()=>{A(null),z(null),te(""),G(!1),E(""),D(!1),Ss(""),Ns(""),Fs(""),Ks("")},[]),Zs="Search KG",Ua=dt.nodes.length,ii=dt.edges.length,Eo=Sr.length;return s.jsx("div",{className:"amx-host",children:s.jsxs("div",{className:"amx-root",children:[s.jsxs("div",{className:"amx-left",children:[s.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:s.jsxs("div",{className:"amx-graphbar-row",children:[s.jsx("span",{className:"amx-graphbar-title",children:"layout"}),s.jsxs("select",{value:Ue,onChange:q=>ut(Kg(q.target.value,Ue)),disabled:!fn.length,children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]}),Ue==="force"?s.jsxs("label",{className:"amx-graphbar-spread",children:[s.jsx("span",{className:"amx-graphbar-title",children:"spread"}),s.jsx("input",{type:"range",min:"0.7",max:"2.2",step:"0.1",value:ce,onChange:q=>oe(zj(Number(q.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[ce.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ys({kind:Ue,seed:De}),disabled:!fn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ci,disabled:!fn.length||Ue!=="force",children:at?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:rt,children:[s.jsx(qy,{children:s.jsxs(Rj,{nodes:No,edges:kc,defaultViewport:{x:0,y:0,zoom:1},minZoom:Vg,maxZoom:Gg,onInit:q=>{b.current=q;const ue=he.current;if(ue&&typeof q.setViewport=="function")try{q.setViewport(ue,{duration:0})}catch{try{q.setViewport(ue)}catch{}}if(Ce.current&&typeof q.fitView=="function")try{q.fitView({padding:.2,duration:0})}catch{try{q.fitView({padding:.2})}catch{}}he.current=null,Ce.current=!1,$r("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:jc,onNodeClick:(q,ue)=>{Ks(""),Fs(ue.id)},onEdgeClick:(q,ue)=>{Fs(""),Ks(ue.id)},onPaneClick:()=>{Fs(""),Ks("")},children:[s.jsx(yO,{className:"amx-flow-controls",children:s.jsx(Mu,{type:"button",className:`amx-control-legend ${pe?"amx-control-legend-active":""}`,onClick:()=>ye(q=>!q),title:pe?"Hide node color legend":"Show node color legend","aria-label":pe?"Hide node color legend":"Show node color legend",children:s.jsx(IO,{})})}),s.jsx(Hf,{position:"bottom-right",className:"amx-panel-bottom-right",children:s.jsx("div",{className:"amx-panel-toggles",children:s.jsx("button",{type:"button",className:"amx-minimap-toggle",onClick:()=>_e(q=>!q),title:ie?"Hide minimap preview":"Show minimap preview","aria-label":ie?"Hide minimap preview":"Show minimap preview",children:ie?"minimap on":"minimap off"})})}),ie?s.jsx(dO,{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:le?120:160,height:le?80:110,marginBottom:56},nodeColor:q=>{var ue;return pf((ue=q.data)==null?void 0:ue.kind).minimap}}):null,pe?s.jsxs(Hf,{position:"bottom-left",className:"amx-legend-panel",children:[s.jsx("div",{className:"amx-legend-title",children:"node colors"}),s.jsx("div",{className:"amx-legend",children:[{k:"person",label:"person"},{k:"org",label:"org"},{k:"concept",label:"concept"},{k:"claim",label:"claim"},{k:"event",label:"event"},{k:"doc",label:"doc"},{k:"vocab",label:"vocab"}].map(({k:q,label:ue})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:pf(q).stroke},children:ue},q))})]}):null,s.jsx(jO,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},Te),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:Zs}),s.jsxs("span",{className:"amx-small",children:[Eo," assertions · ",Ua," nodes · ",ii," edges"]})]}),s.jsxs("div",{className:"amx-toolbar",style:{marginTop:10},children:[s.jsxs("div",{className:"amx-toolbar-grid",children:[s.jsxs("label",{children:["search / highlight",s.jsx("input",{value:L,onChange:q=>M(q.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(ee),onChange:q=>F(q.target.value==="true"),children:[s.jsx("option",{value:"true",children:"group (subject→object)"}),s.jsx("option",{value:"false",children:"no grouping"})]})]}),s.jsxs("label",{children:["view",s.jsxs("select",{value:String(O),onChange:q=>V(q.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(U),onChange:q=>K(q.target.value==="true"),children:[s.jsx("option",{value:"false",children:"undirected"}),s.jsx("option",{value:"true",children:"directed"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"layout"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["layout",s.jsxs("select",{value:Ue,onChange:q=>ut(Kg(q.target.value,Ue)),children:[s.jsx("option",{value:"grid",children:"grid (deterministic)"}),s.jsx("option",{value:"radial",children:"radial (bfs)"}),s.jsx("option",{value:"circle",children:"circle"}),s.jsx("option",{value:"force",children:"force (simulation)"})]})]}),s.jsxs("label",{children:["seed",s.jsx("input",{type:"number",step:"1",value:De,onChange:q=>Qe(Math.trunc(Number(q.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Ys({kind:Ue,seed:De}),disabled:!fn.length,children:"Apply layout"}),Ue==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:Ci,disabled:!fn.length,children:at?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:Co,disabled:!fn.length,children:"Save layout"}),On?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:wr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:aa,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.",On?s.jsxs("span",{children:[" ","(saved",yn?`: ${yn}`:"",")"]}):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:xn,onChange:q=>Ss(q.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),fn.map(q=>s.jsx("option",{value:q,children:(()=>{const ue=Vr.get(q)||q;return ue===q?ue:`${ue} (${q})`})()},q))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:Kn,onChange:q=>Ns(q.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),fn.map(q=>s.jsx("option",{value:q,children:(()=>{const ue=Vr.get(q)||q;return ue===q?ue:`${ue} (${q})`})()},q))]})]})]}),Fn?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:Js.map((q,ue)=>{const je=Vr.get(q.from)||q.from,$e=Vr.get(q.to)||q.to,Ee=q.dir==="reverse"?" ← ":" → ",Ve=q.predicate?` (${q.predicate})`:"";return s.jsxs("div",{children:[ue===0?s.jsx("span",{children:je}):null,Ee,s.jsxs("span",{children:[$e,Ve]})]},`${q.edgeId}:${ue}`)})}):xn&&Kn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Hn==null?void 0:Hn.assertions)??Eo," assertions · ",(Hn==null?void 0:Hn.nodes)??dt.nodes.length," nodes ·"," ",(Hn==null?void 0:Hn.edges)??dt.edges.length," edges). Start reaches ",(Hn==null?void 0:Hn.reachableFromStart)??0," nodes.",g?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Xs(),disabled:Q,children:Q?"Expanding…":"Expand neighborhood"})}):null]}):s.jsx("div",{className:"amx-small",style:{marginTop:10},children:"(no path)"})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"query"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["query_text (semantic)",s.jsx("input",{value:Ze,onChange:q=>ct(q.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:mt,onChange:q=>It(q.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:Ct,onChange:q=>Qt(q.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:jt,onChange:q=>en(q.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:Gt,onChange:q=>Ut(q.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:Pt,onChange:q=>Dt(q.target.value),placeholder:"0/-1 = unlimited (if supported)"})]})]})]}),s.jsxs("details",{className:"amx-details",children:[s.jsx("summary",{children:"advanced"}),s.jsxs("div",{className:"amx-toolbar-grid",style:{marginTop:10},children:[s.jsxs("label",{children:["scope",s.jsxs("select",{value:Dn,onChange:q=>fe(Dx(q.target.value,Dn)),children:[s.jsx("option",{value:"run",children:"run"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"all",children:"all"})]})]}),s.jsxs("label",{children:["recall level",s.jsxs("select",{value:Se,onChange:q=>et(q.target.value||"standard"),children:[s.jsx("option",{value:"urgent",children:"urgent"}),s.jsx("option",{value:"standard",children:"standard"}),s.jsx("option",{value:"deep",children:"deep"})]})]}),s.jsxs("label",{children:["max_input_tokens",s.jsx("input",{type:"number",min:"0",step:"1",value:We,onChange:q=>ln(q.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:pt,onChange:q=>rn(q.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void Yu(),disabled:!g||H,children:H?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:oa,disabled:!$&&!re&&!H,children:"Reset to step output"}),$?s.jsxs("span",{className:"amx-small",children:["showing: ",W||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),re?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:re}):null,T?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:T}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const q=zO(mr);return q?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:q}):null})(),(()=>{const q=na;if(!q)return null;const ue=typeof q=="string"?q:Array.isArray(q)?q.map(je=>String(je)).join(" · "):JSON.stringify(q);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 q=($==null?void 0:$.packets_version)??Gs,ue=($==null?void 0:$.packed_count)??ls,je=($==null?void 0:$.dropped)??qr,$e=($==null?void 0:$.estimated_tokens)??hr,Ee=[];return typeof q=="number"&&Ee.push(`packets_v${q}`),typeof ue=="number"&&Ee.push(`packed=${ue}`),typeof je=="number"&&Ee.push(`dropped=${je}`),typeof $e=="number"&&Ee.push(`est_tokens=${$e}`),Ee.length?Ee.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:UO(me||"(empty)",L)}),(()=>{const q=$!=null&&$.packets&&Array.isArray($.packets)?$.packets:cn;return!Array.isArray(q)||q.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>un(ue=>!ue),children:[ra?"Hide":"Show"," packets (",q.length,")"]}),ra?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:q.slice(0,120).map((ue,je)=>{const $e=ue&&typeof ue=="object"&&!Array.isArray(ue)?ue:null,Ee=$e&&typeof $e.statement=="string"?$e.statement:typeof ue=="string"?ue:"",Ve=$e&&(typeof $e.retrieval_score=="number"||typeof $e.retrieval_score=="string")?$e.retrieval_score:null,yt=$e&&typeof $e.observed_at=="string"?$e.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ee||"(packet)"}),yt||Ve!==null?s.jsxs("div",{className:"amx-small",children:[yt?`[${yt}]`:null,yt&&Ve!==null?" ":null,Ve!==null?`score:${Ve}`:null]}):null]},je)})}):null]})})(),s.jsx("div",{style:{marginTop:14,marginBottom:12,borderTop:"1px solid var(--ui-border-1, rgba(255,255,255,0.08))"}}),s.jsx("div",{className:"amx-small",style:{marginBottom:8,fontWeight:700,opacity:.9},children:"Inspect"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Click a node or edge to inspect its assertions."}),Mn?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:Vr.get(Mn)||Mn}),s.jsxs("div",{className:"amx-small",children:["kind=",cs.get(Mn)||"entity"," · id=",Mn]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void yr(Mn),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Er,children:"Focus"})]})]}):ys&&ys.source&&ys.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:[ys.source," —",String(ys.label||((ai=ys.data)==null?void 0:ai.predicateSummary)||"").trim()||"?","→ ",ys.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",ys.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void yr(ys.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Er,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Cr.slice(0,80).map((q,ue)=>{const je=String(q.subject||"").trim(),$e=String(q.predicate||"").trim(),Ee=String(q.object||"").trim(),Ve=Vr.get(je)||je,yt=Vr.get(Ee)||Ee,_t=cs.get(je)||"entity",vt=cs.get(Ee)||"entity",qt=pf(_t),Yt=pf(vt),ws=gf(q.observed_at),Ft=BO(q),dn=q.provenance&&typeof q.provenance=="object"&&!Array.isArray(q.provenance)?q.provenance:null,En=dn&&typeof dn.span_id=="string"?dn.span_id.trim():"",vn=dn&&typeof dn.writer_run_id=="string"?dn.writer_run_id.trim():"",ts=typeof q.owner_id=="string"?q.owner_id.trim():"",Qs=vn||ts,Gr=!!((k||w)&&En&&Qs),$i=!!(k&&vn&&!En),$o=Gr||$i;return s.jsxs("div",{className:"amx-item amx-triple-card",children:[s.jsxs("div",{className:"amx-triple-row",children:[s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:qt.stroke,background:qt.bg},title:je,onClick:()=>{je&&(Ks(""),Fs(je))},children:Ve||je||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:$e,children:Uj($e)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:Yt.stroke,background:Yt.bg},title:Ee,onClick:()=>{Ee&&(Ks(""),Fs(Ee))},children:yt||Ee||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[ws?s.jsxs("span",{className:"amx-small",title:String(q.observed_at||""),children:["[",ws,"]"]}):null,Ft?s.jsx("span",{className:"amx-small",children:Ft}):null]}),En||vn?s.jsxs("div",{className:"amx-triple-actions",children:[En?s.jsxs("span",{className:"amx-small",children:["span:",En]}):null,vn?s.jsxs("span",{className:"amx-small",children:["run:",vn]}):null,$o?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Gr&&En&&Qs){Cs({run_id:Qs,span_id:En,assertion:q});return}$i&&vn&&Cs({run_id:vn,assertion:q})},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)."}),ia.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:ia.slice(0,60).map(q=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["span:",q.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",q.span_run_id," · assertions=",q.count,q.last_observed_at_fmt?` · last=[${q.last_observed_at_fmt}]`:""]})]}),w||k?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Cs({run_id:q.span_run_id,span_id:q.span_id,assertion:q.assertion}),children:"Open transcript"}):null]},`${q.span_run_id}|${q.span_id}`))})]}):null,k&&gr.length?s.jsxs("div",{style:{marginBottom:12},children:[s.jsx("div",{className:"amx-small",style:{marginBottom:6,opacity:.85},children:"runs (fallback)"}),s.jsx("div",{className:"amx-list",style:{maxHeight:240},children:gr.slice(0,40).map(q=>s.jsxs("div",{className:"amx-item",style:{display:"flex",justifyContent:"space-between",gap:10,alignItems:"center"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{className:"amx-mono",style:{fontSize:11,opacity:.95},children:["run:",q.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",q.count,q.last_observed_at_fmt?` · last=[${q.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Cs({run_id:q.run_id,assertion:q.assertion}),children:"Open transcript"})]},q.run_id))})]}):null,!ia.length&&!(k&&gr.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function lc({open:e,title:t,children:n,actions:r,variant:a="default",onClose:l}){const c=_.useId();if(_.useEffect(()=>{if(!e)return;const f=h=>{h.key==="Escape"&&l()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,l]),!e)return null;const u=a==="fullscreen";return s.jsx("div",{className:`modal_backdrop${u?" fullscreen":""}`,onMouseDown:f=>{f.target===f.currentTarget&&l()},children:s.jsxs("div",{className:`modal_panel${u?" fullscreen":""}`,role:"dialog","aria-modal":"true","aria-labelledby":c,children:[s.jsxs("div",{className:"modal_header",children:[s.jsx("div",{className:"modal_title",id:c,children:t}),s.jsx("button",{className:"btn",onClick:l,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function Hp(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function ul(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 oc(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"),a=String(t.getUTCDate()).padStart(2,"0"),l=String(t.getUTCHours()).padStart(2,"0"),c=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${a} ${l}:${c}`}function VO(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=ul(t);return n!==null?oc(n):t}function Vy(e){const t=typeof e=="string"?e:String(e??"");return t?!t.includes("\\n")&&!t.includes("\\r")&&!t.includes("\\t")?t:t.replace(/\\r\\n/g,`
|
|
150
|
-
`).replace(/\\n/g,`
|
|
151
|
-
`).replace(/\\t/g," "):""}function Wj(e){return String(e??"").replace(/[*_`~]/g,"")}function Rm(e,t){const n=!!(t!=null&&t.strip_punct),r=Vy(e);let a=Wj(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(a=a.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),a}function Lm(e,t){const n=String(t??"").trim();if(!n)return!1;const r=Rm(n,{strip_punct:!1});if(!r)return!1;if(Rm(String(e??""),{strip_punct:!1}).includes(r))return!0;const l=Rm(n,{strip_punct:!0});return l?Rm(String(e??""),{strip_punct:!0}).includes(l):!1}function zx(e){const t=Vy(e).trim();if(!t)return[];const n=[],r=c=>{const u=String(c??"").replace(/\s+/g," ").trim();u&&(u.length<6||n.includes(u)||n.push(u))},a=t.search(/[`*_~]/);if(a>0){const c=t.slice(0,a);c.replace(/\s+/g," ").trim().length>=10&&r(c)}const l=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const c of l){let u;for(;(u=c.exec(t))!==null;){const f=String(u[1]??"").trim();f&&r(f)}}return r(Wj(t)),n}function GO(e){const t=String(e??"").replace(/\r\n/g,`
|
|
152
|
-
`).replace(/\r/g,`
|
|
153
|
-
`);if(!t)return null;const n=t.split(`
|
|
154
|
-
`);let r;const a=[],l=[];let c=null,u=[],f=!1;const h=()=>{if(!c)return;const y=u.join(`
|
|
155
|
-
`).trim();y&&l.push({role:c,lines:[y]}),c=null,u=[]};for(const y of n){const w=r?null:y.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(w&&w[1]){r=w[1].trim();continue}const k=y.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(k){f=!0,h();const b=String(k[1]||"").trim().toLowerCase();c=b==="user"?"user":b==="assistant"?"assistant":"system";const S=String(k[2]??"");u=S?[S]:[];continue}c?u.push(y):a.push(y)}if(h(),!f||!l.length)return null;const m=a.join(`
|
|
156
|
-
`).trim(),g={messages:[]};r&&(g.created_at=r),m&&g.messages.push({role:"system",content:m});for(const y of l)g.messages.push({role:y.role,content:y.lines.join(`
|
|
157
|
-
`)});return g.messages.length?g:null}function Bx(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function Ux(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(),a=String((e==null?void 0:e.observed_at)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),c=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${a}|${l}|${c}`}function KO(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(),a=String((e==null?void 0:e.object)||"").trim(),l=String((e==null?void 0:e.scope)||"").trim(),c=String((e==null?void 0:e.owner_id)||"").trim(),u=[];l&&u.push(`scope=${l}`),c&&u.push(`owner=${c}`);const f=u.length?` (${u.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${a}${f}`}function YO({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,a]=_.useState(String(t||"").trim()),[l,c]=_.useState(String(n||"").trim()),[u,f]=_.useState("all"),h=u==="all",[m,g]=_.useState(!0),[y,w]=_.useState(750),[k,b]=_.useState(5e3),[S,N]=_.useState([]),[R,$]=_.useState(void 0),[A,W]=_.useState(""),[z,H]=_.useState(!1),[G,re]=_.useState([]),[te,Q]=_.useState(!1),[D,T]=_.useState(!1),[E,L]=_.useState(""),[M,ee]=_.useState(""),[F,U]=_.useState(""),[K,O]=_.useState(""),[V,J]=_.useState("artifact"),[le,ie]=_.useState(null),[_e,pe]=_.useState(""),[ye,Ne]=_.useState(null),Be=_.useRef(!1),Ue=_.useMemo(()=>{const fe=ye,Se=fe!=null&&fe.attributes&&typeof fe.attributes=="object"&&!Array.isArray(fe.attributes)?fe.attributes:null;return(Se&&typeof Se.evidence_quote=="string"?String(Se.evidence_quote):"").trim()},[ye]),ut=_.useMemo(()=>{const fe=le,Se=fe&&typeof fe=="object"&&!Array.isArray(fe)?fe:null,et=Se&&typeof Se.note=="string"?String(Se.note):"";return Vy(et).trim()},[le]),De=_.useMemo(()=>{const fe=le&&typeof le=="object"&&!Array.isArray(le)?le:null,Se=fe&&Array.isArray(fe.messages)?fe.messages:null;return Array.isArray(Se)?Se:null},[le]),Qe=_.useMemo(()=>{const fe=ut,Se=Ue;return!fe||!Se?!1:Lm(fe,Se)},[Ue,ut]),at=_.useMemo(()=>{const fe=De,Se=Ue;if(!fe||!Se)return[];const et=[];for(let Ze=0;Ze<Math.min(fe.length,500);Ze++){const ct=fe[Ze],mt=(ct==null?void 0:ct.content)==null?"":String(ct.content);Lm(mt,Se)&&et.push(Ze)}return et},[Ue,De]),Ke=_.useMemo(()=>new Set(at),[at]),ce=at.length?at[0]:null,oe=_.useCallback(fe=>{const Se=document.getElementById(`source_msg_${fe}`);Se&&typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({block:"center",behavior:"smooth"})},[]),Ae=_.useCallback(()=>{const fe=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");fe&&typeof fe.scrollIntoView=="function"&&fe.scrollIntoView({block:"center",behavior:"smooth"})},[]);_.useEffect(()=>{if(te&&!(D||E)&&!Be.current){if(ce!==null){Be.current=!0,window.setTimeout(()=>oe(ce),0);return}if(Qe){Be.current=!0,window.setTimeout(()=>Ae(),0);return}}},[oe,Ae,E,ce,D,Qe,te]);const he=_.useRef(new Set),Ce=_.useRef(""),Te=_.useRef(null),Ye=_.useRef(null);_.useEffect(()=>{a(String(t||"").trim())},[t]),_.useEffect(()=>{c(String(n||"").trim())},[n]);const rt=_.useMemo(()=>{const fe=String(r||"").trim(),Se=String(l||"").trim();return`mindmap:${u}:${fe}:${Se}`},[r,l,u]),ht=_.useMemo(()=>{let fe=null,Se=null;for(const et of S){const Ze=ul(et==null?void 0:et.observed_at);Ze!==null&&(fe=fe===null?Ze:Math.min(fe,Ze),Se=Se===null?Ze:Math.max(Se,Ze))}return{min_ms:fe,max_ms:Se}},[S]),lt=1e3,St=_.useMemo(()=>{const fe=ht.min_ms,Se=ht.max_ms;if(typeof fe!="number"||typeof Se!="number"||!Number.isFinite(fe)||!Number.isFinite(Se))return null;if(Se<=fe)return{min_ms:fe,max_ms:fe,real_max_ms:Se};const et=fe+Math.ceil((Se-fe)/lt)*lt;return{min_ms:fe,max_ms:et,real_max_ms:Se}},[ht.max_ms,ht.min_ms]),[Zt,On]=_.useState(!0),[Bt,yn]=_.useState(null);_.useEffect(()=>{Zt&&St&&yn(St.max_ms)},[Zt,St]);const zn=_.useMemo(()=>{const fe=typeof Bt=="number"?Bt:null;return fe===null?S:S.filter(Se=>{const et=ul(Se==null?void 0:Se.observed_at);return et===null?!0:et<=fe})},[S,Bt]),Tn=_.useCallback((fe,Se)=>{const et=Array.isArray(fe)?fe:[],Ze=String(Ce.current||"").trim(),ct=new Set,mt=[];let It="";for(const Ct of et){if(!Ct||typeof Ct!="object"||typeof Ct.subject!="string"||typeof Ct.predicate!="string"||typeof Ct.object!="string")continue;const Qt=Ux(Ct);if(ct.has(Qt))continue;ct.add(Qt),mt.push(Ct);const jt=String(Ct.observed_at||"").trim();jt&&(It=Bx(It,jt))}N(mt),$(Se==null?void 0:Se.warnings),he.current=ct,Ce.current=It||Ze},[]),wn=_.useCallback(async fe=>{const Se=Hp(fe.scope,"session"),et=String(fe.subject||"").trim(),Ze=String(fe.predicate||"").trim(),ct=String(fe.object||"").trim(),mt=String(fe.since||"").trim(),It=String(fe.until||"").trim(),Ct=String(fe.active_at||"").trim(),Qt=String(fe.query_text||"").trim(),jt=typeof fe.min_score=="number"&&Number.isFinite(fe.min_score)?Number(fe.min_score):void 0,en=fe.order==="asc"?"asc":"desc",Gt=typeof fe.limit=="number"&&Number.isFinite(fe.limit)?Number(fe.limit):0,Ut=String(r||"").trim(),Pt=String(l||"").trim(),Dt={scope:Se,all_owners:h,limit:Gt,order:en};et&&(Dt.subject=et),Ze&&(Dt.predicate=Ze),ct&&(Dt.object=ct),mt&&(Dt.since=mt),It&&(Dt.until=It),Ct&&(Dt.active_at=Ct),Qt&&(Dt.query_text=Qt),typeof jt=="number"&&(Dt.min_score=jt),h||(Se==="run"?Ut&&(Dt.run_id=Ut):Se==="session"?Pt?Dt.session_id=Pt:Ut&&(Dt.run_id=Ut):Se==="all"&&(Ut?Dt.run_id=Ut:Pt&&(Dt.session_id=Pt)));try{const We=await e.kg_query(Dt),ln=Array.isArray(We==null?void 0:We.items)?We.items:[],pt=We==null?void 0:We.warnings;return{ok:(We==null?void 0:We.ok)!==!1,count:Number((We==null?void 0:We.count)||ln.length),items:ln,warnings:pt,raw:We}}catch(We){const ln=We instanceof Error?We.message:String(We);if(ln.includes("Run '")&&ln.includes("not found")&&!Pt&&(Se==="session"||Se==="all")&&Ut){const rn=await e.kg_query({...Dt,run_id:void 0,session_id:Ut}),gt=Array.isArray(rn==null?void 0:rn.items)?rn.items:[],Bn=rn==null?void 0:rn.warnings;return{ok:(rn==null?void 0:rn.ok)!==!1,count:Number((rn==null?void 0:rn.count)||gt.length),items:gt,warnings:Bn,raw:rn}}throw new Error(ln||"KG query failed")}},[h,e,r,l]),Pn=_.useCallback(async fe=>{var Ze;const Se=String(fe.run_id||"").trim(),et=String(fe.span_id||"").trim();if(!(!Se||!et)){Q(!0),T(!0),L(""),U(Se),O(et),J("artifact"),ee(`source span:${et}`),ie(null),pe(""),Ne(fe.assertion&&typeof fe.assertion=="object"?fe.assertion:null),Be.current=!1;try{const ct=[Se],mt=typeof((Ze=fe.assertion)==null?void 0:Ze.owner_id)=="string"?String(fe.assertion.owner_id).trim():"";mt&&mt!==Se&&ct.push(mt);let It=null,Ct=null;for(const Qt of ct)try{Ct=await(await e.download_run_artifact_content(Qt,et)).text(),Qt!==Se&&U(Qt);break}catch(jt){It=jt instanceof Error?jt.message:String(jt)}if(Ct==null)throw new Error(It||"Failed to load source span");pe(Ct);try{const Qt=JSON.parse(Ct);ie(Qt)}catch{ie(null)}}catch(ct){const mt=ct instanceof Error?ct.message:String(ct);L(mt||"Failed to load source span")}finally{T(!1)}}},[e]),xn=_.useCallback(async fe=>{const Se=String(fe.run_id||"").trim();if(!Se)return null;try{const et=await e.list_run_artifacts(Se,{limit:200}),ct=(Array.isArray(et==null?void 0:et.items)?et.items:[]).map(jt=>{const en=typeof(jt==null?void 0:jt.artifact_id)=="string"?String(jt.artifact_id).trim():"",Gt=jt!=null&&jt.tags&&typeof jt.tags=="object"&&!Array.isArray(jt.tags)?jt.tags:null,Ut=Gt&&typeof Gt.kind=="string"?String(Gt.kind).trim():"";return{artifact_id:en,kind:Ut}}).filter(jt=>!!(jt.artifact_id&&(jt.kind==="conversation_span"||jt.kind==="memory_note")));if(!ct.length)return null;if(ct.length===1)return ct[0].artifact_id;const mt=fe.assertion,It=mt!=null&&mt.attributes&&typeof mt.attributes=="object"&&!Array.isArray(mt.attributes)?mt.attributes:null,Qt=(It&&typeof It.evidence_quote=="string"?String(It.evidence_quote):"").trim();if(!Qt)return null;for(const jt of ct.slice(0,10))try{const Gt=await(await e.download_run_artifact_content(Se,jt.artifact_id)).text(),Ut=JSON.parse(Gt);if(Ut&&typeof Ut=="object"){const Pt=typeof Ut.note=="string"?String(Ut.note):"";if(Pt&&Pt.includes(Qt))return jt.artifact_id;const Dt=Array.isArray(Ut.messages)?Ut.messages:null;if(Dt){for(const We of Dt.slice(0,200))if(((We==null?void 0:We.content)==null?"":String(We.content)).includes(Qt))return jt.artifact_id}}}catch{}}catch{}return null},[e]),Ss=_.useCallback(async fe=>{const Se=String(fe.run_id||"").trim();if(Se){Q(!0),T(!0),L(""),U(Se),O(""),J("run_input"),ee(`transcript run:${Se}`),ie(null),pe(""),Ne(fe.assertion&&typeof fe.assertion=="object"?fe.assertion:null),Be.current=!1;try{const et=await xn({run_id:Se,assertion:fe.assertion});if(et){await Pn({run_id:Se,span_id:et,assertion:fe.assertion});return}const Ze=await e.get_run_input_data(Se),ct=Ze&&typeof Ze=="object"&&!Array.isArray(Ze)?Ze.input_data:null,mt={kind:"run_input_data",run_id:Se};if(Ze&&typeof(Ze==null?void 0:Ze.workflow_id)=="string"&&(mt.workflow_id=String(Ze.workflow_id)),ct&&typeof ct=="object"&&!Array.isArray(ct)){const It=ct.context,Qt=(It&&typeof It=="object"&&Array.isArray(It.messages)?It.messages:null)||(Array.isArray(ct.messages)?ct.messages:null);Array.isArray(Qt)&&(mt.messages=Qt);const jt=["text","prompt","task","message"];for(const en of jt){const Gt=ct[en];if(typeof Gt=="string"&&Gt.trim()){mt.note=Gt.trim();break}}mt.input_data=ct}!mt.messages&&!mt.note&&(mt.note=JSON.stringify(ct??Ze??{},null,2));try{const It=await e.get_run(Se),Ct=It&&typeof(It==null?void 0:It.created_at)=="string"?String(It.created_at):"";Ct&&(mt.created_at=Ct)}catch{}ie(mt),pe(JSON.stringify(Ze,null,2))}catch(et){const Ze=et instanceof Error?et.message:String(et);L(Ze||"Failed to load run input transcript")}finally{T(!1)}}},[e,Pn,xn]),Kn=_.useCallback(async()=>{W(""),H(!0);try{const fe=u==="all"?"all":u,Se=await wn({scope:fe,limit:0,order:"desc"});Tn(Se.items||[],{warnings:Se.warnings}),Te.current={scope:fe}}catch(fe){const Se=fe instanceof Error?fe.message:String(fe);W(Se||"Load failed")}finally{H(!1)}},[wn,Tn,u]);_.useEffect(()=>{S.length||Kn()},[]);const Ns=_.useCallback(async fe=>{const Se=Hp(fe.scope,"session");return Ye.current=fe,await wn({scope:Se,subject:fe.subject,predicate:fe.predicate,object:fe.object,query_text:fe.query_text,min_score:fe.min_score,since:fe.since,until:fe.until,active_at:fe.active_at,limit:typeof fe.limit=="number"?fe.limit:0,order:"desc"})},[wn]),jr=_.useCallback((fe,Se)=>{var et;if((Se==null?void 0:Se.kind)==="live query"){const Ze=Ye.current;Ze&&(Te.current={scope:Hp(Ze.scope,"session"),subject:typeof Ze.subject=="string"?Ze.subject:void 0,predicate:typeof Ze.predicate=="string"?Ze.predicate:void 0,object:typeof Ze.object=="string"?Ze.object:void 0})}Tn(fe,{warnings:(et=Se==null?void 0:Se.result)==null?void 0:et.warnings})},[Tn]),Dn=_.useCallback(async()=>{const fe=Te.current;if(!fe)return;const Se=String(Ce.current||"").trim(),et=await wn({scope:fe.scope,subject:fe.subject,predicate:fe.predicate,object:fe.object,since:Se||void 0,order:"asc",limit:0}),Ze=Array.isArray(et.items)?et.items:[];if(!Ze.length)return;const mt=Date.now()+Math.max(250,Math.min(2e4,k)),It=he.current,Ct=[],Qt=[];let jt=String(Ce.current||"").trim();for(const en of Ze){if(!en||typeof en!="object"||typeof en.subject!="string"||typeof en.predicate!="string"||typeof en.object!="string")continue;const Gt=Ux(en);if(It.has(Gt))continue;It.add(Gt),Ct.push(en),Qt.push({id:Gt,assertion:en,expires_at_ms:mt});const Ut=String(en.observed_at||"").trim();Ut&&(jt=Bx(jt,Ut))}Ct.length&&(Ce.current=jt,N(en=>{const Gt=en.concat(Ct);return Gt.sort((Ut,Pt)=>String((Pt==null?void 0:Pt.observed_at)||"").localeCompare(String((Ut==null?void 0:Ut.observed_at)||""))),Gt}),re(en=>{const Gt=en.concat(Qt);return Gt.sort((Ut,Pt)=>Pt.expires_at_ms-Ut.expires_at_ms),Gt.slice(0,30)}))},[k,wn]);return _.useEffect(()=>{if(!m)return;let fe=!1,Se=null;const et=async()=>{if(!fe){try{await Dn()}catch{}fe||(Se=window.setTimeout(()=>void et(),Math.max(250,Math.min(6e4,y))))}};return et(),()=>{fe=!0,Se!==null&&window.clearTimeout(Se)}},[m,y,Dn]),_.useEffect(()=>{if(!G.length)return;const fe=window.setInterval(()=>{const Se=Date.now();re(et=>et.filter(Ze=>Ze.expires_at_ms>Se))},250);return()=>window.clearInterval(fe)},[G.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void Kn(),disabled:z,children:z?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:u,onChange:fe=>{const Se=String(fe.target.value||"").trim();(Se==="all"||Se==="global"||Se==="session"||Se==="run")&&f(Se)},children:[s.jsx("option",{value:"all",children:"all memory"}),s.jsx("option",{value:"global",children:"global"}),s.jsx("option",{value:"session",children:"session"}),s.jsx("option",{value:"run",children:"run"})]})]}),s.jsx(nM,{checked:m,onChange:g}),u==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:l,onChange:fe=>c(String(fe.target.value||"")),placeholder:"(required)"})]}):null,u==="run"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"run_id"}),s.jsx("input",{className:"mono",value:r,onChange:fe=>a(String(fe.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:fe=>w(Math.max(250,Number(fe.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:k,onChange:fe=>b(Math.max(250,Number(fe.target.value||0)||5e3))})]})})]})]}),A?s.jsx("div",{className:"mindmap_error mono",children:A}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(HO,{title:"mindmap",resetKey:rt,queryMode:"replace",items:zn,warnings:R,onQuery:Ns,onItemsReplace:jr,onOpenSpan:({run_id:fe,span_id:Se,assertion:et})=>{Pn({run_id:fe,span_id:Se,assertion:et})},onOpenTranscript:({run_id:fe,span_id:Se,assertion:et})=>{const Ze=String(fe||"").trim(),ct=typeof Se=="string"?String(Se).trim():"";Ze&&(ct?Pn({run_id:Ze,span_id:ct,assertion:et}):Ss({run_id:Ze,assertion:et}))}},rt),G.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:G.slice().sort((fe,Se)=>Se.expires_at_ms-fe.expires_at_ms).slice(0,12).map(fe=>s.jsx("div",{className:"mindmap_recent_item mono",children:KO(fe.assertion)},fe.id))})]}):null,St?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:oc(Math.min(typeof Bt=="number"?Bt:St.max_ms,St.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:St.min_ms,max:St.max_ms,step:lt,value:typeof Bt=="number"?Bt:St.max_ms,onChange:fe=>{const Se=Number(fe.target.value||0);yn(Se),On(Se>=St.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[zn.length.toLocaleString(),"/",S.length.toLocaleString()]})]})}):null]}),s.jsxs(lc,{open:te,title:M||"source",onClose:()=>{Q(!1)},children:[D?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,E?s.jsx("div",{className:"mindmap_error mono",children:E}):null,!D&&!E?s.jsxs("div",{className:"source_span",children:[(()=>{const fe=ye;if(!fe)return null;const Se=String(fe.subject||"").trim(),et=String(fe.predicate||"").trim(),Ze=String(fe.object||"").trim(),ct=oc(ul(fe.observed_at)),mt=fe.attributes&&typeof fe.attributes=="object"&&!Array.isArray(fe.attributes)?fe.attributes:null,It=mt&&typeof mt.evidence_quote=="string"?String(mt.evidence_quote):"",Ct=mt&&typeof mt.original_context=="string"?String(mt.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${Se} --${et}--> ${Ze}`,children:[Se," ",s.jsxs("span",{className:"muted",children:["—",et,"→"]})," ",Ze," ",ct?s.jsxs("span",{className:"muted",children:["[",ct,"]"]}):null]}),It?s.jsxs("div",{className:"source_evidence",children:[s.jsx("div",{className:"mono muted",style:{fontSize:11,marginBottom:6},children:"evidence_quote"}),s.jsx("pre",{className:"mono source_evidence_quote",children:It}),Ct?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:Ct})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",F," · ",V==="artifact"?`span_id=${K}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[ce!==null?s.jsx("button",{className:"btn",onClick:()=>oe(ce),children:"Jump to evidence"}):null,ce===null&&Qe?s.jsx("button",{className:"btn",onClick:()=>Ae(),children:"Jump to evidence"}):null]}),(()=>{const fe=le,Se=fe&&typeof fe=="object"&&!Array.isArray(fe)?fe:null,et=De,Ze=ut,ct=Se&&typeof Se.created_at=="string"?String(Se.created_at):"",mt=ct?ul(ct):null,It=mt!==null?oc(mt):ct,Ct=Se&&Se.span&&typeof Se.span=="object"&&!Array.isArray(Se.span)?Se.span:null,Qt=Ct&&typeof Ct.from_timestamp=="string"?String(Ct.from_timestamp):"",jt=Ct&&typeof Ct.to_timestamp=="string"?String(Ct.to_timestamp):"",en=Qt?ul(Qt):null,Gt=jt?ul(jt):null,Ut=en!==null&&Gt!==null?`${oc(en)} → ${oc(Gt)}`:"";if(Ze){const Pt=GO(Ze);if(Pt){const Dt=Ue,We=Dt?Pt.messages.findIndex(gt=>Lm(gt.content,Dt)):-1,ln=Dt?zx(Dt):[],pt=Pt.created_at||ct,rn=pt?VO(pt):ct?It:"";return s.jsx("div",{className:"source_chat",children:Pt.messages.map((gt,Bn)=>{const cn=gt.role,Gs=!!(Dt&&Lm(gt.content,Dt)),ls=cn==="user"?"USER":cn==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Bn===We?"source_note_msg_hit_0":void 0,className:`source_msg source_${cn} ${Gs?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Bn+1," · ",ls,Gs?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),rn?s.jsx("span",{title:pt||"",children:rn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Si,{text:gt.content,highlights:Gs&&ln.length?ln:void 0,highlightClassName:"source_note_hit",highlightId:Bn===We?"source_note_hit_0":void 0})})]},`note_msg:${Bn}`)})})}return s.jsxs("div",{className:"source_note",children:[ct?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:ct,children:["created_at=",It]})}):null,s.jsx(Si,{text:Ze,highlights:Ue?zx(Ue):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(et){const Pt=new Map;for(const We of et){const ln=typeof(We==null?void 0:We.role)=="string"?String(We.role):"unknown";Pt.set(ln,(Pt.get(ln)||0)+1)}const Dt=Array.from(Pt.entries()).sort((We,ln)=>ln[1]-We[1]||We[0].localeCompare(ln[0])).map(([We,ln])=>`${We}×${ln}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[ct?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:ct,children:["created_at=",It]})," · messages=",et.length]}):null,Ut?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",Ut]}):null,Dt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",Dt]}):null,et.slice(0,200).map((We,ln)=>{var qr,hr;const pt=typeof(We==null?void 0:We.role)=="string"?String(We.role):"unknown",rn=(We==null?void 0:We.content)==null?"":String(We.content),gt=typeof(We==null?void 0:We.timestamp)=="string"?String(We.timestamp):"",Bn=gt?ul(gt):null,cn=Bn!==null?oc(Bn):gt,Gs=typeof(We==null?void 0:We.message_id)=="string"?String(We.message_id):typeof((qr=We==null?void 0:We.metadata)==null?void 0:qr.message_id)=="string"?String(We.metadata.message_id):typeof((hr=We==null?void 0:We.metadata)==null?void 0:hr.id)=="string"?String(We.metadata.id):"",ls=Ke.has(ln);return s.jsxs("div",{id:`source_msg_${ln}`,className:`source_msg source_${pt} ${ls?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",ln+1," · ",pt,ls?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Gs?s.jsx("span",{className:"source_msg_id",children:Gs}):null]}),gt?s.jsx("span",{title:gt,children:cn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Si,{text:rn})})]},ln)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof fe=="string"?fe:_e)||"(empty)"})})()]}):null]})]})}const Vp=4;function JO(e){var l;const t=(l=e==null?void 0:e.discoveries)==null?void 0:l.dreams_signals_brief;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=typeof t.count=="number"&&Number.isInteger(t.count)&&t.count>0?t.count:0;if(!n)return null;const r=c=>Array.isArray(c)?c.filter(u=>typeof u=="string").map(u=>u.trim()).filter(Boolean):[],a=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:a}}function Wx(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 XO(e){var u,f;const t=h=>{var g;const m=(g=e==null?void 0:e[h])==null?void 0:g.open;return Array.isArray(m)?m.map(Wx).filter(y=>y!==null):[]},n=t("questions"),r=t("problems"),a=(u=e==null?void 0:e.lessons)==null?void 0:u.lessons,l=Array.isArray(a)?a.map(Wx).filter(h=>h!==null):[],c=typeof((f=e==null?void 0:e.lessons)==null?void 0:f.total)=="number"?e.lessons.total:l.length;return{questions:n.slice(0,Vp),questions_total:n.length,problems:r.slice(0,Vp),problems_total:r.length,lessons:l.slice(0,Vp),lessons_total:c}}function Gp(e){return e===null||!Number.isFinite(e)||e<0?"":e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(1)}M`}const qx={review:"Review",working:"Working",pending:"Pending",done:"Done"},ZO={review:"nothing needs you",working:"idle",pending:"nothing scheduled",done:"no recent runs"},QO={pending:"scheduled or queued — will run without you",working:"running or parked listening — no action needed",review:"needs a human decision — act here",done:"terminal — read the outcome"};function eP(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(Oa(t))return"done";const n=Ku(e);return n==="tool_approval"||n==="user_response"?"review":n==="scheduled"||t==="pending"||t==="queued"||t==="created"?"pending":"working"}function tP(e){const t=Ku(e);return t==="tool_approval"||t==="user_response"}function Hx(e,t=Date.now()){const n=eP(e),r=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,a=sh(r),l=qn((r==null?void 0:r.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"");return{run_id:String((e==null?void 0:e.run_id)||""),column:n,workflow:String((e==null?void 0:e.workflow_id)||"").trim()||"(workflow?)",status:String((e==null?void 0:e.status)||"").trim().toLowerCase(),wait_kind:Ku(e),reason:fk(e),tool_names:a.map(c=>String((c==null?void 0:c.name)||"tool")).filter(Boolean),wait_key:String((r==null?void 0:r.wait_key)||"").trim(),allow_free_text:(r==null?void 0:r.allow_free_text)!==!1,prompt:String((r==null?void 0:r.prompt)||"").trim(),since_ms:l,duration_ms:wy(e,t),tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?e.tokens_total:null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?e.llm_calls:null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?e.tool_calls:null,is_scheduled:!!(e!=null&&e.is_scheduled),schedule_interval:String((e==null?void 0:e.schedule_interval)||"").trim(),failed:String((e==null?void 0:e.status)||"").trim().toLowerCase()==="failed",error:String((e==null?void 0:e.error)||"").trim(),paused:!!(e!=null&&e.paused),is_subrun:!!String((e==null?void 0:e.parent_run_id)||"").trim(),tag:If(e),tag_label:L0(e),archived:(e==null?void 0:e.archived)===!0,automation_id:If(e)==="occurrence"?String((e==null?void 0:e.automation_id)||"").trim():""}}function nP(e,t,n=Date.now()){const r={pending:[],working:[],review:[],done:[]},a=t&&t.length?t:e,l=new Set;for(const c of a||[]){const u=String((c==null?void 0:c.run_id)||"").trim();!c||!u||l.has(u)||gv(c)||tP(c)&&(l.add(u),r.review.push(Hx(c,n)))}for(const c of e||[]){const u=String((c==null?void 0:c.run_id)||"").trim();if(!c||!u||l.has(u)||gv(c))continue;const f=Hx(c,n);r[f.column].push(f)}return r.review.sort((c,u)=>(c.since_ms??0)-(u.since_ms??0)),r.working.sort((c,u)=>(u.since_ms??0)-(c.since_ms??0)),r.pending.sort((c,u)=>(u.since_ms??0)-(c.since_ms??0)),r.done.sort((c,u)=>Number(u.failed)-Number(c.failed)||(u.since_ms??0)-(c.since_ms??0)),r}const Yg={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},Kp={"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"},Vx="48h";function sP(e,t,n=Date.now()){const r=Yg[t]??null;if(r===null)return{visible:e,hidden_count:0};const a=n-r,l=[];let c=0;for(const u of e)u.since_ms===null||u.since_ms>=a?l.push(u):c+=1;return{visible:l,hidden_count:c}}function rP(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 iP=6e4;function yf(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 aP(e){return!Number.isFinite(e)||e<0?"":e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.floor(e/6e4)}m${Math.round(e%6e4/1e3)}s`:`${(e/36e5).toFixed(1)}h`}function oP(e){const t=String(e||"");return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function Yp(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function lP(e){const t=String(e||"");let n=t.includes(":")?t.slice(t.lastIndexOf(":")+1):t;if(t.includes(":")&&/^[0-9a-f]{6,}$/i.test(n.trim())){const r=t.slice(0,t.lastIndexOf(":"));/[a-z]/i.test(r)&&!/^[0-9a-f]+$/i.test(r.replace(/[@.\-_]/g,""))&&(n=r)}return n.length>34?`${n.slice(0,32)}…`:n}function qm(e){return e.toLowerCase().replace(/[_-]+/g," ")}function cP(e){var h,m;const t=e!=null&&e.spec&&typeof e.spec=="object"?e.spec:null,n=t!=null&&t.phases&&typeof t.phases=="object"&&!Array.isArray(t.phases)?t.phases:null;if(!n)return null;const r=Object.keys(n).filter(g=>g&&typeof g=="string");if(!r.length)return null;const a=[];for(const g of r){a.push({needle:qm(g),phase:g});const y=(h=n[g])==null?void 0:h.spoken_synonyms;if(Array.isArray(y))for(const w of y){const k=qm(String(w||"").trim());k&&a.push({needle:k,phase:g})}}const c=(typeof t.initial_phase=="string"&&r.includes(t.initial_phase)?t.initial_phase:null)??(r.includes("sleep")?"sleep":null);if(!c)return null;const u=[],f=(m=t==null?void 0:t.state_mode_axis)==null?void 0:m.words;if(f&&typeof f=="object"&&!Array.isArray(f))for(const[g,y]of Object.entries(f)){const w=String((y==null?void 0:y.phase)||"").trim(),k=qm(String(g||"").trim());k&&r.includes(w)&&u.push({needle:k,phase:w})}return{phases:r,synonyms:a,modes:u,initial:c,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const uP=["asleep","sleep","dream"],dP=["rest"],fP=["awake","idle"];function hP(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=qm(n),a=t.synonyms.filter(c=>r.includes(c.needle)).sort((c,u)=>u.needle.length-c.needle.length);if(a.length)return a[0].phase;const l=t.modes.filter(c=>r.includes(c.needle)).sort((c,u)=>u.needle.length-c.needle.length);return l.length?l[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":uP.some(c=>n.includes(c))?t.initial:dP.some(c=>n.includes(c))&&t.phases.includes("personal")?"personal":fP.some(c=>n.includes(c))?t.initial:n.includes("stop")?"stopped":n.includes("pause")?"paused":n}return n.includes("visit")?"visit":n.includes("sleep")||n.includes("dream")?"sleep":n.includes("personal")||n.includes("own_time")||n.includes("own time")?"personal":n.includes("task")&&!n.includes("no_task")||n.includes("work")?"work":n.includes("awake")||n.includes("idle")?"sleep":n.includes("stop")?"stopped":n.includes("pause")?"paused":n.includes("rest")?"resting":n}const mP=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),_P=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function pP(e){if(!e)return mP;const t=e.phases.filter(n=>_P.has(n));return new Set([...t,"paused","stopped","unknown"])}function gP(e){const[t,n]=Of(`board_${e.col}`),r=`mc_column_body_${e.col}`;return s.jsxs("div",{className:`mc_column mc_column_${e.col}${t?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"mc_column_head",children:[s.jsx(Pf,{open:t,on_toggle:n,controls:r,title:e.title,className:"mc_column_title"}),e.head]}),s.jsx("div",{className:"mc_column_body",id:r,hidden:!t,children:e.children})]})}function yP(e){var z,H,G,re,te,Q;const t=Date.now(),n=_.useMemo(()=>nP(e.runs,e.all_runs,Date.now()),[e.runs,e.all_runs]),[r,a]=_.useState(""),[l,c]=_.useState(""),[u,f]=_.useState(!1),[h,m]=_.useState(()=>{try{const D=localStorage.getItem("abstractobserver_done_window_v1");return D&&D in Yg?D:Vx}catch{return Vx}}),g=_.useMemo(()=>sP(n.done,h,t),[n.done,h]),y=yf(e.runs_refreshed_at,t),w=n.review.length,k=g.visible.filter(D=>D.failed).length,[b,S]=_.useState(""),[N,R]=_.useState(null),$=D=>`${D.run_id}:${D.wait_key}:${D.since_ms??""}`;_.useEffect(()=>{r&&(n.review.some(D=>$(D)===r)||a(""))},[n,r]);async function A(D,T){a($(D)),c("");try{await e.on_resume_wait(D.run_id,D.wait_key,T)}catch(E){c(`${D.run_id}: ${String((E==null?void 0:E.message)||E||"resume failed")}`),a("")}}function W(D){const T=r===$(D),E=D.column==="review",L=E&&!D.wait_key;return s.jsxs("div",{className:`mc_card ${E?"mc_card_review":""} ${D.failed?"mc_card_failed":""}`,onClick:()=>e.on_open_run(D.run_id),role:"button",tabIndex:0,onKeyDown:M=>{M.key==="Enter"&&M.target===M.currentTarget&&e.on_open_run(D.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:"mc_card_title",title:D.workflow,children:lP(D.workflow)}),(()=>{const M=D.failed?"failed":Zm({status:D.status,paused:D.paused});return s.jsx("span",{className:`mc_status ${wc(M)}`,children:M==="unknown"?"?":M})})()]}),s.jsxs("div",{className:"mc_card_meta",children:[s.jsx("span",{className:"mono",title:D.run_id,children:oP(D.run_id)}),D.is_subrun?s.jsx("span",{title:"This wait lives in a child run of an agent workflow",children:"subrun"}):null,D.tag?s.jsx("span",{className:"mc_pill","data-tag":D.tag,children:D.tag_label}):null,D.archived?s.jsx("span",{className:"mc_pill","data-tag":"archived",title:"This conversation is archived: hidden from chat lists, kept here and in the ledger",children:"Archived"}):null,D.automation_id?s.jsx("button",{type:"button",className:"btn btn_sm",title:"Open this occurrence's automation",onClick:M=>{M.stopPropagation(),e.on_open_automation(D.automation_id)},onKeyDown:M=>M.stopPropagation(),children:"Automation"}):null,D.duration_ms>=0?s.jsx("span",{children:aP(D.duration_ms)}):null,D.tokens_total!==null?s.jsxs("span",{children:[D.tokens_total.toLocaleString()," tk"]}):null,D.tool_calls!==null&&D.tool_calls>0?s.jsxs("span",{children:[D.tool_calls," tools"]}):null]}),D.is_scheduled&&D.schedule_interval?s.jsxs("div",{className:"mc_card_line",children:["every ",D.schedule_interval]}):null,D.failed&&D.error?s.jsx("div",{className:"mc_card_error",title:D.error,children:D.error.length>120?`${D.error.slice(0,118)}…`:D.error}):null,E?s.jsxs("div",{className:"mc_card_review_body",onClick:M=>M.stopPropagation(),onKeyDown:M=>M.stopPropagation(),children:[s.jsx("div",{className:"mc_card_reason",children:D.reason||"Needs a decision"}),D.prompt?s.jsx("div",{className:"mc_card_prompt",title:D.prompt,children:D.prompt.length>240?`${D.prompt.slice(0,238)}…`:D.prompt}):null,D.tool_names.length?s.jsxs("div",{className:"mc_card_tools",title:"Tool calls awaiting your approval",children:[D.tool_names.slice(0,4).map((M,ee)=>s.jsx("span",{className:"mc_tool_chip mono",children:M},`${M}_${ee}`)),D.tool_names.length>4?s.jsxs("span",{className:"mc_tool_chip",children:["+",D.tool_names.length-4," more"]}):null]}):null,D.since_ms!==null?s.jsxs("div",{className:"mc_card_waiting",children:["waiting ",yf(D.since_ms,t)]}):null,L?s.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,L?s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(D.run_id),children:"Open the run →"})}):D.wait_kind==="tool_approval"?s.jsxs("div",{className:"mc_card_actions",children:[s.jsx("button",{className:"btn success",disabled:T,onClick:()=>void A(D,{approved:!0}),children:T?"Resuming…":"Approve"}),s.jsx("button",{className:"btn danger",disabled:T,onClick:()=>void A(D,{approved:!1}),children:"Reject"})]}):s.jsx("div",{className:"mc_card_actions",children:s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(D.run_id),children:"Review & answer →"})})]}):null]},D.run_id)}return s.jsxs("div",{className:"page page_scroll mc_page",children:[s.jsxs("div",{className:"mc_health",children:[s.jsx("span",{className:`mc_led ${e.gateway_connected?"ok":"bad"}`,title:e.gateway_connected?"Gateway connected":"Gateway unreachable"}),e.gateway_connected?null:s.jsx("span",{className:"mc_health_text",children:"gateway unreachable"}),e.runs_refreshed_at===null?s.jsx("span",{className:"mc_health_text muted mc_loading",children:"loading runs…"}):s.jsxs("div",{className:"mc_stats",children:[s.jsxs("div",{className:`mc_stat ${w?"is_hot":""}`,title:"runs blocked on a human decision (Review column)",children:[s.jsx("span",{className:"mc_stat_value",children:w}),s.jsx("span",{className:"mc_stat_label",children:"need you"})]}),s.jsxs("div",{className:`mc_stat ${k?"is_bad":""}`,title:"failed runs in the Done column",children:[s.jsx("span",{className:"mc_stat_value",children:k}),s.jsx("span",{className:"mc_stat_label",children:"failed"})]}),s.jsxs("div",{className:"mc_stat",title:"runs executing or parked listening",children:[s.jsx("span",{className:"mc_stat_value",children:n.working.length}),s.jsx("span",{className:"mc_stat_label",children:"working"})]})]}),s.jsx("span",{className:"mc_spacer"}),s.jsxs("div",{className:"mc_health_side",children:[y?s.jsxs("span",{className:"mc_health_text muted",title:"age of the last runs poll — the board is only as live as this",children:["data ",y," old"]}):null,s.jsx("button",{className:"btn",onClick:e.on_refresh,disabled:e.refreshing,children:e.refreshing?"Refreshing…":"Refresh"})]})]}),l?s.jsx("div",{className:"mc_error",children:l}):null,e.entities.length||e.entities_error?s.jsxs("div",{className:"mc_entities",children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",e.entities_total>e.entities.length?` (${e.entities.length} of ${e.entities_total} — open the entity app for all)`:""]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,s.jsx("div",{className:"mc_entities_row",children:e.entities.map(D=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("a",{className:"mc_entity",href:`${e.entity_app_href}${e.entity_app_href.includes("?")?"&":"?"}entity=${encodeURIComponent(D.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[D.error,D.age_days!==null?`${D.age_days.toFixed(0)} days old`:"",D.last_moment].filter(Boolean).join(" — ")||D.name,children:[s.jsx("span",{className:"mc_entity_name",children:D.name}),(()=>{var U;const T=String(D.live_phase||D.state||"").trim(),E=hP(T,e.phase_graph),L=pP(e.phase_graph).has(E)?E:"other",M=((U=e.phase_graph)==null?void 0:U.initial)??"sleep",ee=/awake|idle/i.test(T)&&E===M,F=T&&T.toLowerCase()!==E?` — wire word: ${T}${ee?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${L}`,title:(D.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+F,children:E})})(),D.last_moment?s.jsx("span",{className:"mc_entity_moment",title:D.last_moment,children:D.last_moment.replace(/_/g," ")}):null,(()=>{if(D.working===!0)return s.jsx("span",{className:"mc_entity_live",title:"busy now (loop mid-day or live visit — store-read, never fabricated)",children:"● busy"});const T=rP(D.last_moment_at,t);return D.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",T!==null?` · ${yf(t-T,t)} ago`:""]}):T===null?null:T<=iP?s.jsx("span",{className:"mc_entity_live",title:`last moment ${yf(t-T,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[yf(t-T,t)," ago"]})})(),D.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${D.live_visit_tokens!==null?`; open visit: ${Gp(D.live_visit_tokens)} tk`:""}${D.spend_warning?`; ${D.spend_warning}`:""}`,children:[Gp(D.tokens_total)," tk",D.live_visit_tokens!==null?` (+${Gp(D.live_visit_tokens)})`:"",D.spend_warning?"*":""]}):null]}),D.open_questions_total||D.open_problems_total||D.lessons_total||D.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":b===D.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>S(b===D.name?"":D.name),children:[D.open_questions_total?`${D.open_questions_total} question${D.open_questions_total>1?"s":""}`:"",D.open_problems_total?`${D.open_problems_total} problem${D.open_problems_total>1?"s":""}`:"",D.lessons_total?`${D.lessons_total} lesson${D.lessons_total>1?"s":""}`:"",D.dreams_brief?`night: ${D.dreams_brief.count} signal${D.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},D.name))}),(()=>{if(!b)return null;const D=e.entities.find(L=>L.name===b);if(!D||!D.open_questions.length&&!D.open_problems.length&&!D.lessons.length&&!D.dreams_brief)return null;const T=e.on_read_diary?async L=>{const M=await e.on_read_diary(D.name,L);R({entity:D.name,entry:(M==null?void 0:M.entry)??M,seq:typeof(M==null?void 0:M.read_recorded_at_seq)=="number"?M.read_recorded_at_seq:null})}:void 0,E=D.open_questions_total-D.open_questions.length+(D.open_problems_total-D.open_problems.length)+(D.lessons_total-D.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[D.open_questions.map((L,M)=>s.jsx(cp,{kind:"question",label:L.title||Yp(L.statement),entryId:L.entry_id,onOpen:T,title:L.statement||L.title},`q_${L.record_id||M}`)),D.open_problems.map((L,M)=>s.jsx(cp,{kind:"problem",label:L.title||Yp(L.statement),entryId:L.entry_id,onOpen:T,title:L.statement||L.title},`p_${L.record_id||M}`)),D.lessons.map((L,M)=>s.jsx(cp,{kind:"lesson",label:L.title||Yp(L.statement),entryId:L.entry_id,onOpen:T,title:L.statement||L.title},`l_${L.record_id||M}`)),D.dreams_brief?s.jsxs("span",{className:"mc_entity_dreams muted",title:"night signals carried by STANDING dreams (the sleep pass's maintenance stream; count = signals, not dreams); felt tones color the content, they never rank it — the entity app renders the full stream",children:["night signals: ",D.dreams_brief.count,D.dreams_brief.dreams?` across ${D.dreams_brief.dreams} dream${D.dreams_brief.dreams>1?"s":""}`:"",D.dreams_brief.kinds.length?` — ${D.dreams_brief.kinds.slice(0,6).join(", ")}${D.dreams_brief.kinds.length>6?` +${D.dreams_brief.kinds.length-6} more`:""}`:"",D.dreams_brief.felt_tones.length?` · felt: ${D.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,E>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",E," more — open the entity app"]}):null]})})()]}):null,N?s.jsx(lc,{open:!0,title:`${N.entity} — diary entry`,onClose:()=>R(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(z=N.entry)!=null&&z.kind?`kind: ${N.entry.kind}`:"",(H=N.entry)!=null&&H.visibility?`visibility: ${N.entry.visibility}`:"",(G=N.entry)!=null&&G.written_at?`written: ${N.entry.written_at}`:"",(re=N.entry)!=null&&re.entry_id?`id: ${N.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",N.entity,"’s stream",N.seq!==null?` (seq ${N.seq})`:""]}),(te=N.entry)!=null&&te.gist?s.jsx("div",{className:"mc_diary_gist",children:String(N.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((Q=N.entry)==null?void 0:Q.text)||"(entry carries no text)")})]})}):null,s.jsx("div",{className:"mc_board",children:Object.keys(qx).map(D=>{const T=D==="done"?g.visible:n[D],E=D==="done"&&!u?T.slice(0,8):T;return s.jsxs(gP,{col:D,title:qx[D],head:s.jsxs(s.Fragment,{children:[D==="done"?s.jsx("select",{className:"mc_window_select",value:h,title:"Show terminal runs from this time window",onClick:L=>L.stopPropagation(),onChange:L=>{const M=L.target.value;m(M),f(!1);try{localStorage.setItem("abstractobserver_done_window_v1",M)}catch{}},children:Object.keys(Yg).map(L=>s.jsx("option",{value:L,children:Kp[L]},L))}):null,s.jsx("span",{className:"mc_column_count",title:D==="done"&&g.hidden_count?`${g.hidden_count} older run(s) outside this window`:void 0,children:T.length})]}),children:[s.jsx("div",{className:"mc_column_hint muted",children:QO[D]}),s.jsxs("div",{className:"mc_column_cards",children:[E.map(L=>W(L)),T.length?null:s.jsx("div",{className:"mc_empty muted",children:e.runs_refreshed_at===null?"loading…":D==="done"&&g.hidden_count?`none in the ${Kp[h]} — ${g.hidden_count} older`:ZO[D]}),D==="done"&&T.length>8&&!u?s.jsxs("button",{className:"btn mc_more",onClick:()=>f(!0),children:["show all ",T.length]}):null,D==="done"&&g.hidden_count&&T.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",g.hidden_count," older outside ",Kp[h]]}):null]})]},D)})})]})}const Im=500,h_="http://127.0.0.1:8080";function Gx(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 wf(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function Jp(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 Xp(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function wP(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 vP(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const u of t){if(!u||typeof u!="object")continue;const f=u.data&&typeof u.data=="object"?u.data:{};if(String(f.nodeType||u.type||"").trim()==="on_flow_start"){n=u;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},a=Array.isArray(r.outputs)?r.outputs:[],l=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},c=[];for(const u of a){if(!u||typeof u!="object")continue;const f=String(u.id||"").trim();if(!f)continue;const h=String(u.type||"").trim();if(h==="execution"||f==="exec-out"||f==="exec")continue;const m=String(u.label||f).trim()||f,g={id:f,label:m,type:h||"unknown"};l&&Object.prototype.hasOwnProperty.call(l,f)&&(g.default=l[f]),c.push(g)}return c}function Zp(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 xP(){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)||h_),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:h_,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 bP(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function kP(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(a,l)=>{const c=String(l??"").trim();c&&(t.some(u=>u.label===a&&u.value===c)||t.push({label:a,value:c}))},r=String(e.display??"").trim().replace(/^\[/,"").replace(/\]$/,"");return n("time",r||e.local_datetime),n("tz",e.timezone),n("country",e.country),n("user",e.user),t}function Kx(e){const t=kP(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 jP(){return typeof window>"u"?"":O$(window.location)}function SP(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${Rs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function NP(){var Zn,tl,Ta,Xl,fu,nl,qs,hu,ho,wi,Zl,mu,Gi,Ql,Ki;const[e,t]=_.useState("board"),[n,r]=_.useState(()=>xP()),a=typeof window<"u"&&((Zn=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Zn.monitor_gpu)===!0,l=typeof window<"u"&&(((tl=window.__ABSTRACT_UI_CONFIG__)==null?void 0:tl.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",c=_.useRef(null),[u,f]=_.useState(""),[h,m]=_.useState(""),[g,y]=_.useState(()=>jP()),[w,k]=_.useState(""),[b,S]=_.useState(""),[N,R]=_.useState(""),[$,A]=_.useState("{}"),[W]=_.useState(()=>SP()),[z,H]=_.useState(null),[G,re]=_.useState(!1),[te,Q]=_.useState(""),[D,T]=_.useState(!1),[E,L]=_.useState(""),[M,ee]=_.useState(!1),F=GS({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((Ta=window.__ABSTRACT_UI_CONFIG__)==null?void 0:Ta.gateway_url)||h_,onStatusChange:v=>qo(v)}),[U,K]=_.useState(null),[O,V]=_.useState(null),[J,le]=_.useState(!1),[ie,_e]=_.useState(null),[pe,ye]=_.useState("once"),[Ne,Be]=_.useState(""),[Ue,ut]=_.useState(xg),[De,Qe]=_.useState([]),[at,Ke]=_.useState(null),[ce,oe]=_.useState(!1),[Ae,he]=_.useState([]),Ce=_.useRef(new IA(Rs)),[Te,Ye]=_.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[rt,ht]=v1("abstractobserver",{legacyKey:"abstractobserver_settings"}),[lt,St]=_.useState(!1),[Zt,On]=_.useState(!1),[Bt,yn]=_.useState([]),[zn,Tn]=_.useState([]),[wn,Pn]=_.useState([]),[xn,Ss]=_.useState(!1),[Kn,Ns]=_.useState(null),[jr,Dn]=_.useState([]),[fe,Se]=_.useState(0),[et,Ze]=_.useState(""),ct=_.useRef(!1),mt=_.useRef(0),It=_.useRef(0),[Ct,Qt]=_.useState(!1),[jt,en]=_.useState([]),[Gt,Ut]=_.useState([]),[Pt,Dt]=_.useState({}),[We,ln]=_.useState(!1),[pt,rn]=_.useState(!1),[gt,Bn]=_.useState(!1),[cn,Gs]=_.useState([]),[ls,qr]=_.useState([]),hr=_.useRef(0),ni=_.useRef(null);ni.current||(ni.current=new Fv(v=>window.setTimeout(v,40),v=>Gs(C=>C.concat(v))));const si=_.useRef(null);si.current||(si.current=new Fv(v=>window.setTimeout(v,40),v=>qr(C=>C.concat(v))));const Ps=_.useRef({scanned:0,found:null}),[me,mr]=_.useState(null),[na,_r]=_.useState(""),[Sr,Hr]=_.useState(!1),dt=_.useRef(null),[fn,Ds]=_.useState({}),[Vr,cs]=_.useState({}),[Da,Fa]=_.useState(!1),[za,Fn]=_.useState(""),[pr,Hn]=_.useState(!0),[sa,ri]=_.useState(""),[Mn,Fs]=_.useState(!1),[ps,Ks]=_.useState(!1),[gs,So]=_.useState(6),[ra,un]=_.useState("standard"),[No,kc]=_.useState(""),[Ba,ys]=_.useState(""),[Nr,Cr]=_.useState(!1),[ia,gr]=_.useState(!1),[Cs,yr]=_.useState("pause"),[Er,Ys]=_.useState(""),[Ci,us]=_.useState(""),[$r,Co]=_.useState(""),wr=_.useRef(null),aa=_.useRef(null),[jc,Ei]=_.useState(!1),Js=_.useRef(null),[Yu,Xs]=_.useState(""),[oa,Zs]=_.useState(""),[Ua,ii]=_.useState(""),[Eo,ai]=_.useState(""),[q,ue]=_.useState(!1),[je,$e]=_.useState("idle"),[Ee,Ve]=_.useState([]),[yt,_t]=_.useState(null),vt=_.useRef(null),[qt,Yt]=_.useState(!1),[ws,Ft]=_.useState(""),[dn,En]=_.useState(""),[vn,ts]=_.useState(""),[Qs,Gr]=_.useState([]),[$i,$o]=_.useState(!1),[oh,Sc]=_.useState(""),[wl,Nc]=_.useState(""),[Cc,Ec]=_.useState(!1),[lh,Wa]=_.useState(""),Ju=_.useMemo(()=>{if(!Ee.length)return"";try{return JSON.stringify(Ee.map(v=>({role:v.role,content:v.content,ts:v.ts})))}catch{return"1"}},[Ee]),Xu=_.useMemo(()=>Ee.length?vn?Ju!==vn:!0:!1,[Ju,Ee.length,vn]),Zu=_.useMemo(()=>Qs.map(v=>{const C=String(v.title||"").trim()||`Chat ${String(v.thread_id||"").slice(0,8)}`,I=String(v.created_at||"").trim(),B=I?I.replace("T"," ").slice(0,19):"",Z=String(v.run_id||"").trim()?String(v.run_id).slice(0,8):"",Y=[C,B&&`(${B})`,Z&&`run ${Z}`].filter(Boolean).join(" • ");return{value:String(v.thread_id||""),label:Y}}),[Qs]);_.useEffect(()=>{a&&pM()},[a]),_.useEffect(()=>{if(!a)return;const v=c.current;v&&(v.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[a,n.auth_token,n.gateway_auth_mode]);const[T_,Qu]=_.useState([]),[vl,an]=_.useState(""),[ed,M_]=_.useState(""),[$c,R_]=_.useState("all"),[td,L_]=_.useState("status"),[er,la]=_.useState("ledger"),ch=mw(rp.md),I_=mw(`${rp.sm}, ${rp.short}`),ca=E$({is_drawer:ch,page:e}),qa=ca.open,xl=ca.set_open,[nd,uh]=Of("observe_runs"),dh=ca.toggle_ref,fh=ca.sidebar_ref,sd=_.useRef(null),[Ao,hh]=_.useState(()=>lv(typeof window<"u"?window.location.hash:"")),[O_,mh]=_.useState(""),[rd,Ac]=_.useState(""),[oi,Ai]=_.useState(""),[To,ua]=_.useState(null),[Tc,Mc]=_.useState({}),[Rc,Ha]=_.useState(!1),[id,Mo]=_.useState(""),[Ro,P_]=_.useState(!1),[ad,D_]=_.useState(!1),[F_,Lc]=_.useState(()=>Date.now()),[ns,li]=_.useState(""),[_h,bl]=_.useState({}),[ph,Ic]=_.useState({}),Va=_.useRef([]),Ar=_.useRef(null),da=_.useRef(""),Ti=_.useRef({}),fa=_.useRef({}),Ga=_.useRef({}),Ka=_.useRef(new Set),[Mi,Ya]=_.useState([]),ci=_.useRef(""),ha=_.useRef({}),Ri=_.useRef(null),vs=_.useRef(null),ma=_.useRef(0),Ja=_.useRef({}),kl=_.useRef(!1),_a=_.useRef(new Set),[Oc,jl]=_.useState(""),[xs,ui]=_.useState(""),Tr=_.useRef(""),gh=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[Sl,Lo]=_.useState("activity"),[od,ld]=_.useState([]),[cd,Sn]=_.useState(0),[ud,Nl]=_.useState(0),[Cl,dd]=_.useState({}),[fd,Io]=_.useState({}),[Pc,Xa]=_.useState(!1),[yh,wh]=_.useState(""),[El,vh]=_.useState(""),[pa,Oo]=_.useState("all"),[Po,Dc]=_.useState(""),[ga,hd]=_.useState([]),[Fc,xh]=_.useState("all"),[Do,z_]=_.useState("type"),[Fo,ya]=_.useState("newest"),[Li,Za]=_.useState(""),[tr,Ii]=_.useState(""),[di,$l]=_.useState(""),[Al,md]=_.useState(0),[Mr,Qa]=_.useState(()=>gh()),[zo,Bo]=_.useState(!1),[Tl,Uo]=_.useState(""),[wa,mn]=_.useState(""),[Ht,Kr]=_.useState(""),[ds,nr]=_.useState("text"),[eo,va]=_.useState(null),[sr,to]=_.useState(!1),[_d,Ml]=_.useState(""),[Rl,pd]=_.useState(""),[Oi,Ll]=_.useState(""),[zc,gd]=_.useState(!1),[B_,Pi]=_.useState(""),[Di,Wo]=_.useState("run_ledger"),[Bc,Uc]=_.useState(""),[Rr,rr]=_.useState([]),[no,Yr]=_.useState(""),[Fi,xa]=_.useState(!1),[bh,Il]=_.useState(""),Pe=_.useMemo(()=>new Cp({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]),on=_.useMemo(()=>new JA(Pe.automations_client(),GA(Pe,Rs,Rt)),[Pe]),zs=_.useSyncExternalStore(v=>on.subscribe(v),()=>on.state),$n=EA(n.gateway_url),ir=$n?()=>{window.open($n,"_blank","noopener,noreferrer")}:void 0,kh=Ib(e==="launch"&&pe==="automate"&&M?MA(Ue):null,on.preview_schedule);_.useEffect(()=>{e==="launch"&&pe==="automate"&&M&&on.load_email_status()},[e,pe,M,on]),_.useEffect(()=>{const v=()=>{const C=AA(window.location.hash);if(C){if(C.page==="run"){y(C.run_id),hh(lv(window.location.hash));return}C.page==="launch"&&ye(C.mode),t(C.page)}};return v(),window.addEventListener("hashchange",v),()=>window.removeEventListener("hashchange",v)},[]);const jh=_.useMemo(()=>{const v={};for(const C of zs.items)v[C.automation_id]=C.title;return v},[zs.items]),yd=_.useMemo(()=>iM(),[]),[wd,vd]=_.useState(kv),Ol=_.useRef(0);function Sh(){const v=++Ol.current;vd(kv),aM(Pe).then(C=>{v===Ol.current&&vd(C)})}const zi=_.useMemo(()=>n.worker_url.trim()?new mR({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Wc=_.useMemo(()=>dR(Pe.fetch_gateway,Cg),[Pe]),Bs=cn.length?cn[cn.length-1].record:null,Wt=_.useMemo(()=>go(Bs),[Bs]),ss=_.useMemo(()=>{const v=N.trim();if(!z||!v||String(z.bundle_id||"").trim()&&String(z.bundle_id||"").trim()!==v)return null;const C=Array.isArray(z.entrypoints)?z.entrypoints:[];if(!C.length)return null;const I=b.trim();if(I)return C.find(Z=>String(Z.flow_id||"").trim()===I)||null;if(C.length===1)return C[0];const B=String(z.default_entrypoint||"").trim();return B&&C.find(Z=>String(Z.flow_id||"").trim()===B)||null},[z,N,b]),qc=_.useMemo(()=>{const v=ss==null?void 0:ss.inputs;return Array.isArray(v)?v:[]},[ss]),xd=_.useMemo(()=>vP(To),[To]),fi=_.useMemo(()=>qc.length?qc:xd,[qc,xd]),so=_.useMemo(()=>{const v=typeof(me==null?void 0:me.workflow_id)=="string"?String(me.workflow_id):"",C=Gx(v);if(C&&z&&String(z.bundle_id||"").trim()===C.bundle_id){const Z=(Array.isArray(z.entrypoints)?z.entrypoints:[]).find(Y=>String((Y==null?void 0:Y.flow_id)||"").trim()===C.flow_id);if(Z&&Z.node_index&&typeof Z.node_index=="object")return Z.node_index}const I=ss==null?void 0:ss.node_index;return I&&typeof I=="object"?I:{}},[me,z,ss]);_.useEffect(()=>{bP(n)},[n]),_.useEffect(()=>()=>{Ri.current&&Ri.current.abort(),vs.current&&vs.current.abort(),wr.current&&window.clearTimeout(wr.current),aa.current&&window.clearTimeout(aa.current),Ar.current&&window.clearTimeout(Ar.current),Js.current&&window.clearTimeout(Js.current)},[]);const Et=_.useMemo(()=>{const v=$.trim();if(!v)return{};try{const C=JSON.parse(v);return typeof C!="object"||C===null||Array.isArray(C)?null:C}catch{return null}},[$]),Hc=typeof(Et==null?void 0:Et.prompt)=="string"?String(Et.prompt):"",ba=typeof(Et==null?void 0:Et.provider)=="string"?String(Et.provider):"",bd=typeof(Et==null?void 0:Et.model)=="string"?String(Et.model):"",kd=typeof(Et==null?void 0:Et.workspace_root)=="string"?String(Et.workspace_root):"",jd=_.useMemo(()=>{const v=Et==null?void 0:Et.workspace;return v&&typeof v=="object"&&!Array.isArray(v)?v:null},[Et]),Sd=fi.length>0&&!!N.trim(),ka=v=>{const C=String(v||"").trim().toLowerCase();return C==="object"||C==="memory"||C==="assertion"||C==="assertions"||C==="any"};_.useEffect(()=>{cs({})},[N,b]),_.useEffect(()=>{Et!==null&&Ds(v=>{const C={};for(const I of fi){if(!I||typeof I!="object")continue;const B=String(I.id||"").trim();if(!B)continue;const Z=String(I.type||"").trim();if(!ka(Z))continue;if(String(Vr[B]||"").trim()){C[B]=typeof v[B]=="string"?v[B]:"";continue}const X=Et==null?void 0:Et[B];X===void 0?C[B]="":C[B]=oA(X)}return C})},[fi,Et,Vr]);const Yn=Ne?{kind:"default",interface:Ne}:N.trim()&&b.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:b.trim()}:null,ja=jA(Yn),Bi=Array.isArray(Et==null?void 0:Et.skills)?Et.skills.map(v=>String(v||"").trim()).filter(Boolean):[],Lr=_.useMemo(()=>{const v={};for(const C of Bt){const I=String(C.workflow_id||"").trim(),B=String(C.label||"").trim();I&&B&&(v[I]=B)}return v},[Bt]),Ir=Bb({interfaceId:null,defaultInterface:Lu,request:(v,C)=>Pe.get_gateway_json(v,C.signal),enabled:M,reloadKey:Bt}),Sa=_.useMemo(()=>{const v=new Set;for(const C of Array.isArray(Gt)?Gt:[]){const I=String((C==null?void 0:C.name)||"").trim();I&&v.add(I)}return Array.from(v).sort()},[Gt]),Nd=_.useMemo(()=>{const v=[];for(const C of Array.isArray(Gt)?Gt:[]){const I=String((C==null?void 0:C.name)||"").trim();if(!I)continue;const B=String((C==null?void 0:C.display_name)||"").trim();v.push({name:I,display_name:B||void 0})}return v},[Gt]),Vc=_.useMemo(()=>{const v=new Set;for(const C of jt||[]){if(!C||typeof C!="object")continue;const I=String(C.name||"").trim();I&&v.add(I)}return Array.from(v).sort()},[jt]),hi=_.useMemo(()=>{const v=n.maintenance_ai_provider.trim();if(!v)return{models:[],error:""};const C=Pt[v];return C?{models:(Array.isArray(C.models)?C.models:[]).map(B=>String(B||"").trim()).filter(Boolean),error:String(C.error||"")}:{models:[],error:""}},[Pt,n.maintenance_ai_provider]),mi=n.maintenance_ai_provider.trim(),Gc=!!(mi&&M&&!Object.prototype.hasOwnProperty.call(Pt,mi));_.useEffect(()=>{const v=ba.trim();if(!v||Pt[v]||ha.current[v])return;ha.current[v]=!0;let C=!1;return(async()=>{try{const B=await Pe.discovery_provider_models(v);if(C)return;const Z=Array.isArray(B==null?void 0:B.models)?B.models:[],Y=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";Dt(X=>({...X,[v]:{models:Z,error:Y||void 0}}))}catch(B){if(C)return;Dt(Z=>({...Z,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete ha.current[v]}})(),()=>{C=!0}},[ba,Pt,Pe]),_.useEffect(()=>{const v=n.maintenance_ai_provider.trim();if(!v||!M||Pt[v]||ha.current[v])return;ha.current[v]=!0;let C=!1;return(async()=>{try{const B=await Pe.discovery_provider_models(v);if(C)return;const Z=Array.isArray(B==null?void 0:B.models)?B.models:[],Y=typeof(B==null?void 0:B.error)=="string"?String(B.error):"";Dt(X=>({...X,[v]:{models:Z,error:Y||void 0}}))}catch(B){if(C)return;Dt(Z=>({...Z,[v]:{models:[],error:String((B==null?void 0:B.message)||B||"Failed to load models")}}))}finally{delete ha.current[v]}})(),()=>{C=!0}},[n.maintenance_ai_provider,Pt,Pe,M]);function Un(v,C){const I=String(v||"").trim();if(!I)return;let B={};try{const Z=JSON.parse($||"{}");typeof Z=="object"&&Z!==null&&!Array.isArray(Z)&&(B=Z)}catch{B={}}if(C==null){delete B[I],A(JSON.stringify(B,null,2));return}if(typeof C=="string")C?B[I]=C:delete B[I];else if(Array.isArray(C)){const Z=C.map(Y=>Y).filter(Y=>Y!=null);Z.length?B[I]=Z:delete B[I]}else B[I]=C;A(JSON.stringify(B,null,2))}async function Pl(v){const C=String(v||"").trim();if(!C)return Q("Missing bundle_id"),null;Q(""),re(!0);try{const I=await Pe.get_bundle(C);return H(I),zt({ts:Rt(),kind:"info",title:`Loaded bundle ${C}`}),I}catch(I){return H(null),Q(String((I==null?void 0:I.message)||I||"Failed to load bundle")),null}finally{re(!1)}}function Kc(v){const C=[],I=Array.isArray(v==null?void 0:v.items)?v.items:[];for(const B of I){const Z=String((B==null?void 0:B.bundle_id)||"").trim();if(!Z)continue;const Y=Array.isArray(B==null?void 0:B.entrypoints)?B.entrypoints:[];if(Y.length)for(const X of Y){const se=String((X==null?void 0:X.flow_id)||"").trim();if(!se||(X==null?void 0:X.deprecated)===!0)continue;const Re=`${Z}:${se}`,be=String((X==null?void 0:X.name)||"").trim(),ke=be?`${Z} · ${be}`:`${Z} · ${se}`,Me=String((X==null?void 0:X.description)||"").trim(),Ge=(Array.isArray(X==null?void 0:X.interfaces)?X.interfaces:[]).some(Xe=>String(Xe||"").trim().length>0),nt=Array.isArray(X==null?void 0:X.agent_default_interfaces)?X.agent_default_interfaces.map(Xe=>String(Xe||"").trim()).filter(Boolean):[];C.push({workflow_id:Re,bundle_id:Z,bundle_ref:String((B==null?void 0:B.bundle_ref)||"").trim(),flow_id:se,label:ke,description:Me||void 0,has_interface:Ge,agent_default_interfaces:nt})}}return C.sort((B,Z)=>B.label.localeCompare(Z.label)),C}async function fs(v=Pe,C){if(ct.current&&!(C!=null&&C.force))return;ct.current=!0;const I=Xr.current;Ss(!0);try{const B=ke=>ke.map(PA).filter(Me=>!!Me.run_id),[Z,Y,X]=await Promise.all([v.list_runs({limit:200,root_only:!0,include_metrics:!0}),v.list_runs({limit:500,root_only:!1,include_metrics:!0}),v.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0})]);if(I!==Xr.current)return;const se=DA(Array.isArray(Z==null?void 0:Z.items)?Z.items:[],Array.isArray(X==null?void 0:X.items)?X.items:[]),Re=Array.isArray(Y==null?void 0:Y.items)?Y.items:[],be=B(se).filter(ke=>!String(ke.parent_run_id||"").trim()||ke.role==="occurrence");Tn(be),Pn(B(Re).filter(ke=>!!ke.run_id)),Ns(Date.now()),It.current=0,mt.current=0}catch(B){const Z=String((B==null?void 0:B.message)||B||"");if(zt({ts:Rt(),kind:"error",title:"Refresh runs failed",preview:At(Z)}),(/\b40[13]\b/.test(Z)||/unauthorized|forbidden/i.test(Z))&&F.refresh().catch(()=>{}),/\b429\b/.test(Z)||/too many requests/i.test(Z)){const Y=Math.min(12e4,Math.max(15e3,It.current*2||15e3));It.current=Y,mt.current=Date.now()+Y,zt({ts:Rt(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(Y/1e3)}s`})}}finally{ct.current=!1,Ss(!1)}}async function Jr(v){var se,Re,be;const C=Xr.current;ee(!0),Dt({});const[I,,B,Z,Y]=await Promise.allSettled([v.list_bundles(),fs(v),v.discovery_tools(),v.discovery_providers({include_models:!1}),v.discovery_capabilities()]);if(C!==Xr.current)return;if(I.status==="rejected"&&B.status==="rejected"&&Z.status==="rejected"){ee(!1),L(Zp(I.reason,n)),zt({ts:Rt(),kind:"error",title:"Discovery failed",preview:At(String(I.reason||""))});return}Ye(Y.status==="fulfilled"?FA(Y.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((se=Y.reason)==null?void 0:se.message)||Y.reason)}`});let X=0;if(I.status==="fulfilled"){const ke=Kc(I.value);X=ke.length,yn(ke)}else yn([]),zt({ts:Rt(),kind:"error",title:"Discovery bundles failed",preview:At(String(I.reason||""))});if(B.status==="fulfilled"){const ke=Array.isArray((Re=B.value)==null?void 0:Re.items)?B.value.items:[];en(ke)}else en([]),zt({ts:Rt(),kind:"error",title:"Discovery tools failed",preview:At(String(B.reason||""))});if(Z.status==="fulfilled"){const ke=Array.isArray((be=Z.value)==null?void 0:be.items)?Z.value.items:[];Ut(ke)}else Ut([]),zt({ts:Rt(),kind:"error",title:"Discovery providers failed",preview:At(String(Z.reason||""))});zt({ts:Rt(),kind:"info",title:"Gateway discovery loaded",preview:At(`workflows: ${X}`)})}async function Ui(v){var C,I;L(""),ee(!1),T(!0);try{if(!(v!=null&&v.prefer_direct)&&(await F.refresh(),ro.current))return;const B=String(n.auth_token||"").trim();if(!B){v!=null&&v.open_modal_if_needed&&F.openModal();return}const Z=String(n.gateway_url||"").trim();if(Z){const X=Z.toLowerCase();if(!X.startsWith("http://")&&!X.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:"&&X.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 Re=new URL(Z),be=String(((I=window==null?void 0:window.location)==null?void 0:I.hostname)||"").trim().toLowerCase(),ke=String(Re.hostname||"").trim().toLowerCase(),Me=qe=>qe==="localhost"||qe==="127.0.0.1"||qe==="::1";if(Me(ke)&&be&&!Me(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(se){throw new Error(String((se==null?void 0:se.message)||se||"Invalid Gateway URL"))}}const Y=new Cp({base_url:Z,auth_token:B});await Y.list_bundles(),r(X=>({...X,gateway_auth_mode:"direct"})),await Jr(Y)}catch(B){L(Zp(B,n))}finally{T(!1)}}const ro=_.useRef(!1),Xr=_.useRef(0),Dl=_.useRef(!1);function qo(v){var I,B,Z;K(v);const C=!!(v&&v.has_session&&((I=v.gateway)!=null&&I.ok));if(ro.current=C,C){if(Dl.current=!1,M&&n.gateway_auth_mode==="direct")return;const Y=String(((Z=(B=v==null?void 0:v.gateway)==null?void 0:B.principal)==null?void 0:Z.user_id)||"").trim();if(r(X=>({...X,gateway_auth_mode:"session",auth_token:"",gateway_user:Y||X.gateway_user})),M&&n.gateway_auth_mode==="session")return;L(""),T(!0),Jr(new Cp({base_url:"",auth_token:""})).catch(X=>L(Zp(X,n))).finally(()=>T(!1));return}v&&!v.has_session&&(n.gateway_auth_mode==="session"&&An({keep_session:!0}),String(n.auth_token||"").trim()&&!M&&!Dl.current&&(Dl.current=!0,Ui({prefer_direct:!0})))}async function Nh(){if(!(Ct||D)){Qt(!0);try{await Pe.reload_bundles();const v=await Pe.list_bundles(),C=Kc(v);yn(C),zt({ts:Rt(),kind:"info",title:"Bundles reloaded",preview:At(`workflows: ${C.length}`)})}catch(v){const C=String((v==null?void 0:v.message)||v||"Bundle reload failed");zt({ts:Rt(),kind:"error",title:"Bundle reload failed",preview:At(C),data:{error:C}})}finally{Qt(!1)}}}async function Cd(v){if(Sr||D||!M)return;const C=v;if(C){Hr(!0),an("");try{const I=await Pe.upload_bundle(C,{overwrite:!1,reload:!0});zt({ts:Rt(),kind:"info",title:"Bundle uploaded",preview:At(String((I==null?void 0:I.bundle_ref)||""))});const B=await Pe.list_bundles(),Z=Kc(B);yn(Z)}catch(I){const B=String((I==null?void 0:I.message)||I||"Upload failed");an(B),zt({ts:Rt(),kind:"error",title:"Upload .flow failed",preview:At(B),data:{error:B}})}finally{Hr(!1);try{dt.current&&(dt.current.value="")}catch{}}}}function An(v){Xr.current+=1,v!=null&&v.keep_session||(F.signOut().catch(()=>{}),ro.current=!1),Go(),R(""),S(""),Ai(""),H(null),Q(""),re(!1),yn([]),Tn([]),Pn([]),Ns(null),Dn([]),en([]),Ut([]),Dt({}),L(""),ee(!1),K(null),r(C=>({...C,auth_token:""})),zt({ts:Rt(),kind:"info",title:"Gateway disconnected"})}async function Fl(v){const C=String(v??"");C&&bn(await sT(C)?"Copied to clipboard":tT,2)}_.useEffect(()=>{const v=u.trim();if(!We||!v)return;let C=!1;const I=async()=>{if(!(mt.current>Date.now()))try{const Z=await Pe.get_run(v);C||mr(Z)}catch{}};I();const B=window.setInterval(I,2e3);return()=>{C=!0,window.clearInterval(B)}},[We,u,Pe]),_.useEffect(()=>{if(!M)return;let v=null,C=!1,I=!1;const B=X=>{C||(v!==null&&window.clearTimeout(v),v=window.setTimeout(()=>void Z(),X))},Z=async()=>{if(I)return;const X=mt.current-Date.now();if(X>0){B(X+500);return}I=!0;const se=Date.now();try{await fs(Pe)}finally{I=!1;const Re=Date.now()-se,be=document.visibilityState==="hidden"?3e4:5e3;B(Math.max(be,Re*3))}},Y=()=>{document.visibilityState==="visible"&&Z()};return Z(),document.addEventListener("visibilitychange",Y),()=>{C=!0,v!==null&&window.clearTimeout(v),document.removeEventListener("visibilitychange",Y)}},[M,Pe]);const[Ed,zl]=_.useState(null);_.useEffect(()=>{if(!M){zl(null);return}let v=!1;return(async()=>{try{const C=await Pe.get_entity_phases_spec();if(v)return;const I=cP(C);if(zl(I),I)try{const B=localStorage.getItem("abstractobserver_phase_graph_id_v1"),Z=B?JSON.parse(B):null;Z&&Z.sha256&&I.sha256&&Z.sha256!==I.sha256&&Z.version===I.version&&zt({ts:Rt(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:At(`v${I.version}: ${String(Z.sha256).slice(0,12)}… -> ${String(I.sha256).slice(0,12)}…`),data:{prev:Z,now:{sha256:I.sha256,version:I.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:I.sha256,version:I.version}))}catch{}}catch(C){if(!v){zl(null);const I=String((C==null?void 0:C.message)||C||"");/404|not found/i.test(I)||zt({ts:Rt(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:At(I),data:{error:I}})}}})(),()=>{v=!0}},[M]),_.useEffect(()=>{if(!M){Dn([]),Ze("");return}let v=!1,C=null;const I=async()=>{if(!(mt.current>Date.now())){try{const B=await Pe.list_entities(),Z=B.entities.map(X=>String((X==null?void 0:X.name)||(X==null?void 0:X.slug)||"").trim()).filter(Boolean).slice(0,12),Y=await Promise.all(Z.map(async X=>{var se,Re;try{const[be,ke]=await Promise.all([Pe.get_entity_card(X),Pe.get_entity_cognition(X).catch(()=>null)]),Me=be!=null&&be.state&&typeof be.state=="object"?be.state:null,qe=Array.isArray(be==null?void 0:be.moments)?be.moments:[],Ge=qe.length?qe[qe.length-1]:null,nt=(se=ke==null?void 0:ke.spend)==null?void 0:se.lifetime,Xe=(Re=ke==null?void 0:ke.spend)==null?void 0:Re.live_visit,Kt=Array.isArray(ke==null?void 0:ke.warnings)?ke.warnings.map(He=>String(He||"")).filter(Boolean):[],Ot=XO(be);return{name:X,state:String((Me==null?void 0:Me.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((Ge==null?void 0:Ge.kind)||"").trim(),last_moment_at:String((Ge==null?void 0:Ge.at)||"").trim(),working:typeof(ke==null?void 0:ke.working)=="boolean"?ke.working:null,tokens_total:typeof(nt==null?void 0:nt.tokens_total)=="number"?nt.tokens_total:null,live_visit_tokens:typeof(Xe==null?void 0:Xe.tokens_total)=="number"?Xe.tokens_total:null,spend_warning:Kt.join(" | "),live_phase:typeof(ke==null?void 0:ke.phase)=="string"?ke.phase:"",open_questions:Ot.questions,open_questions_total:Ot.questions_total,open_problems:Ot.problems,open_problems_total:Ot.problems_total,lessons:Ot.lessons,lessons_total:Ot.lessons_total,dreams_brief:JO(be),error:""}}catch(be){return{name:X,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||(Dn(Y),Se(B.entities.length),Ze(""))}catch(B){if(!v){Dn([]);const Z=String((B==null?void 0:B.message)||B||"");Ze(/404|not found/i.test(Z)?"":Z)}}v||(C=window.setTimeout(()=>void I(),3e4))}};return I(),()=>{v=!0,C!==null&&window.clearTimeout(C)}},[M,Pe]);async function Yc(v,C,I){const B=String(C||"").trim();if(!v||!B)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Pe.submit_command({command_id:Rs(),run_id:v,type:"resume",payload:{wait_key:B,payload:I||{}},client_id:"web_pwa"}),zt({ts:Rt(),kind:"info",title:"Board resume submitted",preview:At(`run ${v} · wait ${B}`),data:{run_id:v,wait_key:B}}),fs(Pe,{force:!0}),window.setTimeout(()=>void fs(Pe,{force:!0}),1200)}const Wi=_.useMemo(()=>{const v=me==null?void 0:me.session_id;return typeof v=="string"?v.trim():v==null?"":String(v||"").trim()},[me]),io=_.useMemo(()=>{const v=String(Wi||"").trim();return v||String(W||"").trim()},[Wi,W]);_.useEffect(()=>{M||ai("")},[M]);const[Nn,rs]=z0(),is=B0(M?Pe:null,M),Or=U0({gateway:M?Pe:null,session_id:io,prefs:Nn,on_error:ai,on_transcript:v=>{const C=String(v||"").trim();C&&(Zs(I=>{const B=String(I||"");return B.trim()?`${B.trimEnd()}
|
|
158
|
-
${C}`:C}),window.setTimeout(()=>{var I;return(I=vt.current)==null?void 0:I.focus()},0))}}),Bl=_.useMemo(()=>{for(let v=Ee.length-1;v>=0;v-=1){const C=Ee[v];if(C.role==="assistant")return C.local_error?null:{key:String(C.id||C.ts||""),text:String(C.content||"")}}return null},[Ee]);W0(Or,Nn.read_aloud===!0,Bl);function Ul(v,C){try{const I=URL.createObjectURL(v),B=document.createElement("a");B.href=I,B.download=C||"download",B.rel="noreferrer",document.body.appendChild(B),B.click(),document.body.removeChild(B),window.setTimeout(()=>URL.revokeObjectURL(I),5e3)}catch{}}async function U_(){const v=rd.trim();if(!v){bn("This run recorded no workspace",2);return}try{const C=await fetch(M$,{method:"POST",headers:{"Content-Type":"application/json",...Cg()},body:JSON.stringify({path:v})}),I=await C.json().catch(()=>({}));C.ok&&(I!=null&&I.ok)?bn(`Opened ${String(I.path||v)}`,2):bn(String((I==null?void 0:I.error)||`Folder reveal failed (${C.status})`),3)}catch(C){bn(String((C==null?void 0:C.message)||C||"Folder reveal failed"),3)}}async function Es(v){const C=String((v==null?void 0:v.run_id)||"").trim(),I=String((v==null?void 0:v.artifact_id)||"").trim();if(!C||!I){bn("Artifact download needs a run id",3);return}const B=t_(v)||I;try{const Z=await Pe.download_run_artifact_content(C,I,{access:"preview"});Ul(Z,dv(B)),bn("Downloaded artifact",2)}catch(Z){bn(String((Z==null?void 0:Z.message)||Z||"Download failed"),3)}}async function $d(v){const C=String((v==null?void 0:v.run_id)||"").trim(),I=String((v==null?void 0:v.artifact_id)||"").trim();if(!C||!I){bn("Artifact preview needs a run id",3);return}const B=t_(v),Z=String((v==null?void 0:v.content_type)||"").trim().toLowerCase(),Y=Tf(v);if(Uo(B||I),mn(""),Ml(""),nr(Y),va(v),Bo(!0),Ht&&(URL.revokeObjectURL(Ht),Kr("")),Y==="binary"){mn(`(Binary artifact: ${Z||"unknown"}; download to view.)`);return}if(Y==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>15e5){mn(`(Text artifact is ${v.size_bytes.toLocaleString()} bytes; download to view.)`);return}to(!0);try{const X=await Pe.download_run_artifact_content(C,I,{access:"preview"});if(Y==="text"){const se=await X.text(),Re=e_(v,se),be=Re==="json"?15e5:Re==="markdown"?25e4:Re==="html"?3e5:22e3;mn(se.length>be&&Re!=="text"?`${cc(v.size_bytes??se.length)} ${Re.toUpperCase()} artifact. Download to inspect it.`:se.length>be?`${se.slice(0,Math.max(0,be-1))}…`:se)}else Kr(URL.createObjectURL(X))}catch(X){Ml(String((X==null?void 0:X.message)||X||"Preview failed"))}finally{to(!1)}}_.useEffect(()=>()=>{Ht&&URL.revokeObjectURL(Ht)},[Ht]);async function Ad(v){const C=String(v.artifact_id||"").trim(),I=String(v.run_id||"").trim(),B=Tf(v);if(!I||!C)return{artifact_id:C,kind:B,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(B==="binary")return{artifact_id:C,kind:B,render_kind:"",text:`Preview unavailable for ${v.content_type||v.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(B==="text"&&typeof v.size_bytes=="number"&&v.size_bytes>5e5)return{artifact_id:C,kind:B,render_kind:"",text:`${cc(v.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const Z=await Pe.download_run_artifact_content(I,C,{access:"preview"});if(B==="text"){const Y=await Z.text(),X=e_(v,Y),se=X==="json"?5e5:X==="markdown"?12e4:X==="html"?3e5:8e3;return{artifact_id:C,kind:B,render_kind:X,text:Y.length>se&&X!=="text"?`${cc(v.size_bytes??Y.length)} ${X.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:Y.length>se?`${Y.slice(0,Math.max(0,se-1))}…`:Y,url:"",loading:!1,error:""}}return{artifact_id:C,kind:B,render_kind:"",text:"",url:URL.createObjectURL(Z),loading:!1,error:""}}catch(Z){return{artifact_id:C,kind:B,render_kind:"",text:"",url:"",loading:!1,error:String((Z==null?void 0:Z.message)||Z||"Preview failed")}}}async function Td(v){if(Mr.url&&URL.revokeObjectURL(Mr.url),!v){Qa(gh());return}const C=String(v.artifact_id||"").trim(),I=Tf(v);Qa({artifact_id:C,kind:I,render_kind:"",text:"",url:"",loading:!0,error:""}),Qa(await Ad(v))}function zt(v){const C=String(v.id||"").trim()||Rs();Qu(I=>[{...v,id:C},...I].slice(0,800))}function bn(v,C){Co(v),aa.current&&window.clearTimeout(aa.current),Ei(!1),window.requestAnimationFrame(()=>Ei(!0)),aa.current=window.setTimeout(()=>{Ei(!1),aa.current=null},1500),wr.current&&(window.clearTimeout(wr.current),wr.current=null),C>0&&(wr.current=window.setTimeout(()=>{Co(""),wr.current=null},Math.max(1,C)*1e3))}function hs(v,C){const I=String(v||"").trim(),B=String(C||"").trim();if(!B)return"";const Z=I?String(Ti.current[I]||"").trim():"";return Z?`${Z}::${B}`:B}function Wl(v,C,I){const B=String(v||"").trim(),Z=String(C||"").trim(),Y=String(I||"").trim();if(!B||!Z||!Y)return;const X=hs(B,Z);X&&(Ti.current[Y]=X,fa.current[Y]=B,Ga.current[Y]={parent_run_id:B,parent_node_id:Z},Ka.current.has(Y)||(Ka.current.add(Y),Ya(se=>se.includes(Y)?se:[...se,Y])))}function Ho(v){const C=String(v||"").trim();if(!C)return;const I=Date.now(),B=da.current;da.current=C,Lc(I),bl(Z=>{const Y={};for(const[be,ke]of Object.entries(Z))typeof ke=="number"&&ke>I&&(Y[be]=ke);Y[C]=Math.max(Y[C]||0,I+2e3),B&&B!==C&&(Y[B]=Math.max(Y[B]||0,I+2e3));const X=Object.keys(Y);if(X.length<=200)return Y;const se=X.sort((be,ke)=>(Y[ke]||0)-(Y[be]||0)).slice(0,200),Re={};for(const be of se)Re[be]=Y[be]||0;return Re}),Ic(Z=>{if(typeof Z[C]=="number")return Z;const Y={...Z,[C]:I};if(Va.current.push(C),Va.current.length>8e3){const X=Va.current.splice(0,1500);for(const se of X)delete Y[se]}return Y}),Ar.current&&window.clearTimeout(Ar.current),Ar.current=window.setTimeout(()=>{const Z=Date.now();bl(Y=>{const X={};for(const[se,Re]of Object.entries(Y))typeof Re=="number"&&Re>Z&&(X[se]=Re);return X}),Lc(Z),Ar.current=null},2200)}function Md(v,C){var Xe,Kt,Ot;const I=String(C||"").trim()||u.trim();hr.current=v.cursor,(Xe=ni.current)==null||Xe.push({cursor:v.cursor,record:v.record}),I&&_a.current.add(`${I}:${v.cursor}`);const B=bm(v.record),Z=B&&B.name?wf(B.name):"",Y=v.record,X=typeof(Y==null?void 0:Y.node_id)=="string"?Y.node_id:"",se=typeof(Y==null?void 0:Y.status)=="string"?Y.status:"",Re=typeof((Kt=Y==null?void 0:Y.effect)==null?void 0:Kt.type)=="string"?Y.effect.type:"",be=typeof(Y==null?void 0:Y.run_id)=="string"?Y.run_id:"",ke=be||I;if(Z==="abstract.status"&&ke===I){const{text:He,duration:Nt}=vu(B==null?void 0:B.payload);bn(He,Nt)}const Me=X?hs(ke,X):"";if(se==="waiting"){const He=go(Y);if(String((He==null?void 0:He.reason)||"").trim()==="subworkflow"){const kn=typeof((Ot=He==null?void 0:He.details)==null?void 0:Ot.sub_run_id)=="string"?String(He.details.sub_run_id):"";kn&&X&&Wl(ke,X,kn)}}if(X&&(Ho(hs(ke,X)),se==="waiting"||se==="running")){const He=hs(ke,X);He&&(da.current=He,li(He))}let qe="step",Ge=Me||X||"(node?)",nt="";if(B&&B.name&&Xp(B.name))qe=Z==="abstract.message"?"message":"event",Ge=Z||B.name,nt=At(Z==="abstract.steer_seen"?Jp(B==null?void 0:B.payload):vu(B==null?void 0:B.payload).text);else if(Y!=null&&Y.error)qe="error",Ge="error",nt=At(dr(Y.error,360));else if(se==="waiting"){const He=go(Y),Nt=String((He==null?void 0:He.reason)||"").trim();nt=At(Nt?`waiting • ${Nt}`:"waiting")}else Y!=null&&Y.result?nt=At(dr(Y.result,360)):Re?nt=At(Re):nt=At(Fm(Y));zt({id:`step:${be||I||"?"}:${v.cursor}`,ts:String((Y==null?void 0:Y.ended_at)||(Y==null?void 0:Y.started_at)||Rt()),kind:qe,title:Ge,preview:nt,data:Y,cursor:v.cursor,run_id:be||I||void 0,node_id:Me||X,status:se,effect_type:Re,emit_name:Z||(B==null?void 0:B.name)||void 0})}function Ch(v,C){var nt,Xe,Kt;ma.current=Math.max(ma.current,C.cursor);const I=`${v}:${C.cursor}`;if(!!_a.current.has(I))return;_a.current.add(I),(nt=si.current)==null||nt.push({run_id:v,cursor:C.cursor,record:C.record});const Z=bm(C.record),Y=Z&&Z.name?wf(Z.name):"",X=C.record,se=typeof(X==null?void 0:X.node_id)=="string"?X.node_id:"",Re=se?hs(v,se):"",be=typeof(X==null?void 0:X.status)=="string"?X.status:"",ke=typeof((Xe=X==null?void 0:X.effect)==null?void 0:Xe.type)=="string"?X.effect.type:"";if(be==="waiting"){const Ot=go(X);if(String((Ot==null?void 0:Ot.reason)||"").trim()==="subworkflow"){const Nt=typeof((Kt=Ot==null?void 0:Ot.details)==null?void 0:Kt.sub_run_id)=="string"?String(Ot.details.sub_run_id):"";Nt&&se&&Wl(v,se,Nt),Nt&&Tr.current.trim()===String(v||"").trim()&&(Tr.current=Nt,ui(Nt))}}if(se&&(Ho(hs(v,se)),be==="waiting"||be==="running")){const Ot=hs(v,se);Ot&&(da.current=Ot,li(Ot))}if((be==="completed"||be==="failed")&&Tr.current.trim()===String(v||"").trim()){const Ot=String(fa.current[String(v||"").trim()]||"").trim();Ot&&Ot!==u.trim()?(Tr.current=Ot,ui(Ot)):(Tr.current="",ui(""))}if(Y==="abstract.status"&&v===u.trim()){const{text:Ot,duration:He}=vu(Z==null?void 0:Z.payload);bn(Ot,He)}let Me="step",qe=Re||se||"(node?)",Ge="";if(Z&&Z.name&&Xp(Z.name))Me=Y==="abstract.message"?"message":"event",qe=`subrun • ${Y||Z.name}`,Ge=At(Y==="abstract.steer_seen"?Jp(Z==null?void 0:Z.payload):vu(Z==null?void 0:Z.payload).text);else if(X!=null&&X.error)Me="error",qe="error",Ge=At(dr(X.error,360));else if(be==="waiting"){const Ot=go(X),He=String((Ot==null?void 0:Ot.reason)||"").trim();Ge=At(He?`waiting • ${He}`:"waiting")}else X!=null&&X.result?Ge=At(dr(X.result,360)):ke?Ge=At(ke):Ge=At(Fm(X));zt({id:`step:${v}:${C.cursor}`,ts:String((X==null?void 0:X.ended_at)||(X==null?void 0:X.started_at)||Rt()),kind:Me,title:qe,preview:Ge,data:X,cursor:C.cursor,run_id:v,node_id:Re||se,status:be,effect_type:ke,emit_name:Y||(Z==null?void 0:Z.name)||""})}function Eh(v,C){var Xe,Kt,Ot;const I=String(v||"").trim();if(!I)return;const B=`${I}:${C.cursor}`;if(!!_a.current.has(B))return;_a.current.add(B),(Xe=si.current)==null||Xe.push({run_id:I,cursor:C.cursor,record:C.record});const Y=bm(C.record),X=Y&&Y.name?wf(Y.name):"",se=C.record,Re=typeof(se==null?void 0:se.node_id)=="string"?se.node_id:"",be=Re?hs(I,Re):"",ke=typeof(se==null?void 0:se.status)=="string"?se.status:"",Me=typeof((Kt=se==null?void 0:se.effect)==null?void 0:Kt.type)=="string"?se.effect.type:"";if(ke==="waiting"){const He=go(se);if(String((He==null?void 0:He.reason)||"").trim()==="subworkflow"){const kn=typeof((Ot=He==null?void 0:He.details)==null?void 0:Ot.sub_run_id)=="string"?String(He.details.sub_run_id):"";kn&&Re&&Wl(I,Re,kn)}}if(Re&&(Ho(hs(I,Re)),ke==="waiting"||ke==="running")){const He=hs(I,Re);He&&(da.current=He,li(He))}if(X==="abstract.status"&&I===u.trim()){const{text:He,duration:Nt}=vu(Y==null?void 0:Y.payload);bn(He,Nt)}let qe="step",Ge=be||Re||"(node?)",nt="";if(Y&&Y.name&&Xp(Y.name))qe=X==="abstract.message"?"message":"event",Ge=`subrun • ${X||Y.name}`,nt=At(X==="abstract.steer_seen"?Jp(Y==null?void 0:Y.payload):vu(Y==null?void 0:Y.payload).text);else if(se!=null&&se.error)qe="error",Ge="error",nt=At(dr(se.error,360));else if(ke==="waiting"){const He=go(se),Nt=String((He==null?void 0:He.reason)||"").trim();nt=At(Nt?`waiting • ${Nt}`:"waiting")}else se!=null&&se.result?nt=At(dr(se.result,360)):Me?nt=At(Me):nt=At(Fm(se));zt({id:`step:${I}:${C.cursor}`,ts:String((se==null?void 0:se.ended_at)||(se==null?void 0:se.started_at)||Rt()),kind:qe,title:Ge,preview:nt,data:se,cursor:C.cursor,run_id:I,node_id:be||Re,status:ke,effect_type:Me,emit_name:X||(Y==null?void 0:Y.name)||""})}async function Rd(v,C){var B,Z;let I=C.after;for(;;){if((B=C.signal)!=null&&B.aborted)return I;const Y=await Pe.get_ledger(v,{after:I,limit:200,signal:C.signal});if((Z=C.signal)!=null&&Z.aborted)return I;const X=Array.isArray(Y.items)?Y.items:[];if(!X.length)return hr.current=I,I;const se=I;for(let Re=0;Re<X.length;Re++){const be=X[Re];Md({cursor:se+Re+1,record:be},v)}I=typeof Y.next_after=="number"?Y.next_after:I}}async function ql(v){var Y,X,se,Re;const C=String(v||"").trim();an(""),rn(!0),ln(!1),(Y=ni.current)==null||Y.reset(),(X=si.current)==null||X.reset(),Ps.current={scanned:0,found:null},Gs([]),hr.current=0,qr([]),_a.current=new Set,Qu([]),mh(""),Co(""),mr(null),Xs(""),Ac(""),li(""),da.current="",bl({}),Ic({}),Va.current=[],Lc(Date.now()),Ti.current=C?{[C]:""}:{},fa.current={},Ga.current={},Ka.current=new Set,Ya([]),ci.current="",Tr.current="",ui(""),Ja.current={},Ar.current&&window.clearTimeout(Ar.current),Ar.current=null,Js.current&&window.clearTimeout(Js.current),Js.current=null,Ri.current&&Ri.current.abort(),vs.current&&vs.current.abort(),vs.current=null,ma.current=0,jl("");const I=new AbortController;Ri.current=I;let B=!1;try{let be="",ke="";try{const Me=await Pe.get_run(C);mr(Me);const qe=typeof(Me==null?void 0:Me.workflow_id)=="string"?String(Me.workflow_id):"",Ge=Gx(qe);Ge&&(be=Ge.bundle_id,ke=Ge.flow_id)}catch{}try{const Me=await Pe.get_run_input_data(C);typeof(Me==null?void 0:Me.bundle_id)=="string"&&(be=String(Me.bundle_id||"").trim()||be),typeof(Me==null?void 0:Me.flow_id)=="string"&&(ke=String(Me.flow_id||"").trim()||ke);const qe=Me&&typeof Me.input_data=="object"&&Me.input_data&&!Array.isArray(Me.input_data)?Me.input_data:null;qe&&A(JSON.stringify(qe,null,2));const Ge=Me==null?void 0:Me.workspace,nt=typeof(Ge==null?void 0:Ge.workspace_root)=="string"?String(Ge.workspace_root).trim():"";Ac(nt)}catch{Ac("")}be&&ke&&(R(be),S(ke),Ai(ke),await Pl(be)),await Rd(C,{after:0,signal:I.signal});try{const Me=await Pe.get_run_history_bundle(C,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),qe=Me&&typeof Me=="object"?Me.ledgers:null,nt=(qe&&typeof qe=="object"?Object.keys(qe):[]).map(Xe=>String(Xe||"").trim()).filter(Boolean).filter(Xe=>Xe!==C);if(nt.length){for(const Xe of nt)Ka.current.add(Xe);Ya(Xe=>Array.from(new Set([...Xe,...nt])));try{const Xe=typeof((se=qe==null?void 0:qe[C])==null?void 0:se.total)=="number"?Number(qe[C].total):0;let Kt="",Ot=-1;for(const He of nt){const Nt=typeof((Re=qe==null?void 0:qe[He])==null?void 0:Re.total)=="number"?Number(qe[He].total):0;Nt>Ot&&(Kt=He,Ot=Nt)}Kt&&Ot>Math.max(Xe*3,Xe+20)&&(Tr.current=Kt,ui(Kt))}catch{}}}catch{}ln(!0),zt({ts:Rt(),kind:"info",title:`Attached to run ${C}`,data:{run_id:C}}),B=!0}catch(be){const ke=String((be==null?void 0:be.message)||be||"unknown error");an(ke),zt({ts:Rt(),kind:"error",title:"Connection error",preview:At(ke),data:{error:ke}}),ln(!1)}finally{rn(!1)}if(!B||I.signal.aborted)return;(async()=>{let be=250;for(;!I.signal.aborted;){try{const ke=await Rd(C,{after:hr.current,signal:I.signal});await Pe.stream_ledger(C,{after:ke,on_step:Me=>Md(Me,C),signal:I.signal})}catch(ke){if(I.signal.aborted)break;const Me=String((ke==null?void 0:ke.message)||ke||"stream error");zt({ts:Rt(),kind:"error",title:"Ledger stream error (will retry)",preview:At(Me),data:{error:Me}})}if(I.signal.aborted)break;await new Promise(ke=>setTimeout(ke,be)),be=Math.min(5e3,Math.floor(be*1.6))}})()}async function $h(){const v=Yn,C=(v==null?void 0:v.kind)==="bundle"?v.flow_id:(v==null?void 0:v.kind)==="default"?"@default":"",I=(v==null?void 0:v.kind)==="bundle"?v.bundle_id:"";if(!v){const B="Select a workflow first (Launch → pick a workflow).";return an(B),B}an(""),rn(!0);try{let B={};const Z=$.trim();if(Z)try{if(B=JSON.parse(Z),typeof B!="object"||B===null||Array.isArray(B))throw new Error("input_data must be a JSON object")}catch(Me){const qe=`Invalid input_data JSON: ${String((Me==null?void 0:Me.message)||Me)}`;return an(qe),qe}for(const[Me,qe]of Object.entries(B)){if(typeof qe!="string")continue;const Ge=qe.trim();Ge?B[Me]=Ge:delete B[Me]}const Y=(fi||[]).find(Me=>Me&&typeof Me=="object"&&Me.id==="prompt"),X=Y&&typeof Y=="object"&&Object.prototype.hasOwnProperty.call(Y,"default"),se=B==null?void 0:B.prompt,Re=typeof se=="string"?se.trim():"";if(Y&&!X&&!Re){const Me="Missing required input_data.prompt";return an(Me),Me}const be=B.workspace&&typeof B.workspace=="object"?B.workspace:null;delete B.workspace;const ke=await Pe.start_run(C,B,{...be?{workspace:be}:{},...I?{bundle_id:I}:{},...v.kind==="default"?{interface:v.interface}:{},session_id:String(W||"").trim()||null});return m(ke),f(ke),_r(""),await ql(ke),fs(),null}catch(B){const Z=String((B==null?void 0:B.message)||B||"start failed");return an(Z),Z}finally{rn(!1)}}async function Ah(){if(Qe([]),Ke(null),!Te.available){Qe([Te.reason]);return}const v=OA(Ue,{choice:Yn,bundle_ref_for:C=>{var I;return((I=Bt.find(B=>B.bundle_id===C))==null?void 0:I.bundle_ref)||""},input_data:Et,email_usable:on.email_usable},Ce.current);if(!v.ok){Qe(v.errors);return}oe(!0);try{const C=await Pe.automations_client().createAutomation(v.body);Ce.current.reset(),he([]),ut(xg),zt({ts:Rt(),kind:"info",title:"Automation created",preview:At(`${v.body.title} · ${C.automation_id}`)}),t("automations"),await on.refresh(),await on.select(C.automation_id)}catch(C){const I=(C&&typeof C=="object"&&typeof C.code=="string"?C:null)||{status:0,code:"client_error",message:String((C==null?void 0:C.message)||C||"Create failed")};Ke(I)}finally{oe(!1)}}async function Th(){if(_r(""),pe==="automate"){await Ah();return}const v=await $h();if(v){_r(v);return}la("ledger"),t("observe")}async function Vo(v){if(Un("skills",void 0),!!v){if(v.kind==="default"){Be(v.interface),R(""),S(""),H(null);return}Be(""),R(v.bundle_id),S(v.flow_id),Ai(v.flow_id),await Pl(v.bundle_id)}}async function Ld(v){const[C,I]=await Promise.all([Pe.get_run(v),Pe.get_run_input_data(v)]),B=HA(C,I);await Vo(B.choice),A(JSON.stringify(B.input_data,null,2)),ut(B.form),he([`Recreating the legacy schedule ${sn(v,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...B.notes]),Ce.current.reset(),ye("automate"),t("launch")}async function _i(v,C){const I=String(v||"").trim();if(!I)return;if(pt){bn(`Still attaching — retry in a moment (${sn(I,14)})`,2500);return}an(""),k("");const B=String((C==null?void 0:C.root_run_id)||I).trim()||I;m(B),f(I),await ql(I)}_.useEffect(()=>{const v=String(g||"").trim();if(!v)return;let C=!1;return(async()=>{try{if(M||await Ui({open_modal_if_needed:!0}),C)return;la("ledger"),t("observe");const I=await Pe.find_run(v);if(C)return;if(I===null){Go(),k(v);return}await _i(v),du()}catch(I){C||an(String((I==null?void 0:I.message)||I||"Failed to attach run from URL"))}finally{C||y("")}})(),()=>{C=!0}},[g]);function Go(){var v,C;Ri.current&&Ri.current.abort(),Ri.current=null,vs.current&&vs.current.abort(),vs.current=null,ma.current=0,jl(""),f(""),m(""),Ti.current={},fa.current={},Ga.current={},Ka.current=new Set,Ya([]),ci.current="",Tr.current="",ui(""),Ja.current={},Xs(""),Ar.current&&window.clearTimeout(Ar.current),Ar.current=null,Js.current&&window.clearTimeout(Js.current),Js.current=null,ln(!1),rn(!1),Bn(!1),hr.current=0,(v=ni.current)==null||v.reset(),(C=si.current)==null||C.reset(),Ps.current={scanned:0,found:null},Gs([]),qr([]),_a.current=new Set,mr(null),Qu([]),li(""),da.current="",bl({}),Ic({}),Va.current=[],Lc(Date.now()),bn("",-1),an(""),Ve([]),_t(null),Zs(""),ii(""),ue(!1),Yt(!1),Ft(""),En(""),ts(""),Gr([]),$o(!1),Sc(""),Nc(""),Ec(!1),Wa("")}_.useEffect(()=>{Ve([]),_t(null),Zs(""),ii(""),ue(!1),Yt(!1),Ft(""),En(""),ts(""),Gr([]),$o(!1),Sc(""),Nc(""),Ec(!1),Wa("")},[u]),_.useEffect(()=>{er==="chat"&&u.trim()&&M&&Fd()},[er,u,M,me==null?void 0:me.workflow_id]);async function Id(v,C,I){const B=String(v||"").trim();if(!B)return an("Missing run_id"),"Missing run_id";an("");try{const Z={},Y=String((I==null?void 0:I.reason)||"").trim();Y&&(Z.reason=Y),await Pe.submit_command({command_id:Rs(),run_id:B,type:C,payload:Z,client_id:"web_pwa"}),zt({ts:Rt(),kind:"info",title:`${C} submitted`,preview:Y?`reason: ${Y}`:"",data:{run_id:B,type:C,reason:Y}});try{if(B===u.trim()){const X=await Pe.get_run(B);mr(X)}}catch{}return fs(Pe,{force:!0}),window.setTimeout(()=>void fs(Pe,{force:!0}),900),window.setTimeout(()=>void fs(Pe,{force:!0}),2400),null}catch(Z){const Y=String((Z==null?void 0:Z.message)||Z||`${C} failed`);return an(Y),Y}}async function Hl(v,C){return Id(u.trim(),v,C)}async function Od(v,C="Stopped from AbstractObserver"){const I=String(v||"").trim();if(!I||!window.confirm(`Cancel run ${sn(I,24)}?`))return;await Id(I,"cancel",{reason:C})||bn("Cancel submitted",2)}async function Mh(){var I;const v=u.trim();if(!v){an("Select a run first.");return}if(!M){an("Connect to the gateway first.");return}if(gt)return;const C=String(((I=me==null?void 0:me.waiting)==null?void 0:I.reason)||"").trim().toLowerCase()||String(Jn||"").trim().toLowerCase();if(!or||Vn||Ea||Ca.toLowerCase()!=="waiting"||C!=="until"){an("This run is not a scheduled wait that can be triggered now.");return}an(""),Bn(!0);try{const B={payload:{mode:"run_now",requested_at:Rt()}},Z=String($s||"").trim();Z&&(B.wait_key=Z),await Pe.submit_command({command_id:Rs(),run_id:v,type:"resume",payload:B,client_id:"web_pwa"}),zt({ts:Rt(),kind:"info",title:"Scheduled run triggered",preview:At(`run ${v}`),data:{run_id:v,until:pi||null}});try{const Y=await Pe.get_run(v);mr(Y)}catch{}}catch(B){an(String((B==null?void 0:B.message)||B||"Failed to trigger scheduled run"))}finally{Bn(!1)}}async function Rh(v){const C=u.trim();if(!C)return an("Missing run_id"),"Missing run_id";if(Mn)return"Schedule update already in progress";const I=String(v.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(I)){const Z="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return ri(Z),Z}ri(""),an(""),Fs(!0),rn(!0);try{await Pe.submit_command({command_id:Rs(),run_id:C,type:"update_schedule",payload:{interval:I,apply_immediately:v.apply_immediately!==!1},client_id:"web_pwa"}),zt({ts:Rt(),kind:"info",title:"Schedule updated",preview:At(`interval: ${I}`),data:{interval:I},run_id:C});try{const Z=await Pe.get_run(C);mr(Z)}catch{}return null}catch(Z){const Y=String((Z==null?void 0:Z.message)||Z||"update_schedule failed");return ri(Y),an(Y),Y}finally{rn(!1),Fs(!1)}}async function Lh(v){const C=u.trim();if(!C)return an("Missing run_id"),"Missing run_id";if(Nr)return"Compaction already in progress";const I=typeof(v==null?void 0:v.preserve_recent)=="number"?v.preserve_recent:gs,B=Math.max(0,Math.min(500,Math.floor(Number.isFinite(I)?I:6))),Z=(v==null?void 0:v.compression_mode)||ra,Y=String((v==null?void 0:v.focus)??No??"").trim();ys(""),an(""),Cr(!0),rn(!0);try{const X={preserve_recent:B,compression_mode:Z};return Y&&(X.focus=Y),await Pe.submit_command({command_id:Rs(),run_id:C,type:"compact_memory",payload:X,client_id:"web_pwa"}),zt({ts:Rt(),kind:"info",title:"Compaction requested",preview:At(`mode: ${Z} • preserve_recent: ${B}`),data:X,run_id:C}),null}catch(X){const se=String((X==null?void 0:X.message)||X||"compact_memory failed");return ys(se),an(se),se}finally{rn(!1),Cr(!1)}}async function Pd(){const v=u.trim();if(!v){ii("Select a run first.");return}if(!M){ii("Connect to the gateway first.");return}const C=oa.trim();if(!C||q)return;if(Or.voice_ptt_busy){ai("Wait for transcription to finish.");return}ii(""),ai(""),ue(!0);const B={id:`local:${Rs()}`,role:"user",content:C,ts:Rt()};Ve(Z=>[...Z,B]),Zs("");try{const Z=$$(Ee,B),Y=n.maintenance_ai_provider.trim(),X=n.maintenance_ai_model.trim(),se=await Pe.run_chat(v,{provider:Y||void 0,model:X||void 0,include_subruns:!0,messages:Z}),Re=String((se==null?void 0:se.answer)||"").trim()||"(empty response)",be=String((se==null?void 0:se.generated_at)||"").trim()||Rt();_t((se==null?void 0:se.history)??null),Ve(ke=>[...ke,{id:`local:${Rs()}`,role:"assistant",content:Re,ts:be}])}catch(Z){const Y=dA(Z);ii(Y),Ve(X=>[...X,{id:`local:${Rs()}`,role:"assistant",content:`(error: ${Y})`,ts:Rt(),local_error:!0}])}finally{ue(!1)}}function Ih(v){const C=String(v.id||v.ts||"").trim(),I=String(v.content||"").trim();!C||!I||(ai(""),Or.toggle_tts(C,I))}function Oh(v){const C=String(v.id||v.ts||"").trim(),I=Or.tts_playback;return!C||!I.key||I.key!==C?"idle":I.status}function Dd(v){if(!Ee.length)return;const C=u.trim(),I=C?`Run ${C}`:"Chat",B=NC(Ee.map(Z=>({role:Z.role,content:Z.content,ts:Z.ts})),{heading:I});if(v==="download"){const Z=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),Y=`abstractobserver-chat-${dv(C||"run")}-${Z}.md`;CC({filename:Y,text:B,mime:"text/markdown;charset=utf-8"});return}(async()=>{const Z=await yl(B);$e(Z?"copied":"failed"),window.setTimeout(()=>$e("idle"),900)})()}async function Fd(){const v=typeof(me==null?void 0:me.workflow_id)=="string"?String(me.workflow_id).trim():"";if(!v){Gr([]);return}if(M&&!$i){Sc(""),$o(!0);try{const C=await Pe.list_runs({limit:200,workflow_id:v,root_only:!0}),I=Array.isArray(C==null?void 0:C.items)?C.items:[],B=[];for(const be of I){const ke=typeof(be==null?void 0:be.run_id)=="string"?String(be.run_id).trim():"";if(!ke)continue;const Me=typeof(be==null?void 0:be.ledger_len)=="number"?Number(be.ledger_len):0;B.push({run_id:ke,ledger_len:Number.isFinite(Me)?Me:0})}if(!B.length){Gr([]);return}const Z=400,Y=B.map(be=>({run_id:be.run_id,after:Math.max(0,(be.ledger_len||0)-Z)})),X=await Pe.get_ledger_batch({runs:Y,limit:Z}),se=[],Re=new Set;for(const be of B){const ke=X!=null&&X.runs&&typeof X.runs=="object"?X.runs[be.run_id]:null,Me=Array.isArray(ke==null?void 0:ke.items)?ke.items:[];for(const qe of Me){const Ge=qe==null?void 0:qe.effect;if(!Ge||typeof Ge!="object"||String(Ge.type||"")!=="emit_event")continue;const nt=Ge.payload;if(!nt||typeof nt!="object"||String(nt.name||"")!=="abstract.chat.thread")continue;const Xe=nt.payload;if(!Xe||typeof Xe!="object")continue;const Kt=typeof Xe.thread_id=="string"?String(Xe.thread_id).trim():"";if(!Kt||Re.has(Kt))continue;Re.add(Kt);const Ot=typeof Xe.created_at=="string"?String(Xe.created_at):"",He=typeof Xe.title=="string"?String(Xe.title):"",Nt=typeof Xe.workflow_id=="string"?String(Xe.workflow_id):v,kn=typeof Xe.run_id=="string"?String(Xe.run_id):be.run_id,Cn=typeof Xe.provider=="string"?String(Xe.provider):"",bs=typeof Xe.model=="string"?String(Xe.model):"",Fr=typeof Xe.message_count=="number"?Number(Xe.message_count):null,Qr=Xe.chat_artifact,sl=Qr&&typeof Qr=="object"&&typeof Qr.$artifact=="string"?String(Qr.$artifact):"";sl&&se.push({thread_id:Kt,created_at:Ot,title:He||`Chat ${Kt.slice(0,8)}`,run_id:kn,workflow_id:Nt,message_count:Fr,provider:Cn,model:bs,artifact_id:sl})}}se.sort((be,ke)=>String(ke.created_at||"").localeCompare(String(be.created_at||""))),Gr(se)}catch(C){Sc(String((C==null?void 0:C.message)||C||"Failed to load saved discussions"))}finally{$o(!1)}}}async function Ph(){const v=u.trim();if(!v){Ft("Select a run first.");return}if(!M){Ft("Connect to the gateway first.");return}if(Ee.length&&!qt){Ft(""),Yt(!0);try{const C=n.maintenance_ai_provider.trim(),I=n.maintenance_ai_model.trim(),B=await Pe.save_chat_thread(v,{provider:C||void 0,model:I||void 0,include_subruns:!0,messages:Ee.map(X=>({role:X.role,content:X.content,ts:X.ts}))}),Z=typeof(B==null?void 0:B.created_at)=="string"?String(B.created_at):Rt();En(Z);try{const X=JSON.stringify(Ee.map(se=>({role:se.role,content:se.content,ts:se.ts})));ts(X)}catch{ts("1")}typeof(B==null?void 0:B.thread_id)=="string"&&String(B.thread_id).trim()&&Nc(String(B.thread_id).trim());const Y=!!(B!=null&&B.duplicate);bn(Y?"Already saved":"Saved discussion",2),await Fd()}catch(C){Ft(String((C==null?void 0:C.message)||C||"Failed to save discussion"))}finally{Yt(!1)}}}async function W_(){const v=String(wl||"").trim();if(!v)return;const C=Qs.find(Z=>String(Z.thread_id||"").trim()===v)||null;if(!C){Wa("Saved discussion not found (refresh list).");return}if(!M){Wa("Connect to the gateway first.");return}if(Cc)return;const I=Ee.length>0,B=(()=>{if(!I)return!1;if(!vn)return!0;try{return JSON.stringify(Ee.map(Y=>({role:Y.role,content:Y.content,ts:Y.ts})))!==vn}catch{return!0}})();if(!(I&&B&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Wa(""),Ec(!0);try{const Y=await(await Pe.download_run_artifact_content(C.run_id,C.artifact_id)).text(),X=JSON.parse(Y),se=Array.isArray(X==null?void 0:X.messages)?X.messages:[],Re=typeof(X==null?void 0:X.created_at)=="string"?String(X.created_at):String(C.created_at||""),be=[];for(let ke=0;ke<se.length;ke++){const Me=se[ke];if(!Me||typeof Me!="object")continue;const qe=String(Me.role||"").trim()==="assistant"?"assistant":"user",Ge=typeof Me.content=="string"?String(Me.content):"";if(!Ge.trim())continue;const nt=typeof Me.ts=="string"?String(Me.ts):Re||Rt();be.push({id:`thread:${v}:${ke}`,role:qe,content:Ge.trim(),ts:nt})}Ve(be),_t(null),Zs(""),ii(""),Ft(""),En(Re||"");try{const ke=JSON.stringify(be.map(Me=>({role:Me.role,content:Me.content,ts:Me.ts})));ts(ke)}catch{ts("1")}bn("Loaded discussion",2)}catch(Z){Wa(String((Z==null?void 0:Z.message)||Z||"Failed to load saved discussion"))}finally{Ec(!1)}}}async function Jc(v){const C=u.trim(),I=String((Wt==null?void 0:Wt.wait_key)||"").trim();if(!C||!I){an("No active wait to resume");return}if(String((Wt==null?void 0:Wt.reason)||"").trim()==="subworkflow"){an("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}an(""),Bn(!0);try{await Pe.submit_command({command_id:Rs(),run_id:C,type:"resume",payload:{wait_key:I,payload:v||{}},client_id:"web_pwa"}),zt({ts:Rt(),kind:"info",title:"Resume submitted",preview:At(`wait_key: ${I}`),data:{wait_key:I,payload:v||{}}}),Xs(I);try{const B=await Pe.get_run(C);mr(B)}catch{}fs(Pe,{force:!0}),window.setTimeout(()=>void fs(Pe,{force:!0}),900),window.setTimeout(()=>void fs(Pe,{force:!0}),2400),Js.current&&window.clearTimeout(Js.current),Js.current=window.setTimeout(()=>{Xs(B=>B===I?"":B)},2e3)}catch(B){an(String((B==null?void 0:B.message)||B||"resume failed"))}finally{Bn(!1)}}async function Dh(v){if(!zi){an("No worker configured");return}if(!gt){an(""),Bn(!0);try{const C=[];for(const I of v){const B=await zi.call_tool(I);C.push(B)}await Jc({mode:"executed",results:C})}finally{Bn(!1)}}}const Na=_.useMemo(()=>sh(Wt),[Wt]),$s=String((Wt==null?void 0:Wt.wait_key)||"").trim(),Jn=String((Wt==null?void 0:Wt.reason)||"").trim(),pi=typeof(Wt==null?void 0:Wt.until)=="string"?String(Wt.until):"",Ca=typeof(me==null?void 0:me.status)=="string"?String(me.status):"",Ea=!!(me!=null&&me.paused),Vn=Ca==="completed"||Ca==="failed"||Ca==="cancelled",zd=Jn==="until"&&!!pi,ao=!Vn&&UM(Bs)&&(!!$s||zd),Fh=Jn==="user",Xc=Jn==="event"?wf(wP($s)):"",zh=Jn==="event"&&Xc==="abstract.ask",Bd=Na.length>0,oo=ao&&$s&&(Fh||zh||Bd)&&Yu!==$s&&e!=="board",qi=typeof((Xl=Wt==null?void 0:Wt.details)==null?void 0:Xl.sub_run_id)=="string"?String(Wt.details.sub_run_id):"",lo={run_id:u.trim(),workflow_id:typeof(me==null?void 0:me.workflow_id)=="string"?String(me.workflow_id):null,status:Ca,created_at:typeof(me==null?void 0:me.created_at)=="string"?String(me.created_at):null,updated_at:typeof(me==null?void 0:me.updated_at)=="string"?String(me.updated_at):null,session_id:typeof(me==null?void 0:me.session_id)=="string"?String(me.session_id):null,current_node:typeof(me==null?void 0:me.current_node)=="string"?String(me.current_node):null},Bh=cn.slice(-10).map(v=>{var C,I,B,Z,Y,X;return{cursor:v.cursor,node_id:String(((C=v.record)==null?void 0:C.node_id)||"").trim(),status:String(((I=v.record)==null?void 0:I.status)||"").trim(),effect_type:String(((Z=(B=v.record)==null?void 0:B.effect)==null?void 0:Z.type)||"").trim(),ts:String(((Y=v.record)==null?void 0:Y.ended_at)||((X=v.record)==null?void 0:X.started_at)||"").trim(),summary:ok(v.record)}}),Ud=Sy(Wt,Na),Uh=sk(Wt,Na),Wd=rk(Wt,Et),co=Wd.text,Wh=Wd.runtime_metadata,Zc=String((Wt==null?void 0:Wt.prompt)||"").trim(),Us=CM(Et,6),Ws=!!(Zc&&ek(Zc)),Qc=!!(Zc&&!Ws),qh=Qc?"Question from workflow":co&&co!==Zc?"Closest prior user request":"Request context",Hh=AM(Et,$),Vh=!!$.trim(),ar=me!=null&&me.schedule&&typeof me.schedule=="object"?me.schedule:null,$a=typeof(ar==null?void 0:ar.interval)=="string"?String(ar.interval).trim():"",Gh=typeof(ar==null?void 0:ar.share_context)=="boolean"?!!ar.share_context:null,eu=typeof(ar==null?void 0:ar.repeat_count)=="number"?Number(ar.repeat_count):null,or=!!(me!=null&&me.is_scheduled)||!!ar,tu=or&&!!$a,nu=Ca==="running"&&!Ea?"Pause":"Resume",su=or?Ea?"resume":"pause":nu==="Pause"?"pause":"resume",Kh=or?!u.trim()||pt||gt||Vn:!u.trim()||pt||gt||Vn||su==="resume"&&!Ea,qd=u.trim()?Vn?"The schedule has ended.":null:"No run selected.",ru=or&&!Ea&&!Vn&&!pt&&!gt&&Ca.toLowerCase()==="waiting"&&(String(((fu=me==null?void 0:me.waiting)==null?void 0:fu.reason)||"").trim().toLowerCase()==="until"||Jn==="until")&&!!String(pi||"").trim(),vr=(nl=me==null?void 0:me.limits)==null?void 0:nl.tokens,Ko=typeof(vr==null?void 0:vr.pct)=="number"?Number(vr.pct):null,iu=vr==null?void 0:vr.estimated_used,Hd=(vr==null?void 0:vr.max_input_tokens)??(vr==null?void 0:vr.max_tokens),Hi=_.useMemo(()=>{const v=Ps.current;cn.length<v.scanned&&(v.scanned=0,v.found=null);for(let C=v.scanned;C<cn.length;C++){const I=cn[C],B=I==null?void 0:I.record;if(!B)continue;const Z=bm(B);if((Z&&Z.name?wf(Z.name):"")!=="abstract.summary")continue;const X=Z!=null&&Z.payload&&typeof Z.payload=="object"?Z.payload:{},se=typeof(X==null?void 0:X.text)=="string"?String(X.text):"";se.trim()&&(v.found={cursor:I.cursor,ts:String((B==null?void 0:B.ended_at)||(B==null?void 0:B.started_at)||""),text:se,provider:typeof(X==null?void 0:X.provider)=="string"?String(X.provider):void 0,model:typeof(X==null?void 0:X.model)=="string"?String(X.model):void 0,generated_at:typeof(X==null?void 0:X.generated_at)=="string"?String(X.generated_at):void 0,source:X==null?void 0:X.source})}return v.scanned=cn.length,v.found},[cn]);_.useEffect(()=>{Tr.current=xs.trim()},[xs]),_.useEffect(()=>{const v=u.trim(),C=qi.trim();if(!(We&&Jn==="subworkflow"&&!!C&&C!==v)){ci.current="",xs.trim()&&ui("");return}ci.current!==C&&(ci.current=C,Tr.current=C,ui(C))},[We,u,Jn,qi,xs]),_.useEffect(()=>{Mc({})},[N]);const gi=_.useMemo(()=>((Array.isArray(z==null?void 0:z.entrypoints)?z==null?void 0:z.entrypoints:[])||[]).map(C=>String((C==null?void 0:C.flow_id)||"").trim()).filter(Boolean),[z]),Vi=_.useMemo(()=>{const v=String((me==null?void 0:me.workflow_id)||"").trim();return We&&or?v:""},[We,or,me==null?void 0:me.workflow_id]),Yh=_.useMemo(()=>{var X;if(!We||!u.trim()||!Vi.trim())return ns;const v=String((me==null?void 0:me.status)||"").trim().toLowerCase(),C=String((me==null?void 0:me.current_node)||"").trim();if(v!=="waiting"&&v!=="running"||!C)return ns;const I=hs(u.trim(),C);if(!I)return ns;const B=String(Jn||((X=me==null?void 0:me.waiting)==null?void 0:X.reason)||"").trim().toLowerCase(),Z=typeof(Bs==null?void 0:Bs.node_id)=="string"?String(Bs.node_id).trim():"",Y=typeof(Bs==null?void 0:Bs.status)=="string"?String(Bs.status).trim().toLowerCase():"";return v==="waiting"&&B==="until"||!ns.trim()||(Y==="waiting"||Y==="running")&&!Z?I:ns},[We,u,Vi,me==null?void 0:me.status,me==null?void 0:me.current_node,(qs=me==null?void 0:me.waiting)==null?void 0:qs.reason,Jn,ns,Bs]),Vd=_.useMemo(()=>{const v={},C=u.trim(),I=(B,Z)=>{if(!Z)return;const Y=typeof(Z==null?void 0:Z.node_id)=="string"?String(Z.node_id).trim():"";if(!Y)return;const X=hs(B,Y);if(!X)return;const se=String((Z==null?void 0:Z.ended_at)||(Z==null?void 0:Z.started_at)||"").trim(),Re=qn(se);Re!==null&&(v[X]=Math.max(v[X]||0,Re))};for(const B of cn)B&&B.record&&I(C,B.record);for(const B of ls)B&&B.record&&I(String(B.run_id||"").trim(),B.record);return v},[cn,ls,u,Mi]);_.useEffect(()=>{var I;if(!We||!u.trim()||!Vi.trim())return;const v=String((me==null?void 0:me.current_node)||"").trim();!v||String(((I=me==null?void 0:me.waiting)==null?void 0:I.reason)||"").trim()==="subworkflow"||Ho(hs(u.trim(),v))},[We,u,Vi,me==null?void 0:me.current_node,(hu=me==null?void 0:me.waiting)==null?void 0:hu.reason]),_.useEffect(()=>{const v=String((ss==null?void 0:ss.flow_id)||"").trim();v&&(oi.trim()||Ai(v))},[ss,oi]),_.useEffect(()=>{const v=Vi.trim(),C=N.trim(),I=oi.trim();if(v){let Z=!1;return Ha(!0),Mo(""),Pe.get_workflow_flow(v).then(Y=>{if(Z)return;const X=Y==null?void 0:Y.flow;ua(X&&typeof X=="object"?X:null)}).catch(Y=>{Z||(ua(null),Mo(String((Y==null?void 0:Y.message)||Y||"Failed to load workflow flow")))}).finally(()=>{Z||Ha(!1)}),()=>{Z=!0}}if(!C||!I){ua(null),Mo(""),Ha(!1);return}let B=!1;return Ha(!0),Mo(""),Pe.get_bundle_flow(C,I).then(Z=>{if(B)return;const Y=Z==null?void 0:Z.flow,X=Y&&typeof Y=="object"?Y:null;ua(X),X&&Mc(se=>({...se,[I]:X}))}).catch(Z=>{B||(ua(null),Mo(String((Z==null?void 0:Z.message)||Z||"Failed to load flow")))}).finally(()=>{B||Ha(!1)}),()=>{B=!0}},[Vi,N,oi,Pe]),_.useEffect(()=>{const v=N.trim();if(!Ro||!v||!To)return;let C=!1;const I=3,B=be=>{const ke=Array.isArray(be==null?void 0:be.nodes)?be.nodes:[],Me=[];for(const qe of ke){const Ge=qe!=null&&qe.data&&typeof qe.data=="object"?qe.data:{};if(String((Ge==null?void 0:Ge.nodeType)||(qe==null?void 0:qe.type)||"").trim()!=="subflow")continue;const Xe=(Ge==null?void 0:Ge.subflowId)||(Ge==null?void 0:Ge.flowId),Kt=typeof Xe=="string"?Xe.trim():"";Kt&&Me.push(Kt.includes(":")?Kt.split(":",2)[1]:Kt)}return Me},Z=new Set,Y=new Set,X=(be,ke)=>{if(!(!be||ke>=I))for(const Me of B(be)){const qe=String(Me||"").trim();if(!qe||Z.has(qe))continue;Z.add(qe),Y.add(qe);const Ge=Tc[qe];Ge&&X(Ge,ke+1)}};X(To,0);const se=Array.from(Y).filter(be=>!Tc[be]).slice(0,20);return se.length?((async()=>{for(const be of se){if(C)return;try{const ke=await Pe.get_bundle_flow(v,be),Me=ke==null?void 0:ke.flow,qe=Me&&typeof Me=="object"?Me:null;if(!qe)continue;Mc(Ge=>Ge[be]?Ge:{...Ge,[be]:qe})}catch{}}})(),()=>{C=!0}):void 0},[Ro,N,To,Tc,Pe]);const Gd=_.useMemo(()=>{const C=(Array.isArray(z==null?void 0:z.flows)?z==null?void 0:z.flows:[]).map(I=>String(I||"").trim()).filter(Boolean);return C.length?Array.from(new Set(C)).sort():Array.from(new Set(gi)).sort()},[z,gi]);_.useEffect(()=>{Vn&&ns.trim()&&(li(""),da.current="")},[Vn,u,ns]),_.useEffect(()=>{const v=xs.trim(),C=u.trim();if(!(We&&!!v&&v!==C)){vs.current&&vs.current.abort(),vs.current=null,ma.current=0,Oc&&jl("");return}if(Oc===v)return;vs.current&&vs.current.abort();const B=new AbortController;vs.current=B,ma.current=0,jl(v),zt({ts:Rt(),kind:"info",title:`Following run ${v} (status/events)`});let Z=250;return(async()=>{for(;!B.signal.aborted;){try{await Pe.stream_ledger(v,{after:ma.current,on_step:X=>Ch(v,X),signal:B.signal});return}catch(X){if(B.signal.aborted)break;const se=String((X==null?void 0:X.message)||X||"stream error");zt({ts:Rt(),kind:"error",title:"Child ledger stream error (will retry)",preview:At(se),data:{child_run_id:v,error:se}})}if(B.signal.aborted)break;await new Promise(X=>setTimeout(X,Z)),Z=Math.min(5e3,Math.floor(Z*1.6))}})(),()=>{B.abort()}},[We,xs,u,Pe,Oc]),_.useEffect(()=>{if(!We||!u.trim())return;let v=!1;const C=async()=>{if(!v&&!kl.current&&Mi.length&&!(mt.current>Date.now())){kl.current=!0;try{const B=Mi.map(se=>String(se||"").trim()).filter(Boolean);if(!B.length)return;const Z=B.map(se=>({run_id:se,after:Number(Ja.current[se]||0)})),Y=await Pe.get_ledger_batch({runs:Z,limit:200}),X=Y&&typeof Y=="object"?Y.runs:{};for(const se of B){if(v)return;const Re=X&&typeof X=="object"?X[se]:null,be=Array.isArray(Re==null?void 0:Re.items)?Re.items:[],ke=typeof(Re==null?void 0:Re.next_after)=="number"?Re.next_after:Number(Ja.current[se]||0),Me=Number(Ja.current[se]||0);for(let qe=0;qe<be.length;qe++){const Ge=be[qe];Eh(se,{cursor:Me+qe+1,record:Ge})}Ja.current[se]=ke}}catch(B){if(v)return;zt({ts:Rt(),kind:"error",title:"Subrun digest poll failed",preview:At(String((B==null?void 0:B.message)||B||""))})}finally{kl.current=!1}}};C();const I=window.setInterval(()=>void C(),2e3);return()=>{v=!0,window.clearInterval(I),kl.current=!1}},[We,u,Mi,Pe]);const uo=_.useMemo(()=>{const v=u.trim(),C=[];for(const I of cn)!I||!I.record||C.push({run_id:v,cursor:I.cursor,record:I.record});for(const I of ls)!I||!I.record||C.push({run_id:String(I.run_id||"").trim(),cursor:I.cursor,record:I.record});return C},[cn,ls,u]),fo=_.useMemo(()=>{var C,I,B,Z;const v={};for(const Y of uo){const X=String(Y.run_id||((C=Y.record)==null?void 0:C.run_id)||"").trim();!X||String(((B=(I=Y.record)==null?void 0:I.effect)==null?void 0:B.type)||"").trim()!=="llm_call"||String(((Z=Y.record)==null?void 0:Z.status)||"")!=="started"&&(v[X]=(v[X]||0)+1)}return v},[uo]),As=_.useMemo(()=>{const v=xs.trim();if(v)return v;let C="",I=-1;for(const[B,Z]of Object.entries(fo))Z>I&&(C=B,I=Z);return C||u.trim()},[fo,xs,u]),q_=(O_.trim()||As).trim(),H_=_.useMemo(()=>{var Z;const v=new Set,C=u.trim(),I=xs.trim();C&&v.add(C),I&&v.add(I);for(const Y of Mi){const X=String(Y||"").trim();X&&v.add(X)}for(const Y of uo){const X=String(Y.run_id||((Z=Y.record)==null?void 0:Z.run_id)||"").trim();X&&v.add(X)}const B=Array.from(v);return B.sort((Y,X)=>C&&Y===C&&X!==C?-1:C&&X===C&&Y!==C?1:I&&Y===I&&X!==I?-1:I&&X===I&&Y!==I?1:Y<X?-1:Y>X?1:0),B},[u,xs,Mi,uo]),Vl=_.useMemo(()=>{var v;for(let C=cn.length-1;C>=0;C--){const I=lk((v=cn[C])==null?void 0:v.record);if(I)return I}return""},[cn]);function Ts(v){hh(v);const C=u.trim();if(!(!C||typeof window>"u"))try{window.history.replaceState(null,"",tA(L$(C),v))}catch{}}const Wn=_.useMemo(()=>{const v=u.trim();return v&&(wn.find(C=>String(C.run_id||"").trim()===v)||zn.find(C=>String(C.run_id||"").trim()===v))||null},[wn,zn,u]),Je=String((me==null?void 0:me.status)||(Wn==null?void 0:Wn.status)||"").trim(),Yo=String(Jn||((ho=me==null?void 0:me.waiting)==null?void 0:ho.reason)||(Wn==null?void 0:Wn.waiting_reason)||"").trim().toLowerCase(),au=!!(me!=null&&me.is_scheduled||Wn!=null&&Wn.is_scheduled),Kd=!!(me!=null&&me.paused||Wn!=null&&Wn.paused),Jh=au&&Je.toLowerCase()==="waiting",Jo=Jh&&Yo==="until",Gl=qn(pi),Kl=Jo&&Gl!==null?fv(Gl-Date.now()):"",Xo=fA(me),Yl=au&&Kd?"Suspended":Jh?"Scheduled":Zm({status:Je,paused:Kd,stop_reason:Xo});async function Yd(){if(M){Xa(!0),wh("");try{const v=pa,C=v==="session"?String(Po||Wi||W||"").trim():"",I=v==="run"?String(Li||u||"").trim():"",B=PM(Fc),Z=ga.length?ga.join(","):"",Y=DM(Fo),X=Math.max(0,Al)*Im,se=await Pe.search_artifacts({scope:v,session_id:C||void 0,run_id:I||void 0,query:El||void 0,artifact_kind:Z||void 0,created_after:B||void 0,include_stats:!0,limit:Im,offset:X,order_by:Y.order_by,order:Y.order}),Re=[],be=new Set;for(const nt of Array.isArray(se==null?void 0:se.items)?se.items:[]){const Xe=LM(nt,"search");!Xe||be.has(Xe.artifact_id)||(be.add(Xe.artifact_id),Re.push(Xe))}const ke=se!=null&&se.stats&&typeof se.stats=="object"?se.stats:{},Me=Number((ke==null?void 0:ke.total)??(se==null?void 0:se.total)??Re.length),qe=$v(se);let Ge=qe;if(ga.length)try{const nt=await Pe.search_artifacts({scope:v,session_id:C||void 0,run_id:I||void 0,query:El||void 0,created_after:B||void 0,include_stats:!0,limit:1,offset:0,order_by:Y.order_by,order:Y.order});Ge=$v(nt)}catch{Ge=qe}Sn(Number.isFinite(Me)?Math.max(0,Me):Re.length),Nl(Number((ke==null?void 0:ke.total_bytes)??(ke==null?void 0:ke.byte_total)??0)||0),dd(qe),Io(Ge),ld(Re),$l(nt=>{var Xe;return nt&&Re.some(Kt=>Kt.artifact_id===nt)?nt:((Xe=Re[0])==null?void 0:Xe.artifact_id)||""})}catch(v){wh(String((v==null?void 0:v.message)||v||"Failed to load artifacts")),ld([]),Sn(0),Nl(0),dd({}),Io({}),$l("")}finally{Xa(!1)}}}async function ou(){if(M){gd(!0),Pi("");try{const v=await Pe.audit_log_tail({max_bytes:16e4}),C=typeof(v==null?void 0:v.bytes)=="number"?Number(v.bytes):0,I=!!(v!=null&&v.truncated);pd(String((v==null?void 0:v.content)||"")),Ll(`${C.toLocaleString()} bytes${I?" (tail)":""}`)}catch(v){Pi(String((v==null?void 0:v.message)||v||"Failed to load audit log")),pd(""),Ll("")}finally{gd(!1)}}}async function lu(v){if(!M)return;const C=String(v||tr||Li||u||"").trim();if(!C){rr([]),Yr(""),Il("Select a run in Activity or Artifacts to load its runtime ledger.");return}xa(!0),Il("");try{const I=await Pe.get_ledger(C,{after:0,limit:2e3}),B=Array.isArray(I.items)?I.items:[];rr(B.map((Y,X)=>({cursor:X+1,record:Y})));const Z=typeof I.next_after=="number"?Number(I.next_after):B.length;Yr(`${B.length.toLocaleString()} record${B.length===1?"":"s"}${Z>=2e3?" (first 2,000)":""}`)}catch(I){Il(String((I==null?void 0:I.message)||I||"Failed to load run ledger")),rr([]),Yr("")}finally{xa(!1)}}_.useEffect(()=>{M&&e==="runtime"&&Yd()},[M,e,pa,Po,Li,El,ga,Fc,Fo,Al]),_.useEffect(()=>{M&&(zc||Rl||e==="runtime"&&ou())},[M,e,er]),_.useEffect(()=>{if(!M||e!=="runtime"||Sl!=="logs"||Di!=="run_ledger"&&Di!=="provider_calls")return;const v=String(tr||Li||u||"").trim();v&&lu(v)},[M,e,Sl,Di,tr,Li,u]);const Rn=_.useMemo(()=>{const v=new Map;for(const C of[...zn,...wn]){const I=String(C.run_id||"").trim();I&&v.set(I,C)}for(const C of Mi){const I=String(C||"").trim();!I||v.has(I)||v.set(I,{run_id:I,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:fa.current[I]||null,session_id:Wi||null})}return u.trim()&&!v.has(u.trim())&&v.set(u.trim(),{run_id:u.trim(),workflow_id:typeof(me==null?void 0:me.workflow_id)=="string"?String(me.workflow_id):null,status:typeof(me==null?void 0:me.status)=="string"?String(me.status):"",created_at:typeof(me==null?void 0:me.created_at)=="string"?String(me.created_at):null,updated_at:typeof(me==null?void 0:me.updated_at)=="string"?String(me.updated_at):null,ledger_len:cn.length||null,parent_run_id:typeof(me==null?void 0:me.parent_run_id)=="string"?String(me.parent_run_id):null,session_id:typeof(me==null?void 0:me.session_id)=="string"?String(me.session_id):Wi||null}),Array.from(v.values()).sort((C,I)=>{const B=qn(C.updated_at||C.created_at)??0;return(qn(I.updated_at||I.created_at)??0)-B})},[wn,zn,u,me,cn.length,Mi,Wi]),Zr=_.useMemo(()=>pR(Rn,{query:ed,filter:$c,group_by:td,workflow_label_by_id:Lr,parent_hint:v=>fa.current[v]||""}),[Rn,ed,$c,td,Lr]),lr=_.useMemo(()=>{const v={};for(const C of Rn){const I=String(C.run_id||"").trim();I&&(v[I]=C)}return v},[Rn]),cu=String(tr||Li||u||"").trim(),uu=cu&&lr[cu]||null,Pr=String(Po||(uu==null?void 0:uu.session_id)||Wi||W||"").trim(),Jd=_.useMemo(()=>od.map(v=>n_(v,lr,Lr)),[od,lr,Lr]);_.useEffect(()=>{md(0)},[El,ga,Fc,Li,Fo,Do,pa,Po]);const yi=Math.max(1,Math.ceil(cd/Im)),Jl=Math.min(Math.max(0,Al),yi-1);_.useEffect(()=>{Al!==Jl&&md(Jl)},[Al,Jl]);const Aa=_.useMemo(()=>Jd,[Jd,Jl]),Xh=_.useMemo(()=>{const v={};for(const C of Aa){const I=Do==="type"?Ng(C,lr,Lr):IM(C,Do);v[I]||(v[I]=[]),v[I].push(C)}return Object.entries(v).map(([C,I])=>({key:C,items:I})).sort((C,I)=>{var B,Z;if(Do==="time"){const Y=qn((B=C.items[0])==null?void 0:B.created_at)??0,X=qn((Z=I.items[0])==null?void 0:Z.created_at)??0;if(Y!==X)return X-Y}return C.key.localeCompare(I.key)})},[Aa,Do,lr,Lr]),Zo=_.useMemo(()=>{const v=di.trim();return v?Aa.find(C=>C.artifact_id===v)||Aa[0]||null:Aa[0]||null},[Aa,di]);_.useEffect(()=>{e!=="runtime"||Sl!=="artifacts"||Td(Zo)},[e,Sl,Zo==null?void 0:Zo.artifact_id]),_.useEffect(()=>()=>{Mr.url&&URL.revokeObjectURL(Mr.url)},[Mr.url]);const Zh=_.useMemo(()=>Rn.filter(v=>Bu(v.status)),[Rn]);_.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!M||J)return;let v=!1;return(async()=>{const[C,I]=await Promise.all([Pe.list_skills(),Pe.list_mcp_servers()]);v||(V(C),_e(I),le(!0))})(),()=>{v=!0}},[e,M,J]);function du(){I_&&window.setTimeout(()=>{var v;return(v=sd.current)==null?void 0:v.scrollIntoView({block:"start"})},60)}function Qo(v){la(v),du()}const Xd=[{id:"board",label:"Board",icon:s.jsx(ze,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(ze,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(ze,{name:"server",size:16})},{id:"launch",label:"Launch",icon:s.jsx(ze,{name:"send",size:16})},{id:"automations",label:"Automations",icon:s.jsx(ze,{name:"refresh",size:16})}],Dr={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},tn=s.jsx(fR,{connected:M,request:Wc,value:jd,onChange:v=>Un("workspace",v===null?void 0:v),disabled:pt||gt}),as=s.jsx(s.Fragment,{children:Yn?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",Bi.length?` · ${Bi.length} skill${Bi.length===1?"":"s"}`:""]}),s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Skills attach knowledge procedures to this run. The gateway resolves selections through the trust gate at start: validated skills activate, unverified ones are held for review, blocked ones never ride."}),O===null?s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"This gateway does not serve a skills inventory yet — the shelf lights up here when it ships."}):O.length?s.jsx("div",{className:"launch_skill_list",children:O.map(v=>{var Z;const C=Bi.includes(v.name),I=v.blocked===!0,B=v.requires_review===!0&&!I;return s.jsxs("label",{className:`launch_skill_row ${I?"is_blocked":""} ${C?"is_on":""}`,title:[v.description||"",v.tree_hash?`tree ${v.tree_hash.slice(0,16)}…`:"",I&&((Z=v.reasons)!=null&&Z.length)?`blocked: ${v.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
159
|
-
`),children:[s.jsx("input",{type:"checkbox",checked:C,disabled:I||pt||gt||ce,onChange:Y=>{const X=Y.target.checked?Array.from(new Set([...Bi,v.name])):Bi.filter(se=>se!==v.name);Un("skills",X.length?X:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:v.name}),v.trust_level?s.jsx("span",{className:`chip ${I?"danger":B?"warn":"muted"}`,children:I?"blocked":B?"review":v.trust_level}):null,v.description?s.jsx("span",{className:"launch_skill_desc",children:v.description}):null]},v.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),Bi.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}),Xn=s.jsxs("section",{className:"launch_workspaces","data-section":"workspaces",style:{marginTop:"10px"},children:[s.jsx("div",{className:"launch_label launch_section_title",children:"Workspaces"}),tn,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:kd,onChange:v=>Un("workspace_root",v.target.value||void 0),placeholder:"/path/to/workspace",disabled:pt||gt}),s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-xxs)"},children:"Empty = the run's own private workspace. Otherwise a workspace the gateway's posture reaches; the gateway refuses any other."})]})})]}),ms=s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Workflow bundles"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:dt,type:"file",accept:".flow",style:{display:"none"},onChange:v=>{const C=v.target.files&&v.target.files.length?v.target.files[0]:null;C&&Cd(C)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var v;return(v=dt.current)==null?void 0:v.click()},disabled:!M||D||Sr||pt||gt,title:"Upload a .flow bundle",children:Sr?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Nh(),disabled:!M||D||Ct||pt||gt,title:"Reload picks up server-side edits",children:[s.jsx(ze,{name:"refresh",size:14}),Ct?"…":"Reload bundles"]})]})]});function cr(v){t("observe"),la("ledger"),_i(v)}const el={on_select:v=>void on.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"){on.ask_archive(v.automation_id);return}on.row_action(v,C)},on_legacy_action:(v,C)=>{if(C==="open_run"){cr(v.automation_id);return}if(C==="recreate"){Ld(v.automation_id).catch(I=>on.report_error(I));return}on.legacy_action(v,C)},on_confirm_archive:v=>void on.row_action(v,"archive"),on_cancel_archive:()=>on.ask_archive(""),on_status_filter:v=>void on.set_status_filter(v),on_refresh:()=>void on.refresh(),on_new:()=>{ye("automate"),t("launch")},on_show_archived:v=>on.set_show_archived(v)};return s.jsxs("div",{className:`app-shell shell${qa?" nav_open":""}`,children:[ch&&qa?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>xl(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:fh,...ca.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:()=>xl(!1),children:s.jsx(ze,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[Xd.map(v=>s.jsxs("button",{className:`shell_nav_item ${e===v.id?"active":""}`,onClick:()=>{t(v.id),xl(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:v.icon}),s.jsx("span",{className:"shell_nav_label",children:v.label})]},v.id)),s.jsxs("a",{className:"shell_nav_item",href:l,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(ze,{name:"bot",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Entities ↗"})]}),s.jsxs("button",{className:`shell_nav_item ${e==="settings"?"active":""}`,onClick:()=>{t("settings"),xl(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(ze,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:M?"Gateway connected":D?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${M?"ok":D?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${M&&((Zl=(wi=U==null?void 0:U.gateway)==null?void 0:wi.principal)!=null&&Zl.user_id)?"mono":""}`,children:M?((Gi=(mu=U==null?void 0:U.gateway)==null?void 0:mu.principal)==null?void 0:Gi.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):D?"connecting…":"signed out"})]})})]}),s.jsxs("div",{className:"shell_main",...ca.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:dh,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":qa,title:"Navigation",onClick:()=>xl(!0),children:s.jsx(ze,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:Dr[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[a?s.jsx("monitor-gpu",{ref:c,mode:"icon","history-size":"5","tick-ms":"1500","base-url":n.gateway_auth_mode==="session"?"":n.gateway_url,title:"GPU usage (host)",style:{"--monitor-gpu-width":"34px","--monitor-gpu-bars-height":"22px","--monitor-gpu-padding":"2px 4px","--monitor-gpu-radius":"999px","--monitor-gpu-bg":"rgba(0,0,0,0.22)","--monitor-gpu-border":"rgba(255,255,255,0.16)",flexShrink:0}}):null,s.jsx(g1,{docs:{open:Zt,onToggle:()=>On(v=>!v),label:"Docs assistant"},appearance:{onOpen:()=>St(!0)},about:{identity:yd,versions:wd,onOpen:Sh},connection:{phase:F.phase,signingOut:F.signingOut,onConnect:()=>F.openModal(),onDisconnect:()=>An()}})]})]}),s.jsx(HS,{...F.modalProps}),s.jsx(x1,{open:lt,onClose:()=>St(!1),value:rt,onChange:ht}),s.jsx(b$,{open:Zt,onClose:()=>On(!1),connected:M,topOffset:44,gateway:Pe}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?M?s.jsx(yP,{gateway_connected:M,runs:zn,all_runs:wn,runs_refreshed_at:Kn,entities:jr,entities_total:fe,entities_error:et,refreshing:xn,on_refresh:()=>void fs(Pe,{force:!0}),on_open_run:v=>{t("observe"),la("ledger"),_i(v)},on_resume_wait:Yc,on_open_automation:v=>{t("automations"),on.refresh().then(()=>on.select(v))},entity_app_href:l,on_read_diary:(v,C)=>Pe.read_entity_diary_entry(v,C),phase_graph:Ed}):s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card mc_hero",children:[s.jsx("div",{className:"title",children:s.jsx("h1",{children:"Connect to your gateway"})}),s.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",E?` Last attempt: ${E}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>F.openModal(),disabled:D,children:D?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Ui({open_modal_if_needed:!0}),disabled:D,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?s.jsx("div",{className:"page page_scroll",children:s.jsxs("div",{className:"page_inner settings_col",children:[s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Gateway"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:`chip ${M?"ok":"warn"}`,children:nb(U).label})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsxs("div",{className:"settings_row",children:[s.jsxs("div",{className:"settings_row_main",children:[s.jsx("div",{className:"settings_row_title",children:"Connection"}),s.jsx("div",{className:"settings_row_help",children:"The shared AbstractFramework sign-in: a gateway user token exchanges for an HTTP-only browser session. Raw tokens are never stored."})]}),s.jsxs("div",{className:"settings_row_actions",children:[s.jsx("button",{className:"btn",onClick:()=>F.openModal(),children:"Manage connection…"}),M?s.jsx("button",{className:"btn",onClick:()=>An(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),E?s.jsx("div",{className:"warn_callout",children:E}):null,s.jsx("div",{className:"settings_row",children:s.jsx(ZT,{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:h_})]}),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 Ui({prefer_direct:!0}),disabled:D,children:D?"Connecting…":"Connect directly"})]})]})]}),s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Assistant"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"chip muted",children:"docs Q&A + run Ask"})]}),s.jsxs("div",{className:"pane_body settings_body",children:[s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"The model answering the header assistant and the run page's Ask tab. Blank fields follow the gateway defaults."}),s.jsx(Zx,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Nd,models:hi.models,loadingProviders:D,loadingModels:Gc,modelError:mi?hi.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:v=>r(C=>({...C,maintenance_ai_provider:v.provider,maintenance_ai_model:v.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),O===null?s.jsx("div",{className:"settings_row_help",children:M?J?"The gateway does not serve a skills inventory yet — the abstractskill shelf list lights up here the day it ships.":"Probing the gateway for the skills inventory…":"Connect to the gateway to list installable skills (abstractskill shelf)."}):O.length?s.jsx("div",{className:"settings_choice_list",children:O.map(v=>{const C=n.assistant_skill_names.includes(v.name);return s.jsx(QT,{name:v.name,version:v.version,description:v.description,checked:C,onChange:I=>r(B=>({...B,assistant_skill_names:I?Array.from(new Set([...B.assistant_skill_names,v.name])):B.assistant_skill_names.filter(Z=>Z!==v.name)}))},v.name)})}):s.jsx("div",{className:"settings_row_help",children:"The gateway serves an empty skills inventory."}),s.jsx("div",{className:"settings_row_help",children:"Selected skills ride the assistant's runs once the gateway's skills-attachment lane serves them; the selection persists here meanwhile."}),s.jsx("div",{className:"settings_subhead",children:"MCP servers"}),s.jsx("div",{className:"settings_row_help",style:{marginTop:0},children:"Remote tool endpoints the assistant may call. The gateway does not serve an MCP inventory yet — one manual endpoint is supported (advanced / potentially dangerous: it executes tool waits from this browser)."}),s.jsxs("div",{className:"settings_mcp_row",children:[s.jsx("input",{className:"mono",value:n.worker_url,onChange:v=>r(C=>({...C,worker_url:v.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:v=>r(C=>({...C,worker_token:v.target.value})),placeholder:"Bearer token (optional)"}),s.jsx("span",{className:`chip ${n.worker_url.trim()?"ok":"muted"}`,children:n.worker_url.trim()?"configured":"none"})]})]})]}),s.jsxs("section",{className:"pane","data-settings-section":"voice",children:[s.jsx("div",{className:"pane_header",children:s.jsx("span",{className:"pane_title",children:"Voice"})}),s.jsx("div",{className:"pane_body settings_body",children:s.jsx(fT,{gateway:M?Pe:null,connected:M,defaults:is,value:Nn,onChange:rs})})]})]})}):null,e==="launch"?s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(ZA,{mode:pe,automate_available:Te.available,automate_reason:Te.reason,on_change:ye}),pe==="automate"&&!Te.available&&M?s.jsx("div",{className:"warn_callout",role:"note",children:Te.reason}):null,pe==="automate"&&Ae.length?s.jsx("div",{className:"help_text",role:"note",children:Ae.map(v=>s.jsx("div",{children:v},v))}):null,M?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>F.openModal(),children:"Sign in"})," ","to launch workflows on this gateway."]}),pe==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(Wb,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:Lu,ariaLabel:"Workflow",workflows:Ir,value:_v(Yn,((Ql=Ir.data)==null?void 0:Ql.entries)??[]),currentLabel:Yn&&!_v(Yn,((Ki=Ir.data)==null?void 0:Ki.entries)??[])?{name:Lr[ja]||ja}:null,unavailableReason:M?D?"Loading workflows…":null:"Sign in to load workflows.",onChange:(v,C)=>{const I=kA(v,C);I&&Vo(I)}})}),s.jsxs("div",{className:"field",children:[ss!=null&&ss.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(ss.description)}):null,G?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading workflow…"}):null,te?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:te}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),Yn?Et===null?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginTop:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"input error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Sd?s.jsx("div",{className:"launch_inputs",children:(()=>{const v=pt||gt,C=[],I=[];for(const Y of fi){if(!Y||typeof Y!="object")continue;const X=String(Y.id||"").trim();if(!X||pe==="automate"&&R0.includes(X))continue;const se=String(Y.type||"").trim().toLowerCase();se==="tools"||se==="skills"||se==="mcp"||se==="mcp_servers"||X==="skills"||X==="mcp"||X==="mcp_servers"||se==="array"||ka(se)||X==="prompt"||X==="system"?C.push(Y):I.push(Y)}const B=Y=>String(Y||"").trim().replace(/_/g," ").replace(/\b\w/g,X=>X.toUpperCase()),Z=(Y,X)=>{const se=String(Y.id||"").trim();if(!se)return null;const Re=String(Y.label||se).trim()||se,be=Re===se?B(se):Re,ke=String(Y.type||"").trim().toLowerCase(),Me=Object.prototype.hasOwnProperty.call(Y,"default"),qe=Me?Y.default:void 0,Ge=Me?typeof qe=="string"?qe:dr(qe,80):"",nt=Et==null?void 0:Et[se],Xe=Me?`${Ge}`:"";if(ke==="tools"){if(pe==="automate"&&se==="tools")return null;const He=Array.isArray(nt)?nt.map(Cn=>String(Cn||"").trim()).filter(Boolean):[],Nt=Array.isArray(qe)?qe.map(Cn=>String(Cn||"").trim()).filter(Boolean):[],kn=Array.from(new Set([...Vc,...He,...Nt])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx(cg,{options:kn,value:He,disabled:v,placeholder:"(no tools selected)",onChange:Cn=>Un(se,Cn)})]},se)}if(ke==="skills"||se==="skills")return null;if(ke==="mcp"||ke==="mcp_servers"||se==="mcp"||se==="mcp_servers"){const He=Array.isArray(nt)?nt.map(Cn=>String(Cn||"").trim()).filter(Boolean):[];if(ie===null&&!He.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."})]},se);const Nt=(ie||[]).map(Cn=>Cn.name),kn=Array.from(new Set([...Nt,...He])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx(cg,{options:kn,value:He,disabled:v,placeholder:"(no MCP servers selected)",onChange:Cn=>Un(se,Cn)})]},se)}if(ke==="provider"||ke==="provider_text"){const He=typeof nt=="string"?String(nt):"";return s.jsxs("div",{className:X||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsxs("select",{value:He,onChange:Nt=>Un(se,Nt.target.value),disabled:v,children:[s.jsx("option",{value:"",children:Xe||"(select)"}),Sa.map(Nt=>s.jsx("option",{value:Nt,children:Nt},Nt))]})]},se)}if(ke==="model"||ke==="model_text"){const He=typeof nt=="string"?String(nt):"",Nt=String((Et==null?void 0:Et.provider)||"").trim(),kn=Nt?Pt[Nt]:void 0,Cn=kn&&Array.isArray(kn.models)?kn.models.map(bs=>String(bs||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:X||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),Cn.length?s.jsxs("select",{value:He,onChange:bs=>Un(se,bs.target.value),disabled:v,children:[s.jsx("option",{value:"",children:Xe||"(select)"}),Cn.map(bs=>s.jsx("option",{value:bs,children:bs},bs))]}):s.jsx("input",{value:He,onChange:bs=>Un(se,bs.target.value),placeholder:Xe||"model id",disabled:v})]},se)}if(ke==="boolean"){const He=typeof nt=="boolean"?nt?"true":"false":"";return s.jsxs("div",{className:X||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsxs("select",{value:He,onChange:Nt=>{const kn=String(Nt.target.value||"").trim();kn?Un(se,kn==="true"):Un(se,void 0)},disabled:v,children:[s.jsx("option",{value:"",children:Xe||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},se)}if(ke==="number"){const He=typeof nt=="number"&&Number.isFinite(nt)?String(nt):"";return s.jsxs("div",{className:X||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("input",{type:"number",value:He,onChange:Nt=>{const kn=String(Nt.target.value||"").trim();if(!kn){Un(se,void 0);return}const Cn=Number(kn);Number.isFinite(Cn)&&Un(se,Cn)},placeholder:Xe,disabled:v})]},se)}if(ke==="array"){const He=Array.isArray(nt)?nt.map(Nt=>String(Nt||"").trim()).filter(Boolean).join(`
|
|
160
|
-
`):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("textarea",{className:"mono",value:He,onChange:Nt=>{const kn=String(Nt.target.value||"").split(/\r?\n/g).map(Cn=>String(Cn||"").trim()).filter(Boolean);Un(se,kn.length?kn:void 0)},placeholder:Xe||"(one item per line)",rows:2,disabled:v})]},se)}if(ka(ke)){const He=typeof fn[se]=="string"?fn[se]:"",Nt=String(Vr[se]||"").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:ke})]}),s.jsx("textarea",{className:"mono",value:He,onChange:kn=>{const Cn=String(kn.target.value??"");Ds(Fr=>({...Fr,[se]:Cn}));const bs=Cn.trim();if(!bs){cs(Fr=>{const Qr={...Fr};return delete Qr[se],Qr}),Un(se,void 0);return}try{const Fr=JSON.parse(bs);cs(Qr=>{const sl={...Qr};return delete sl[se],sl}),Un(se,Fr)}catch(Fr){cs(Qr=>({...Qr,[se]:String((Fr==null?void 0:Fr.message)||Fr||"Invalid JSON")}))}},placeholder:Xe||"{...}",rows:3,disabled:v}),Nt?s.jsx("div",{className:"launch_field_error",children:Nt}):null]},se)}const Kt=typeof nt=="string"?String(nt):"";return se==="prompt"||se==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("textarea",{value:Kt,onChange:He=>Un(se,He.target.value),placeholder:Xe||(se==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:v})]},se):s.jsxs("div",{className:X||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("input",{value:Kt,onChange:He=>Un(se,He.target.value),placeholder:Xe,disabled:v})]},se)};return C.sort((Y,X)=>{const se={system:0,prompt:1,tools:2};return(se[String(Y.id||"")]??10)-(se[String(X.id||"")]??10)}),s.jsxs(s.Fragment,{children:[C.map(Y=>Z(Y)),I.length>0?s.jsx("div",{className:"launch_grid",children:I.map(Y=>Z(Y,"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:Hc,onChange:v=>Un("prompt",v.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:pt||gt})]}),s.jsxs("div",{className:"row",children:[s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Provider (common)"}),s.jsx("input",{value:ba,onChange:v=>Un("provider",v.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:pt||gt})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:bd,onChange:v=>Un("model",v.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:pt||gt})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Select a workflow above to configure inputs."}),pe==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(QA,{form:Ue,email_status:zs.email_status,on_open_my_email:ir,served:kh,on_open_preferences:ir,tools:ob(Et||{})??void 0,available_tools:Vc,on_tools_change:v=>A(JSON.stringify(lb(Et||{},v),null,2)),disabled:ce,on_change:v=>ut(C=>({...C,...v})),workspaces:tn}),s.jsx(eT,{form:Ue,disabled:ce,on_change:v=>ut(C=>({...C,...v}))}),as,ms]}):s.jsxs(s.Fragment,{children:[as,Xn,ms]}),s.jsx("div",{className:"section_divider"}),na?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:na})]}):null,pe==="automate"&&De.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:De.map(v=>s.jsx("li",{children:v},v))}):null,pe==="automate"&&at?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":at.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:at.code}),s.jsxs("span",{children:[s.jsx("strong",{children:Gm(at).title})," ",Gm(at).detail,at.field?s.jsxs("span",{className:"mono",children:[" (",at.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const v=pe==="automate",C=M?Yn?Et===null?"Inputs contain invalid JSON":v&&!Te.available?"Automations unavailable on this gateway":pt||gt?"Attaching to a run…":D||G?"Loading…":ce?"Submitting…":"":"Select a workflow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void Th(),disabled:!!C,title:C,children:v?ce?"Creating…":"Create automation":pt?"Launching…":"Launch now"}),C&&!ce&&!pt?s.jsx("span",{className:"mono muted launch_disabled_reason",children:C}):null]})})()})]})})}):null,e==="automations"?s.jsx(XT,{workflowPickerOptions:{interfaceId:null,defaultInterface:Lu,workflows:Ir,request:(v,C)=>Pe.get_gateway_json(v,C.signal)},availableTools:Vc,ctl:on,gateway:Pe,active:e==="automations"&&M,available:Te,h:el,voice_session_id:W,workspace_request:Wc,host:{on_open_run:v=>cr(v),...ir?{on_open_my_email:ir}:{},on_open_session:(v,C)=>{zt({ts:Rt(),kind:"info",title:"Discussion started",preview:At(C),data:v})}}}):null,e==="runtime"?s.jsx(iR,{gateway_connected:M,tab:Sl,runs:Rn,active_runs:Zh,all_artifacts:od,artifacts:Aa,artifact_total_count:cd,artifact_total_bytes:ud,artifact_facets:Cl,artifact_type_facets:fd,artifact_page:Jl,artifact_page_size:Im,artifact_groups:Xh,selected_artifact:Zo,embedded_preview:Mr,loading:Pc,error:yh,query:El,scope:pa,type_filters:ga,date_filter:Fc,group_by:Do,sort_by:Fo,artifact_run_filter:Li,audit_log_text:Rl,audit_log_meta:Oi,audit_log_loading:zc,audit_log_error:B_,workflow_label_by_id:Lr,run_by_id:lr,selected_run_id:cu,session_id:Pr,runtime_log_source:Di,runtime_log_query:Bc,runtime_ledger_log_items:Rr,runtime_ledger_log_meta:no,runtime_ledger_log_loading:Fi,runtime_ledger_log_error:bh,on_tab_change:Lo,on_query_change:vh,on_scope_change:Oo,on_session_filter_change:Dc,on_type_filters_change:hd,on_date_filter_change:xh,on_group_by_change:z_,on_sort_by_change:ya,on_artifact_page_change:md,on_artifact_run_filter_change:v=>{const C=String(v||"").trim();Za(C),C&&Ii(C),C&&pa!=="run"&&Oo("run")},on_refresh_artifacts:()=>void Yd(),on_refresh_audit:()=>void ou(),on_refresh_runtime_ledger:v=>void lu(v),on_runtime_log_source_change:Wo,on_runtime_log_query_change:Uc,on_select_run:v=>{const C=String(v||"").trim();Ii(C);const I=C&&lr[C]||null,B=String((I==null?void 0:I.session_id)||"").trim();B&&Dc(B)},on_select_artifact:$l,on_preview_artifact:v=>void $d(v),on_download_artifact:v=>void Es(v),on_open_run:v=>{Ii(String(v||"").trim()),t("observe"),la("ledger"),_i(v)},on_open_ledger:v=>{Ii(String(v||"").trim()),t("observe"),la("ledger"),_i(v)},on_refresh_runs:()=>void fs(Pe,{force:!0}),on_reconnect:()=>void Ui({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:M?s.jsx(YO,{gateway:Pe,selected_run_id:tr,selected_session_id:Pr}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${nd?"":" list_collapsed"}`,children:[s.jsx(oR,{sections:Zr,selected_run_id:u,root_run_id:h,search:ed,filter:$c,group_by:td,loading:xn,connected:M,on_sign_in:()=>F.openModal(),total_runs:Rn.length,workflow_label_by_id:Lr,automation_titles:jh,on_search:M_,on_filter:R_,on_group_by:L_,on_refresh:()=>void fs(),on_select:(v,C)=>{_i(v,{root_run_id:C||v}),du()},list:{open:nd,on_toggle:uh}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[u.trim()?s.jsxs("div",{className:"observe_run_identity",title:u.trim(),children:[s.jsx("span",{className:"observe_run_name",children:Lr[String((Wn==null?void 0:Wn.workflow_id)||"")]||String((Wn==null?void 0:Wn.workflow_id)||"").trim()||sn(u.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:sn(u.trim(),14)}),s.jsx("span",{className:`chip ${wc(Yl||Je,Xo)}`,title:String((Xo==null?void 0:Xo.headline)||""),children:Yl||Je||"unknown"})]}):w?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:I$(w)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),u.trim()?s.jsxs(s.Fragment,{children:[or?s.jsx(tM,{active:!Ea,unavailableReason:qd,busy:pt||gt,onChange:v=>{if(!v){yr("pause"),Ys(""),us(""),gr(!0);return}Hl("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(su==="pause"){yr("pause"),Ys(""),us(""),gr(!0);return}Hl("resume")},disabled:Kh,children:nu}),ru?s.jsx("button",{className:"btn primary",onClick:()=>void Mh(),disabled:pt||gt||Vn||Ea,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{yr("cancel"),Ys(""),us(""),gr(!0)},disabled:pt||gt||Vn,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Go,title:"Clear the run view",children:s.jsx(ze,{name:"x",size:14})})]}):null]}),u.trim()&&!Vn?s.jsx("div",{className:"observe_steer_row",children:s.jsx(QS,{runId:u.trim(),parked:ao,submit:(v,C)=>Pe.submit_command({command_id:`steer-${Rs()}`,run_id:v,type:"inject_guidance",payload:{guidance:C},client_id:"web_pwa"}).then(I=>({accepted:!!(I!=null&&I.accepted),duplicate:!!(I!=null&&I.duplicate),seq:Number((I==null?void 0:I.seq)??0)})),onSent:()=>zt({ts:Rt(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,ao||or||vl?s.jsxs("div",{className:"observe_toolbar_context",children:[ao?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const v=or?Ea?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${wc(v)}`,children:v})})(),s.jsx("span",{className:"muted",children:Jn||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[$s?s.jsxs("span",{className:"mono",title:$s,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",sn($s,46)]}):null,Jn==="event"&&Xc?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",Xc]}):null,Jn==="subworkflow"&&qi?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",sn(qi,18)]}):null,Jn==="until"&&pi?s.jsxs("span",{className:"mono",title:pi,children:[s.jsx("span",{className:"muted",children:"until"}),": ",sn(pi,46)]}):null,Jn==="until"&&pi?s.jsx("span",{className:"mono muted",children:(()=>{const v=qn(pi),C=v!==null?new Date(v).toLocaleString():pi,I=v!==null?fv(v-Date.now()):"";return`Next at ${C}${I?` (in ${I})`:""}`})()}):null]}),Jn==="subworkflow"&&qi?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{f(qi),await ql(qi)},disabled:pt,children:"Attach to child"}),h.trim()&&h.trim()!==u.trim()?s.jsx("button",{className:"btn",onClick:async()=>{f(h.trim()),await ql(h.trim())},disabled:pt,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:tu?`every ${$a}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[$a?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",$a]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",Gh?"yes":"no"]}),typeof eu=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",eu]}):null]}),Ko!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof iu=="number"&&typeof Hd=="number"?`${iu.toLocaleString()} / ${Hd.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Ko))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Ko>=.9?"danger":Ko>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Ko))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[tu?s.jsx("button",{className:"btn",onClick:()=>{Fn($a||""),Hn(!0),ri(""),Fa(!0)},disabled:pt||Mn,children:"Edit schedule"}):null,tu?s.jsx("button",{className:"btn",onClick:()=>{ys(""),Ks(!0)},disabled:pt||Nr,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void Ld(u.trim()).catch(v=>an(String((v==null?void 0:v.message)||v))),disabled:pt||!u.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,vl?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:vl})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:sd,children:[s.jsxs("div",{className:"tab_bar",children:[s.jsxs("div",{role:"tablist","aria-label":"Run views",className:"observe_tablist",children:[s.jsx("button",{role:"tab","aria-selected":er==="ledger",className:`tab ${er==="ledger"?"active":""}`,onClick:()=>Qo("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":er==="graph",className:`tab ${er==="graph"?"active":""}`,onClick:()=>Qo("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":er==="chat",className:`tab ${er==="chat"?"active":""}`,onClick:()=>Qo("chat"),children:"Ask"})]}),er==="ledger"&&(cn.length>0||ls.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!cn.length&&!ls.length,title:"Copy full ledger as JSONL",onClick:()=>{const I=[...cn.map(Y=>({run_id:u.trim()||Y.record.run_id||"",cursor:Y.cursor,record:Y.record})),...ls.map(Y=>({run_id:Y.run_id,cursor:Y.cursor,record:Y.record}))].map(Y=>{var Re,be;const X=String(((Re=Y.record)==null?void 0:Re.ended_at)||((be=Y.record)==null?void 0:be.started_at)||"").trim(),se=qn(X);return{...Y,_ms:se??0}});I.sort((Y,X)=>(Y._ms||0)-(X._ms||0));const Z=(I.length>5e3?I.slice(I.length-5e3):I).map(({_ms:Y,...X})=>JSON.stringify(X)).join(`
|
|
161
|
-
`);Fl(Z)},children:"Copy JSONL"})}):null,er==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Ro?"active":""}`,"aria-pressed":Ro,onClick:()=>P_(v=>!v),children:"Subflows"}),s.jsx("button",{className:`seg_action ${ad?"active":""}`,"aria-pressed":ad,onClick:()=>D_(v=>!v),children:"Path"}),Gd.length?s.jsx("select",{className:"mono seg_select",value:oi,onChange:v=>Ai(String(v.target.value||"")),disabled:!!Vi.trim()||!N.trim()||Rc,children:Gd.map(v=>s.jsx("option",{value:v,children:v},v))}):null]}):null]}),er==="ledger"?u.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(wA,{status:Yl||Je||"unknown",duration:Wn?yc(Wn):"",facts:aA(iA(uo)),error:Df(Wn)||String((me==null?void 0:me.error)||"").trim(),answer:Vl||String((Hi==null?void 0:Hi.text)||"").trim(),waiting_for_user:!!(Wt!=null&&Wt.wait_key)&&String((Wt==null?void 0:Wt.reason)||"")==="user",on_answer_wait:()=>Xs(""),workspace_root:rd,on_reveal_workspace:()=>void U_(),speak:M?s.jsx(yT,{voice:Or,speak_key:`outcome:${u.trim()}`,text:Df(Wn)||String((me==null?void 0:me.error)||"").trim()||Vl||String((Hi==null?void 0:Hi.text)||"").trim(),error:Eo}):null,on_open_artifacts:()=>{const v=String(u||"").trim();v&&(Ii(v),Za(v),Oo("run")),Lo("artifacts"),t("runtime")}}),T_.filter(v=>v.kind==="error"&&!v.data).slice(0,3).map(v=>s.jsxs("p",{className:"rs_notice",children:[v.title,": ",v.preview]},v.id)),s.jsx(yA,{items:uo,run_id:q_,run_options:H_,run_llm_counts:fo,on_select_run:v=>mh(v),state:Ao,on_state:Ts,node_label:(v,C)=>{const I=C?(so==null?void 0:so[hs(v,C)])||(so==null?void 0:so[C]):null;return String((I==null?void 0:I.label)||C||"").trim()},on_copy:v=>void Fl(v),on_open_run:v=>void _i(v,{root_run_id:h||u||v})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,er==="graph"?s.jsxs(s.Fragment,{children:[id?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"graph error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:id})]}):null,Rc?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:Vi.trim()?Vi.trim():oi})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(jR,{flow:To,flow_by_id:Tc,expand_subflows:Ro,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Kl,schedule_interval:$a,node_last_ms:Vd,active_node_id:Yh,recent_nodes:_h,visited_nodes:ph,highlight_path:ad,now_ms:F_})})]}):null,er==="chat"?s.jsxs("div",{className:"ask_tab log_scroll",style:{marginTop:"6px"},children:[s.jsxs("div",{className:"ask_header",children:[s.jsx("span",{className:"ask_title",children:"Ask about this run"}),s.jsx("span",{className:"chip muted",title:"Model comes from Settings → Assistant (blank = gateway default)",children:(n.maintenance_ai_provider.trim()||"gateway")+" / "+(n.maintenance_ai_model.trim()||"default")}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:"ask_hint",children:"Read-only · grounded in this run + subflows"})]}),s.jsxs("details",{className:"ask_manage",children:[s.jsx("summary",{children:"History & export"}),s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsxs("div",{className:"actions",style:{justifyContent:"space-between",alignItems:"center",gap:"10px",flexWrap:"wrap",marginTop:0},children:[s.jsx("div",{style:{flex:1,minWidth:260},children:s.jsx(ei,{value:wl,options:Zu,placeholder:$i?"Loading…":Zu.length?"Select a saved discussion…":"(none saved)",disabled:!u.trim()||!M||!Zu.length,loading:$i,searchable:!0,clearable:!0,onChange:v=>{Nc(v),Wa("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!wl.trim()||!M||Cc,onClick:()=>void W_(),children:Cc?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length||q||qt||Cc,onClick:()=>{Ve([]),_t(null),Zs(""),ii(""),Ft(""),En(""),ts("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Fd(),disabled:!u.trim()||!M||$i,children:$i?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length||!u.trim()||!M||qt||!Xu,onClick:()=>void Ph(),title:Xu?"":"No changes since last save",children:qt?"Saving…":!Xu&&dn?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length,onClick:()=>Dd("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ee.length,onClick:()=>Dd("copy"),children:je==="copied"?"Copied":je==="failed"?"Copy failed":"Copy Markdown"})]}),dn?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",mc(dn)]}):null,ws?s.jsx("div",{className:"chat_hint chat_hint_danger",children:ws}):null,lh?s.jsx("div",{className:"chat_hint chat_hint_danger",children:lh}):null,oh?s.jsx("div",{className:"chat_hint chat_hint_danger",children:oh}):null]})]}),Ua?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Ua})]}):null,Eo?s.jsxs("div",{className:"log_item log_item_danger",children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{children:"voice"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Eo})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(fy,{messages:Ee,className:"log_scroll",after:s.jsx(T$,{history:yt}),afterKey:yt?`${yt.replayed_messages}:${yt.dropped_messages}`:null,messageProps:Or.tts_supported&&M?{onSpeakToggle:Ih,getSpeakState:Oh,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(hy,{ref:vt,value:oa,onChange:Zs,onSubmit:()=>void Pd(),placeholder:"Ask about this run…",disabled:!u.trim()||!M||q,busy:q||Or.voice_ptt_busy,busyLabel:Or.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsx(q0,{voice:Or,defaults:is.value,prefs:Nn,blocked:M?q?"Wait for the answer.":null:"Connect to the gateway first."})}),D0()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:P0})]})]}):null,u.trim()?s.jsxs("div",{className:`status_bar ${jc?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:Yl||Je||"unknown"}),Jo&&Kl?s.jsxs("span",{className:"mono muted",children:[" • next in ",Kl]}):null,$r?s.jsxs("span",{className:"mono muted",children:[" • ",$r]}):null]}):null]})]})]})}):null,s.jsxs(lc,{open:zo,title:Tl||"Artifact",onClose:()=>{Bo(!1),mn(""),Ml(""),to(!1),va(null),Ht&&(URL.revokeObjectURL(Ht),Kr(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{Bo(!1),mn(""),Ml(""),to(!1),va(null),Ht&&(URL.revokeObjectURL(Ht),Kr(""))},children:"Close"}),children:[sr?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,_d?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:_d}):null,ds==="image"&&Ht?s.jsx("img",{className:"runtime_preview_media",src:Ht,alt:Tl||"Artifact preview"}):ds==="audio"&&Ht?s.jsx(v_,{className:"runtime_preview_media",src:Ht,name:Tl||void 0}):ds==="video"&&Ht?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:Ht}):s.jsx(uk,{artifact:eo,text:wa||"(empty)",className:"runtime_preview_text"})]}),Da?s.jsxs(lc,{open:Da,title:"Edit schedule",onClose:()=>{Fa(!1),Fn(""),Hn(!0),ri(""),Fs(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Fa(!1),Fn(""),Hn(!0),ri(""),Fs(!1)},disabled:pt||Mn,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Rh({interval:za,apply_immediately:pr})||(Fa(!1),ri(""),Fs(!1))},disabled:pt||Mn||!za.trim(),children:"Save"})]}),children:[sa?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:sa})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:za,onChange:v=>Fn(String(v.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:pt||Mn}),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:()=>Fn(v),disabled:pt||Mn,children:v},v))})]}),s.jsx("div",{className:"field",children:s.jsx(sM,{checked:pr,busy:pt||Mn,onChange:Hn})})]}):null,ps?s.jsxs(lc,{open:ps,title:"Compact scheduled context",onClose:()=>{Ks(!1),ys(""),Cr(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Ks(!1),ys(""),Cr(!1)},disabled:pt||Nr,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await Lh({preserve_recent:gs,compression_mode:ra,focus:No})||(Ks(!1),ys(""),Cr(!1))},disabled:pt||Nr,children:Nr?"Compacting…":"Compact"})]}),children:[Ba?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Ba})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(gs),onChange:v=>So(Math.max(1,parseInt(v.target.value||"6",10)||6)),disabled:pt||Nr})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:ra,onChange:v=>un(v.target.value),disabled:pt||Nr,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:No,onChange:v=>kc(String(v.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:pt||Nr})]})]}):null,ia?s.jsxs(lc,{open:ia,title:Cs==="cancel"?"Cancel run":or?"Suspend schedule":"Pause run",onClose:()=>{gr(!1),Ys(""),us("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{gr(!1),Ys(""),us("")},disabled:pt||gt,children:"Back"}),s.jsx("button",{className:`btn ${Cs==="cancel"?"danger":"primary"}`,onClick:async()=>{us("");const v=await Hl(Cs,{reason:Er});if(v){us(v);return}gr(!1),Ys(""),us("")},disabled:pt||gt,children:Cs==="pause"?or?"Suspend":"Pause":"Cancel"})]}),children:[Ci?s.jsxs("div",{className:"log_item",style:{borderColor:"rgba(239, 68, 68, 0.35)",marginBottom:"10px"},children:[s.jsxs("div",{className:"meta",children:[s.jsx("span",{className:"mono",children:"error"}),s.jsx("span",{className:"mono",children:Rt()})]}),s.jsx("div",{className:"body mono",children:Ci})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:Er,onChange:v=>Ys(v.target.value),placeholder:"reason…"})]})]}):null,oo?s.jsxs(lc,{open:oo,title:Ud,onClose:()=>{$s&&Xs($s)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{la("ledger"),t("observe"),du(),$s&&Xs($s)},disabled:!u.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>$s&&Xs($s),disabled:gt,children:"Dismiss"}),Na.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:gt,onClick:()=>Jc({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:gt,onClick:()=>Jc({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!zi||gt,onClick:()=>Dh(Na),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:Ud}),s.jsx("p",{children:Uh})]}),s.jsx(vc,{status:Ca||"waiting"})]}),co?s.jsxs("div",{className:`wait_request_card ${Qc?"":"inferred"}`,children:[s.jsx("span",{children:qh}),s.jsx(Kx,{metadata:Wh}),s.jsx(Si,{text:co}),Qc?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."}),Us.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:Us.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:mc(v.ts)}):null]}),s.jsx(Kx,{metadata:v.runtime_metadata}),s.jsx(Si,{text:At(v.text,{max_chars:1200,max_lines:10})})]},`${v.role}:${C}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Zi(lo,Lr)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:sn(u.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:lo.current_node||String((Bs==null?void 0:Bs.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:yc(lo)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:lo.session_id?sn(String(lo.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:sn($s,28)})]})]}),Vh?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!co,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Hh,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:[Bh.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,mc(v.ts)].filter(Boolean).join(" · ")})]},`${v.cursor}:${v.node_id}:${v.status}`)),Bh.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),Na.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:Na.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"}),nk(v).map(I=>s.jsxs("span",{className:"chip mono muted",title:tk,children:[I,"~"]},I))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(Is,{value:(v==null?void 0:v.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((v==null?void 0:v.name)||"tool")}:${C}`))}),zi?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 Od(u.trim(),"Cancelled from wait prompt"),disabled:!u.trim()||gt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Wt||{},collapseAfterDepth:3,showCopy:!0})})]})]}):s.jsxs("div",{className:"wait_action_panel",children:[s.jsx("div",{className:"wait_action_intro",children:"Submit only when the request above is clear. The response resumes this wait only; Cancel run attempts to stop the whole workflow and prevent further work."}),s.jsx("div",{className:"wait_prompt_text",children:co||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(aR,{wait:Wt,disabled:gt,on_submit:v=>Jc({response:v})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void Od(u.trim(),"Cancelled from wait prompt"),disabled:!u.trim()||gt,children:"Cancel whole run"})}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Diagnostics"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(Is,{value:Wt||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(R$).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}wS();hS.createRoot(document.getElementById("root")).render(s.jsx(xe.StrictMode,{children:s.jsx(NP,{})}));
|
|
162
|
-
//# sourceMappingURL=index-KdTDT-qO.js.map
|