@abstractframework/observer 0.10.0 → 0.10.2

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.
@@ -0,0 +1,178 @@
1
+ var cE=Object.defineProperty;var uE=(e,t,n)=>t in e?cE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var jn=(e,t,n)=>uE(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();function Yv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var fy={exports:{}},gh={},hy={exports:{}},Sn={};/**
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 sb;function dE(){if(sb)return Sn;sb=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),c=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),_=Symbol.iterator;function g(B){return B===null||typeof B!="object"?null:(B=_&&B[_]||B["@@iterator"],typeof B=="function"?B:null)}var y={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,k={};function v(B,te,se){this.props=B,this.context=te,this.refs=k,this.updater=se||y}v.prototype.isReactComponent={},v.prototype.setState=function(B,te){if(typeof B!="object"&&typeof B!="function"&&B!=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,B,te,"setState")},v.prototype.forceUpdate=function(B){this.updater.enqueueForceUpdate(this,B,"forceUpdate")};function N(){}N.prototype=v.prototype;function $(B,te,se){this.props=B,this.context=te,this.refs=k,this.updater=se||y}var C=$.prototype=new N;C.constructor=$,x(C,v.prototype),C.isPureReactComponent=!0;var S=Array.isArray,D=Object.prototype.hasOwnProperty,O={current:null},A={key:!0,ref:!0,__self:!0,__source:!0};function P(B,te,se){var de,be={},Me=null,Ne=null;if(te!=null)for(de in te.ref!==void 0&&(Ne=te.ref),te.key!==void 0&&(Me=""+te.key),te)D.call(te,de)&&!A.hasOwnProperty(de)&&(be[de]=te[de]);var ae=arguments.length-2;if(ae===1)be.children=se;else if(1<ae){for(var je=Array(ae),Te=0;Te<ae;Te++)je[Te]=arguments[Te+2];be.children=je}if(B&&B.defaultProps)for(de in ae=B.defaultProps,ae)be[de]===void 0&&(be[de]=ae[de]);return{$$typeof:e,type:B,key:Me,ref:Ne,props:be,_owner:O.current}}function W(B,te){return{$$typeof:e,type:B.type,key:te,ref:B.ref,props:B.props,_owner:B._owner}}function J(B){return typeof B=="object"&&B!==null&&B.$$typeof===e}function G(B){var te={"=":"=0",":":"=2"};return"$"+B.replace(/[=:]/g,function(se){return te[se]})}var V=/\/+/g;function R(B,te){return typeof B=="object"&&B!==null&&B.key!=null?G(""+B.key):te.toString(36)}function M(B,te,se,de,be){var Me=typeof B;(Me==="undefined"||Me==="boolean")&&(B=null);var Ne=!1;if(B===null)Ne=!0;else switch(Me){case"string":case"number":Ne=!0;break;case"object":switch(B.$$typeof){case e:case t:Ne=!0}}if(Ne)return Ne=B,be=be(Ne),B=de===""?"."+R(Ne,0):de,S(be)?(se="",B!=null&&(se=B.replace(V,"$&/")+"/"),M(be,te,se,"",function(Te){return Te})):be!=null&&(J(be)&&(be=W(be,se+(!be.key||Ne&&Ne.key===be.key?"":(""+be.key).replace(V,"$&/")+"/")+B)),te.push(be)),1;if(Ne=0,de=de===""?".":de+":",S(B))for(var ae=0;ae<B.length;ae++){Me=B[ae];var je=de+R(Me,ae);Ne+=M(Me,te,se,je,be)}else if(je=g(B),typeof je=="function")for(B=je.call(B),ae=0;!(Me=B.next()).done;)Me=Me.value,je=de+R(Me,ae++),Ne+=M(Me,te,se,je,be);else if(Me==="object")throw te=String(B),Error("Objects are not valid as a React child (found: "+(te==="[object Object]"?"object with keys {"+Object.keys(B).join(", ")+"}":te)+"). If you meant to render a collection of children, use an array instead.");return Ne}function I(B,te,se){if(B==null)return B;var de=[],be=0;return M(B,de,"","",function(Me){return te.call(se,Me,be++)}),de}function L(B){if(B._status===-1){var te=B._result;te=te(),te.then(function(se){(B._status===0||B._status===-1)&&(B._status=1,B._result=se)},function(se){(B._status===0||B._status===-1)&&(B._status=2,B._result=se)}),B._status===-1&&(B._status=0,B._result=te)}if(B._status===1)return B._result.default;throw B._result}var K={current:null},H={transition:null},z={ReactCurrentDispatcher:K,ReactCurrentBatchConfig:H,ReactCurrentOwner:O};function ee(){throw Error("act(...) is not supported in production builds of React.")}return Sn.Children={map:I,forEach:function(B,te,se){I(B,function(){te.apply(this,arguments)},se)},count:function(B){var te=0;return I(B,function(){te++}),te},toArray:function(B){return I(B,function(te){return te})||[]},only:function(B){if(!J(B))throw Error("React.Children.only expected to receive a single React element child.");return B}},Sn.Component=v,Sn.Fragment=n,Sn.Profiler=i,Sn.PureComponent=$,Sn.StrictMode=r,Sn.Suspense=d,Sn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=z,Sn.act=ee,Sn.cloneElement=function(B,te,se){if(B==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+B+".");var de=x({},B.props),be=B.key,Me=B.ref,Ne=B._owner;if(te!=null){if(te.ref!==void 0&&(Me=te.ref,Ne=O.current),te.key!==void 0&&(be=""+te.key),B.type&&B.type.defaultProps)var ae=B.type.defaultProps;for(je in te)D.call(te,je)&&!A.hasOwnProperty(je)&&(de[je]=te[je]===void 0&&ae!==void 0?ae[je]:te[je])}var je=arguments.length-2;if(je===1)de.children=se;else if(1<je){ae=Array(je);for(var Te=0;Te<je;Te++)ae[Te]=arguments[Te+2];de.children=ae}return{$$typeof:e,type:B.type,key:be,ref:Me,props:de,_owner:Ne}},Sn.createContext=function(B){return B={$$typeof:c,_currentValue:B,_currentValue2:B,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},B.Provider={$$typeof:o,_context:B},B.Consumer=B},Sn.createElement=P,Sn.createFactory=function(B){var te=P.bind(null,B);return te.type=B,te},Sn.createRef=function(){return{current:null}},Sn.forwardRef=function(B){return{$$typeof:l,render:B}},Sn.isValidElement=J,Sn.lazy=function(B){return{$$typeof:m,_payload:{_status:-1,_result:B},_init:L}},Sn.memo=function(B,te){return{$$typeof:h,type:B,compare:te===void 0?null:te}},Sn.startTransition=function(B){var te=H.transition;H.transition={};try{B()}finally{H.transition=te}},Sn.unstable_act=ee,Sn.useCallback=function(B,te){return K.current.useCallback(B,te)},Sn.useContext=function(B){return K.current.useContext(B)},Sn.useDebugValue=function(){},Sn.useDeferredValue=function(B){return K.current.useDeferredValue(B)},Sn.useEffect=function(B,te){return K.current.useEffect(B,te)},Sn.useId=function(){return K.current.useId()},Sn.useImperativeHandle=function(B,te,se){return K.current.useImperativeHandle(B,te,se)},Sn.useInsertionEffect=function(B,te){return K.current.useInsertionEffect(B,te)},Sn.useLayoutEffect=function(B,te){return K.current.useLayoutEffect(B,te)},Sn.useMemo=function(B,te){return K.current.useMemo(B,te)},Sn.useReducer=function(B,te,se){return K.current.useReducer(B,te,se)},Sn.useRef=function(B){return K.current.useRef(B)},Sn.useState=function(B){return K.current.useState(B)},Sn.useSyncExternalStore=function(B,te,se){return K.current.useSyncExternalStore(B,te,se)},Sn.useTransition=function(){return K.current.useTransition()},Sn.version="18.3.1",Sn}var rb;function vm(){return rb||(rb=1,hy.exports=dE()),hy.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 ib;function fE(){if(ib)return gh;ib=1;var e=vm(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function c(l,d,h){var m,_={},g=null,y=null;h!==void 0&&(g=""+h),d.key!==void 0&&(g=""+d.key),d.ref!==void 0&&(y=d.ref);for(m in d)r.call(d,m)&&!o.hasOwnProperty(m)&&(_[m]=d[m]);if(l&&l.defaultProps)for(m in d=l.defaultProps,d)_[m]===void 0&&(_[m]=d[m]);return{$$typeof:t,type:l,key:g,ref:y,props:_,_owner:i.current}}return gh.Fragment=n,gh.jsx=c,gh.jsxs=c,gh}var ob;function hE(){return ob||(ob=1,fy.exports=fE()),fy.exports}var s=hE(),p=vm();const Ae=Yv(p);var G_={},my={exports:{}},xi={},_y={exports:{}},py={};/**
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 ab;function mE(){return ab||(ab=1,(function(e){function t(H,z){var ee=H.length;H.push(z);e:for(;0<ee;){var B=ee-1>>>1,te=H[B];if(0<i(te,z))H[B]=z,H[ee]=te,ee=B;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var z=H[0],ee=H.pop();if(ee!==z){H[0]=ee;e:for(var B=0,te=H.length,se=te>>>1;B<se;){var de=2*(B+1)-1,be=H[de],Me=de+1,Ne=H[Me];if(0>i(be,ee))Me<te&&0>i(Ne,be)?(H[B]=Ne,H[Me]=ee,B=Me):(H[B]=be,H[de]=ee,B=de);else if(Me<te&&0>i(Ne,ee))H[B]=Ne,H[Me]=ee,B=Me;else break e}}return z}function i(H,z){var ee=H.sortIndex-z.sortIndex;return ee!==0?ee:H.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,l=c.now();e.unstable_now=function(){return c.now()-l}}var d=[],h=[],m=1,_=null,g=3,y=!1,x=!1,k=!1,v=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,$=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var z=n(h);z!==null;){if(z.callback===null)r(h);else if(z.startTime<=H)r(h),z.sortIndex=z.expirationTime,t(d,z);else break;z=n(h)}}function S(H){if(k=!1,C(H),!x)if(n(d)!==null)x=!0,L(D);else{var z=n(h);z!==null&&K(S,z.startTime-H)}}function D(H,z){x=!1,k&&(k=!1,N(P),P=-1),y=!0;var ee=g;try{for(C(z),_=n(d);_!==null&&(!(_.expirationTime>z)||H&&!G());){var B=_.callback;if(typeof B=="function"){_.callback=null,g=_.priorityLevel;var te=B(_.expirationTime<=z);z=e.unstable_now(),typeof te=="function"?_.callback=te:_===n(d)&&r(d),C(z)}else r(d);_=n(d)}if(_!==null)var se=!0;else{var de=n(h);de!==null&&K(S,de.startTime-z),se=!1}return se}finally{_=null,g=ee,y=!1}}var O=!1,A=null,P=-1,W=5,J=-1;function G(){return!(e.unstable_now()-J<W)}function V(){if(A!==null){var H=e.unstable_now();J=H;var z=!0;try{z=A(!0,H)}finally{z?R():(O=!1,A=null)}}else O=!1}var R;if(typeof $=="function")R=function(){$(V)};else if(typeof MessageChannel<"u"){var M=new MessageChannel,I=M.port2;M.port1.onmessage=V,R=function(){I.postMessage(null)}}else R=function(){v(V,0)};function L(H){A=H,O||(O=!0,R())}function K(H,z){P=v(function(){H(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,L(D))},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):W=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return g},e.unstable_getFirstCallbackNode=function(){return n(d)},e.unstable_next=function(H){switch(g){case 1:case 2:case 3:var z=3;break;default:z=g}var ee=g;g=z;try{return H()}finally{g=ee}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(H,z){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var ee=g;g=H;try{return z()}finally{g=ee}},e.unstable_scheduleCallback=function(H,z,ee){var B=e.unstable_now();switch(typeof ee=="object"&&ee!==null?(ee=ee.delay,ee=typeof ee=="number"&&0<ee?B+ee:B):ee=B,H){case 1:var te=-1;break;case 2:te=250;break;case 5:te=1073741823;break;case 4:te=1e4;break;default:te=5e3}return te=ee+te,H={id:m++,callback:z,priorityLevel:H,startTime:ee,expirationTime:te,sortIndex:-1},ee>B?(H.sortIndex=ee,t(h,H),n(d)===null&&H===n(h)&&(k?(N(P),P=-1):k=!0,K(S,ee-B))):(H.sortIndex=te,t(d,H),x||y||(x=!0,L(D))),H},e.unstable_shouldYield=G,e.unstable_wrapCallback=function(H){var z=g;return function(){var ee=g;g=z;try{return H.apply(this,arguments)}finally{g=ee}}}})(py)),py}var lb;function _E(){return lb||(lb=1,_y.exports=mE()),_y.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 cb;function pE(){if(cb)return xi;cb=1;var e=vm(),t=_E();function n(a){for(var u="https://reactjs.org/docs/error-decoder.html?invariant="+a,f=1;f<arguments.length;f++)u+="&args[]="+encodeURIComponent(arguments[f]);return"Minified React error #"+a+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,i={};function o(a,u){c(a,u),c(a+"Capture",u)}function c(a,u){for(i[a]=u,a=0;a<u.length;a++)r.add(u[a])}var l=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),d=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={},_={};function g(a){return d.call(_,a)?!0:d.call(m,a)?!1:h.test(a)?_[a]=!0:(m[a]=!0,!1)}function y(a,u,f,w){if(f!==null&&f.type===0)return!1;switch(typeof u){case"function":case"symbol":return!0;case"boolean":return w?!1:f!==null?!f.acceptsBooleans:(a=a.toLowerCase().slice(0,5),a!=="data-"&&a!=="aria-");default:return!1}}function x(a,u,f,w){if(u===null||typeof u>"u"||y(a,u,f,w))return!0;if(w)return!1;if(f!==null)switch(f.type){case 3:return!u;case 4:return u===!1;case 5:return isNaN(u);case 6:return isNaN(u)||1>u}return!1}function k(a,u,f,w,j,E,q){this.acceptsBooleans=u===2||u===3||u===4,this.attributeName=w,this.attributeNamespace=j,this.mustUseProperty=f,this.propertyName=a,this.type=u,this.sanitizeURL=E,this.removeEmptyString=q}var v={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){v[a]=new k(a,0,!1,a,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var u=a[0];v[u]=new k(u,1,!1,a[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){v[a]=new k(a,2,!1,a.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){v[a]=new k(a,2,!1,a,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(a){v[a]=new k(a,3,!1,a.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(a){v[a]=new k(a,3,!0,a,null,!1,!1)}),["capture","download"].forEach(function(a){v[a]=new k(a,4,!1,a,null,!1,!1)}),["cols","rows","size","span"].forEach(function(a){v[a]=new k(a,6,!1,a,null,!1,!1)}),["rowSpan","start"].forEach(function(a){v[a]=new k(a,5,!1,a.toLowerCase(),null,!1,!1)});var N=/[\-:]([a-z])/g;function $(a){return a[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(a){var u=a.replace(N,$);v[u]=new k(u,1,!1,a,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var u=a.replace(N,$);v[u]=new k(u,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(a){var u=a.replace(N,$);v[u]=new k(u,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(a){v[a]=new k(a,1,!1,a.toLowerCase(),null,!1,!1)}),v.xlinkHref=new k("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(a){v[a]=new k(a,1,!1,a.toLowerCase(),null,!0,!0)});function C(a,u,f,w){var j=v.hasOwnProperty(u)?v[u]:null;(j!==null?j.type!==0:w||!(2<u.length)||u[0]!=="o"&&u[0]!=="O"||u[1]!=="n"&&u[1]!=="N")&&(x(u,f,j,w)&&(f=null),w||j===null?g(u)&&(f===null?a.removeAttribute(u):a.setAttribute(u,""+f)):j.mustUseProperty?a[j.propertyName]=f===null?j.type===3?!1:"":f:(u=j.attributeName,w=j.attributeNamespace,f===null?a.removeAttribute(u):(j=j.type,f=j===3||j===4&&f===!0?"":""+f,w?a.setAttributeNS(w,u,f):a.setAttribute(u,f))))}var S=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,D=Symbol.for("react.element"),O=Symbol.for("react.portal"),A=Symbol.for("react.fragment"),P=Symbol.for("react.strict_mode"),W=Symbol.for("react.profiler"),J=Symbol.for("react.provider"),G=Symbol.for("react.context"),V=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),K=Symbol.for("react.offscreen"),H=Symbol.iterator;function z(a){return a===null||typeof a!="object"?null:(a=H&&a[H]||a["@@iterator"],typeof a=="function"?a:null)}var ee=Object.assign,B;function te(a){if(B===void 0)try{throw Error()}catch(f){var u=f.stack.trim().match(/\n( *(at )?)/);B=u&&u[1]||""}return`
34
+ `+B+a}var se=!1;function de(a,u){if(!a||se)return"";se=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(u)if(u=function(){throw Error()},Object.defineProperty(u.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(u,[])}catch(Re){var w=Re}Reflect.construct(a,[],u)}else{try{u.call()}catch(Re){w=Re}a.call(u.prototype)}else{try{throw Error()}catch(Re){w=Re}a()}}catch(Re){if(Re&&w&&typeof Re.stack=="string"){for(var j=Re.stack.split(`
35
+ `),E=w.stack.split(`
36
+ `),q=j.length-1,ie=E.length-1;1<=q&&0<=ie&&j[q]!==E[ie];)ie--;for(;1<=q&&0<=ie;q--,ie--)if(j[q]!==E[ie]){if(q!==1||ie!==1)do if(q--,ie--,0>ie||j[q]!==E[ie]){var ue=`
37
+ `+j[q].replace(" at new "," at ");return a.displayName&&ue.includes("<anonymous>")&&(ue=ue.replace("<anonymous>",a.displayName)),ue}while(1<=q&&0<=ie);break}}}finally{se=!1,Error.prepareStackTrace=f}return(a=a?a.displayName||a.name:"")?te(a):""}function be(a){switch(a.tag){case 5:return te(a.type);case 16:return te("Lazy");case 13:return te("Suspense");case 19:return te("SuspenseList");case 0:case 2:case 15:return a=de(a.type,!1),a;case 11:return a=de(a.type.render,!1),a;case 1:return a=de(a.type,!0),a;default:return""}}function Me(a){if(a==null)return null;if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case A:return"Fragment";case O:return"Portal";case W:return"Profiler";case P:return"StrictMode";case R:return"Suspense";case M:return"SuspenseList"}if(typeof a=="object")switch(a.$$typeof){case G:return(a.displayName||"Context")+".Consumer";case J:return(a._context.displayName||"Context")+".Provider";case V:var u=a.render;return a=a.displayName,a||(a=u.displayName||u.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case I:return u=a.displayName||null,u!==null?u:Me(a.type)||"Memo";case L:u=a._payload,a=a._init;try{return Me(a(u))}catch{}}return null}function Ne(a){var u=a.type;switch(a.tag){case 24:return"Cache";case 9:return(u.displayName||"Context")+".Consumer";case 10:return(u._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=u.render,a=a.displayName||a.name||"",u.displayName||(a!==""?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return u;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Me(u);case 8:return u===P?"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 u=="function")return u.displayName||u.name||null;if(typeof u=="string")return u}return null}function ae(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":return a;case"object":return a;default:return""}}function je(a){var u=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(u==="checkbox"||u==="radio")}function Te(a){var u=je(a)?"checked":"value",f=Object.getOwnPropertyDescriptor(a.constructor.prototype,u),w=""+a[u];if(!a.hasOwnProperty(u)&&typeof f<"u"&&typeof f.get=="function"&&typeof f.set=="function"){var j=f.get,E=f.set;return Object.defineProperty(a,u,{configurable:!0,get:function(){return j.call(this)},set:function(q){w=""+q,E.call(this,q)}}),Object.defineProperty(a,u,{enumerable:f.enumerable}),{getValue:function(){return w},setValue:function(q){w=""+q},stopTracking:function(){a._valueTracker=null,delete a[u]}}}}function Ve(a){a._valueTracker||(a._valueTracker=Te(a))}function _t(a){if(!a)return!1;var u=a._valueTracker;if(!u)return!0;var f=u.getValue(),w="";return a&&(w=je(a)?a.checked?"true":"false":a.value),a=w,a!==f?(u.setValue(a),!0):!1}function Qe(a){if(a=a||(typeof document<"u"?document:void 0),typeof a>"u")return null;try{return a.activeElement||a.body}catch{return a.body}}function it(a,u){var f=u.checked;return ee({},u,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:f??a._wrapperState.initialChecked})}function $t(a,u){var f=u.defaultValue==null?"":u.defaultValue,w=u.checked!=null?u.checked:u.defaultChecked;f=ae(u.value!=null?u.value:f),a._wrapperState={initialChecked:w,initialValue:f,controlled:u.type==="checkbox"||u.type==="radio"?u.checked!=null:u.value!=null}}function ot(a,u){u=u.checked,u!=null&&C(a,"checked",u,!1)}function mt(a,u){ot(a,u);var f=ae(u.value),w=u.type;if(f!=null)w==="number"?(f===0&&a.value===""||a.value!=f)&&(a.value=""+f):a.value!==""+f&&(a.value=""+f);else if(w==="submit"||w==="reset"){a.removeAttribute("value");return}u.hasOwnProperty("value")?Lt(a,u.type,f):u.hasOwnProperty("defaultValue")&&Lt(a,u.type,ae(u.defaultValue)),u.checked==null&&u.defaultChecked!=null&&(a.defaultChecked=!!u.defaultChecked)}function et(a,u,f){if(u.hasOwnProperty("value")||u.hasOwnProperty("defaultValue")){var w=u.type;if(!(w!=="submit"&&w!=="reset"||u.value!==void 0&&u.value!==null))return;u=""+a._wrapperState.initialValue,f||u===a.value||(a.value=u),a.defaultValue=u}f=a.name,f!==""&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,f!==""&&(a.name=f)}function Lt(a,u,f){(u!=="number"||Qe(a.ownerDocument)!==a)&&(f==null?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+f&&(a.defaultValue=""+f))}var ce=Array.isArray;function Se(a,u,f,w){if(a=a.options,u){u={};for(var j=0;j<f.length;j++)u["$"+f[j]]=!0;for(f=0;f<a.length;f++)j=u.hasOwnProperty("$"+a[f].value),a[f].selected!==j&&(a[f].selected=j),j&&w&&(a[f].defaultSelected=!0)}else{for(f=""+ae(f),u=null,j=0;j<a.length;j++){if(a[j].value===f){a[j].selected=!0,w&&(a[j].defaultSelected=!0);return}u!==null||a[j].disabled||(u=a[j])}u!==null&&(u.selected=!0)}}function He(a,u){if(u.dangerouslySetInnerHTML!=null)throw Error(n(91));return ee({},u,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function ne(a,u){var f=u.value;if(f==null){if(f=u.children,u=u.defaultValue,f!=null){if(u!=null)throw Error(n(92));if(ce(f)){if(1<f.length)throw Error(n(93));f=f[0]}u=f}u==null&&(u=""),f=u}a._wrapperState={initialValue:ae(f)}}function we(a,u){var f=ae(u.value),w=ae(u.defaultValue);f!=null&&(f=""+f,f!==a.value&&(a.value=f),u.defaultValue==null&&a.defaultValue!==f&&(a.defaultValue=f)),w!=null&&(a.defaultValue=""+w)}function fe(a){var u=a.textContent;u===a._wrapperState.initialValue&&u!==""&&u!==null&&(a.value=u)}function $e(a){switch(a){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 pe(a,u){return a==null||a==="http://www.w3.org/1999/xhtml"?$e(u):a==="http://www.w3.org/2000/svg"&&u==="foreignObject"?"http://www.w3.org/1999/xhtml":a}var le,ze=(function(a){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(u,f,w,j){MSApp.execUnsafeLocalFunction(function(){return a(u,f,w,j)})}:a})(function(a,u){if(a.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in a)a.innerHTML=u;else{for(le=le||document.createElement("div"),le.innerHTML="<svg>"+u.valueOf().toString()+"</svg>",u=le.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;u.firstChild;)a.appendChild(u.firstChild)}});function st(a,u){if(u){var f=a.firstChild;if(f&&f===a.lastChild&&f.nodeType===3){f.nodeValue=u;return}}a.textContent=u}var kt={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},pt=["Webkit","ms","Moz","O"];Object.keys(kt).forEach(function(a){pt.forEach(function(u){u=u+a.charAt(0).toUpperCase()+a.substring(1),kt[u]=kt[a]})});function jt(a,u,f){return u==null||typeof u=="boolean"||u===""?"":f||typeof u!="number"||u===0||kt.hasOwnProperty(a)&&kt[a]?(""+u).trim():u+"px"}function ct(a,u){a=a.style;for(var f in u)if(u.hasOwnProperty(f)){var w=f.indexOf("--")===0,j=jt(f,u[f],w);f==="float"&&(f="cssFloat"),w?a.setProperty(f,j):a[f]=j}}var It=ee({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 vt(a,u){if(u){if(It[a]&&(u.children!=null||u.dangerouslySetInnerHTML!=null))throw Error(n(137,a));if(u.dangerouslySetInnerHTML!=null){if(u.children!=null)throw Error(n(60));if(typeof u.dangerouslySetInnerHTML!="object"||!("__html"in u.dangerouslySetInnerHTML))throw Error(n(61))}if(u.style!=null&&typeof u.style!="object")throw Error(n(62))}}function nn(a,u){if(a.indexOf("-")===-1)return typeof u.is=="string";switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var wn=null;function On(a){return a=a.target||a.srcElement||window,a.correspondingUseElement&&(a=a.correspondingUseElement),a.nodeType===3?a.parentNode:a}var Ks=null,rs=null,ge=null;function Le(a){if(a=sa(a)){if(typeof Ks!="function")throw Error(n(280));var u=a.stateNode;u&&(u=Mo(u),Ks(a.stateNode,a.type,u))}}function yt(a){rs?ge?ge.push(a):ge=[a]:rs=a}function re(){if(rs){var a=rs,u=ge;if(ge=rs=null,Le(a),u)for(a=0;a<u.length;a++)Le(u[a])}}function he(a,u){return a(u)}function Ee(){}var Ie=!1;function We(a,u,f){if(Ie)return a(u,f);Ie=!0;try{return he(a,u,f)}finally{Ie=!1,(rs!==null||ge!==null)&&(Ee(),re())}}function Ue(a,u){var f=a.stateNode;if(f===null)return null;var w=Mo(f);if(w===null)return null;f=w[u];e:switch(u){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(w=!w.disabled)||(a=a.type,w=!(a==="button"||a==="input"||a==="select"||a==="textarea")),a=!w;break e;default:a=!1}if(a)return null;if(f&&typeof f!="function")throw Error(n(231,u,typeof f));return f}var tt=!1;if(l)try{var ut={};Object.defineProperty(ut,"passive",{get:function(){tt=!0}}),window.addEventListener("test",ut,ut),window.removeEventListener("test",ut,ut)}catch{tt=!1}function xt(a,u,f,w,j,E,q,ie,ue){var Re=Array.prototype.slice.call(arguments,3);try{u.apply(f,Re)}catch(Ze){this.onError(Ze)}}var bt=!1,Mt=null,zt=!1,lt=null,Yt={onError:function(a){bt=!0,Mt=a}};function vn(a,u,f,w,j,E,q,ie,ue){bt=!1,Mt=null,xt.apply(Yt,arguments)}function mn(a,u,f,w,j,E,q,ie,ue){if(vn.apply(this,arguments),bt){if(bt){var Re=Mt;bt=!1,Mt=null}else throw Error(n(198));zt||(zt=!0,lt=Re)}}function rn(a){var u=a,f=a;if(a.alternate)for(;u.return;)u=u.return;else{a=u;do u=a,(u.flags&4098)!==0&&(f=u.return),a=u.return;while(a)}return u.tag===3?f:null}function Ht(a){if(a.tag===13){var u=a.memoizedState;if(u===null&&(a=a.alternate,a!==null&&(u=a.memoizedState)),u!==null)return u.dehydrated}return null}function is(a){if(rn(a)!==a)throw Error(n(188))}function Be(a){var u=a.alternate;if(!u){if(u=rn(a),u===null)throw Error(n(188));return u!==a?null:a}for(var f=a,w=u;;){var j=f.return;if(j===null)break;var E=j.alternate;if(E===null){if(w=j.return,w!==null){f=w;continue}break}if(j.child===E.child){for(E=j.child;E;){if(E===f)return is(j),a;if(E===w)return is(j),u;E=E.sibling}throw Error(n(188))}if(f.return!==w.return)f=j,w=E;else{for(var q=!1,ie=j.child;ie;){if(ie===f){q=!0,f=j,w=E;break}if(ie===w){q=!0,w=j,f=E;break}ie=ie.sibling}if(!q){for(ie=E.child;ie;){if(ie===f){q=!0,f=E,w=j;break}if(ie===w){q=!0,w=E,f=j;break}ie=ie.sibling}if(!q)throw Error(n(189))}}if(f.alternate!==w)throw Error(n(190))}if(f.tag!==3)throw Error(n(188));return f.stateNode.current===f?a:u}function Qt(a){return a=Be(a),a!==null?Ot(a):null}function Ot(a){if(a.tag===5||a.tag===6)return a;for(a=a.child;a!==null;){var u=Ot(a);if(u!==null)return u;a=a.sibling}return null}var Fn=t.unstable_scheduleCallback,hn=t.unstable_cancelCallback,Xe=t.unstable_shouldYield,sn=t.unstable_requestPaint,un=t.unstable_now,Ar=t.unstable_getCurrentPriorityLevel,As=t.unstable_ImmediatePriority,ws=t.unstable_UserBlockingPriority,_r=t.unstable_NormalPriority,ve=t.unstable_LowPriority,Ct=t.unstable_IdlePriority,zn=null,nr=null;function $i(a){if(nr&&typeof nr.onCommitFiberRoot=="function")try{nr.onCommitFiberRoot(zn,a,void 0,(a.current.flags&128)===128)}catch{}}var sr=Math.clz32?Math.clz32:ul,bo=Math.log,dc=Math.LN2;function ul(a){return a>>>=0,a===0?32:31-(bo(a)/dc|0)|0}var js=64,pr=4194304;function Rs(a){switch(a&-a){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 a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function Bi(a,u){var f=a.pendingLanes;if(f===0)return 0;var w=0,j=a.suspendedLanes,E=a.pingedLanes,q=f&268435455;if(q!==0){var ie=q&~j;ie!==0?w=Rs(ie):(E&=q,E!==0&&(w=Rs(E)))}else q=f&~j,q!==0?w=Rs(q):E!==0&&(w=Rs(E));if(w===0)return 0;if(u!==0&&u!==w&&(u&j)===0&&(j=w&-w,E=u&-u,j>=E||j===16&&(E&4194240)!==0))return u;if((w&4)!==0&&(w|=f&16),u=a.entangledLanes,u!==0)for(a=a.entanglements,u&=w;0<u;)f=31-sr(u),j=1<<f,w|=a[f],u&=~j;return w}function dl(a,u){switch(a){case 1:case 2:case 4:return u+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 u+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 vs(a,u){for(var f=a.suspendedLanes,w=a.pingedLanes,j=a.expirationTimes,E=a.pendingLanes;0<E;){var q=31-sr(E),ie=1<<q,ue=j[q];ue===-1?((ie&f)===0||(ie&w)!==0)&&(j[q]=dl(ie,u)):ue<=u&&(a.expiredLanes|=ie),E&=~ie}}function ri(a){return a=a.pendingLanes&-1073741825,a!==0?a:a&1073741824?1073741824:0}function Ls(){var a=js;return js<<=1,(js&4194240)===0&&(js=64),a}function ii(a){for(var u=[],f=0;31>f;f++)u.push(a);return u}function Ss(a,u,f){a.pendingLanes|=u,u!==536870912&&(a.suspendedLanes=0,a.pingedLanes=0),a=a.eventTimes,u=31-sr(u),a[u]=f}function oi(a,u){var f=a.pendingLanes&~u;a.pendingLanes=u,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=u,a.mutableReadLanes&=u,a.entangledLanes&=u,u=a.entanglements;var w=a.eventTimes;for(a=a.expirationTimes;0<f;){var j=31-sr(f),E=1<<j;u[j]=0,w[j]=-1,a[j]=-1,f&=~E}}function Ui(a,u){var f=a.entangledLanes|=u;for(a=a.entanglements;f;){var w=31-sr(f),j=1<<w;j&u|a[w]&u&&(a[w]|=u),f&=~j}}var In=0;function $a(a){return a&=-a,1<a?4<a?(a&268435455)!==0?16:536870912:4:1}var fl,hl,Tr,fc,Wi,Ca=!1,ko=[],Fs=null,zs=null,gr=null,jo=new Map,qr=new Map,Mr=[],Vr="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 hc(a,u){switch(a){case"focusin":case"focusout":Fs=null;break;case"dragenter":case"dragleave":zs=null;break;case"mouseover":case"mouseout":gr=null;break;case"pointerover":case"pointerout":jo.delete(u.pointerId);break;case"gotpointercapture":case"lostpointercapture":qr.delete(u.pointerId)}}function Hr(a,u,f,w,j,E){return a===null||a.nativeEvent!==E?(a={blockedOn:u,domEventName:f,eventSystemFlags:w,nativeEvent:E,targetContainers:[j]},u!==null&&(u=sa(u),u!==null&&hl(u)),a):(a.eventSystemFlags|=w,u=a.targetContainers,j!==null&&u.indexOf(j)===-1&&u.push(j),a)}function ku(a,u,f,w,j){switch(u){case"focusin":return Fs=Hr(Fs,a,u,f,w,j),!0;case"dragenter":return zs=Hr(zs,a,u,f,w,j),!0;case"mouseover":return gr=Hr(gr,a,u,f,w,j),!0;case"pointerover":var E=j.pointerId;return jo.set(E,Hr(jo.get(E)||null,a,u,f,w,j)),!0;case"gotpointercapture":return E=j.pointerId,qr.set(E,Hr(qr.get(E)||null,a,u,f,w,j)),!0}return!1}function Ci(a){var u=Fa(a.target);if(u!==null){var f=rn(u);if(f!==null){if(u=f.tag,u===13){if(u=Ht(f),u!==null){a.blockedOn=u,Wi(a.priority,function(){Tr(f)});return}}else if(u===3&&f.stateNode.current.memoizedState.isDehydrated){a.blockedOn=f.tag===3?f.stateNode.containerInfo:null;return}}}a.blockedOn=null}function Zo(a){if(a.blockedOn!==null)return!1;for(var u=a.targetContainers;0<u.length;){var f=me(a.domEventName,a.eventSystemFlags,u[0],a.nativeEvent);if(f===null){f=a.nativeEvent;var w=new f.constructor(f.type,f);wn=w,f.target.dispatchEvent(w),wn=null}else return u=sa(f),u!==null&&hl(u),a.blockedOn=f,!1;u.shift()}return!0}function ml(a,u,f){Zo(a)&&f.delete(u)}function So(){Ca=!1,Fs!==null&&Zo(Fs)&&(Fs=null),zs!==null&&Zo(zs)&&(zs=null),gr!==null&&Zo(gr)&&(gr=null),jo.forEach(ml),qr.forEach(ml)}function ai(a,u){a.blockedOn===u&&(a.blockedOn=null,Ca||(Ca=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,So)))}function Ea(a){function u(j){return ai(j,a)}if(0<ko.length){ai(ko[0],a);for(var f=1;f<ko.length;f++){var w=ko[f];w.blockedOn===a&&(w.blockedOn=null)}}for(Fs!==null&&ai(Fs,a),zs!==null&&ai(zs,a),gr!==null&&ai(gr,a),jo.forEach(u),qr.forEach(u),f=0;f<Mr.length;f++)w=Mr[f],w.blockedOn===a&&(w.blockedOn=null);for(;0<Mr.length&&(f=Mr[0],f.blockedOn===null);)Ci(f),f.blockedOn===null&&Mr.shift()}var qi=S.ReactCurrentBatchConfig,rr=!0;function uf(a,u,f,w){var j=In,E=qi.transition;qi.transition=null;try{In=1,Kn(a,u,f,w)}finally{In=j,qi.transition=E}}function li(a,u,f,w){var j=In,E=qi.transition;qi.transition=null;try{In=4,Kn(a,u,f,w)}finally{In=j,qi.transition=E}}function Kn(a,u,f,w){if(rr){var j=me(a,u,f,w);if(j===null)jl(a,u,w,Y,f),hc(a,w);else if(ku(j,a,u,f,w))w.stopPropagation();else if(hc(a,w),u&4&&-1<Vr.indexOf(a)){for(;j!==null;){var E=sa(j);if(E!==null&&fl(E),E=me(a,u,f,w),E===null&&jl(a,u,w,Y,f),E===j)break;j=E}j!==null&&w.stopPropagation()}else jl(a,u,w,null,f)}}var Y=null;function me(a,u,f,w){if(Y=null,a=On(w),a=Fa(a),a!==null)if(u=rn(a),u===null)a=null;else if(f=u.tag,f===13){if(a=Ht(u),a!==null)return a;a=null}else if(f===3){if(u.stateNode.current.memoizedState.isDehydrated)return u.tag===3?u.stateNode.containerInfo:null;a=null}else u!==a&&(a=null);return Y=a,null}function Oe(a){switch(a){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(Ar()){case As:return 1;case ws:return 4;case _r:case ve:return 16;case Ct:return 536870912;default:return 16}default:return 16}}var De=null,Ye=null,ht=null;function Wt(){if(ht)return ht;var a,u=Ye,f=u.length,w,j="value"in De?De.value:De.textContent,E=j.length;for(a=0;a<f&&u[a]===j[a];a++);var q=f-a;for(w=1;w<=q&&u[f-w]===j[E-w];w++);return ht=j.slice(a,1<w?1-w:void 0)}function Dt(a){var u=a.keyCode;return"charCode"in a?(a=a.charCode,a===0&&u===13&&(a=13)):a=u,a===10&&(a=13),32<=a||a===13?a:0}function Bt(){return!0}function pn(){return!1}function En(a){function u(f,w,j,E,q){this._reactName=f,this._targetInst=j,this.type=w,this.nativeEvent=E,this.target=q,this.currentTarget=null;for(var ie in a)a.hasOwnProperty(ie)&&(f=a[ie],this[ie]=f?f(E):E[ie]);return this.isDefaultPrevented=(E.defaultPrevented!=null?E.defaultPrevented:E.returnValue===!1)?Bt:pn,this.isPropagationStopped=pn,this}return ee(u.prototype,{preventDefault:function(){this.defaultPrevented=!0;var f=this.nativeEvent;f&&(f.preventDefault?f.preventDefault():typeof f.returnValue!="unknown"&&(f.returnValue=!1),this.isDefaultPrevented=Bt)},stopPropagation:function(){var f=this.nativeEvent;f&&(f.stopPropagation?f.stopPropagation():typeof f.cancelBubble!="unknown"&&(f.cancelBubble=!0),this.isPropagationStopped=Bt)},persist:function(){},isPersistent:Bt}),u}var Js={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ft=En(Js),bn=ee({},Js,{view:0,detail:0}),ls=En(bn),Hn,Rr,yr,Vi=ee({},bn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:pl,button:0,buttons:0,relatedTarget:function(a){return a.relatedTarget===void 0?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){return"movementX"in a?a.movementX:(a!==yr&&(yr&&a.type==="mousemove"?(Hn=a.screenX-yr.screenX,Rr=a.screenY-yr.screenY):Rr=Hn=0,yr=a),Hn)},movementY:function(a){return"movementY"in a?a.movementY:Rr}}),_l=En(Vi),Hi=ee({},Vi,{dataTransfer:0}),df=En(Hi),mc=ee({},bn,{relatedTarget:0}),Aa=En(mc),Ta=ee({},Js,{animationName:0,elapsedTime:0,pseudoElement:0}),ff=En(Ta),_c=ee({},Js,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),pc=En(_c),ju=ee({},Js,{data:0}),hf=En(ju),Su={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},mf={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"},Nu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function $u(a){var u=this.nativeEvent;return u.getModifierState?u.getModifierState(a):(a=Nu[a])?!!u[a]:!1}function pl(){return $u}var Pm=ee({},bn,{key:function(a){if(a.key){var u=Su[a.key]||a.key;if(u!=="Unidentified")return u}return a.type==="keypress"?(a=Dt(a),a===13?"Enter":String.fromCharCode(a)):a.type==="keydown"||a.type==="keyup"?mf[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:pl,charCode:function(a){return a.type==="keypress"?Dt(a):0},keyCode:function(a){return a.type==="keydown"||a.type==="keyup"?a.keyCode:0},which:function(a){return a.type==="keypress"?Dt(a):a.type==="keydown"||a.type==="keyup"?a.keyCode:0}}),Ma=En(Pm),Dm=ee({},Vi,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Cu=En(Dm),_f=ee({},bn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:pl}),pf=En(_f),gl=ee({},Js,{propertyName:0,elapsedTime:0,pseudoElement:0}),Fm=En(gl),zm=ee({},Vi,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),gf=En(zm),Yg=[9,13,27,32],Eu=l&&"CompositionEvent"in window,yl=null;l&&"documentMode"in document&&(yl=document.documentMode);var Xg=l&&"TextEvent"in window&&!yl,Au=l&&(!Eu||yl&&8<yl&&11>=yl),An=" ",Tu=!1;function Bm(a,u){switch(a){case"keyup":return Yg.indexOf(u.keyCode)!==-1;case"keydown":return u.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Mu(a){return a=a.detail,typeof a=="object"&&"data"in a?a.data:null}var wl=!1;function yf(a,u){switch(a){case"compositionend":return Mu(u);case"keypress":return u.which!==32?null:(Tu=!0,An);case"textInput":return a=u.data,a===An&&Tu?null:a;default:return null}}function Zg(a,u){if(wl)return a==="compositionend"||!Eu&&Bm(a,u)?(a=Wt(),ht=Ye=De=null,wl=!1,a):null;switch(a){case"paste":return null;case"keypress":if(!(u.ctrlKey||u.altKey||u.metaKey)||u.ctrlKey&&u.altKey){if(u.char&&1<u.char.length)return u.char;if(u.which)return String.fromCharCode(u.which)}return null;case"compositionend":return Au&&u.locale!=="ko"?null:u.data;default:return null}}var Ns={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 No(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return u==="input"?!!Ns[a.type]:u==="textarea"}function wf(a,u,f,w){yt(w),u=Ai(u,"onChange"),0<u.length&&(f=new Ft("onChange","change",null,f,w),a.push({event:f,listeners:u}))}var gc=null,Gi=null;function vf(a){vr(a,0)}function Qo(a){var u=$l(a);if(_t(u))return a}function Um(a,u){if(a==="change")return u}var Wm=!1;if(l){var xf;if(l){var bf="oninput"in document;if(!bf){var kf=document.createElement("div");kf.setAttribute("oninput","return;"),bf=typeof kf.oninput=="function"}xf=bf}else xf=!1;Wm=xf&&(!document.documentMode||9<document.documentMode)}function qm(){gc&&(gc.detachEvent("onpropertychange",jf),Gi=gc=null)}function jf(a){if(a.propertyName==="value"&&Qo(Gi)){var u=[];wf(u,Gi,a,On(a)),We(vf,u)}}function Qg(a,u,f){a==="focusin"?(qm(),gc=u,Gi=f,gc.attachEvent("onpropertychange",jf)):a==="focusout"&&qm()}function Vm(a){if(a==="selectionchange"||a==="keyup"||a==="keydown")return Qo(Gi)}function Hm(a,u){if(a==="click")return Qo(u)}function Sf(a,u){if(a==="input"||a==="change")return Qo(u)}function vl(a,u){return a===u&&(a!==0||1/a===1/u)||a!==a&&u!==u}var wr=typeof Object.is=="function"?Object.is:vl;function Ki(a,u){if(wr(a,u))return!0;if(typeof a!="object"||a===null||typeof u!="object"||u===null)return!1;var f=Object.keys(a),w=Object.keys(u);if(f.length!==w.length)return!1;for(w=0;w<f.length;w++){var j=f[w];if(!d.call(u,j)||!wr(a[j],u[j]))return!1}return!0}function xl(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function yc(a,u){var f=xl(a);a=0;for(var w;f;){if(f.nodeType===3){if(w=a+f.textContent.length,a<=u&&w>=u)return{node:f,offset:u-a};a=w}e:{for(;f;){if(f.nextSibling){f=f.nextSibling;break e}f=f.parentNode}f=void 0}f=xl(f)}}function Ru(a,u){return a&&u?a===u?!0:a&&a.nodeType===3?!1:u&&u.nodeType===3?Ru(a,u.parentNode):"contains"in a?a.contains(u):a.compareDocumentPosition?!!(a.compareDocumentPosition(u)&16):!1:!1}function Nf(){for(var a=window,u=Qe();u instanceof a.HTMLIFrameElement;){try{var f=typeof u.contentWindow.location.href=="string"}catch{f=!1}if(f)a=u.contentWindow;else break;u=Qe(a.document)}return u}function Ra(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return u&&(u==="input"&&(a.type==="text"||a.type==="search"||a.type==="tel"||a.type==="url"||a.type==="password")||u==="textarea"||a.contentEditable==="true")}function Gm(a){var u=Nf(),f=a.focusedElem,w=a.selectionRange;if(u!==f&&f&&f.ownerDocument&&Ru(f.ownerDocument.documentElement,f)){if(w!==null&&Ra(f)){if(u=w.start,a=w.end,a===void 0&&(a=u),"selectionStart"in f)f.selectionStart=u,f.selectionEnd=Math.min(a,f.value.length);else if(a=(u=f.ownerDocument||document)&&u.defaultView||window,a.getSelection){a=a.getSelection();var j=f.textContent.length,E=Math.min(w.start,j);w=w.end===void 0?E:Math.min(w.end,j),!a.extend&&E>w&&(j=w,w=E,E=j),j=yc(f,E);var q=yc(f,w);j&&q&&(a.rangeCount!==1||a.anchorNode!==j.node||a.anchorOffset!==j.offset||a.focusNode!==q.node||a.focusOffset!==q.offset)&&(u=u.createRange(),u.setStart(j.node,j.offset),a.removeAllRanges(),E>w?(a.addRange(u),a.extend(q.node,q.offset)):(u.setEnd(q.node,q.offset),a.addRange(u)))}}for(u=[],a=f;a=a.parentNode;)a.nodeType===1&&u.push({element:a,left:a.scrollLeft,top:a.scrollTop});for(typeof f.focus=="function"&&f.focus(),f=0;f<u.length;f++)a=u[f],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}}var wc=l&&"documentMode"in document&&11>=document.documentMode,Ji=null,$f=null,La=null,Cf=!1;function Lu(a,u,f){var w=f.window===f?f.document:f.nodeType===9?f:f.ownerDocument;Cf||Ji==null||Ji!==Qe(w)||(w=Ji,"selectionStart"in w&&Ra(w)?w={start:w.selectionStart,end:w.selectionEnd}:(w=(w.ownerDocument&&w.ownerDocument.defaultView||window).getSelection(),w={anchorNode:w.anchorNode,anchorOffset:w.anchorOffset,focusNode:w.focusNode,focusOffset:w.focusOffset}),La&&Ki(La,w)||(La=w,w=Ai($f,"onSelect"),0<w.length&&(u=new Ft("onSelect","select",null,u,f),a.push({event:u,listeners:w}),u.target=Ji)))}function Ia(a,u){var f={};return f[a.toLowerCase()]=u.toLowerCase(),f["Webkit"+a]="webkit"+u,f["Moz"+a]="moz"+u,f}var Lr={animationend:Ia("Animation","AnimationEnd"),animationiteration:Ia("Animation","AnimationIteration"),animationstart:Ia("Animation","AnimationStart"),transitionend:Ia("Transition","TransitionEnd")},ea={},Km={};l&&(Km=document.createElement("div").style,"AnimationEvent"in window||(delete Lr.animationend.animation,delete Lr.animationiteration.animation,delete Lr.animationstart.animation),"TransitionEvent"in window||delete Lr.transitionend.transition);function Oa(a){if(ea[a])return ea[a];if(!Lr[a])return a;var u=Lr[a],f;for(f in u)if(u.hasOwnProperty(f)&&f in Km)return ea[a]=u[f];return a}var Jm=Oa("animationend"),Iu=Oa("animationiteration"),bl=Oa("animationstart"),Gr=Oa("transitionend"),$o=new Map,vc="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 Kr(a,u){$o.set(a,u),o(u,[a])}for(var xc=0;xc<vc.length;xc++){var Pa=vc[xc],Co=Pa.toLowerCase(),Ou=Pa[0].toUpperCase()+Pa.slice(1);Kr(Co,"on"+Ou)}Kr(Jm,"onAnimationEnd"),Kr(Iu,"onAnimationIteration"),Kr(bl,"onAnimationStart"),Kr("dblclick","onDoubleClick"),Kr("focusin","onFocus"),Kr("focusout","onBlur"),Kr(Gr,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),o("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),o("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),o("onBeforeInput",["compositionend","keypress","textInput","paste"]),o("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),o("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),o("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Eo="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(" "),kl=new Set("cancel close invalid load scroll toggle".split(" ").concat(Eo));function Ao(a,u,f){var w=a.type||"unknown-event";a.currentTarget=f,mn(w,u,void 0,a),a.currentTarget=null}function vr(a,u){u=(u&4)!==0;for(var f=0;f<a.length;f++){var w=a[f],j=w.event;w=w.listeners;e:{var E=void 0;if(u)for(var q=w.length-1;0<=q;q--){var ie=w[q],ue=ie.instance,Re=ie.currentTarget;if(ie=ie.listener,ue!==E&&j.isPropagationStopped())break e;Ao(j,ie,Re),E=ue}else for(q=0;q<w.length;q++){if(ie=w[q],ue=ie.instance,Re=ie.currentTarget,ie=ie.listener,ue!==E&&j.isPropagationStopped())break e;Ao(j,ie,Re),E=ue}}}if(zt)throw a=lt,zt=!1,lt=null,a}function Bn(a,u){var f=u[Sl];f===void 0&&(f=u[Sl]=new Set);var w=a+"__bubble";f.has(w)||(Pu(u,a,2,!1),f.add(w))}function ta(a,u,f){var w=0;u&&(w|=4),Pu(f,a,w,u)}var Da="_reactListening"+Math.random().toString(36).slice(2);function Ei(a){if(!a[Da]){a[Da]=!0,r.forEach(function(f){f!=="selectionchange"&&(kl.has(f)||ta(f,!1,a),ta(f,!0,a))});var u=a.nodeType===9?a:a.ownerDocument;u===null||u[Da]||(u[Da]=!0,ta("selectionchange",!1,u))}}function Pu(a,u,f,w){switch(Oe(u)){case 1:var j=uf;break;case 4:j=li;break;default:j=Kn}f=j.bind(null,u,f,a),j=void 0,!tt||u!=="touchstart"&&u!=="touchmove"&&u!=="wheel"||(j=!0),w?j!==void 0?a.addEventListener(u,f,{capture:!0,passive:j}):a.addEventListener(u,f,!0):j!==void 0?a.addEventListener(u,f,{passive:j}):a.addEventListener(u,f,!1)}function jl(a,u,f,w,j){var E=w;if((u&1)===0&&(u&2)===0&&w!==null)e:for(;;){if(w===null)return;var q=w.tag;if(q===3||q===4){var ie=w.stateNode.containerInfo;if(ie===j||ie.nodeType===8&&ie.parentNode===j)break;if(q===4)for(q=w.return;q!==null;){var ue=q.tag;if((ue===3||ue===4)&&(ue=q.stateNode.containerInfo,ue===j||ue.nodeType===8&&ue.parentNode===j))return;q=q.return}for(;ie!==null;){if(q=Fa(ie),q===null)return;if(ue=q.tag,ue===5||ue===6){w=E=q;continue e}ie=ie.parentNode}}w=w.return}We(function(){var Re=E,Ze=On(f),nt=[];e:{var Je=$o.get(a);if(Je!==void 0){var St=Ft,At=a;switch(a){case"keypress":if(Dt(f)===0)break e;case"keydown":case"keyup":St=Ma;break;case"focusin":At="focus",St=Aa;break;case"focusout":At="blur",St=Aa;break;case"beforeblur":case"afterblur":St=Aa;break;case"click":if(f.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":St=_l;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":St=df;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":St=pf;break;case Jm:case Iu:case bl:St=ff;break;case Gr:St=Fm;break;case"scroll":St=ls;break;case"wheel":St=gf;break;case"copy":case"cut":case"paste":St=pc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":St=Cu}var Rt=(u&4)!==0,Os=!Rt&&a==="scroll",xe=Rt?Je!==null?Je+"Capture":null:Je;Rt=[];for(var _e=Re,Ce;_e!==null;){Ce=_e;var at=Ce.stateNode;if(Ce.tag===5&&at!==null&&(Ce=at,xe!==null&&(at=Ue(_e,xe),at!=null&&Rt.push(Ir(_e,at,Ce)))),Os)break;_e=_e.return}0<Rt.length&&(Je=new St(Je,At,null,f,Ze),nt.push({event:Je,listeners:Rt}))}}if((u&7)===0){e:{if(Je=a==="mouseover"||a==="pointerover",St=a==="mouseout"||a==="pointerout",Je&&f!==wn&&(At=f.relatedTarget||f.fromElement)&&(Fa(At)||At[Ti]))break e;if((St||Je)&&(Je=Ze.window===Ze?Ze:(Je=Ze.ownerDocument)?Je.defaultView||Je.parentWindow:window,St?(At=f.relatedTarget||f.toElement,St=Re,At=At?Fa(At):null,At!==null&&(Os=rn(At),At!==Os||At.tag!==5&&At.tag!==6)&&(At=null)):(St=null,At=Re),St!==At)){if(Rt=_l,at="onMouseLeave",xe="onMouseEnter",_e="mouse",(a==="pointerout"||a==="pointerover")&&(Rt=Cu,at="onPointerLeave",xe="onPointerEnter",_e="pointer"),Os=St==null?Je:$l(St),Ce=At==null?Je:$l(At),Je=new Rt(at,_e+"leave",St,f,Ze),Je.target=Os,Je.relatedTarget=Ce,at=null,Fa(Ze)===Re&&(Rt=new Rt(xe,_e+"enter",At,f,Ze),Rt.target=Ce,Rt.relatedTarget=Os,at=Rt),Os=at,St&&At)t:{for(Rt=St,xe=At,_e=0,Ce=Rt;Ce;Ce=xr(Ce))_e++;for(Ce=0,at=xe;at;at=xr(at))Ce++;for(;0<_e-Ce;)Rt=xr(Rt),_e--;for(;0<Ce-_e;)xe=xr(xe),Ce--;for(;_e--;){if(Rt===xe||xe!==null&&Rt===xe.alternate)break t;Rt=xr(Rt),xe=xr(xe)}Rt=null}else Rt=null;St!==null&&Ef(nt,Je,St,Rt,!1),At!==null&&Os!==null&&Ef(nt,Os,At,Rt,!0)}}e:{if(Je=Re?$l(Re):window,St=Je.nodeName&&Je.nodeName.toLowerCase(),St==="select"||St==="input"&&Je.type==="file")var Pt=Um;else if(No(Je))if(Wm)Pt=Sf;else{Pt=Vm;var Gt=Qg}else(St=Je.nodeName)&&St.toLowerCase()==="input"&&(Je.type==="checkbox"||Je.type==="radio")&&(Pt=Hm);if(Pt&&(Pt=Pt(a,Re))){wf(nt,Pt,f,Ze);break e}Gt&&Gt(a,Je,Re),a==="focusout"&&(Gt=Je._wrapperState)&&Gt.controlled&&Je.type==="number"&&Lt(Je,"number",Je.value)}switch(Gt=Re?$l(Re):window,a){case"focusin":(No(Gt)||Gt.contentEditable==="true")&&(Ji=Gt,$f=Re,La=null);break;case"focusout":La=$f=Ji=null;break;case"mousedown":Cf=!0;break;case"contextmenu":case"mouseup":case"dragend":Cf=!1,Lu(nt,f,Ze);break;case"selectionchange":if(wc)break;case"keydown":case"keyup":Lu(nt,f,Ze)}var Kt;if(Eu)e:{switch(a){case"compositionstart":var fn="onCompositionStart";break e;case"compositionend":fn="onCompositionEnd";break e;case"compositionupdate":fn="onCompositionUpdate";break e}fn=void 0}else wl?Bm(a,f)&&(fn="onCompositionEnd"):a==="keydown"&&f.keyCode===229&&(fn="onCompositionStart");fn&&(Au&&f.locale!=="ko"&&(wl||fn!=="onCompositionStart"?fn==="onCompositionEnd"&&wl&&(Kt=Wt()):(De=Ze,Ye="value"in De?De.value:De.textContent,wl=!0)),Gt=Ai(Re,fn),0<Gt.length&&(fn=new hf(fn,a,null,f,Ze),nt.push({event:fn,listeners:Gt}),Kt?fn.data=Kt:(Kt=Mu(f),Kt!==null&&(fn.data=Kt)))),(Kt=Xg?yf(a,f):Zg(a,f))&&(Re=Ai(Re,"onBeforeInput"),0<Re.length&&(Ze=new hf("onBeforeInput","beforeinput",null,f,Ze),nt.push({event:Ze,listeners:Re}),Ze.data=Kt))}vr(nt,u)})}function Ir(a,u,f){return{instance:a,listener:u,currentTarget:f}}function Ai(a,u){for(var f=u+"Capture",w=[];a!==null;){var j=a,E=j.stateNode;j.tag===5&&E!==null&&(j=E,E=Ue(a,f),E!=null&&w.unshift(Ir(a,E,j)),E=Ue(a,u),E!=null&&w.push(Ir(a,E,j))),a=a.return}return w}function xr(a){if(a===null)return null;do a=a.return;while(a&&a.tag!==5);return a||null}function Ef(a,u,f,w,j){for(var E=u._reactName,q=[];f!==null&&f!==w;){var ie=f,ue=ie.alternate,Re=ie.stateNode;if(ue!==null&&ue===w)break;ie.tag===5&&Re!==null&&(ie=Re,j?(ue=Ue(f,E),ue!=null&&q.unshift(Ir(f,ue,ie))):j||(ue=Ue(f,E),ue!=null&&q.push(Ir(f,ue,ie)))),f=f.return}q.length!==0&&a.push({event:u,listeners:q})}var bc=/\r\n?/g,Ym=/\u0000|\uFFFD/g;function Du(a){return(typeof a=="string"?a:""+a).replace(bc,`
38
+ `).replace(Ym,"")}function kc(a,u,f){if(u=Du(u),Du(a)!==u&&f)throw Error(n(425))}function jc(){}var Fu=null,Af=null;function zu(a,u){return a==="textarea"||a==="noscript"||typeof u.children=="string"||typeof u.children=="number"||typeof u.dangerouslySetInnerHTML=="object"&&u.dangerouslySetInnerHTML!==null&&u.dangerouslySetInnerHTML.__html!=null}var Tf=typeof setTimeout=="function"?setTimeout:void 0,Xm=typeof clearTimeout=="function"?clearTimeout:void 0,Zm=typeof Promise=="function"?Promise:void 0,Qm=typeof queueMicrotask=="function"?queueMicrotask:typeof Zm<"u"?function(a){return Zm.resolve(null).then(a).catch(ey)}:Tf;function ey(a){setTimeout(function(){throw a})}function Bu(a,u){var f=u,w=0;do{var j=f.nextSibling;if(a.removeChild(f),j&&j.nodeType===8)if(f=j.data,f==="/$"){if(w===0){a.removeChild(j),Ea(u);return}w--}else f!=="$"&&f!=="$?"&&f!=="$!"||w++;f=j}while(f);Ea(u)}function na(a){for(;a!=null;a=a.nextSibling){var u=a.nodeType;if(u===1||u===3)break;if(u===8){if(u=a.data,u==="$"||u==="$!"||u==="$?")break;if(u==="/$")return null}}return a}function Mf(a){a=a.previousSibling;for(var u=0;a;){if(a.nodeType===8){var f=a.data;if(f==="$"||f==="$!"||f==="$?"){if(u===0)return a;u--}else f==="/$"&&u++}a=a.previousSibling}return null}var Yi=Math.random().toString(36).slice(2),Xi="__reactFiber$"+Yi,To="__reactProps$"+Yi,Ti="__reactContainer$"+Yi,Sl="__reactEvents$"+Yi,e_="__reactListeners$"+Yi,Nl="__reactHandles$"+Yi;function Fa(a){var u=a[Xi];if(u)return u;for(var f=a.parentNode;f;){if(u=f[Ti]||f[Xi]){if(f=u.alternate,u.child!==null||f!==null&&f.child!==null)for(a=Mf(a);a!==null;){if(f=a[Xi])return f;a=Mf(a)}return u}a=f,f=a.parentNode}return null}function sa(a){return a=a[Xi]||a[Ti],!a||a.tag!==5&&a.tag!==6&&a.tag!==13&&a.tag!==3?null:a}function $l(a){if(a.tag===5||a.tag===6)return a.stateNode;throw Error(n(33))}function Mo(a){return a[To]||null}var Rf=[],Ro=-1;function ra(a){return{current:a}}function Pn(a){0>Ro||(a.current=Rf[Ro],Rf[Ro]=null,Ro--)}function Xn(a,u){Ro++,Rf[Ro]=a.current,a.current=u}var ci={},Ts=ra(ci),br=ra(!1),Lo=ci;function Zi(a,u){var f=a.type.contextTypes;if(!f)return ci;var w=a.stateNode;if(w&&w.__reactInternalMemoizedUnmaskedChildContext===u)return w.__reactInternalMemoizedMaskedChildContext;var j={},E;for(E in f)j[E]=u[E];return w&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=u,a.__reactInternalMemoizedMaskedChildContext=j),j}function ir(a){return a=a.childContextTypes,a!=null}function Io(){Pn(br),Pn(Ts)}function Uu(a,u,f){if(Ts.current!==ci)throw Error(n(168));Xn(Ts,u),Xn(br,f)}function t_(a,u,f){var w=a.stateNode;if(u=u.childContextTypes,typeof w.getChildContext!="function")return f;w=w.getChildContext();for(var j in w)if(!(j in u))throw Error(n(108,Ne(a)||"Unknown",j));return ee({},f,w)}function Cl(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||ci,Lo=Ts.current,Xn(Ts,a),Xn(br,br.current),!0}function Wu(a,u,f){var w=a.stateNode;if(!w)throw Error(n(169));f?(a=t_(a,u,Lo),w.__reactInternalMemoizedMergedChildContext=a,Pn(br),Pn(Ts),Xn(Ts,a)):Pn(br),Xn(br,f)}var Oo=null,qu=!1,ia=!1;function or(a){Oo===null?Oo=[a]:Oo.push(a)}function Vu(a){qu=!0,or(a)}function Qi(){if(!ia&&Oo!==null){ia=!0;var a=0,u=In;try{var f=Oo;for(In=1;a<f.length;a++){var w=f[a];do w=w(!0);while(w!==null)}Oo=null,qu=!1}catch(j){throw Oo!==null&&(Oo=Oo.slice(a+1)),Fn(As,Qi),j}finally{In=u,ia=!1}}return null}var El=[],Al=0,Tl=null,Hu=0,kr=[],Jr=0,eo=null,to=1,no="";function za(a,u){El[Al++]=Hu,El[Al++]=Tl,Tl=a,Hu=u}function Lf(a,u,f){kr[Jr++]=to,kr[Jr++]=no,kr[Jr++]=eo,eo=a;var w=to;a=no;var j=32-sr(w)-1;w&=~(1<<j),f+=1;var E=32-sr(u)+j;if(30<E){var q=j-j%5;E=(w&(1<<q)-1).toString(32),w>>=q,j-=q,to=1<<32-sr(u)+j|f<<j|w,no=E+a}else to=1<<E|f<<j|w,no=a}function Gu(a){a.return!==null&&(za(a,1),Lf(a,1,0))}function Ku(a){for(;a===Tl;)Tl=El[--Al],El[Al]=null,Hu=El[--Al],El[Al]=null;for(;a===eo;)eo=kr[--Jr],kr[Jr]=null,no=kr[--Jr],kr[Jr]=null,to=kr[--Jr],kr[Jr]=null}var Yr=null,Or=null,Zn=!1,Mi=null;function n_(a,u){var f=Pe(5,null,null,0);f.elementType="DELETED",f.stateNode=u,f.return=a,u=a.deletions,u===null?(a.deletions=[f],a.flags|=16):u.push(f)}function s_(a,u){switch(a.tag){case 5:var f=a.type;return u=u.nodeType!==1||f.toLowerCase()!==u.nodeName.toLowerCase()?null:u,u!==null?(a.stateNode=u,Yr=a,Or=na(u.firstChild),!0):!1;case 6:return u=a.pendingProps===""||u.nodeType!==3?null:u,u!==null?(a.stateNode=u,Yr=a,Or=null,!0):!1;case 13:return u=u.nodeType!==8?null:u,u!==null?(f=eo!==null?{id:to,overflow:no}:null,a.memoizedState={dehydrated:u,treeContext:f,retryLane:1073741824},f=Pe(18,null,null,0),f.stateNode=u,f.return=a,a.child=f,Yr=a,Or=null,!0):!1;default:return!1}}function If(a){return(a.mode&1)!==0&&(a.flags&128)===0}function Sc(a){if(Zn){var u=Or;if(u){var f=u;if(!s_(a,u)){if(If(a))throw Error(n(418));u=na(f.nextSibling);var w=Yr;u&&s_(a,u)?n_(w,f):(a.flags=a.flags&-4097|2,Zn=!1,Yr=a)}}else{if(If(a))throw Error(n(418));a.flags=a.flags&-4097|2,Zn=!1,Yr=a}}}function r_(a){for(a=a.return;a!==null&&a.tag!==5&&a.tag!==3&&a.tag!==13;)a=a.return;Yr=a}function Ml(a){if(a!==Yr)return!1;if(!Zn)return r_(a),Zn=!0,!1;var u;if((u=a.tag!==3)&&!(u=a.tag!==5)&&(u=a.type,u=u!=="head"&&u!=="body"&&!zu(a.type,a.memoizedProps)),u&&(u=Or)){if(If(a))throw i_(),Error(n(418));for(;u;)n_(a,u),u=na(u.nextSibling)}if(r_(a),a.tag===13){if(a=a.memoizedState,a=a!==null?a.dehydrated:null,!a)throw Error(n(317));e:{for(a=a.nextSibling,u=0;a;){if(a.nodeType===8){var f=a.data;if(f==="/$"){if(u===0){Or=na(a.nextSibling);break e}u--}else f!=="$"&&f!=="$!"&&f!=="$?"||u++}a=a.nextSibling}Or=null}}else Or=Yr?na(a.stateNode.nextSibling):null;return!0}function i_(){for(var a=Or;a;)a=na(a.nextSibling)}function Ba(){Or=Yr=null,Zn=!1}function Of(a){Mi===null?Mi=[a]:Mi.push(a)}var Pf=S.ReactCurrentBatchConfig;function Ke(a,u,f){if(a=f.ref,a!==null&&typeof a!="function"&&typeof a!="object"){if(f._owner){if(f=f._owner,f){if(f.tag!==1)throw Error(n(309));var w=f.stateNode}if(!w)throw Error(n(147,a));var j=w,E=""+a;return u!==null&&u.ref!==null&&typeof u.ref=="function"&&u.ref._stringRef===E?u.ref:(u=function(q){var ie=j.refs;q===null?delete ie[E]:ie[E]=q},u._stringRef=E,u)}if(typeof a!="string")throw Error(n(284));if(!f._owner)throw Error(n(290,a))}return a}function Un(a,u){throw a=Object.prototype.toString.call(u),Error(n(31,a==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":a))}function ui(a){var u=a._init;return u(a._payload)}function Df(a){function u(xe,_e){if(a){var Ce=xe.deletions;Ce===null?(xe.deletions=[_e],xe.flags|=16):Ce.push(_e)}}function f(xe,_e){if(!a)return null;for(;_e!==null;)u(xe,_e),_e=_e.sibling;return null}function w(xe,_e){for(xe=new Map;_e!==null;)_e.key!==null?xe.set(_e.key,_e):xe.set(_e.index,_e),_e=_e.sibling;return xe}function j(xe,_e){return xe=dt(xe,_e),xe.index=0,xe.sibling=null,xe}function E(xe,_e,Ce){return xe.index=Ce,a?(Ce=xe.alternate,Ce!==null?(Ce=Ce.index,Ce<_e?(xe.flags|=2,_e):Ce):(xe.flags|=2,_e)):(xe.flags|=1048576,_e)}function q(xe){return a&&xe.alternate===null&&(xe.flags|=2),xe}function ie(xe,_e,Ce,at){return _e===null||_e.tag!==6?(_e=en(Ce,xe.mode,at),_e.return=xe,_e):(_e=j(_e,Ce),_e.return=xe,_e)}function ue(xe,_e,Ce,at){var Pt=Ce.type;return Pt===A?Ze(xe,_e,Ce.props.children,at,Ce.key):_e!==null&&(_e.elementType===Pt||typeof Pt=="object"&&Pt!==null&&Pt.$$typeof===L&&ui(Pt)===_e.type)?(at=j(_e,Ce.props),at.ref=Ke(xe,_e,Ce),at.return=xe,at):(at=xn(Ce.type,Ce.key,Ce.props,null,xe.mode,at),at.ref=Ke(xe,_e,Ce),at.return=xe,at)}function Re(xe,_e,Ce,at){return _e===null||_e.tag!==4||_e.stateNode.containerInfo!==Ce.containerInfo||_e.stateNode.implementation!==Ce.implementation?(_e=Yn(Ce,xe.mode,at),_e.return=xe,_e):(_e=j(_e,Ce.children||[]),_e.return=xe,_e)}function Ze(xe,_e,Ce,at,Pt){return _e===null||_e.tag!==7?(_e=qt(Ce,xe.mode,at,Pt),_e.return=xe,_e):(_e=j(_e,Ce),_e.return=xe,_e)}function nt(xe,_e,Ce){if(typeof _e=="string"&&_e!==""||typeof _e=="number")return _e=en(""+_e,xe.mode,Ce),_e.return=xe,_e;if(typeof _e=="object"&&_e!==null){switch(_e.$$typeof){case D:return Ce=xn(_e.type,_e.key,_e.props,null,xe.mode,Ce),Ce.ref=Ke(xe,null,_e),Ce.return=xe,Ce;case O:return _e=Yn(_e,xe.mode,Ce),_e.return=xe,_e;case L:var at=_e._init;return nt(xe,at(_e._payload),Ce)}if(ce(_e)||z(_e))return _e=qt(_e,xe.mode,Ce,null),_e.return=xe,_e;Un(xe,_e)}return null}function Je(xe,_e,Ce,at){var Pt=_e!==null?_e.key:null;if(typeof Ce=="string"&&Ce!==""||typeof Ce=="number")return Pt!==null?null:ie(xe,_e,""+Ce,at);if(typeof Ce=="object"&&Ce!==null){switch(Ce.$$typeof){case D:return Ce.key===Pt?ue(xe,_e,Ce,at):null;case O:return Ce.key===Pt?Re(xe,_e,Ce,at):null;case L:return Pt=Ce._init,Je(xe,_e,Pt(Ce._payload),at)}if(ce(Ce)||z(Ce))return Pt!==null?null:Ze(xe,_e,Ce,at,null);Un(xe,Ce)}return null}function St(xe,_e,Ce,at,Pt){if(typeof at=="string"&&at!==""||typeof at=="number")return xe=xe.get(Ce)||null,ie(_e,xe,""+at,Pt);if(typeof at=="object"&&at!==null){switch(at.$$typeof){case D:return xe=xe.get(at.key===null?Ce:at.key)||null,ue(_e,xe,at,Pt);case O:return xe=xe.get(at.key===null?Ce:at.key)||null,Re(_e,xe,at,Pt);case L:var Gt=at._init;return St(xe,_e,Ce,Gt(at._payload),Pt)}if(ce(at)||z(at))return xe=xe.get(Ce)||null,Ze(_e,xe,at,Pt,null);Un(_e,at)}return null}function At(xe,_e,Ce,at){for(var Pt=null,Gt=null,Kt=_e,fn=_e=0,fr=null;Kt!==null&&fn<Ce.length;fn++){Kt.index>fn?(fr=Kt,Kt=null):fr=Kt.sibling;var Wn=Je(xe,Kt,Ce[fn],at);if(Wn===null){Kt===null&&(Kt=fr);break}a&&Kt&&Wn.alternate===null&&u(xe,Kt),_e=E(Wn,_e,fn),Gt===null?Pt=Wn:Gt.sibling=Wn,Gt=Wn,Kt=fr}if(fn===Ce.length)return f(xe,Kt),Zn&&za(xe,fn),Pt;if(Kt===null){for(;fn<Ce.length;fn++)Kt=nt(xe,Ce[fn],at),Kt!==null&&(_e=E(Kt,_e,fn),Gt===null?Pt=Kt:Gt.sibling=Kt,Gt=Kt);return Zn&&za(xe,fn),Pt}for(Kt=w(xe,Kt);fn<Ce.length;fn++)fr=St(Kt,xe,fn,Ce[fn],at),fr!==null&&(a&&fr.alternate!==null&&Kt.delete(fr.key===null?fn:fr.key),_e=E(fr,_e,fn),Gt===null?Pt=fr:Gt.sibling=fr,Gt=fr);return a&&Kt.forEach(function(Hl){return u(xe,Hl)}),Zn&&za(xe,fn),Pt}function Rt(xe,_e,Ce,at){var Pt=z(Ce);if(typeof Pt!="function")throw Error(n(150));if(Ce=Pt.call(Ce),Ce==null)throw Error(n(151));for(var Gt=Pt=null,Kt=_e,fn=_e=0,fr=null,Wn=Ce.next();Kt!==null&&!Wn.done;fn++,Wn=Ce.next()){Kt.index>fn?(fr=Kt,Kt=null):fr=Kt.sibling;var Hl=Je(xe,Kt,Wn.value,at);if(Hl===null){Kt===null&&(Kt=fr);break}a&&Kt&&Hl.alternate===null&&u(xe,Kt),_e=E(Hl,_e,fn),Gt===null?Pt=Hl:Gt.sibling=Hl,Gt=Hl,Kt=fr}if(Wn.done)return f(xe,Kt),Zn&&za(xe,fn),Pt;if(Kt===null){for(;!Wn.done;fn++,Wn=Ce.next())Wn=nt(xe,Wn.value,at),Wn!==null&&(_e=E(Wn,_e,fn),Gt===null?Pt=Wn:Gt.sibling=Wn,Gt=Wn);return Zn&&za(xe,fn),Pt}for(Kt=w(xe,Kt);!Wn.done;fn++,Wn=Ce.next())Wn=St(Kt,xe,fn,Wn.value,at),Wn!==null&&(a&&Wn.alternate!==null&&Kt.delete(Wn.key===null?fn:Wn.key),_e=E(Wn,_e,fn),Gt===null?Pt=Wn:Gt.sibling=Wn,Gt=Wn);return a&&Kt.forEach(function(lE){return u(xe,lE)}),Zn&&za(xe,fn),Pt}function Os(xe,_e,Ce,at){if(typeof Ce=="object"&&Ce!==null&&Ce.type===A&&Ce.key===null&&(Ce=Ce.props.children),typeof Ce=="object"&&Ce!==null){switch(Ce.$$typeof){case D:e:{for(var Pt=Ce.key,Gt=_e;Gt!==null;){if(Gt.key===Pt){if(Pt=Ce.type,Pt===A){if(Gt.tag===7){f(xe,Gt.sibling),_e=j(Gt,Ce.props.children),_e.return=xe,xe=_e;break e}}else if(Gt.elementType===Pt||typeof Pt=="object"&&Pt!==null&&Pt.$$typeof===L&&ui(Pt)===Gt.type){f(xe,Gt.sibling),_e=j(Gt,Ce.props),_e.ref=Ke(xe,Gt,Ce),_e.return=xe,xe=_e;break e}f(xe,Gt);break}else u(xe,Gt);Gt=Gt.sibling}Ce.type===A?(_e=qt(Ce.props.children,xe.mode,at,Ce.key),_e.return=xe,xe=_e):(at=xn(Ce.type,Ce.key,Ce.props,null,xe.mode,at),at.ref=Ke(xe,_e,Ce),at.return=xe,xe=at)}return q(xe);case O:e:{for(Gt=Ce.key;_e!==null;){if(_e.key===Gt)if(_e.tag===4&&_e.stateNode.containerInfo===Ce.containerInfo&&_e.stateNode.implementation===Ce.implementation){f(xe,_e.sibling),_e=j(_e,Ce.children||[]),_e.return=xe,xe=_e;break e}else{f(xe,_e);break}else u(xe,_e);_e=_e.sibling}_e=Yn(Ce,xe.mode,at),_e.return=xe,xe=_e}return q(xe);case L:return Gt=Ce._init,Os(xe,_e,Gt(Ce._payload),at)}if(ce(Ce))return At(xe,_e,Ce,at);if(z(Ce))return Rt(xe,_e,Ce,at);Un(xe,Ce)}return typeof Ce=="string"&&Ce!==""||typeof Ce=="number"?(Ce=""+Ce,_e!==null&&_e.tag===6?(f(xe,_e.sibling),_e=j(_e,Ce),_e.return=xe,xe=_e):(f(xe,_e),_e=en(Ce,xe.mode,at),_e.return=xe,xe=_e),q(xe)):f(xe,_e)}return Os}var Po=Df(!0),Ff=Df(!1),Do=ra(null),Rl=null,Ll=null,zf=null;function Bf(){zf=Ll=Rl=null}function Uf(a){var u=Do.current;Pn(Do),a._currentValue=u}function Ju(a,u,f){for(;a!==null;){var w=a.alternate;if((a.childLanes&u)!==u?(a.childLanes|=u,w!==null&&(w.childLanes|=u)):w!==null&&(w.childLanes&u)!==u&&(w.childLanes|=u),a===f)break;a=a.return}}function Ua(a,u){Rl=a,zf=Ll=null,a=a.dependencies,a!==null&&a.firstContext!==null&&((a.lanes&u)!==0&&(Cs=!0),a.firstContext=null)}function di(a){var u=a._currentValue;if(zf!==a)if(a={context:a,memoizedValue:u,next:null},Ll===null){if(Rl===null)throw Error(n(308));Ll=a,Rl.dependencies={lanes:0,firstContext:a}}else Ll=Ll.next=a;return u}var so=null;function Yu(a){so===null?so=[a]:so.push(a)}function ar(a,u,f,w){var j=u.interleaved;return j===null?(f.next=f,Yu(u)):(f.next=j.next,j.next=f),u.interleaved=f,dn(a,w)}function dn(a,u){a.lanes|=u;var f=a.alternate;for(f!==null&&(f.lanes|=u),f=a,a=a.return;a!==null;)a.childLanes|=u,f=a.alternate,f!==null&&(f.childLanes|=u),f=a,a=a.return;return f.tag===3?f.stateNode:null}var _s=!1;function Nc(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Wf(a,u){a=a.updateQueue,u.updateQueue===a&&(u.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function Xr(a,u){return{eventTime:a,lane:u,tag:0,payload:null,callback:null,next:null}}function Zr(a,u,f){var w=a.updateQueue;if(w===null)return null;if(w=w.shared,(Tn&2)!==0){var j=w.pending;return j===null?u.next=u:(u.next=j.next,j.next=u),w.pending=u,dn(a,f)}return j=w.interleaved,j===null?(u.next=u,Yu(w)):(u.next=j.next,j.next=u),w.interleaved=u,dn(a,f)}function on(a,u,f){if(u=u.updateQueue,u!==null&&(u=u.shared,(f&4194240)!==0)){var w=u.lanes;w&=a.pendingLanes,f|=w,u.lanes=f,Ui(a,f)}}function o_(a,u){var f=a.updateQueue,w=a.alternate;if(w!==null&&(w=w.updateQueue,f===w)){var j=null,E=null;if(f=f.firstBaseUpdate,f!==null){do{var q={eventTime:f.eventTime,lane:f.lane,tag:f.tag,payload:f.payload,callback:f.callback,next:null};E===null?j=E=q:E=E.next=q,f=f.next}while(f!==null);E===null?j=E=u:E=E.next=u}else j=E=u;f={baseState:w.baseState,firstBaseUpdate:j,lastBaseUpdate:E,shared:w.shared,effects:w.effects},a.updateQueue=f;return}a=f.lastBaseUpdate,a===null?f.firstBaseUpdate=u:a.next=u,f.lastBaseUpdate=u}function Il(a,u,f,w){var j=a.updateQueue;_s=!1;var E=j.firstBaseUpdate,q=j.lastBaseUpdate,ie=j.shared.pending;if(ie!==null){j.shared.pending=null;var ue=ie,Re=ue.next;ue.next=null,q===null?E=Re:q.next=Re,q=ue;var Ze=a.alternate;Ze!==null&&(Ze=Ze.updateQueue,ie=Ze.lastBaseUpdate,ie!==q&&(ie===null?Ze.firstBaseUpdate=Re:ie.next=Re,Ze.lastBaseUpdate=ue))}if(E!==null){var nt=j.baseState;q=0,Ze=Re=ue=null,ie=E;do{var Je=ie.lane,St=ie.eventTime;if((w&Je)===Je){Ze!==null&&(Ze=Ze.next={eventTime:St,lane:0,tag:ie.tag,payload:ie.payload,callback:ie.callback,next:null});e:{var At=a,Rt=ie;switch(Je=u,St=f,Rt.tag){case 1:if(At=Rt.payload,typeof At=="function"){nt=At.call(St,nt,Je);break e}nt=At;break e;case 3:At.flags=At.flags&-65537|128;case 0:if(At=Rt.payload,Je=typeof At=="function"?At.call(St,nt,Je):At,Je==null)break e;nt=ee({},nt,Je);break e;case 2:_s=!0}}ie.callback!==null&&ie.lane!==0&&(a.flags|=64,Je=j.effects,Je===null?j.effects=[ie]:Je.push(ie))}else St={eventTime:St,lane:Je,tag:ie.tag,payload:ie.payload,callback:ie.callback,next:null},Ze===null?(Re=Ze=St,ue=nt):Ze=Ze.next=St,q|=Je;if(ie=ie.next,ie===null){if(ie=j.shared.pending,ie===null)break;Je=ie,ie=Je.next,Je.next=null,j.lastBaseUpdate=Je,j.shared.pending=null}}while(!0);if(Ze===null&&(ue=nt),j.baseState=ue,j.firstBaseUpdate=Re,j.lastBaseUpdate=Ze,u=j.shared.interleaved,u!==null){j=u;do q|=j.lane,j=j.next;while(j!==u)}else E===null&&(j.shared.lanes=0);ua|=q,a.lanes=q,a.memoizedState=nt}}function a_(a,u,f){if(a=u.effects,u.effects=null,a!==null)for(u=0;u<a.length;u++){var w=a[u],j=w.callback;if(j!==null){if(w.callback=null,w=f,typeof j!="function")throw Error(n(191,j));j.call(w)}}}var $c={},ro=ra($c),Cc=ra($c),Wa=ra($c);function jr(a){if(a===$c)throw Error(n(174));return a}function Xu(a,u){switch(Xn(Wa,u),Xn(Cc,a),Xn(ro,$c),a=u.nodeType,a){case 9:case 11:u=(u=u.documentElement)?u.namespaceURI:pe(null,"");break;default:a=a===8?u.parentNode:u,u=a.namespaceURI||null,a=a.tagName,u=pe(u,a)}Pn(ro),Xn(ro,u)}function fi(){Pn(ro),Pn(Cc),Pn(Wa)}function hi(a){jr(Wa.current);var u=jr(ro.current),f=pe(u,a.type);u!==f&&(Xn(Cc,a),Xn(ro,f))}function Ol(a){Cc.current===a&&(Pn(ro),Pn(Cc))}var ps=ra(0);function Zu(a){for(var u=a;u!==null;){if(u.tag===13){var f=u.memoizedState;if(f!==null&&(f=f.dehydrated,f===null||f.data==="$?"||f.data==="$!"))return u}else if(u.tag===19&&u.memoizedProps.revealOrder!==void 0){if((u.flags&128)!==0)return u}else if(u.child!==null){u.child.return=u,u=u.child;continue}if(u===a)break;for(;u.sibling===null;){if(u.return===null||u.return===a)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}var Ec=[];function Qu(){for(var a=0;a<Ec.length;a++)Ec[a]._workInProgressVersionPrimary=null;Ec.length=0}var Pl=S.ReactCurrentDispatcher,qf=S.ReactCurrentBatchConfig,Qn=0,cs=null,$s=null,Dn=null,Ac=!1,Fo=!1,qa=0,io=0;function Bs(){throw Error(n(321))}function Vf(a,u){if(u===null)return!1;for(var f=0;f<u.length&&f<a.length;f++)if(!wr(a[f],u[f]))return!1;return!0}function Hf(a,u,f,w,j,E){if(Qn=E,cs=u,u.memoizedState=null,u.updateQueue=null,u.lanes=0,Pl.current=a===null||a.memoizedState===null?Ic:sy,a=f(w,j),Fo){E=0;do{if(Fo=!1,qa=0,25<=E)throw Error(n(301));E+=1,Dn=$s=null,u.updateQueue=null,Pl.current=Qf,a=f(w,j)}while(Fo)}if(Pl.current=Fl,u=$s!==null&&$s.next!==null,Qn=0,Dn=$s=cs=null,Ac=!1,u)throw Error(n(300));return a}function Gf(){var a=qa!==0;return qa=0,a}function mi(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Dn===null?cs.memoizedState=Dn=a:Dn=Dn.next=a,Dn}function Pr(){if($s===null){var a=cs.alternate;a=a!==null?a.memoizedState:null}else a=$s.next;var u=Dn===null?cs.memoizedState:Dn.next;if(u!==null)Dn=u,$s=a;else{if(a===null)throw Error(n(310));$s=a,a={memoizedState:$s.memoizedState,baseState:$s.baseState,baseQueue:$s.baseQueue,queue:$s.queue,next:null},Dn===null?cs.memoizedState=Dn=a:Dn=Dn.next=a}return Dn}function Tc(a,u){return typeof u=="function"?u(a):u}function Mc(a){var u=Pr(),f=u.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=a;var w=$s,j=w.baseQueue,E=f.pending;if(E!==null){if(j!==null){var q=j.next;j.next=E.next,E.next=q}w.baseQueue=j=E,f.pending=null}if(j!==null){E=j.next,w=w.baseState;var ie=q=null,ue=null,Re=E;do{var Ze=Re.lane;if((Qn&Ze)===Ze)ue!==null&&(ue=ue.next={lane:0,action:Re.action,hasEagerState:Re.hasEagerState,eagerState:Re.eagerState,next:null}),w=Re.hasEagerState?Re.eagerState:a(w,Re.action);else{var nt={lane:Ze,action:Re.action,hasEagerState:Re.hasEagerState,eagerState:Re.eagerState,next:null};ue===null?(ie=ue=nt,q=w):ue=ue.next=nt,cs.lanes|=Ze,ua|=Ze}Re=Re.next}while(Re!==null&&Re!==E);ue===null?q=w:ue.next=ie,wr(w,u.memoizedState)||(Cs=!0),u.memoizedState=w,u.baseState=q,u.baseQueue=ue,f.lastRenderedState=w}if(a=f.interleaved,a!==null){j=a;do E=j.lane,cs.lanes|=E,ua|=E,j=j.next;while(j!==a)}else j===null&&(f.lanes=0);return[u.memoizedState,f.dispatch]}function Kf(a){var u=Pr(),f=u.queue;if(f===null)throw Error(n(311));f.lastRenderedReducer=a;var w=f.dispatch,j=f.pending,E=u.memoizedState;if(j!==null){f.pending=null;var q=j=j.next;do E=a(E,q.action),q=q.next;while(q!==j);wr(E,u.memoizedState)||(Cs=!0),u.memoizedState=E,u.baseQueue===null&&(u.baseState=E),f.lastRenderedState=E}return[E,w]}function oa(){}function l_(a,u){var f=cs,w=Pr(),j=u(),E=!wr(w.memoizedState,j);if(E&&(w.memoizedState=j,Cs=!0),w=w.queue,kn(Jf.bind(null,f,w,a),[a]),w.getSnapshot!==u||E||Dn!==null&&Dn.memoizedState.tag&1){if(f.flags|=2048,Dl(9,c_.bind(null,f,w,j,u),void 0,null),Is===null)throw Error(n(349));(Qn&30)!==0||Rc(f,u,j)}return j}function Rc(a,u,f){a.flags|=16384,a={getSnapshot:u,value:f},u=cs.updateQueue,u===null?(u={lastEffect:null,stores:null},cs.updateQueue=u,u.stores=[a]):(f=u.stores,f===null?u.stores=[a]:f.push(a))}function c_(a,u,f,w){u.value=f,u.getSnapshot=w,oo(u)&&u_(a)}function Jf(a,u,f){return f(function(){oo(u)&&u_(a)})}function oo(a){var u=a.getSnapshot;a=a.value;try{var f=u();return!wr(a,f)}catch{return!0}}function u_(a){var u=dn(a,1);u!==null&&yi(u,a,1,-1)}function d_(a){var u=mi();return typeof a=="function"&&(a=a()),u.memoizedState=u.baseState=a,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Tc,lastRenderedState:a},u.queue=a,a=a.dispatch=ny.bind(null,cs,a),[u.memoizedState,a]}function Dl(a,u,f,w){return a={tag:a,create:u,destroy:f,deps:w,next:null},u=cs.updateQueue,u===null?(u={lastEffect:null,stores:null},cs.updateQueue=u,u.lastEffect=a.next=a):(f=u.lastEffect,f===null?u.lastEffect=a.next=a:(w=f.next,f.next=a,a.next=w,u.lastEffect=a)),a}function f_(){return Pr().memoizedState}function ed(a,u,f,w){var j=mi();cs.flags|=a,j.memoizedState=Dl(1|u,f,void 0,w===void 0?null:w)}function td(a,u,f,w){var j=Pr();w=w===void 0?null:w;var E=void 0;if($s!==null){var q=$s.memoizedState;if(E=q.destroy,w!==null&&Vf(w,q.deps)){j.memoizedState=Dl(u,f,E,w);return}}cs.flags|=a,j.memoizedState=Dl(1|u,f,E,w)}function h_(a,u){return ed(8390656,8,a,u)}function kn(a,u){return td(2048,8,a,u)}function Us(a,u){return td(4,2,a,u)}function lr(a,u){return td(4,4,a,u)}function nd(a,u){if(typeof u=="function")return a=a(),u(a),function(){u(null)};if(u!=null)return a=a(),u.current=a,function(){u.current=null}}function Lc(a,u,f){return f=f!=null?f.concat([a]):null,td(4,4,nd.bind(null,u,a),f)}function sd(){}function m_(a,u){var f=Pr();u=u===void 0?null:u;var w=f.memoizedState;return w!==null&&u!==null&&Vf(u,w[1])?w[0]:(f.memoizedState=[a,u],a)}function __(a,u){var f=Pr();u=u===void 0?null:u;var w=f.memoizedState;return w!==null&&u!==null&&Vf(u,w[1])?w[0]:(a=a(),f.memoizedState=[a,u],a)}function Yf(a,u,f){return(Qn&21)===0?(a.baseState&&(a.baseState=!1,Cs=!0),a.memoizedState=f):(wr(f,u)||(f=Ls(),cs.lanes|=f,ua|=f,a.baseState=!0),u)}function rd(a,u){var f=In;In=f!==0&&4>f?f:4,a(!0);var w=qf.transition;qf.transition={};try{a(!1),u()}finally{In=f,qf.transition=w}}function p_(){return Pr().memoizedState}function ty(a,u,f){var w=Wo(a);if(f={lane:w,action:f,hasEagerState:!1,eagerState:null,next:null},Xf(a))Zf(u,f);else if(f=ar(a,u,f,w),f!==null){var j=$r();yi(f,a,w,j),Ri(f,u,w)}}function ny(a,u,f){var w=Wo(a),j={lane:w,action:f,hasEagerState:!1,eagerState:null,next:null};if(Xf(a))Zf(u,j);else{var E=a.alternate;if(a.lanes===0&&(E===null||E.lanes===0)&&(E=u.lastRenderedReducer,E!==null))try{var q=u.lastRenderedState,ie=E(q,f);if(j.hasEagerState=!0,j.eagerState=ie,wr(ie,q)){var ue=u.interleaved;ue===null?(j.next=j,Yu(u)):(j.next=ue.next,ue.next=j),u.interleaved=j;return}}catch{}finally{}f=ar(a,u,j,w),f!==null&&(j=$r(),yi(f,a,w,j),Ri(f,u,w))}}function Xf(a){var u=a.alternate;return a===cs||u!==null&&u===cs}function Zf(a,u){Fo=Ac=!0;var f=a.pending;f===null?u.next=u:(u.next=f.next,f.next=u),a.pending=u}function Ri(a,u,f){if((f&4194240)!==0){var w=u.lanes;w&=a.pendingLanes,f|=w,u.lanes=f,Ui(a,f)}}var Fl={readContext:di,useCallback:Bs,useContext:Bs,useEffect:Bs,useImperativeHandle:Bs,useInsertionEffect:Bs,useLayoutEffect:Bs,useMemo:Bs,useReducer:Bs,useRef:Bs,useState:Bs,useDebugValue:Bs,useDeferredValue:Bs,useTransition:Bs,useMutableSource:Bs,useSyncExternalStore:Bs,useId:Bs,unstable_isNewReconciler:!1},Ic={readContext:di,useCallback:function(a,u){return mi().memoizedState=[a,u===void 0?null:u],a},useContext:di,useEffect:h_,useImperativeHandle:function(a,u,f){return f=f!=null?f.concat([a]):null,ed(4194308,4,nd.bind(null,u,a),f)},useLayoutEffect:function(a,u){return ed(4194308,4,a,u)},useInsertionEffect:function(a,u){return ed(4,2,a,u)},useMemo:function(a,u){var f=mi();return u=u===void 0?null:u,a=a(),f.memoizedState=[a,u],a},useReducer:function(a,u,f){var w=mi();return u=f!==void 0?f(u):u,w.memoizedState=w.baseState=u,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:u},w.queue=a,a=a.dispatch=ty.bind(null,cs,a),[w.memoizedState,a]},useRef:function(a){var u=mi();return a={current:a},u.memoizedState=a},useState:d_,useDebugValue:sd,useDeferredValue:function(a){return mi().memoizedState=a},useTransition:function(){var a=d_(!1),u=a[0];return a=rd.bind(null,a[1]),mi().memoizedState=a,[u,a]},useMutableSource:function(){},useSyncExternalStore:function(a,u,f){var w=cs,j=mi();if(Zn){if(f===void 0)throw Error(n(407));f=f()}else{if(f=u(),Is===null)throw Error(n(349));(Qn&30)!==0||Rc(w,u,f)}j.memoizedState=f;var E={value:f,getSnapshot:u};return j.queue=E,h_(Jf.bind(null,w,E,a),[a]),w.flags|=2048,Dl(9,c_.bind(null,w,E,f,u),void 0,null),f},useId:function(){var a=mi(),u=Is.identifierPrefix;if(Zn){var f=no,w=to;f=(w&~(1<<32-sr(w)-1)).toString(32)+f,u=":"+u+"R"+f,f=qa++,0<f&&(u+="H"+f.toString(32)),u+=":"}else f=io++,u=":"+u+"r"+f.toString(32)+":";return a.memoizedState=u},unstable_isNewReconciler:!1},sy={readContext:di,useCallback:m_,useContext:di,useEffect:kn,useImperativeHandle:Lc,useInsertionEffect:Us,useLayoutEffect:lr,useMemo:__,useReducer:Mc,useRef:f_,useState:function(){return Mc(Tc)},useDebugValue:sd,useDeferredValue:function(a){var u=Pr();return Yf(u,$s.memoizedState,a)},useTransition:function(){var a=Mc(Tc)[0],u=Pr().memoizedState;return[a,u]},useMutableSource:oa,useSyncExternalStore:l_,useId:p_,unstable_isNewReconciler:!1},Qf={readContext:di,useCallback:m_,useContext:di,useEffect:kn,useImperativeHandle:Lc,useInsertionEffect:Us,useLayoutEffect:lr,useMemo:__,useReducer:Kf,useRef:f_,useState:function(){return Kf(Tc)},useDebugValue:sd,useDeferredValue:function(a){var u=Pr();return $s===null?u.memoizedState=a:Yf(u,$s.memoizedState,a)},useTransition:function(){var a=Kf(Tc)[0],u=Pr().memoizedState;return[a,u]},useMutableSource:oa,useSyncExternalStore:l_,useId:p_,unstable_isNewReconciler:!1};function _i(a,u){if(a&&a.defaultProps){u=ee({},u),a=a.defaultProps;for(var f in a)u[f]===void 0&&(u[f]=a[f]);return u}return u}function eh(a,u,f,w){u=a.memoizedState,f=f(w,u),f=f==null?u:ee({},u,f),a.memoizedState=f,a.lanes===0&&(a.updateQueue.baseState=f)}var id={isMounted:function(a){return(a=a._reactInternals)?rn(a)===a:!1},enqueueSetState:function(a,u,f){a=a._reactInternals;var w=$r(),j=Wo(a),E=Xr(w,j);E.payload=u,f!=null&&(E.callback=f),u=Zr(a,E,j),u!==null&&(yi(u,a,j,w),on(u,a,j))},enqueueReplaceState:function(a,u,f){a=a._reactInternals;var w=$r(),j=Wo(a),E=Xr(w,j);E.tag=1,E.payload=u,f!=null&&(E.callback=f),u=Zr(a,E,j),u!==null&&(yi(u,a,j,w),on(u,a,j))},enqueueForceUpdate:function(a,u){a=a._reactInternals;var f=$r(),w=Wo(a),j=Xr(f,w);j.tag=2,u!=null&&(j.callback=u),u=Zr(a,j,w),u!==null&&(yi(u,a,w,f),on(u,a,w))}};function g_(a,u,f,w,j,E,q){return a=a.stateNode,typeof a.shouldComponentUpdate=="function"?a.shouldComponentUpdate(w,E,q):u.prototype&&u.prototype.isPureReactComponent?!Ki(f,w)||!Ki(j,E):!0}function y_(a,u,f){var w=!1,j=ci,E=u.contextType;return typeof E=="object"&&E!==null?E=di(E):(j=ir(u)?Lo:Ts.current,w=u.contextTypes,E=(w=w!=null)?Zi(a,j):ci),u=new u(f,E),a.memoizedState=u.state!==null&&u.state!==void 0?u.state:null,u.updater=id,a.stateNode=u,u._reactInternals=a,w&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=j,a.__reactInternalMemoizedMaskedChildContext=E),u}function w_(a,u,f,w){a=u.state,typeof u.componentWillReceiveProps=="function"&&u.componentWillReceiveProps(f,w),typeof u.UNSAFE_componentWillReceiveProps=="function"&&u.UNSAFE_componentWillReceiveProps(f,w),u.state!==a&&id.enqueueReplaceState(u,u.state,null)}function th(a,u,f,w){var j=a.stateNode;j.props=f,j.state=a.memoizedState,j.refs={},Nc(a);var E=u.contextType;typeof E=="object"&&E!==null?j.context=di(E):(E=ir(u)?Lo:Ts.current,j.context=Zi(a,E)),j.state=a.memoizedState,E=u.getDerivedStateFromProps,typeof E=="function"&&(eh(a,u,E,f),j.state=a.memoizedState),typeof u.getDerivedStateFromProps=="function"||typeof j.getSnapshotBeforeUpdate=="function"||typeof j.UNSAFE_componentWillMount!="function"&&typeof j.componentWillMount!="function"||(u=j.state,typeof j.componentWillMount=="function"&&j.componentWillMount(),typeof j.UNSAFE_componentWillMount=="function"&&j.UNSAFE_componentWillMount(),u!==j.state&&id.enqueueReplaceState(j,j.state,null),Il(a,f,j,w),j.state=a.memoizedState),typeof j.componentDidMount=="function"&&(a.flags|=4194308)}function Va(a,u){try{var f="",w=u;do f+=be(w),w=w.return;while(w);var j=f}catch(E){j=`
39
+ Error generating stack: `+E.message+`
40
+ `+E.stack}return{value:a,source:u,stack:j,digest:null}}function Oc(a,u,f){return{value:a,source:null,stack:f??null,digest:u??null}}function nh(a,u){try{console.error(u.value)}catch(f){setTimeout(function(){throw f})}}var ry=typeof WeakMap=="function"?WeakMap:Map;function Pc(a,u,f){f=Xr(-1,f),f.tag=3,f.payload={element:null};var w=u.value;return f.callback=function(){Hc||(Hc=!0,ch=w),nh(a,u)},f}function v_(a,u,f){f=Xr(-1,f),f.tag=3;var w=a.type.getDerivedStateFromError;if(typeof w=="function"){var j=u.value;f.payload=function(){return w(j)},f.callback=function(){nh(a,u)}}var E=a.stateNode;return E!==null&&typeof E.componentDidCatch=="function"&&(f.callback=function(){nh(a,u),typeof w!="function"&&(gi===null?gi=new Set([this]):gi.add(this));var q=u.stack;this.componentDidCatch(u.value,{componentStack:q!==null?q:""})}),f}function aa(a,u,f){var w=a.pingCache;if(w===null){w=a.pingCache=new ry;var j=new Set;w.set(u,j)}else j=w.get(u),j===void 0&&(j=new Set,w.set(u,j));j.has(f)||(j.add(f),a=X.bind(null,a,u,f),u.then(a,a))}function cr(a){do{var u;if((u=a.tag===13)&&(u=a.memoizedState,u=u!==null?u.dehydrated!==null:!0),u)return a;a=a.return}while(a!==null);return null}function Ws(a,u,f,w,j){return(a.mode&1)===0?(a===u?a.flags|=65536:(a.flags|=128,f.flags|=131072,f.flags&=-52805,f.tag===1&&(f.alternate===null?f.tag=17:(u=Xr(-1,1),u.tag=2,Zr(f,u,1))),f.lanes|=1),a):(a.flags|=65536,a.lanes=j,a)}var ao=S.ReactCurrentOwner,Cs=!1;function xs(a,u,f,w){u.child=a===null?Ff(u,null,f,w):Po(u,a.child,f,w)}function pi(a,u,f,w,j){f=f.render;var E=u.ref;return Ua(u,j),w=Hf(a,u,f,w,E,j),f=Gf(),a!==null&&!Cs?(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~j,Bo(a,u,j)):(Zn&&f&&Gu(u),u.flags|=1,xs(a,u,w,j),u.child)}function x_(a,u,f,w,j){if(a===null){var E=f.type;return typeof E=="function"&&!rt(E)&&E.defaultProps===void 0&&f.compare===null&&f.defaultProps===void 0?(u.tag=15,u.type=E,Dc(a,u,E,w,j)):(a=xn(f.type,null,w,u,u.mode,j),a.ref=u.ref,a.return=u,u.child=a)}if(E=a.child,(a.lanes&j)===0){var q=E.memoizedProps;if(f=f.compare,f=f!==null?f:Ki,f(q,w)&&a.ref===u.ref)return Bo(a,u,j)}return u.flags|=1,a=dt(E,w),a.ref=u.ref,a.return=u,u.child=a}function Dc(a,u,f,w,j){if(a!==null){var E=a.memoizedProps;if(Ki(E,w)&&a.ref===u.ref)if(Cs=!1,u.pendingProps=w=E,(a.lanes&j)!==0)(a.flags&131072)!==0&&(Cs=!0);else return u.lanes=a.lanes,Bo(a,u,j)}return sh(a,u,f,w,j)}function b_(a,u,f){var w=u.pendingProps,j=w.children,E=a!==null?a.memoizedState:null;if(w.mode==="hidden")if((u.mode&1)===0)u.memoizedState={baseLanes:0,cachePool:null,transitions:null},Xn(uo,Nr),Nr|=f;else{if((f&1073741824)===0)return a=E!==null?E.baseLanes|f:f,u.lanes=u.childLanes=1073741824,u.memoizedState={baseLanes:a,cachePool:null,transitions:null},u.updateQueue=null,Xn(uo,Nr),Nr|=a,null;u.memoizedState={baseLanes:0,cachePool:null,transitions:null},w=E!==null?E.baseLanes:f,Xn(uo,Nr),Nr|=w}else E!==null?(w=E.baseLanes|f,u.memoizedState=null):w=f,Xn(uo,Nr),Nr|=w;return xs(a,u,j,f),u.child}function od(a,u){var f=u.ref;(a===null&&f!==null||a!==null&&a.ref!==f)&&(u.flags|=512,u.flags|=2097152)}function sh(a,u,f,w,j){var E=ir(f)?Lo:Ts.current;return E=Zi(u,E),Ua(u,j),f=Hf(a,u,f,w,E,j),w=Gf(),a!==null&&!Cs?(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~j,Bo(a,u,j)):(Zn&&w&&Gu(u),u.flags|=1,xs(a,u,f,j),u.child)}function k_(a,u,f,w,j){if(ir(f)){var E=!0;Cl(u)}else E=!1;if(Ua(u,j),u.stateNode===null)Bl(a,u),y_(u,f,w),th(u,f,w,j),w=!0;else if(a===null){var q=u.stateNode,ie=u.memoizedProps;q.props=ie;var ue=q.context,Re=f.contextType;typeof Re=="object"&&Re!==null?Re=di(Re):(Re=ir(f)?Lo:Ts.current,Re=Zi(u,Re));var Ze=f.getDerivedStateFromProps,nt=typeof Ze=="function"||typeof q.getSnapshotBeforeUpdate=="function";nt||typeof q.UNSAFE_componentWillReceiveProps!="function"&&typeof q.componentWillReceiveProps!="function"||(ie!==w||ue!==Re)&&w_(u,q,w,Re),_s=!1;var Je=u.memoizedState;q.state=Je,Il(u,w,q,j),ue=u.memoizedState,ie!==w||Je!==ue||br.current||_s?(typeof Ze=="function"&&(eh(u,f,Ze,w),ue=u.memoizedState),(ie=_s||g_(u,f,ie,w,Je,ue,Re))?(nt||typeof q.UNSAFE_componentWillMount!="function"&&typeof q.componentWillMount!="function"||(typeof q.componentWillMount=="function"&&q.componentWillMount(),typeof q.UNSAFE_componentWillMount=="function"&&q.UNSAFE_componentWillMount()),typeof q.componentDidMount=="function"&&(u.flags|=4194308)):(typeof q.componentDidMount=="function"&&(u.flags|=4194308),u.memoizedProps=w,u.memoizedState=ue),q.props=w,q.state=ue,q.context=Re,w=ie):(typeof q.componentDidMount=="function"&&(u.flags|=4194308),w=!1)}else{q=u.stateNode,Wf(a,u),ie=u.memoizedProps,Re=u.type===u.elementType?ie:_i(u.type,ie),q.props=Re,nt=u.pendingProps,Je=q.context,ue=f.contextType,typeof ue=="object"&&ue!==null?ue=di(ue):(ue=ir(f)?Lo:Ts.current,ue=Zi(u,ue));var St=f.getDerivedStateFromProps;(Ze=typeof St=="function"||typeof q.getSnapshotBeforeUpdate=="function")||typeof q.UNSAFE_componentWillReceiveProps!="function"&&typeof q.componentWillReceiveProps!="function"||(ie!==nt||Je!==ue)&&w_(u,q,w,ue),_s=!1,Je=u.memoizedState,q.state=Je,Il(u,w,q,j);var At=u.memoizedState;ie!==nt||Je!==At||br.current||_s?(typeof St=="function"&&(eh(u,f,St,w),At=u.memoizedState),(Re=_s||g_(u,f,Re,w,Je,At,ue)||!1)?(Ze||typeof q.UNSAFE_componentWillUpdate!="function"&&typeof q.componentWillUpdate!="function"||(typeof q.componentWillUpdate=="function"&&q.componentWillUpdate(w,At,ue),typeof q.UNSAFE_componentWillUpdate=="function"&&q.UNSAFE_componentWillUpdate(w,At,ue)),typeof q.componentDidUpdate=="function"&&(u.flags|=4),typeof q.getSnapshotBeforeUpdate=="function"&&(u.flags|=1024)):(typeof q.componentDidUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=1024),u.memoizedProps=w,u.memoizedState=At),q.props=w,q.state=At,q.context=ue,w=Re):(typeof q.componentDidUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||ie===a.memoizedProps&&Je===a.memoizedState||(u.flags|=1024),w=!1)}return ad(a,u,f,w,E,j)}function ad(a,u,f,w,j,E){od(a,u);var q=(u.flags&128)!==0;if(!w&&!q)return j&&Wu(u,f,!1),Bo(a,u,E);w=u.stateNode,ao.current=u;var ie=q&&typeof f.getDerivedStateFromError!="function"?null:w.render();return u.flags|=1,a!==null&&q?(u.child=Po(u,a.child,null,E),u.child=Po(u,null,ie,E)):xs(a,u,ie,E),u.memoizedState=w.state,j&&Wu(u,f,!0),u.child}function la(a){var u=a.stateNode;u.pendingContext?Uu(a,u.pendingContext,u.pendingContext!==u.context):u.context&&Uu(a,u.context,!1),Xu(a,u.containerInfo)}function zl(a,u,f,w,j){return Ba(),Of(j),u.flags|=256,xs(a,u,f,w),u.child}var ld={dehydrated:null,treeContext:null,retryLane:0};function cd(a){return{baseLanes:a,cachePool:null,transitions:null}}function j_(a,u,f){var w=u.pendingProps,j=ps.current,E=!1,q=(u.flags&128)!==0,ie;if((ie=q)||(ie=a!==null&&a.memoizedState===null?!1:(j&2)!==0),ie?(E=!0,u.flags&=-129):(a===null||a.memoizedState!==null)&&(j|=1),Xn(ps,j&1),a===null)return Sc(u),a=u.memoizedState,a!==null&&(a=a.dehydrated,a!==null)?((u.mode&1)===0?u.lanes=1:a.data==="$!"?u.lanes=8:u.lanes=1073741824,null):(q=w.children,a=w.fallback,E?(w=u.mode,E=u.child,q={mode:"hidden",children:q},(w&1)===0&&E!==null?(E.childLanes=0,E.pendingProps=q):E=ft(q,w,0,null),a=qt(a,w,f,null),E.return=u,a.return=u,E.sibling=a,u.child=E,u.child.memoizedState=cd(f),u.memoizedState=ld,a):ud(u,q));if(j=a.memoizedState,j!==null&&(ie=j.dehydrated,ie!==null))return iy(a,u,q,w,ie,j,f);if(E){E=w.fallback,q=u.mode,j=a.child,ie=j.sibling;var ue={mode:"hidden",children:w.children};return(q&1)===0&&u.child!==j?(w=u.child,w.childLanes=0,w.pendingProps=ue,u.deletions=null):(w=dt(j,ue),w.subtreeFlags=j.subtreeFlags&14680064),ie!==null?E=dt(ie,E):(E=qt(E,q,f,null),E.flags|=2),E.return=u,w.return=u,w.sibling=E,u.child=w,w=E,E=u.child,q=a.child.memoizedState,q=q===null?cd(f):{baseLanes:q.baseLanes|f,cachePool:null,transitions:q.transitions},E.memoizedState=q,E.childLanes=a.childLanes&~f,u.memoizedState=ld,w}return E=a.child,a=E.sibling,w=dt(E,{mode:"visible",children:w.children}),(u.mode&1)===0&&(w.lanes=f),w.return=u,w.sibling=null,a!==null&&(f=u.deletions,f===null?(u.deletions=[a],u.flags|=16):f.push(a)),u.child=w,u.memoizedState=null,w}function ud(a,u){return u=ft({mode:"visible",children:u},a.mode,0,null),u.return=a,a.child=u}function zo(a,u,f,w){return w!==null&&Of(w),Po(u,a.child,null,f),a=ud(u,u.pendingProps.children),a.flags|=2,u.memoizedState=null,a}function iy(a,u,f,w,j,E,q){if(f)return u.flags&256?(u.flags&=-257,w=Oc(Error(n(422))),zo(a,u,q,w)):u.memoizedState!==null?(u.child=a.child,u.flags|=128,null):(E=w.fallback,j=u.mode,w=ft({mode:"visible",children:w.children},j,0,null),E=qt(E,j,q,null),E.flags|=2,w.return=u,E.return=u,w.sibling=E,u.child=w,(u.mode&1)!==0&&Po(u,a.child,null,q),u.child.memoizedState=cd(q),u.memoizedState=ld,E);if((u.mode&1)===0)return zo(a,u,q,null);if(j.data==="$!"){if(w=j.nextSibling&&j.nextSibling.dataset,w)var ie=w.dgst;return w=ie,E=Error(n(419)),w=Oc(E,w,void 0),zo(a,u,q,w)}if(ie=(q&a.childLanes)!==0,Cs||ie){if(w=Is,w!==null){switch(q&-q){case 4:j=2;break;case 16:j=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:j=32;break;case 536870912:j=268435456;break;default:j=0}j=(j&(w.suspendedLanes|q))!==0?0:j,j!==0&&j!==E.retryLane&&(E.retryLane=j,dn(a,j),yi(w,a,j,-1))}return gd(),w=Oc(Error(n(421))),zo(a,u,q,w)}return j.data==="$?"?(u.flags|=128,u.child=a.child,u=oe.bind(null,a),j._reactRetry=u,null):(a=E.treeContext,Or=na(j.nextSibling),Yr=u,Zn=!0,Mi=null,a!==null&&(kr[Jr++]=to,kr[Jr++]=no,kr[Jr++]=eo,to=a.id,no=a.overflow,eo=u),u=ud(u,w.children),u.flags|=4096,u)}function Fc(a,u,f){a.lanes|=u;var w=a.alternate;w!==null&&(w.lanes|=u),Ju(a.return,u,f)}function dd(a,u,f,w,j){var E=a.memoizedState;E===null?a.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:w,tail:f,tailMode:j}:(E.isBackwards=u,E.rendering=null,E.renderingStartTime=0,E.last=w,E.tail=f,E.tailMode=j)}function S_(a,u,f){var w=u.pendingProps,j=w.revealOrder,E=w.tail;if(xs(a,u,w.children,f),w=ps.current,(w&2)!==0)w=w&1|2,u.flags|=128;else{if(a!==null&&(a.flags&128)!==0)e:for(a=u.child;a!==null;){if(a.tag===13)a.memoizedState!==null&&Fc(a,f,u);else if(a.tag===19)Fc(a,f,u);else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===u)break e;for(;a.sibling===null;){if(a.return===null||a.return===u)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}w&=1}if(Xn(ps,w),(u.mode&1)===0)u.memoizedState=null;else switch(j){case"forwards":for(f=u.child,j=null;f!==null;)a=f.alternate,a!==null&&Zu(a)===null&&(j=f),f=f.sibling;f=j,f===null?(j=u.child,u.child=null):(j=f.sibling,f.sibling=null),dd(u,!1,j,f,E);break;case"backwards":for(f=null,j=u.child,u.child=null;j!==null;){if(a=j.alternate,a!==null&&Zu(a)===null){u.child=j;break}a=j.sibling,j.sibling=f,f=j,j=a}dd(u,!0,f,null,E);break;case"together":dd(u,!1,null,null,void 0);break;default:u.memoizedState=null}return u.child}function Bl(a,u){(u.mode&1)===0&&a!==null&&(a.alternate=null,u.alternate=null,u.flags|=2)}function Bo(a,u,f){if(a!==null&&(u.dependencies=a.dependencies),ua|=u.lanes,(f&u.childLanes)===0)return null;if(a!==null&&u.child!==a.child)throw Error(n(153));if(u.child!==null){for(a=u.child,f=dt(a,a.pendingProps),u.child=f,f.return=u;a.sibling!==null;)a=a.sibling,f=f.sibling=dt(a,a.pendingProps),f.return=u;f.sibling=null}return u.child}function oy(a,u,f){switch(u.tag){case 3:la(u),Ba();break;case 5:hi(u);break;case 1:ir(u.type)&&Cl(u);break;case 4:Xu(u,u.stateNode.containerInfo);break;case 10:var w=u.type._context,j=u.memoizedProps.value;Xn(Do,w._currentValue),w._currentValue=j;break;case 13:if(w=u.memoizedState,w!==null)return w.dehydrated!==null?(Xn(ps,ps.current&1),u.flags|=128,null):(f&u.child.childLanes)!==0?j_(a,u,f):(Xn(ps,ps.current&1),a=Bo(a,u,f),a!==null?a.sibling:null);Xn(ps,ps.current&1);break;case 19:if(w=(f&u.childLanes)!==0,(a.flags&128)!==0){if(w)return S_(a,u,f);u.flags|=128}if(j=u.memoizedState,j!==null&&(j.rendering=null,j.tail=null,j.lastEffect=null),Xn(ps,ps.current),w)break;return null;case 22:case 23:return u.lanes=0,b_(a,u,f)}return Bo(a,u,f)}var N_,Sr,Ha,$_;N_=function(a,u){for(var f=u.child;f!==null;){if(f.tag===5||f.tag===6)a.appendChild(f.stateNode);else if(f.tag!==4&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===u)break;for(;f.sibling===null;){if(f.return===null||f.return===u)return;f=f.return}f.sibling.return=f.return,f=f.sibling}},Sr=function(){},Ha=function(a,u,f,w){var j=a.memoizedProps;if(j!==w){a=u.stateNode,jr(ro.current);var E=null;switch(f){case"input":j=it(a,j),w=it(a,w),E=[];break;case"select":j=ee({},j,{value:void 0}),w=ee({},w,{value:void 0}),E=[];break;case"textarea":j=He(a,j),w=He(a,w),E=[];break;default:typeof j.onClick!="function"&&typeof w.onClick=="function"&&(a.onclick=jc)}vt(f,w);var q;f=null;for(Re in j)if(!w.hasOwnProperty(Re)&&j.hasOwnProperty(Re)&&j[Re]!=null)if(Re==="style"){var ie=j[Re];for(q in ie)ie.hasOwnProperty(q)&&(f||(f={}),f[q]="")}else Re!=="dangerouslySetInnerHTML"&&Re!=="children"&&Re!=="suppressContentEditableWarning"&&Re!=="suppressHydrationWarning"&&Re!=="autoFocus"&&(i.hasOwnProperty(Re)?E||(E=[]):(E=E||[]).push(Re,null));for(Re in w){var ue=w[Re];if(ie=j!=null?j[Re]:void 0,w.hasOwnProperty(Re)&&ue!==ie&&(ue!=null||ie!=null))if(Re==="style")if(ie){for(q in ie)!ie.hasOwnProperty(q)||ue&&ue.hasOwnProperty(q)||(f||(f={}),f[q]="");for(q in ue)ue.hasOwnProperty(q)&&ie[q]!==ue[q]&&(f||(f={}),f[q]=ue[q])}else f||(E||(E=[]),E.push(Re,f)),f=ue;else Re==="dangerouslySetInnerHTML"?(ue=ue?ue.__html:void 0,ie=ie?ie.__html:void 0,ue!=null&&ie!==ue&&(E=E||[]).push(Re,ue)):Re==="children"?typeof ue!="string"&&typeof ue!="number"||(E=E||[]).push(Re,""+ue):Re!=="suppressContentEditableWarning"&&Re!=="suppressHydrationWarning"&&(i.hasOwnProperty(Re)?(ue!=null&&Re==="onScroll"&&Bn("scroll",a),E||ie===ue||(E=[])):(E=E||[]).push(Re,ue))}f&&(E=E||[]).push("style",f);var Re=E;(u.updateQueue=Re)&&(u.flags|=4)}},$_=function(a,u,f,w){f!==w&&(u.flags|=4)};function Ul(a,u){if(!Zn)switch(a.tailMode){case"hidden":u=a.tail;for(var f=null;u!==null;)u.alternate!==null&&(f=u),u=u.sibling;f===null?a.tail=null:f.sibling=null;break;case"collapsed":f=a.tail;for(var w=null;f!==null;)f.alternate!==null&&(w=f),f=f.sibling;w===null?u||a.tail===null?a.tail=null:a.tail.sibling=null:w.sibling=null}}function Jn(a){var u=a.alternate!==null&&a.alternate.child===a.child,f=0,w=0;if(u)for(var j=a.child;j!==null;)f|=j.lanes|j.childLanes,w|=j.subtreeFlags&14680064,w|=j.flags&14680064,j.return=a,j=j.sibling;else for(j=a.child;j!==null;)f|=j.lanes|j.childLanes,w|=j.subtreeFlags,w|=j.flags,j.return=a,j=j.sibling;return a.subtreeFlags|=w,a.childLanes=f,u}function rh(a,u,f){var w=u.pendingProps;switch(Ku(u),u.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Jn(u),null;case 1:return ir(u.type)&&Io(),Jn(u),null;case 3:return w=u.stateNode,fi(),Pn(br),Pn(Ts),Qu(),w.pendingContext&&(w.context=w.pendingContext,w.pendingContext=null),(a===null||a.child===null)&&(Ml(u)?u.flags|=4:a===null||a.memoizedState.isDehydrated&&(u.flags&256)===0||(u.flags|=1024,Mi!==null&&(uh(Mi),Mi=null))),Sr(a,u),Jn(u),null;case 5:Ol(u);var j=jr(Wa.current);if(f=u.type,a!==null&&u.stateNode!=null)Ha(a,u,f,w,j),a.ref!==u.ref&&(u.flags|=512,u.flags|=2097152);else{if(!w){if(u.stateNode===null)throw Error(n(166));return Jn(u),null}if(a=jr(ro.current),Ml(u)){w=u.stateNode,f=u.type;var E=u.memoizedProps;switch(w[Xi]=u,w[To]=E,a=(u.mode&1)!==0,f){case"dialog":Bn("cancel",w),Bn("close",w);break;case"iframe":case"object":case"embed":Bn("load",w);break;case"video":case"audio":for(j=0;j<Eo.length;j++)Bn(Eo[j],w);break;case"source":Bn("error",w);break;case"img":case"image":case"link":Bn("error",w),Bn("load",w);break;case"details":Bn("toggle",w);break;case"input":$t(w,E),Bn("invalid",w);break;case"select":w._wrapperState={wasMultiple:!!E.multiple},Bn("invalid",w);break;case"textarea":ne(w,E),Bn("invalid",w)}vt(f,E),j=null;for(var q in E)if(E.hasOwnProperty(q)){var ie=E[q];q==="children"?typeof ie=="string"?w.textContent!==ie&&(E.suppressHydrationWarning!==!0&&kc(w.textContent,ie,a),j=["children",ie]):typeof ie=="number"&&w.textContent!==""+ie&&(E.suppressHydrationWarning!==!0&&kc(w.textContent,ie,a),j=["children",""+ie]):i.hasOwnProperty(q)&&ie!=null&&q==="onScroll"&&Bn("scroll",w)}switch(f){case"input":Ve(w),et(w,E,!0);break;case"textarea":Ve(w),fe(w);break;case"select":case"option":break;default:typeof E.onClick=="function"&&(w.onclick=jc)}w=j,u.updateQueue=w,w!==null&&(u.flags|=4)}else{q=j.nodeType===9?j:j.ownerDocument,a==="http://www.w3.org/1999/xhtml"&&(a=$e(f)),a==="http://www.w3.org/1999/xhtml"?f==="script"?(a=q.createElement("div"),a.innerHTML="<script><\/script>",a=a.removeChild(a.firstChild)):typeof w.is=="string"?a=q.createElement(f,{is:w.is}):(a=q.createElement(f),f==="select"&&(q=a,w.multiple?q.multiple=!0:w.size&&(q.size=w.size))):a=q.createElementNS(a,f),a[Xi]=u,a[To]=w,N_(a,u,!1,!1),u.stateNode=a;e:{switch(q=nn(f,w),f){case"dialog":Bn("cancel",a),Bn("close",a),j=w;break;case"iframe":case"object":case"embed":Bn("load",a),j=w;break;case"video":case"audio":for(j=0;j<Eo.length;j++)Bn(Eo[j],a);j=w;break;case"source":Bn("error",a),j=w;break;case"img":case"image":case"link":Bn("error",a),Bn("load",a),j=w;break;case"details":Bn("toggle",a),j=w;break;case"input":$t(a,w),j=it(a,w),Bn("invalid",a);break;case"option":j=w;break;case"select":a._wrapperState={wasMultiple:!!w.multiple},j=ee({},w,{value:void 0}),Bn("invalid",a);break;case"textarea":ne(a,w),j=He(a,w),Bn("invalid",a);break;default:j=w}vt(f,j),ie=j;for(E in ie)if(ie.hasOwnProperty(E)){var ue=ie[E];E==="style"?ct(a,ue):E==="dangerouslySetInnerHTML"?(ue=ue?ue.__html:void 0,ue!=null&&ze(a,ue)):E==="children"?typeof ue=="string"?(f!=="textarea"||ue!=="")&&st(a,ue):typeof ue=="number"&&st(a,""+ue):E!=="suppressContentEditableWarning"&&E!=="suppressHydrationWarning"&&E!=="autoFocus"&&(i.hasOwnProperty(E)?ue!=null&&E==="onScroll"&&Bn("scroll",a):ue!=null&&C(a,E,ue,q))}switch(f){case"input":Ve(a),et(a,w,!1);break;case"textarea":Ve(a),fe(a);break;case"option":w.value!=null&&a.setAttribute("value",""+ae(w.value));break;case"select":a.multiple=!!w.multiple,E=w.value,E!=null?Se(a,!!w.multiple,E,!1):w.defaultValue!=null&&Se(a,!!w.multiple,w.defaultValue,!0);break;default:typeof j.onClick=="function"&&(a.onclick=jc)}switch(f){case"button":case"input":case"select":case"textarea":w=!!w.autoFocus;break e;case"img":w=!0;break e;default:w=!1}}w&&(u.flags|=4)}u.ref!==null&&(u.flags|=512,u.flags|=2097152)}return Jn(u),null;case 6:if(a&&u.stateNode!=null)$_(a,u,a.memoizedProps,w);else{if(typeof w!="string"&&u.stateNode===null)throw Error(n(166));if(f=jr(Wa.current),jr(ro.current),Ml(u)){if(w=u.stateNode,f=u.memoizedProps,w[Xi]=u,(E=w.nodeValue!==f)&&(a=Yr,a!==null))switch(a.tag){case 3:kc(w.nodeValue,f,(a.mode&1)!==0);break;case 5:a.memoizedProps.suppressHydrationWarning!==!0&&kc(w.nodeValue,f,(a.mode&1)!==0)}E&&(u.flags|=4)}else w=(f.nodeType===9?f:f.ownerDocument).createTextNode(w),w[Xi]=u,u.stateNode=w}return Jn(u),null;case 13:if(Pn(ps),w=u.memoizedState,a===null||a.memoizedState!==null&&a.memoizedState.dehydrated!==null){if(Zn&&Or!==null&&(u.mode&1)!==0&&(u.flags&128)===0)i_(),Ba(),u.flags|=98560,E=!1;else if(E=Ml(u),w!==null&&w.dehydrated!==null){if(a===null){if(!E)throw Error(n(318));if(E=u.memoizedState,E=E!==null?E.dehydrated:null,!E)throw Error(n(317));E[Xi]=u}else Ba(),(u.flags&128)===0&&(u.memoizedState=null),u.flags|=4;Jn(u),E=!1}else Mi!==null&&(uh(Mi),Mi=null),E=!0;if(!E)return u.flags&65536?u:null}return(u.flags&128)!==0?(u.lanes=f,u):(w=w!==null,w!==(a!==null&&a.memoizedState!==null)&&w&&(u.child.flags|=8192,(u.mode&1)!==0&&(a===null||(ps.current&1)!==0?ys===0&&(ys=3):gd())),u.updateQueue!==null&&(u.flags|=4),Jn(u),null);case 4:return fi(),Sr(a,u),a===null&&Ei(u.stateNode.containerInfo),Jn(u),null;case 10:return Uf(u.type._context),Jn(u),null;case 17:return ir(u.type)&&Io(),Jn(u),null;case 19:if(Pn(ps),E=u.memoizedState,E===null)return Jn(u),null;if(w=(u.flags&128)!==0,q=E.rendering,q===null)if(w)Ul(E,!1);else{if(ys!==0||a!==null&&(a.flags&128)!==0)for(a=u.child;a!==null;){if(q=Zu(a),q!==null){for(u.flags|=128,Ul(E,!1),w=q.updateQueue,w!==null&&(u.updateQueue=w,u.flags|=4),u.subtreeFlags=0,w=f,f=u.child;f!==null;)E=f,a=w,E.flags&=14680066,q=E.alternate,q===null?(E.childLanes=0,E.lanes=a,E.child=null,E.subtreeFlags=0,E.memoizedProps=null,E.memoizedState=null,E.updateQueue=null,E.dependencies=null,E.stateNode=null):(E.childLanes=q.childLanes,E.lanes=q.lanes,E.child=q.child,E.subtreeFlags=0,E.deletions=null,E.memoizedProps=q.memoizedProps,E.memoizedState=q.memoizedState,E.updateQueue=q.updateQueue,E.type=q.type,a=q.dependencies,E.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),f=f.sibling;return Xn(ps,ps.current&1|2),u.child}a=a.sibling}E.tail!==null&&un()>da&&(u.flags|=128,w=!0,Ul(E,!1),u.lanes=4194304)}else{if(!w)if(a=Zu(q),a!==null){if(u.flags|=128,w=!0,f=a.updateQueue,f!==null&&(u.updateQueue=f,u.flags|=4),Ul(E,!0),E.tail===null&&E.tailMode==="hidden"&&!q.alternate&&!Zn)return Jn(u),null}else 2*un()-E.renderingStartTime>da&&f!==1073741824&&(u.flags|=128,w=!0,Ul(E,!1),u.lanes=4194304);E.isBackwards?(q.sibling=u.child,u.child=q):(f=E.last,f!==null?f.sibling=q:u.child=q,E.last=q)}return E.tail!==null?(u=E.tail,E.rendering=u,E.tail=u.sibling,E.renderingStartTime=un(),u.sibling=null,f=ps.current,Xn(ps,w?f&1|2:f&1),u):(Jn(u),null);case 22:case 23:return pd(),w=u.memoizedState!==null,a!==null&&a.memoizedState!==null!==w&&(u.flags|=8192),w&&(u.mode&1)!==0?(Nr&1073741824)!==0&&(Jn(u),u.subtreeFlags&6&&(u.flags|=8192)):Jn(u),null;case 24:return null;case 25:return null}throw Error(n(156,u.tag))}function C_(a,u){switch(Ku(u),u.tag){case 1:return ir(u.type)&&Io(),a=u.flags,a&65536?(u.flags=a&-65537|128,u):null;case 3:return fi(),Pn(br),Pn(Ts),Qu(),a=u.flags,(a&65536)!==0&&(a&128)===0?(u.flags=a&-65537|128,u):null;case 5:return Ol(u),null;case 13:if(Pn(ps),a=u.memoizedState,a!==null&&a.dehydrated!==null){if(u.alternate===null)throw Error(n(340));Ba()}return a=u.flags,a&65536?(u.flags=a&-65537|128,u):null;case 19:return Pn(ps),null;case 4:return fi(),null;case 10:return Uf(u.type._context),null;case 22:case 23:return pd(),null;case 24:return null;default:return null}}var zc=!1,ur=!1,ay=typeof WeakSet=="function"?WeakSet:Set,Nt=null;function qs(a,u){var f=a.ref;if(f!==null)if(typeof f=="function")try{f(null)}catch(w){Z(a,u,w)}else f.current=null}function Ga(a,u,f){try{f()}catch(w){Z(a,u,w)}}var ih=!1;function E_(a,u){if(Fu=rr,a=Nf(),Ra(a)){if("selectionStart"in a)var f={start:a.selectionStart,end:a.selectionEnd};else e:{f=(f=a.ownerDocument)&&f.defaultView||window;var w=f.getSelection&&f.getSelection();if(w&&w.rangeCount!==0){f=w.anchorNode;var j=w.anchorOffset,E=w.focusNode;w=w.focusOffset;try{f.nodeType,E.nodeType}catch{f=null;break e}var q=0,ie=-1,ue=-1,Re=0,Ze=0,nt=a,Je=null;t:for(;;){for(var St;nt!==f||j!==0&&nt.nodeType!==3||(ie=q+j),nt!==E||w!==0&&nt.nodeType!==3||(ue=q+w),nt.nodeType===3&&(q+=nt.nodeValue.length),(St=nt.firstChild)!==null;)Je=nt,nt=St;for(;;){if(nt===a)break t;if(Je===f&&++Re===j&&(ie=q),Je===E&&++Ze===w&&(ue=q),(St=nt.nextSibling)!==null)break;nt=Je,Je=nt.parentNode}nt=St}f=ie===-1||ue===-1?null:{start:ie,end:ue}}else f=null}f=f||{start:0,end:0}}else f=null;for(Af={focusedElem:a,selectionRange:f},rr=!1,Nt=u;Nt!==null;)if(u=Nt,a=u.child,(u.subtreeFlags&1028)!==0&&a!==null)a.return=u,Nt=a;else for(;Nt!==null;){u=Nt;try{var At=u.alternate;if((u.flags&1024)!==0)switch(u.tag){case 0:case 11:case 15:break;case 1:if(At!==null){var Rt=At.memoizedProps,Os=At.memoizedState,xe=u.stateNode,_e=xe.getSnapshotBeforeUpdate(u.elementType===u.type?Rt:_i(u.type,Rt),Os);xe.__reactInternalSnapshotBeforeUpdate=_e}break;case 3:var Ce=u.stateNode.containerInfo;Ce.nodeType===1?Ce.textContent="":Ce.nodeType===9&&Ce.documentElement&&Ce.removeChild(Ce.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(at){Z(u,u.return,at)}if(a=u.sibling,a!==null){a.return=u.return,Nt=a;break}Nt=u.return}return At=ih,ih=!1,At}function lo(a,u,f){var w=u.updateQueue;if(w=w!==null?w.lastEffect:null,w!==null){var j=w=w.next;do{if((j.tag&a)===a){var E=j.destroy;j.destroy=void 0,E!==void 0&&Ga(u,f,E)}j=j.next}while(j!==w)}}function Bc(a,u){if(u=u.updateQueue,u=u!==null?u.lastEffect:null,u!==null){var f=u=u.next;do{if((f.tag&a)===a){var w=f.create;f.destroy=w()}f=f.next}while(f!==u)}}function Li(a){var u=a.ref;if(u!==null){var f=a.stateNode;switch(a.tag){case 5:a=f;break;default:a=f}typeof u=="function"?u(a):u.current=a}}function A_(a){var u=a.alternate;u!==null&&(a.alternate=null,A_(u)),a.child=null,a.deletions=null,a.sibling=null,a.tag===5&&(u=a.stateNode,u!==null&&(delete u[Xi],delete u[To],delete u[Sl],delete u[e_],delete u[Nl])),a.stateNode=null,a.return=null,a.dependencies=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.stateNode=null,a.updateQueue=null}function T_(a){return a.tag===5||a.tag===3||a.tag===4}function oh(a){e:for(;;){for(;a.sibling===null;){if(a.return===null||T_(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;a.tag!==5&&a.tag!==6&&a.tag!==18;){if(a.flags&2||a.child===null||a.tag===4)continue e;a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}function Ii(a,u,f){var w=a.tag;if(w===5||w===6)a=a.stateNode,u?f.nodeType===8?f.parentNode.insertBefore(a,u):f.insertBefore(a,u):(f.nodeType===8?(u=f.parentNode,u.insertBefore(a,f)):(u=f,u.appendChild(a)),f=f._reactRootContainer,f!=null||u.onclick!==null||(u.onclick=jc));else if(w!==4&&(a=a.child,a!==null))for(Ii(a,u,f),a=a.sibling;a!==null;)Ii(a,u,f),a=a.sibling}function Uc(a,u,f){var w=a.tag;if(w===5||w===6)a=a.stateNode,u?f.insertBefore(a,u):f.appendChild(a);else if(w!==4&&(a=a.child,a!==null))for(Uc(a,u,f),a=a.sibling;a!==null;)Uc(a,u,f),a=a.sibling}var Ys=null,Oi=!1;function ca(a,u,f){for(f=f.child;f!==null;)ah(a,u,f),f=f.sibling}function ah(a,u,f){if(nr&&typeof nr.onCommitFiberUnmount=="function")try{nr.onCommitFiberUnmount(zn,f)}catch{}switch(f.tag){case 5:ur||qs(f,u);case 6:var w=Ys,j=Oi;Ys=null,ca(a,u,f),Ys=w,Oi=j,Ys!==null&&(Oi?(a=Ys,f=f.stateNode,a.nodeType===8?a.parentNode.removeChild(f):a.removeChild(f)):Ys.removeChild(f.stateNode));break;case 18:Ys!==null&&(Oi?(a=Ys,f=f.stateNode,a.nodeType===8?Bu(a.parentNode,f):a.nodeType===1&&Bu(a,f),Ea(a)):Bu(Ys,f.stateNode));break;case 4:w=Ys,j=Oi,Ys=f.stateNode.containerInfo,Oi=!0,ca(a,u,f),Ys=w,Oi=j;break;case 0:case 11:case 14:case 15:if(!ur&&(w=f.updateQueue,w!==null&&(w=w.lastEffect,w!==null))){j=w=w.next;do{var E=j,q=E.destroy;E=E.tag,q!==void 0&&((E&2)!==0||(E&4)!==0)&&Ga(f,u,q),j=j.next}while(j!==w)}ca(a,u,f);break;case 1:if(!ur&&(qs(f,u),w=f.stateNode,typeof w.componentWillUnmount=="function"))try{w.props=f.memoizedProps,w.state=f.memoizedState,w.componentWillUnmount()}catch(ie){Z(f,u,ie)}ca(a,u,f);break;case 21:ca(a,u,f);break;case 22:f.mode&1?(ur=(w=ur)||f.memoizedState!==null,ca(a,u,f),ur=w):ca(a,u,f);break;default:ca(a,u,f)}}function M_(a){var u=a.updateQueue;if(u!==null){a.updateQueue=null;var f=a.stateNode;f===null&&(f=a.stateNode=new ay),u.forEach(function(w){var j=Ge.bind(null,a,w);f.has(w)||(f.add(w),w.then(j,j))})}}function Cn(a,u){var f=u.deletions;if(f!==null)for(var w=0;w<f.length;w++){var j=f[w];try{var E=a,q=u,ie=q;e:for(;ie!==null;){switch(ie.tag){case 5:Ys=ie.stateNode,Oi=!1;break e;case 3:Ys=ie.stateNode.containerInfo,Oi=!0;break e;case 4:Ys=ie.stateNode.containerInfo,Oi=!0;break e}ie=ie.return}if(Ys===null)throw Error(n(160));ah(E,q,j),Ys=null,Oi=!1;var ue=j.alternate;ue!==null&&(ue.return=null),j.return=null}catch(Re){Z(j,u,Re)}}if(u.subtreeFlags&12854)for(u=u.child;u!==null;)gs(u,a),u=u.sibling}function gs(a,u){var f=a.alternate,w=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:if(Cn(u,a),us(a),w&4){try{lo(3,a,a.return),Bc(3,a)}catch(Rt){Z(a,a.return,Rt)}try{lo(5,a,a.return)}catch(Rt){Z(a,a.return,Rt)}}break;case 1:Cn(u,a),us(a),w&512&&f!==null&&qs(f,f.return);break;case 5:if(Cn(u,a),us(a),w&512&&f!==null&&qs(f,f.return),a.flags&32){var j=a.stateNode;try{st(j,"")}catch(Rt){Z(a,a.return,Rt)}}if(w&4&&(j=a.stateNode,j!=null)){var E=a.memoizedProps,q=f!==null?f.memoizedProps:E,ie=a.type,ue=a.updateQueue;if(a.updateQueue=null,ue!==null)try{ie==="input"&&E.type==="radio"&&E.name!=null&&ot(j,E),nn(ie,q);var Re=nn(ie,E);for(q=0;q<ue.length;q+=2){var Ze=ue[q],nt=ue[q+1];Ze==="style"?ct(j,nt):Ze==="dangerouslySetInnerHTML"?ze(j,nt):Ze==="children"?st(j,nt):C(j,Ze,nt,Re)}switch(ie){case"input":mt(j,E);break;case"textarea":we(j,E);break;case"select":var Je=j._wrapperState.wasMultiple;j._wrapperState.wasMultiple=!!E.multiple;var St=E.value;St!=null?Se(j,!!E.multiple,St,!1):Je!==!!E.multiple&&(E.defaultValue!=null?Se(j,!!E.multiple,E.defaultValue,!0):Se(j,!!E.multiple,E.multiple?[]:"",!1))}j[To]=E}catch(Rt){Z(a,a.return,Rt)}}break;case 6:if(Cn(u,a),us(a),w&4){if(a.stateNode===null)throw Error(n(162));j=a.stateNode,E=a.memoizedProps;try{j.nodeValue=E}catch(Rt){Z(a,a.return,Rt)}}break;case 3:if(Cn(u,a),us(a),w&4&&f!==null&&f.memoizedState.isDehydrated)try{Ea(u.containerInfo)}catch(Rt){Z(a,a.return,Rt)}break;case 4:Cn(u,a),us(a);break;case 13:Cn(u,a),us(a),j=a.child,j.flags&8192&&(E=j.memoizedState!==null,j.stateNode.isHidden=E,!E||j.alternate!==null&&j.alternate.memoizedState!==null||(Vc=un())),w&4&&M_(a);break;case 22:if(Ze=f!==null&&f.memoizedState!==null,a.mode&1?(ur=(Re=ur)||Ze,Cn(u,a),ur=Re):Cn(u,a),us(a),w&8192){if(Re=a.memoizedState!==null,(a.stateNode.isHidden=Re)&&!Ze&&(a.mode&1)!==0)for(Nt=a,Ze=a.child;Ze!==null;){for(nt=Nt=Ze;Nt!==null;){switch(Je=Nt,St=Je.child,Je.tag){case 0:case 11:case 14:case 15:lo(4,Je,Je.return);break;case 1:qs(Je,Je.return);var At=Je.stateNode;if(typeof At.componentWillUnmount=="function"){w=Je,f=Je.return;try{u=w,At.props=u.memoizedProps,At.state=u.memoizedState,At.componentWillUnmount()}catch(Rt){Z(w,f,Rt)}}break;case 5:qs(Je,Je.return);break;case 22:if(Je.memoizedState!==null){fd(nt);continue}}St!==null?(St.return=Je,Nt=St):fd(nt)}Ze=Ze.sibling}e:for(Ze=null,nt=a;;){if(nt.tag===5){if(Ze===null){Ze=nt;try{j=nt.stateNode,Re?(E=j.style,typeof E.setProperty=="function"?E.setProperty("display","none","important"):E.display="none"):(ie=nt.stateNode,ue=nt.memoizedProps.style,q=ue!=null&&ue.hasOwnProperty("display")?ue.display:null,ie.style.display=jt("display",q))}catch(Rt){Z(a,a.return,Rt)}}}else if(nt.tag===6){if(Ze===null)try{nt.stateNode.nodeValue=Re?"":nt.memoizedProps}catch(Rt){Z(a,a.return,Rt)}}else if((nt.tag!==22&&nt.tag!==23||nt.memoizedState===null||nt===a)&&nt.child!==null){nt.child.return=nt,nt=nt.child;continue}if(nt===a)break e;for(;nt.sibling===null;){if(nt.return===null||nt.return===a)break e;Ze===nt&&(Ze=null),nt=nt.return}Ze===nt&&(Ze=null),nt.sibling.return=nt.return,nt=nt.sibling}}break;case 19:Cn(u,a),us(a),w&4&&M_(a);break;case 21:break;default:Cn(u,a),us(a)}}function us(a){var u=a.flags;if(u&2){try{e:{for(var f=a.return;f!==null;){if(T_(f)){var w=f;break e}f=f.return}throw Error(n(160))}switch(w.tag){case 5:var j=w.stateNode;w.flags&32&&(st(j,""),w.flags&=-33);var E=oh(a);Uc(a,E,j);break;case 3:case 4:var q=w.stateNode.containerInfo,ie=oh(a);Ii(a,ie,q);break;default:throw Error(n(161))}}catch(ue){Z(a,a.return,ue)}a.flags&=-3}u&4096&&(a.flags&=-4097)}function R_(a,u,f){Nt=a,L_(a)}function L_(a,u,f){for(var w=(a.mode&1)!==0;Nt!==null;){var j=Nt,E=j.child;if(j.tag===22&&w){var q=j.memoizedState!==null||zc;if(!q){var ie=j.alternate,ue=ie!==null&&ie.memoizedState!==null||ur;ie=zc;var Re=ur;if(zc=q,(ur=ue)&&!Re)for(Nt=j;Nt!==null;)q=Nt,ue=q.child,q.tag===22&&q.memoizedState!==null?O_(j):ue!==null?(ue.return=q,Nt=ue):O_(j);for(;E!==null;)Nt=E,L_(E),E=E.sibling;Nt=j,zc=ie,ur=Re}I_(a)}else(j.subtreeFlags&8772)!==0&&E!==null?(E.return=j,Nt=E):I_(a)}}function I_(a){for(;Nt!==null;){var u=Nt;if((u.flags&8772)!==0){var f=u.alternate;try{if((u.flags&8772)!==0)switch(u.tag){case 0:case 11:case 15:ur||Bc(5,u);break;case 1:var w=u.stateNode;if(u.flags&4&&!ur)if(f===null)w.componentDidMount();else{var j=u.elementType===u.type?f.memoizedProps:_i(u.type,f.memoizedProps);w.componentDidUpdate(j,f.memoizedState,w.__reactInternalSnapshotBeforeUpdate)}var E=u.updateQueue;E!==null&&a_(u,E,w);break;case 3:var q=u.updateQueue;if(q!==null){if(f=null,u.child!==null)switch(u.child.tag){case 5:f=u.child.stateNode;break;case 1:f=u.child.stateNode}a_(u,q,f)}break;case 5:var ie=u.stateNode;if(f===null&&u.flags&4){f=ie;var ue=u.memoizedProps;switch(u.type){case"button":case"input":case"select":case"textarea":ue.autoFocus&&f.focus();break;case"img":ue.src&&(f.src=ue.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(u.memoizedState===null){var Re=u.alternate;if(Re!==null){var Ze=Re.memoizedState;if(Ze!==null){var nt=Ze.dehydrated;nt!==null&&Ea(nt)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}ur||u.flags&512&&Li(u)}catch(Je){Z(u,u.return,Je)}}if(u===a){Nt=null;break}if(f=u.sibling,f!==null){f.return=u.return,Nt=f;break}Nt=u.return}}function fd(a){for(;Nt!==null;){var u=Nt;if(u===a){Nt=null;break}var f=u.sibling;if(f!==null){f.return=u.return,Nt=f;break}Nt=u.return}}function O_(a){for(;Nt!==null;){var u=Nt;try{switch(u.tag){case 0:case 11:case 15:var f=u.return;try{Bc(4,u)}catch(ue){Z(u,f,ue)}break;case 1:var w=u.stateNode;if(typeof w.componentDidMount=="function"){var j=u.return;try{w.componentDidMount()}catch(ue){Z(u,j,ue)}}var E=u.return;try{Li(u)}catch(ue){Z(u,E,ue)}break;case 5:var q=u.return;try{Li(u)}catch(ue){Z(u,q,ue)}}}catch(ue){Z(u,u.return,ue)}if(u===a){Nt=null;break}var ie=u.sibling;if(ie!==null){ie.return=u.return,Nt=ie;break}Nt=u.return}}var ly=Math.ceil,co=S.ReactCurrentDispatcher,lh=S.ReactCurrentOwner,Qr=S.ReactCurrentBatchConfig,Tn=0,Is=null,Es=null,Vs=0,Nr=0,uo=ra(0),ys=0,Wl=null,ua=0,Wc=0,fo=0,qc=null,Ms=null,Vc=0,da=1/0,ho=null,Hc=!1,ch=null,gi=null,mo=!1,fa=null,ha=0,Gc=0,ql=null,Uo=-1,hd=0;function $r(){return(Tn&6)!==0?un():Uo!==-1?Uo:Uo=un()}function Wo(a){return(a.mode&1)===0?1:(Tn&2)!==0&&Vs!==0?Vs&-Vs:Pf.transition!==null?(hd===0&&(hd=Ls()),hd):(a=In,a!==0||(a=window.event,a=a===void 0?16:Oe(a.type)),a)}function yi(a,u,f,w){if(50<Gc)throw Gc=0,ql=null,Error(n(185));Ss(a,f,w),((Tn&2)===0||a!==Is)&&(a===Is&&((Tn&2)===0&&(Wc|=f),ys===4&&qo(a,Vs)),Dr(a,w),f===1&&Tn===0&&(u.mode&1)===0&&(da=un()+500,qu&&Qi()))}function Dr(a,u){var f=a.callbackNode;vs(a,u);var w=Bi(a,a===Is?Vs:0);if(w===0)f!==null&&hn(f),a.callbackNode=null,a.callbackPriority=0;else if(u=w&-w,a.callbackPriority!==u){if(f!=null&&hn(f),u===1)a.tag===0?Vu(dh.bind(null,a)):or(dh.bind(null,a)),Qm(function(){(Tn&6)===0&&Qi()}),f=null;else{switch($a(w)){case 1:f=As;break;case 4:f=ws;break;case 16:f=_r;break;case 536870912:f=Ct;break;default:f=_r}f=ye(f,P_.bind(null,a))}a.callbackPriority=u,a.callbackNode=f}}function P_(a,u){if(Uo=-1,hd=0,(Tn&6)!==0)throw Error(n(327));var f=a.callbackNode;if(F()&&a.callbackNode!==f)return null;var w=Bi(a,a===Is?Vs:0);if(w===0)return null;if((w&30)!==0||(w&a.expiredLanes)!==0||u)u=Kc(a,w);else{u=w;var j=Tn;Tn|=2;var E=hh();(Is!==a||Vs!==u)&&(ho=null,da=un()+500,_a(a,u));do try{z_();break}catch(ie){fh(a,ie)}while(!0);Bf(),co.current=E,Tn=j,Es!==null?u=0:(Is=null,Vs=0,u=ys)}if(u!==0){if(u===2&&(j=ri(a),j!==0&&(w=j,u=md(a,j))),u===1)throw f=Wl,_a(a,0),qo(a,w),Dr(a,un()),f;if(u===6)qo(a,w);else{if(j=a.current.alternate,(w&30)===0&&!D_(j)&&(u=Kc(a,w),u===2&&(E=ri(a),E!==0&&(w=E,u=md(a,E))),u===1))throw f=Wl,_a(a,0),qo(a,w),Dr(a,un()),f;switch(a.finishedWork=j,a.finishedLanes=w,u){case 0:case 1:throw Error(n(345));case 2:b(a,Ms,ho);break;case 3:if(qo(a,w),(w&130023424)===w&&(u=Vc+500-un(),10<u)){if(Bi(a,0)!==0)break;if(j=a.suspendedLanes,(j&w)!==w){$r(),a.pingedLanes|=a.suspendedLanes&j;break}a.timeoutHandle=Tf(b.bind(null,a,Ms,ho),u);break}b(a,Ms,ho);break;case 4:if(qo(a,w),(w&4194240)===w)break;for(u=a.eventTimes,j=-1;0<w;){var q=31-sr(w);E=1<<q,q=u[q],q>j&&(j=q),w&=~E}if(w=j,w=un()-w,w=(120>w?120:480>w?480:1080>w?1080:1920>w?1920:3e3>w?3e3:4320>w?4320:1960*ly(w/1960))-w,10<w){a.timeoutHandle=Tf(b.bind(null,a,Ms,ho),w);break}b(a,Ms,ho);break;case 5:b(a,Ms,ho);break;default:throw Error(n(329))}}}return Dr(a,un()),a.callbackNode===f?P_.bind(null,a):null}function md(a,u){var f=qc;return a.current.memoizedState.isDehydrated&&(_a(a,u).flags|=256),a=Kc(a,u),a!==2&&(u=Ms,Ms=f,u!==null&&uh(u)),a}function uh(a){Ms===null?Ms=a:Ms.push.apply(Ms,a)}function D_(a){for(var u=a;;){if(u.flags&16384){var f=u.updateQueue;if(f!==null&&(f=f.stores,f!==null))for(var w=0;w<f.length;w++){var j=f[w],E=j.getSnapshot;j=j.value;try{if(!wr(E(),j))return!1}catch{return!1}}}if(f=u.child,u.subtreeFlags&16384&&f!==null)f.return=u,u=f;else{if(u===a)break;for(;u.sibling===null;){if(u.return===null||u.return===a)return!0;u=u.return}u.sibling.return=u.return,u=u.sibling}}return!0}function qo(a,u){for(u&=~fo,u&=~Wc,a.suspendedLanes|=u,a.pingedLanes&=~u,a=a.expirationTimes;0<u;){var f=31-sr(u),w=1<<f;a[f]=-1,u&=~w}}function dh(a){if((Tn&6)!==0)throw Error(n(327));F();var u=Bi(a,0);if((u&1)===0)return Dr(a,un()),null;var f=Kc(a,u);if(a.tag!==0&&f===2){var w=ri(a);w!==0&&(u=w,f=md(a,w))}if(f===1)throw f=Wl,_a(a,0),qo(a,u),Dr(a,un()),f;if(f===6)throw Error(n(345));return a.finishedWork=a.current.alternate,a.finishedLanes=u,b(a,Ms,ho),Dr(a,un()),null}function _d(a,u){var f=Tn;Tn|=1;try{return a(u)}finally{Tn=f,Tn===0&&(da=un()+500,qu&&Qi())}}function ma(a){fa!==null&&fa.tag===0&&(Tn&6)===0&&F();var u=Tn;Tn|=1;var f=Qr.transition,w=In;try{if(Qr.transition=null,In=1,a)return a()}finally{In=w,Qr.transition=f,Tn=u,(Tn&6)===0&&Qi()}}function pd(){Nr=uo.current,Pn(uo)}function _a(a,u){a.finishedWork=null,a.finishedLanes=0;var f=a.timeoutHandle;if(f!==-1&&(a.timeoutHandle=-1,Xm(f)),Es!==null)for(f=Es.return;f!==null;){var w=f;switch(Ku(w),w.tag){case 1:w=w.type.childContextTypes,w!=null&&Io();break;case 3:fi(),Pn(br),Pn(Ts),Qu();break;case 5:Ol(w);break;case 4:fi();break;case 13:Pn(ps);break;case 19:Pn(ps);break;case 10:Uf(w.type._context);break;case 22:case 23:pd()}f=f.return}if(Is=a,Es=a=dt(a.current,null),Vs=Nr=u,ys=0,Wl=null,fo=Wc=ua=0,Ms=qc=null,so!==null){for(u=0;u<so.length;u++)if(f=so[u],w=f.interleaved,w!==null){f.interleaved=null;var j=w.next,E=f.pending;if(E!==null){var q=E.next;E.next=j,w.next=q}f.pending=w}so=null}return a}function fh(a,u){do{var f=Es;try{if(Bf(),Pl.current=Fl,Ac){for(var w=cs.memoizedState;w!==null;){var j=w.queue;j!==null&&(j.pending=null),w=w.next}Ac=!1}if(Qn=0,Dn=$s=cs=null,Fo=!1,qa=0,lh.current=null,f===null||f.return===null){ys=1,Wl=u,Es=null;break}e:{var E=a,q=f.return,ie=f,ue=u;if(u=Vs,ie.flags|=32768,ue!==null&&typeof ue=="object"&&typeof ue.then=="function"){var Re=ue,Ze=ie,nt=Ze.tag;if((Ze.mode&1)===0&&(nt===0||nt===11||nt===15)){var Je=Ze.alternate;Je?(Ze.updateQueue=Je.updateQueue,Ze.memoizedState=Je.memoizedState,Ze.lanes=Je.lanes):(Ze.updateQueue=null,Ze.memoizedState=null)}var St=cr(q);if(St!==null){St.flags&=-257,Ws(St,q,ie,E,u),St.mode&1&&aa(E,Re,u),u=St,ue=Re;var At=u.updateQueue;if(At===null){var Rt=new Set;Rt.add(ue),u.updateQueue=Rt}else At.add(ue);break e}else{if((u&1)===0){aa(E,Re,u),gd();break e}ue=Error(n(426))}}else if(Zn&&ie.mode&1){var Os=cr(q);if(Os!==null){(Os.flags&65536)===0&&(Os.flags|=256),Ws(Os,q,ie,E,u),Of(Va(ue,ie));break e}}E=ue=Va(ue,ie),ys!==4&&(ys=2),qc===null?qc=[E]:qc.push(E),E=q;do{switch(E.tag){case 3:E.flags|=65536,u&=-u,E.lanes|=u;var xe=Pc(E,ue,u);o_(E,xe);break e;case 1:ie=ue;var _e=E.type,Ce=E.stateNode;if((E.flags&128)===0&&(typeof _e.getDerivedStateFromError=="function"||Ce!==null&&typeof Ce.componentDidCatch=="function"&&(gi===null||!gi.has(Ce)))){E.flags|=65536,u&=-u,E.lanes|=u;var at=v_(E,ie,u);o_(E,at);break e}}E=E.return}while(E!==null)}_h(f)}catch(Pt){u=Pt,Es===f&&f!==null&&(Es=f=f.return);continue}break}while(!0)}function hh(){var a=co.current;return co.current=Fl,a===null?Fl:a}function gd(){(ys===0||ys===3||ys===2)&&(ys=4),Is===null||(ua&268435455)===0&&(Wc&268435455)===0||qo(Is,Vs)}function Kc(a,u){var f=Tn;Tn|=2;var w=hh();(Is!==a||Vs!==u)&&(ho=null,_a(a,u));do try{F_();break}catch(j){fh(a,j)}while(!0);if(Bf(),Tn=f,co.current=w,Es!==null)throw Error(n(261));return Is=null,Vs=0,ys}function F_(){for(;Es!==null;)mh(Es)}function z_(){for(;Es!==null&&!Xe();)mh(Es)}function mh(a){var u=ke(a.alternate,a,Nr);a.memoizedProps=a.pendingProps,u===null?_h(a):Es=u,lh.current=null}function _h(a){var u=a;do{var f=u.alternate;if(a=u.return,(u.flags&32768)===0){if(f=rh(f,u,Nr),f!==null){Es=f;return}}else{if(f=C_(f,u),f!==null){f.flags&=32767,Es=f;return}if(a!==null)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{ys=6,Es=null;return}}if(u=u.sibling,u!==null){Es=u;return}Es=u=a}while(u!==null);ys===0&&(ys=5)}function b(a,u,f){var w=In,j=Qr.transition;try{Qr.transition=null,In=1,T(a,u,f,w)}finally{Qr.transition=j,In=w}return null}function T(a,u,f,w){do F();while(fa!==null);if((Tn&6)!==0)throw Error(n(327));f=a.finishedWork;var j=a.finishedLanes;if(f===null)return null;if(a.finishedWork=null,a.finishedLanes=0,f===a.current)throw Error(n(177));a.callbackNode=null,a.callbackPriority=0;var E=f.lanes|f.childLanes;if(oi(a,E),a===Is&&(Es=Is=null,Vs=0),(f.subtreeFlags&2064)===0&&(f.flags&2064)===0||mo||(mo=!0,ye(_r,function(){return F(),null})),E=(f.flags&15990)!==0,(f.subtreeFlags&15990)!==0||E){E=Qr.transition,Qr.transition=null;var q=In;In=1;var ie=Tn;Tn|=4,lh.current=null,E_(a,f),gs(f,a),Gm(Af),rr=!!Fu,Af=Fu=null,a.current=f,R_(f),sn(),Tn=ie,In=q,Qr.transition=E}else a.current=f;if(mo&&(mo=!1,fa=a,ha=j),E=a.pendingLanes,E===0&&(gi=null),$i(f.stateNode),Dr(a,un()),u!==null)for(w=a.onRecoverableError,f=0;f<u.length;f++)j=u[f],w(j.value,{componentStack:j.stack,digest:j.digest});if(Hc)throw Hc=!1,a=ch,ch=null,a;return(ha&1)!==0&&a.tag!==0&&F(),E=a.pendingLanes,(E&1)!==0?a===ql?Gc++:(Gc=0,ql=a):Gc=0,Qi(),null}function F(){if(fa!==null){var a=$a(ha),u=Qr.transition,f=In;try{if(Qr.transition=null,In=16>a?16:a,fa===null)var w=!1;else{if(a=fa,fa=null,ha=0,(Tn&6)!==0)throw Error(n(331));var j=Tn;for(Tn|=4,Nt=a.current;Nt!==null;){var E=Nt,q=E.child;if((Nt.flags&16)!==0){var ie=E.deletions;if(ie!==null){for(var ue=0;ue<ie.length;ue++){var Re=ie[ue];for(Nt=Re;Nt!==null;){var Ze=Nt;switch(Ze.tag){case 0:case 11:case 15:lo(8,Ze,E)}var nt=Ze.child;if(nt!==null)nt.return=Ze,Nt=nt;else for(;Nt!==null;){Ze=Nt;var Je=Ze.sibling,St=Ze.return;if(A_(Ze),Ze===Re){Nt=null;break}if(Je!==null){Je.return=St,Nt=Je;break}Nt=St}}}var At=E.alternate;if(At!==null){var Rt=At.child;if(Rt!==null){At.child=null;do{var Os=Rt.sibling;Rt.sibling=null,Rt=Os}while(Rt!==null)}}Nt=E}}if((E.subtreeFlags&2064)!==0&&q!==null)q.return=E,Nt=q;else e:for(;Nt!==null;){if(E=Nt,(E.flags&2048)!==0)switch(E.tag){case 0:case 11:case 15:lo(9,E,E.return)}var xe=E.sibling;if(xe!==null){xe.return=E.return,Nt=xe;break e}Nt=E.return}}var _e=a.current;for(Nt=_e;Nt!==null;){q=Nt;var Ce=q.child;if((q.subtreeFlags&2064)!==0&&Ce!==null)Ce.return=q,Nt=Ce;else e:for(q=_e;Nt!==null;){if(ie=Nt,(ie.flags&2048)!==0)try{switch(ie.tag){case 0:case 11:case 15:Bc(9,ie)}}catch(Pt){Z(ie,ie.return,Pt)}if(ie===q){Nt=null;break e}var at=ie.sibling;if(at!==null){at.return=ie.return,Nt=at;break e}Nt=ie.return}}if(Tn=j,Qi(),nr&&typeof nr.onPostCommitFiberRoot=="function")try{nr.onPostCommitFiberRoot(zn,a)}catch{}w=!0}return w}finally{In=f,Qr.transition=u}}return!1}function U(a,u,f){u=Va(f,u),u=Pc(a,u,1),a=Zr(a,u,1),u=$r(),a!==null&&(Ss(a,1,u),Dr(a,u))}function Z(a,u,f){if(a.tag===3)U(a,a,f);else for(;u!==null;){if(u.tag===3){U(u,a,f);break}else if(u.tag===1){var w=u.stateNode;if(typeof u.type.getDerivedStateFromError=="function"||typeof w.componentDidCatch=="function"&&(gi===null||!gi.has(w))){a=Va(f,a),a=v_(u,a,1),u=Zr(u,a,1),a=$r(),u!==null&&(Ss(u,1,a),Dr(u,a));break}}u=u.return}}function X(a,u,f){var w=a.pingCache;w!==null&&w.delete(u),u=$r(),a.pingedLanes|=a.suspendedLanes&f,Is===a&&(Vs&f)===f&&(ys===4||ys===3&&(Vs&130023424)===Vs&&500>un()-Vc?_a(a,0):fo|=f),Dr(a,u)}function Q(a,u){u===0&&((a.mode&1)===0?u=1:(u=pr,pr<<=1,(pr&130023424)===0&&(pr=4194304)));var f=$r();a=dn(a,u),a!==null&&(Ss(a,u,f),Dr(a,f))}function oe(a){var u=a.memoizedState,f=0;u!==null&&(f=u.retryLane),Q(a,f)}function Ge(a,u){var f=0;switch(a.tag){case 13:var w=a.stateNode,j=a.memoizedState;j!==null&&(f=j.retryLane);break;case 19:w=a.stateNode;break;default:throw Error(n(314))}w!==null&&w.delete(u),Q(a,f)}var ke;ke=function(a,u,f){if(a!==null)if(a.memoizedProps!==u.pendingProps||br.current)Cs=!0;else{if((a.lanes&f)===0&&(u.flags&128)===0)return Cs=!1,oy(a,u,f);Cs=(a.flags&131072)!==0}else Cs=!1,Zn&&(u.flags&1048576)!==0&&Lf(u,Hu,u.index);switch(u.lanes=0,u.tag){case 2:var w=u.type;Bl(a,u),a=u.pendingProps;var j=Zi(u,Ts.current);Ua(u,f),j=Hf(null,u,w,a,j,f);var E=Gf();return u.flags|=1,typeof j=="object"&&j!==null&&typeof j.render=="function"&&j.$$typeof===void 0?(u.tag=1,u.memoizedState=null,u.updateQueue=null,ir(w)?(E=!0,Cl(u)):E=!1,u.memoizedState=j.state!==null&&j.state!==void 0?j.state:null,Nc(u),j.updater=id,u.stateNode=j,j._reactInternals=u,th(u,w,a,f),u=ad(null,u,w,!0,E,f)):(u.tag=0,Zn&&E&&Gu(u),xs(null,u,j,f),u=u.child),u;case 16:w=u.elementType;e:{switch(Bl(a,u),a=u.pendingProps,j=w._init,w=j(w._payload),u.type=w,j=u.tag=gt(w),a=_i(w,a),j){case 0:u=sh(null,u,w,a,f);break e;case 1:u=k_(null,u,w,a,f);break e;case 11:u=pi(null,u,w,a,f);break e;case 14:u=x_(null,u,w,_i(w.type,a),f);break e}throw Error(n(306,w,""))}return u;case 0:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:_i(w,j),sh(a,u,w,j,f);case 1:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:_i(w,j),k_(a,u,w,j,f);case 3:e:{if(la(u),a===null)throw Error(n(387));w=u.pendingProps,E=u.memoizedState,j=E.element,Wf(a,u),Il(u,w,null,f);var q=u.memoizedState;if(w=q.element,E.isDehydrated)if(E={element:w,isDehydrated:!1,cache:q.cache,pendingSuspenseBoundaries:q.pendingSuspenseBoundaries,transitions:q.transitions},u.updateQueue.baseState=E,u.memoizedState=E,u.flags&256){j=Va(Error(n(423)),u),u=zl(a,u,w,f,j);break e}else if(w!==j){j=Va(Error(n(424)),u),u=zl(a,u,w,f,j);break e}else for(Or=na(u.stateNode.containerInfo.firstChild),Yr=u,Zn=!0,Mi=null,f=Ff(u,null,w,f),u.child=f;f;)f.flags=f.flags&-3|4096,f=f.sibling;else{if(Ba(),w===j){u=Bo(a,u,f);break e}xs(a,u,w,f)}u=u.child}return u;case 5:return hi(u),a===null&&Sc(u),w=u.type,j=u.pendingProps,E=a!==null?a.memoizedProps:null,q=j.children,zu(w,j)?q=null:E!==null&&zu(w,E)&&(u.flags|=32),od(a,u),xs(a,u,q,f),u.child;case 6:return a===null&&Sc(u),null;case 13:return j_(a,u,f);case 4:return Xu(u,u.stateNode.containerInfo),w=u.pendingProps,a===null?u.child=Po(u,null,w,f):xs(a,u,w,f),u.child;case 11:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:_i(w,j),pi(a,u,w,j,f);case 7:return xs(a,u,u.pendingProps,f),u.child;case 8:return xs(a,u,u.pendingProps.children,f),u.child;case 12:return xs(a,u,u.pendingProps.children,f),u.child;case 10:e:{if(w=u.type._context,j=u.pendingProps,E=u.memoizedProps,q=j.value,Xn(Do,w._currentValue),w._currentValue=q,E!==null)if(wr(E.value,q)){if(E.children===j.children&&!br.current){u=Bo(a,u,f);break e}}else for(E=u.child,E!==null&&(E.return=u);E!==null;){var ie=E.dependencies;if(ie!==null){q=E.child;for(var ue=ie.firstContext;ue!==null;){if(ue.context===w){if(E.tag===1){ue=Xr(-1,f&-f),ue.tag=2;var Re=E.updateQueue;if(Re!==null){Re=Re.shared;var Ze=Re.pending;Ze===null?ue.next=ue:(ue.next=Ze.next,Ze.next=ue),Re.pending=ue}}E.lanes|=f,ue=E.alternate,ue!==null&&(ue.lanes|=f),Ju(E.return,f,u),ie.lanes|=f;break}ue=ue.next}}else if(E.tag===10)q=E.type===u.type?null:E.child;else if(E.tag===18){if(q=E.return,q===null)throw Error(n(341));q.lanes|=f,ie=q.alternate,ie!==null&&(ie.lanes|=f),Ju(q,f,u),q=E.sibling}else q=E.child;if(q!==null)q.return=E;else for(q=E;q!==null;){if(q===u){q=null;break}if(E=q.sibling,E!==null){E.return=q.return,q=E;break}q=q.return}E=q}xs(a,u,j.children,f),u=u.child}return u;case 9:return j=u.type,w=u.pendingProps.children,Ua(u,f),j=di(j),w=w(j),u.flags|=1,xs(a,u,w,f),u.child;case 14:return w=u.type,j=_i(w,u.pendingProps),j=_i(w.type,j),x_(a,u,w,j,f);case 15:return Dc(a,u,u.type,u.pendingProps,f);case 17:return w=u.type,j=u.pendingProps,j=u.elementType===w?j:_i(w,j),Bl(a,u),u.tag=1,ir(w)?(a=!0,Cl(u)):a=!1,Ua(u,f),y_(u,w,j),th(u,w,j,f),ad(null,u,w,!0,a,f);case 19:return S_(a,u,f);case 22:return b_(a,u,f)}throw Error(n(156,u.tag))};function ye(a,u){return Fn(a,u)}function Fe(a,u,f,w){this.tag=a,this.key=f,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=w,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Pe(a,u,f,w){return new Fe(a,u,f,w)}function rt(a){return a=a.prototype,!(!a||!a.isReactComponent)}function gt(a){if(typeof a=="function")return rt(a)?1:0;if(a!=null){if(a=a.$$typeof,a===V)return 11;if(a===I)return 14}return 2}function dt(a,u){var f=a.alternate;return f===null?(f=Pe(a.tag,u,a.key,a.mode),f.elementType=a.elementType,f.type=a.type,f.stateNode=a.stateNode,f.alternate=a,a.alternate=f):(f.pendingProps=u,f.type=a.type,f.flags=0,f.subtreeFlags=0,f.deletions=null),f.flags=a.flags&14680064,f.childLanes=a.childLanes,f.lanes=a.lanes,f.child=a.child,f.memoizedProps=a.memoizedProps,f.memoizedState=a.memoizedState,f.updateQueue=a.updateQueue,u=a.dependencies,f.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext},f.sibling=a.sibling,f.index=a.index,f.ref=a.ref,f}function xn(a,u,f,w,j,E){var q=2;if(w=a,typeof a=="function")rt(a)&&(q=1);else if(typeof a=="string")q=5;else e:switch(a){case A:return qt(f.children,j,E,u);case P:q=8,j|=8;break;case W:return a=Pe(12,f,u,j|2),a.elementType=W,a.lanes=E,a;case R:return a=Pe(13,f,u,j),a.elementType=R,a.lanes=E,a;case M:return a=Pe(19,f,u,j),a.elementType=M,a.lanes=E,a;case K:return ft(f,j,E,u);default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case J:q=10;break e;case G:q=9;break e;case V:q=11;break e;case I:q=14;break e;case L:q=16,w=null;break e}throw Error(n(130,a==null?a:typeof a,""))}return u=Pe(q,f,u,j),u.elementType=a,u.type=w,u.lanes=E,u}function qt(a,u,f,w){return a=Pe(7,a,w,u),a.lanes=f,a}function ft(a,u,f,w){return a=Pe(22,a,w,u),a.elementType=K,a.lanes=f,a.stateNode={isHidden:!1},a}function en(a,u,f){return a=Pe(6,a,null,u),a.lanes=f,a}function Yn(a,u,f){return u=Pe(4,a.children!==null?a.children:[],a.key,u),u.lanes=f,u.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},u}function ds(a,u,f,w,j){this.tag=u,this.containerInfo=a,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ii(0),this.expirationTimes=ii(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ii(0),this.identifierPrefix=w,this.onRecoverableError=j,this.mutableSourceEagerHydrationData=null}function dr(a,u,f,w,j,E,q,ie,ue){return a=new ds(a,u,f,ie,ue),u===1?(u=1,E===!0&&(u|=8)):u=0,E=Pe(3,null,null,u),a.current=E,E.stateNode=a,E.memoizedState={element:w,isDehydrated:f,cache:null,transitions:null,pendingSuspenseBoundaries:null},Nc(E),a}function wi(a,u,f){var w=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:O,key:w==null?null:""+w,children:a,containerInfo:u,implementation:f}}function vi(a){if(!a)return ci;a=a._reactInternals;e:{if(rn(a)!==a||a.tag!==1)throw Error(n(170));var u=a;do{switch(u.tag){case 3:u=u.stateNode.context;break e;case 1:if(ir(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break e}}u=u.return}while(u!==null);throw Error(n(171))}if(a.tag===1){var f=a.type;if(ir(f))return t_(a,f,u)}return u}function Vl(a,u,f,w,j,E,q,ie,ue){return a=dr(f,w,!0,a,j,E,q,ie,ue),a.context=vi(null),f=a.current,w=$r(),j=Wo(f),E=Xr(w,j),E.callback=u??null,Zr(f,E,j),a.current.lanes=j,Ss(a,j,w),Dr(a,w),a}function B_(a,u,f,w){var j=u.current,E=$r(),q=Wo(j);return f=vi(f),u.context===null?u.context=f:u.pendingContext=f,u=Xr(E,q),u.payload={element:a},w=w===void 0?null:w,w!==null&&(u.callback=w),a=Zr(j,u,q),a!==null&&(yi(a,j,q,E),on(a,j,q)),q}function U_(a){if(a=a.current,!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function eb(a,u){if(a=a.memoizedState,a!==null&&a.dehydrated!==null){var f=a.retryLane;a.retryLane=f!==0&&f<u?f:u}}function cy(a,u){eb(a,u),(a=a.alternate)&&eb(a,u)}function rE(){return null}var tb=typeof reportError=="function"?reportError:function(a){console.error(a)};function uy(a){this._internalRoot=a}W_.prototype.render=uy.prototype.render=function(a){var u=this._internalRoot;if(u===null)throw Error(n(409));B_(a,u,null,null)},W_.prototype.unmount=uy.prototype.unmount=function(){var a=this._internalRoot;if(a!==null){this._internalRoot=null;var u=a.containerInfo;ma(function(){B_(null,a,null,null)}),u[Ti]=null}};function W_(a){this._internalRoot=a}W_.prototype.unstable_scheduleHydration=function(a){if(a){var u=fc();a={blockedOn:null,target:a,priority:u};for(var f=0;f<Mr.length&&u!==0&&u<Mr[f].priority;f++);Mr.splice(f,0,a),f===0&&Ci(a)}};function dy(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11)}function q_(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11&&(a.nodeType!==8||a.nodeValue!==" react-mount-point-unstable "))}function nb(){}function iE(a,u,f,w,j){if(j){if(typeof w=="function"){var E=w;w=function(){var Re=U_(q);E.call(Re)}}var q=Vl(u,w,a,0,null,!1,!1,"",nb);return a._reactRootContainer=q,a[Ti]=q.current,Ei(a.nodeType===8?a.parentNode:a),ma(),q}for(;j=a.lastChild;)a.removeChild(j);if(typeof w=="function"){var ie=w;w=function(){var Re=U_(ue);ie.call(Re)}}var ue=dr(a,0,!1,null,null,!1,!1,"",nb);return a._reactRootContainer=ue,a[Ti]=ue.current,Ei(a.nodeType===8?a.parentNode:a),ma(function(){B_(u,ue,f,w)}),ue}function V_(a,u,f,w,j){var E=f._reactRootContainer;if(E){var q=E;if(typeof j=="function"){var ie=j;j=function(){var ue=U_(q);ie.call(ue)}}B_(u,q,a,j)}else q=iE(f,u,a,j,w);return U_(q)}fl=function(a){switch(a.tag){case 3:var u=a.stateNode;if(u.current.memoizedState.isDehydrated){var f=Rs(u.pendingLanes);f!==0&&(Ui(u,f|1),Dr(u,un()),(Tn&6)===0&&(da=un()+500,Qi()))}break;case 13:ma(function(){var w=dn(a,1);if(w!==null){var j=$r();yi(w,a,1,j)}}),cy(a,1)}},hl=function(a){if(a.tag===13){var u=dn(a,134217728);if(u!==null){var f=$r();yi(u,a,134217728,f)}cy(a,134217728)}},Tr=function(a){if(a.tag===13){var u=Wo(a),f=dn(a,u);if(f!==null){var w=$r();yi(f,a,u,w)}cy(a,u)}},fc=function(){return In},Wi=function(a,u){var f=In;try{return In=a,u()}finally{In=f}},Ks=function(a,u,f){switch(u){case"input":if(mt(a,f),u=f.name,f.type==="radio"&&u!=null){for(f=a;f.parentNode;)f=f.parentNode;for(f=f.querySelectorAll("input[name="+JSON.stringify(""+u)+'][type="radio"]'),u=0;u<f.length;u++){var w=f[u];if(w!==a&&w.form===a.form){var j=Mo(w);if(!j)throw Error(n(90));_t(w),mt(w,j)}}}break;case"textarea":we(a,f);break;case"select":u=f.value,u!=null&&Se(a,!!f.multiple,u,!1)}},he=_d,Ee=ma;var oE={usingClientEntryPoint:!1,Events:[sa,$l,Mo,yt,re,_d]},ph={findFiberByHostInstance:Fa,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},aE={bundleType:ph.bundleType,version:ph.version,rendererPackageName:ph.rendererPackageName,rendererConfig:ph.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:S.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){return a=Qt(a),a===null?null:a.stateNode},findFiberByHostInstance:ph.findFiberByHostInstance||rE,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 H_=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!H_.isDisabled&&H_.supportsFiber)try{zn=H_.inject(aE),nr=H_}catch{}}return xi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=oE,xi.createPortal=function(a,u){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!dy(u))throw Error(n(200));return wi(a,u,null,f)},xi.createRoot=function(a,u){if(!dy(a))throw Error(n(299));var f=!1,w="",j=tb;return u!=null&&(u.unstable_strictMode===!0&&(f=!0),u.identifierPrefix!==void 0&&(w=u.identifierPrefix),u.onRecoverableError!==void 0&&(j=u.onRecoverableError)),u=dr(a,1,!1,null,null,f,!1,w,j),a[Ti]=u.current,Ei(a.nodeType===8?a.parentNode:a),new uy(u)},xi.findDOMNode=function(a){if(a==null)return null;if(a.nodeType===1)return a;var u=a._reactInternals;if(u===void 0)throw typeof a.render=="function"?Error(n(188)):(a=Object.keys(a).join(","),Error(n(268,a)));return a=Qt(u),a=a===null?null:a.stateNode,a},xi.flushSync=function(a){return ma(a)},xi.hydrate=function(a,u,f){if(!q_(u))throw Error(n(200));return V_(null,a,u,!0,f)},xi.hydrateRoot=function(a,u,f){if(!dy(a))throw Error(n(405));var w=f!=null&&f.hydratedSources||null,j=!1,E="",q=tb;if(f!=null&&(f.unstable_strictMode===!0&&(j=!0),f.identifierPrefix!==void 0&&(E=f.identifierPrefix),f.onRecoverableError!==void 0&&(q=f.onRecoverableError)),u=Vl(u,null,a,1,f??null,j,!1,E,q),a[Ti]=u.current,Ei(a),w)for(a=0;a<w.length;a++)f=w[a],j=f._getVersion,j=j(f._source),u.mutableSourceEagerHydrationData==null?u.mutableSourceEagerHydrationData=[f,j]:u.mutableSourceEagerHydrationData.push(f,j);return new W_(u)},xi.render=function(a,u,f){if(!q_(u))throw Error(n(200));return V_(null,a,u,!1,f)},xi.unmountComponentAtNode=function(a){if(!q_(a))throw Error(n(40));return a._reactRootContainer?(ma(function(){V_(null,null,a,!1,function(){a._reactRootContainer=null,a[Ti]=null})}),!0):!1},xi.unstable_batchedUpdates=_d,xi.unstable_renderSubtreeIntoContainer=function(a,u,f,w){if(!q_(f))throw Error(n(200));if(a==null||a._reactInternals===void 0)throw Error(n(38));return V_(a,u,f,!1,w)},xi.version="18.3.1-next-f1338f8080-20240426",xi}var ub;function Kj(){if(ub)return my.exports;ub=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(),my.exports=pE(),my.exports}var db;function gE(){if(db)return G_;db=1;var e=Kj();return G_.createRoot=e.createRoot,G_.hydrateRoot=e.hydrateRoot,G_}var yE=gE();const wE=Yv(yE),Jj=[{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"]}];Jj.map(e=>({id:e.id,label:e.label}));function vE(e){return`theme-${String(e||"").trim()||"dark"}`}function fb(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(vE(e))}catch{}}const Lw=[{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}],Iw=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function xE(e){const t=String(e).trim();return Lw.find(n=>n.id===t)||Lw[1]}function bE(e){const t=String(e).trim();return Iw.find(n=>n.id===t)||Iw[1]}function hb(e){try{const t=document.documentElement,n=xE(e.font_scale||"md"),r=bE(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const gy={sm:"(max-width: 767.98px)",md:"(max-width: 1023.98px)",short:"(max-height: 500px)"};function kE(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function mb(e){const[t,n]=p.useState(()=>kE(e));return p.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),i=()=>n(r.matches);return i(),typeof r.addEventListener=="function"?r.addEventListener("change",i):r.addListener(i),()=>{typeof r.removeEventListener=="function"?r.removeEventListener("change",i):r.removeListener(i)}},[e]),t}let yh=null;function jE(e,t){const n=Math.max(0,Math.round(e));if(!(t.scale<=1.01))return{vvHeight:n,keyboardInset:0};const r=Math.max(0,Math.min(n,Math.round(t.height))),i=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:r,keyboardInset:i}}function SE(){if(yh)return yh;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:o,keyboardInset:c}=jE(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${o}px`),t.style.setProperty("--keyboard-inset",`${c}px`)},i=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("orientationchange",i),yh=()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("orientationchange",i),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),yh=null},yh}var jg=Kj();function yd(...e){return e.filter(Boolean).join(" ")}function Wr({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:i=!1,searchable:o=!0,searchPlaceholder:c="Search…",allowCustom:l=!1,clearable:d=!1,minPopoverWidth:h=240,variant:m="panel",className:_,triggerClassName:g,ariaLabel:y,id:x,includeValueOption:k=!1,onOpen:v,customOptionLabel:N,validateCustomValue:$,onChange:C,renderOption:S,renderValue:D}){const O=p.useRef(null),A=p.useRef(null),P=p.useRef(null),W=p.useRef(v),J=p.useId(),G=x||`af-select-${J.replace(/[^a-zA-Z0-9_-]/g,"")}`,V=`${G}-listbox`,[R,M]=p.useState(!1),[I,L]=p.useState(""),[K,H]=p.useState(0),[z,ee]=p.useState("bottom"),[B,te]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{W.current=v},[v]);const se=p.useMemo(()=>{if(!k)return t;const ce=String(e??"").trim();return!ce||t.some(Se=>Se.value===ce)?t:[...t,{value:ce,label:ce}]},[k,t,e]),de=p.useMemo(()=>{const ce=String(e??"");return se.find(Se=>Se.value===ce)||null},[se,e]),be=p.useMemo(()=>(de==null?void 0:de.label)||String(e||"").trim()||"",[de,e]),Me=p.useMemo(()=>{const ce=I.trim().toLowerCase();return ce?se.filter(Se=>Se.label.toLowerCase().includes(ce)||Se.value.toLowerCase().includes(ce)):se},[se,I]),Ne=p.useMemo(()=>{if(!l)return null;const ce=I.trim();if(!ce||se.some(ne=>ne.value===ce))return null;const He=($==null?void 0:$(ce,{options:se}))||"";return{value:ce,label:N?N(ce):`Use "${ce}"`,disabled:!!He,reason:He}},[l,N,se,I,$]),ae=p.useMemo(()=>{const ce=Ne?[Ne,...Me]:Me;if(ce.length>0)return ce;const Se=String(e??"").trim();return i&&Se?[{value:Se,label:be||Se}]:ce},[Ne,Me,i,be,e]),je=p.useCallback(()=>{const ce=O.current;if(!ce)return;const Se=ce.getBoundingClientRect(),He=Math.max(Se.width,h),ne=Math.max(8,Math.min(Se.left,window.innerWidth-He-8)),we=window.innerHeight-Se.bottom,fe=Se.top,$e=we>=220||we>=fe?"bottom":"top";ee($e);const pe=$e==="bottom"?Se.bottom+6:Se.top-6;te({left:ne,top:pe,width:He})},[h]),Te=p.useCallback(()=>{M(!1),L("")},[]);p.useEffect(()=>{var ce;R&&((ce=W.current)==null||ce.call(W))},[R]),p.useEffect(()=>{if(!R)return;je();const ce=()=>je();return window.addEventListener("resize",ce),window.addEventListener("scroll",ce,!0),()=>{window.removeEventListener("resize",ce),window.removeEventListener("scroll",ce,!0)}},[R,je]),p.useEffect(()=>{if(!R)return;const ce=Se=>{var ne,we;const He=Se.target;He&&((ne=O.current)!=null&&ne.contains(He)||(we=A.current)!=null&&we.contains(He)||Te())};return document.addEventListener("mousedown",ce,!0),()=>document.removeEventListener("mousedown",ce,!0)},[R,Te]),p.useEffect(()=>{if(!R)return;const ce=Math.max(0,ae.findIndex(Se=>Se.value===e));H(ce===-1?0:ce),o&&setTimeout(()=>{var Se;return(Se=P.current)==null?void 0:Se.focus()},0)},[R,o,e,ae]);const Ve=ce=>{var He;const Se=ae.find(ne=>ne.value===ce);Se!=null&&Se.disabled||(C(ce),Te(),(He=O.current)==null||He.focus())},_t=ce=>{var Se,He;if(ce.key==="Escape")return ce.preventDefault(),Te(),(Se=O.current)==null||Se.focus(),!0;if(ce.key==="Tab")return Te(),(He=O.current)==null||He.focus(),!1;if(ce.key==="ArrowDown")return ce.preventDefault(),H(ne=>Math.min(ne+1,Math.max(0,ae.length-1))),!0;if(ce.key==="ArrowUp")return ce.preventDefault(),H(ne=>Math.max(ne-1,0)),!0;if(ce.key==="Home")return ce.preventDefault(),H(0),!0;if(ce.key==="End")return ce.preventDefault(),H(Math.max(0,ae.length-1)),!0;if(ce.key==="Enter"){ce.preventDefault();const ne=ae[K];return ne&&Ve(ne.value),!0}return!1},Qe=ce=>{if(!r){if(R){if(_t(ce))return;if(ce.key===" "&&!o){ce.preventDefault();const Se=ae[K];Se&&Ve(Se.value)}return}(ce.key==="Enter"||ce.key===" "||ce.key==="ArrowDown"||ce.key==="ArrowUp")&&(ce.preventDefault(),M(!0))}},it=!!String(e||"").trim(),$t=it?be:n,ot=Ne!=null&&Ne.disabled?Ne.reason||"Unavailable":"",mt=R&&ae.length>0?`${G}-opt-${K}`:void 0,et=s.jsx("span",{className:yd("af-select-value",!it&&"af-select-value--placeholder"),children:i&&!it?"Loading…":$t}),Lt=D?D(de,String(e||"")):et;return s.jsxs("span",{className:yd("af-select",m==="pin"?"af-select--pin":"af-select--panel",_),children:[s.jsxs("button",{ref:O,id:G,type:"button",className:yd("af-select-trigger",d&&it&&"af-select-trigger--clearable",g),disabled:r,onMouseDown:ce=>ce.stopPropagation(),onClick:ce=>{ce.stopPropagation(),!r&&M(Se=>!Se)},onKeyDown:Qe,role:o?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":R,"aria-controls":R?V:void 0,"aria-activedescendant":o?void 0:mt,"aria-label":y,children:[Lt,s.jsx("span",{className:yd("af-select-caret",R&&"af-select-caret--open"),children:"▾"})]}),d&&it?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:ce=>{ce.preventDefault(),ce.stopPropagation()},onClick:ce=>{var Se;ce.preventDefault(),ce.stopPropagation(),C(""),Te(),(Se=O.current)==null||Se.focus()},title:"Clear",children:"×"}):null,R?jg.createPortal(s.jsxs("div",{ref:A,className:yd("af-select-popover",z==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${B.left}px`,top:`${B.top}px`,width:`${B.width}px`},onMouseDown:ce=>ce.stopPropagation(),onClick:ce=>ce.stopPropagation(),onWheel:ce=>ce.stopPropagation(),onKeyDown:_t,tabIndex:-1,children:[o?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:P,className:"af-select-search-input",value:I,onChange:ce=>L(ce.target.value),placeholder:c,onKeyDown:_t,role:"combobox","aria-expanded":!0,"aria-controls":V,"aria-activedescendant":mt,"aria-invalid":!!ot,"aria-describedby":ot?`${G}-custom-error`:void 0}),ot?s.jsx("div",{id:`${G}-custom-error`,className:"af-select-custom-error",role:"alert",children:ot}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:V,"aria-label":y,children:i&&ae.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):ae.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):ae.map((ce,Se)=>{var pe;const He=ce.value===e,ne=Se===K,we=String(ce.group||"").trim(),fe=Se>0?String(((pe=ae[Se-1])==null?void 0:pe.group)||"").trim():"",$e=!!we&&we!==fe;return s.jsxs(Ae.Fragment,{children:[$e?s.jsx("div",{className:"af-select-group",role:"presentation",children:we}):null,s.jsx("div",{id:`${G}-opt-${Se}`,role:"option","aria-selected":He,className:yd("af-select-option",He&&"af-select-option--selected",ne&&"af-select-option--highlighted",ce.disabled&&"af-select-option--disabled"),title:ce.disabled?ce.reason||"Unavailable":void 0,onMouseEnter:()=>H(Se),onMouseDown:le=>{le.preventDefault(),le.stopPropagation()},onClick:()=>Ve(ce.value),"aria-disabled":ce.disabled?!0:void 0,children:S?S(ce,{selected:He,highlighted:ne}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:ce.label}),ce.reason?s.jsx("small",{className:"af-select-option-reason",children:ce.reason}):null]}),He?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},ce.value)})})]}),document.body):null]})}function NE(e){const t=new Set,n=[];for(const r of e||[]){if(!r||typeof r!="object")continue;const i=String(r.name||"").trim();!i||t.has(i)||(t.add(i),n.push({name:i,display_name:typeof r.display_name=="string"?r.display_name:void 0}))}return n.sort((r,i)=>r.name.localeCompare(i.name)),n}function $E(e){const t=new Set,n=[];for(const r of e||[]){const i=String(r||"").trim();!i||t.has(i)||(t.add(i),n.push(i))}return n.sort(),n}const Ow="Provided by connected pin";function Yj(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,i=String(e.gatewayDefaultLabel||"(gateway default)"),o=String(e.providerLabel||"Provider"),c=String(e.modelLabel||"Model"),l=String(e.providerPlaceholder||"(select)"),d=String(e.modelPlaceholder||"(select)"),h=String(e.provider||"").trim(),m=String(e.model||"").trim(),_=NE(e.providers),g=$E(e.models),y=typeof e.markSaved=="object"?e.markSaved:null,x=(S,D,O,A)=>e.markSaved&&!O&&!A&&(!y||y[D]===S)?`${S} (saved)`:S,k=t||!!e.loadingProviders,v=t||!!e.loadingModels,N=[...r?[{value:"",label:i}]:[],..._.map(S=>({value:S.name,label:S.display_name?`${S.display_name} (${S.name})`:S.name})),...e.markSaved&&h&&!_.some(S=>S.name===h)?[{value:h,label:x(h,"provider",e.loadingProviders,e.providerError)}]:[]],$=[...r?[{value:"",label:i}]:[],...g.map(S=>{var D;return{value:S,label:((D=e.modelDisplayNames)==null?void 0:D[S])||S}}),...e.markSaved&&m&&!g.includes(m)?[{value:m,label:x(m,"model",e.loadingModels,e.modelError)}]:[]],C=(S,D)=>s.jsxs("div",{className:"af-pmp__pinned","data-pinned":S,children:[s.jsx("span",{className:"af-pmp__pinned-text",children:Ow}),D?s.jsxs("span",{className:"mono muted",children:[" · ",D]}):null]});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:o}),e.providerPinned?C("provider",h):s.jsx(Wr,{value:h,options:N,placeholder:r?i:l,disabled:k,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:o,onChange:S=>e.onChange({provider:String(S||"").trim(),model:""})}),e.loadingProviders?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),s.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[s.jsx("label",{children:c}),e.modelPinned?C("model",m):s.jsx(Wr,{value:m,options:$,placeholder:r?i:d,disabled:v,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:c,onChange:S=>e.onChange({provider:h,model:String(S||"").trim()})}),e.loadingModels?s.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?s.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function CE(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 EE(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 _b(e){const t=CE(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function AE(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 TE(e){const t=EE(e.capabilities),n=_b(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],i=_b(t==null?void 0:t.default),o=e.inheritLabel||"Workflow / Gateway default",c=i?`${o} (${i==="off"?"Off":`depth ${i}`})`:o,l=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(Wr,{ariaLabel:"MTP depth",value:n,placeholder:c,disabled:e.disabled||e.loading,options:[{value:"",label:c},{value:"off",label:"Off"},...r.map(d=>({value:d,label:`Depth ${d}`})),...n&&n!=="off"&&!r.includes(n)?[{value:n,label:`Depth ${n} (saved)`}]:[]],onChange:d=>e.onChange(AE(d))}),l&&!e.hideNote?s.jsx("div",{role:"status",className:"af-pmp__hint",children:l}):null]})}const Zh="api/gateway",xm="api/connection/gateway";function wt(e){const t=String(e||"");if(t.startsWith("/"))throw new Error(`gatewayApiPath takes a route relative to the gateway API, got ${JSON.stringify(t)}.`);return t?`${Zh}/${t}`:Zh}function Xv(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 ME(e){const t=String(e||""),n=`/${Zh}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const r=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(r))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const i of r.split("/")){const o=i.replace(/%2e/gi,".");if(o==="."||o==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function RE(e){if(!e)return"";const t=[`${e.provider} / ${e.model}`];return e.reasoning&&t.push(`reasoning ${e.reasoning}`),e.speculation===!1?t.push("MTP off"):e.speculation&&t.push(`MTP depth ${e.speculation.num_draft_tokens}`),t.join(" · ")}function LE(e,t="Gateway default"){const n=RE(e);return n?`${t} · ${n}`:t}const IE="The gateway does not say which reasoning levels this model supports.",OE="Set anyway",PE="Reasoning and MTP choices appear when the gateway can describe the selected model.",DE="Reasoning choices appear when the gateway can describe the selected model.";function Xj(e){const t=e.disabled===!0,n=e.value||{provider:"",model:""},r=!String(n.provider||"").trim()&&!String(n.model||"").trim(),i=e.layout==="compact",o=e.pinned||{},c=!!(o.provider||o.model),[l,d]=p.useState(!r),h=i||c||!(r&&!l),m=r&&(i||c||!l),_=p.useRef(r);p.useEffect(()=>{r&&!_.current&&d(!1),_.current=r},[r]);const[g,y]=p.useState([]),[x,k]=p.useState(!1),[v,N]=p.useState(""),[$,C]=p.useState([]),[S,D]=p.useState({}),[O,A]=p.useState(!1),[P,W]=p.useState(""),J=p.useRef(e);J.current=e;const[G,V]=p.useState({status:"idle",value:null,message:""}),R=e.fetchGatewayDefault;p.useEffect(()=>{if(!R||t)return;let Se=!0;const He=ne=>V(we=>JSON.stringify(we)===JSON.stringify(ne)?we:ne);return V(ne=>ne.status==="idle"?{...ne,status:"loading"}:ne),R().then(ne=>{var we;Se&&(ne?(we=ne.warnings)!=null&&we.length?He({status:"unusable",value:ne,message:ne.warnings.join(" ")}):He({status:"resolved",value:ne,message:""}):He({status:"none",value:null,message:""}))}).catch(ne=>{Se&&He({status:"error",value:null,message:String((ne==null?void 0:ne.message)||ne)})}),()=>{Se=!1}},[R,t]);const M=G.status==="resolved"?G.value:null,I=p.useRef({provider:String(n.provider||"").trim(),model:String(n.model||"").trim()});p.useEffect(()=>{if(!h||o.provider||t)return;let Se=!0;return k(!0),(async()=>{try{const He=await J.current.fetchProviders();if(!Se)return;y(Array.isArray(He)?He:[]),N("")}catch(He){if(!Se)return;y([]),N(`#FALLBACK provider discovery failed: ${String((He==null?void 0:He.message)||He)}`)}finally{Se&&k(!1)}})(),()=>{Se=!1}},[h,o.provider,t]);const L=String(n.provider||"").trim();p.useEffect(()=>{if(!L||t||o.model){C([]),W(""),A(!1);return}let Se=!0;return C([]),A(!0),W(""),(async()=>{try{const He=await J.current.fetchModels(L);if(!Se)return;const ne=[],we={};for(const fe of Array.isArray(He)?He:[]){const $e=typeof fe=="string"?fe:String((fe==null?void 0:fe.id)||"");$e&&(ne.push($e),typeof fe!="string"&&(fe!=null&&fe.label)&&fe.label!==$e&&(we[$e]=String(fe.label)))}C(ne),D(we)}catch(He){if(!Se)return;C([]),W(`#FALLBACK model discovery failed: ${String((He==null?void 0:He.message)||He)}`)}finally{Se&&A(!1)}})(),()=>{Se=!1}},[L,t,o.model]);const K=String(n.model||"").trim(),H=e.defaultModeLabel||"Gateway default",z=G.status==="none"?`${H} · none configured`:LE(M,H),ee=e.customModeLabel||"Custom",B=e.effectiveDefault||(G.value?{provider:G.value.provider,model:G.value.model}:void 0),te=L||(B==null?void 0:B.provider)||"",se=K||(L?"":B==null?void 0:B.model)||"",[de,be]=p.useState({levels:[],error:"",loading:!1}),[Me,Ne]=p.useState(!1),ae=!!e.fetchModelCapabilities,[je,Te]=p.useState();p.useEffect(()=>{let Se=!0;if(Te(void 0),be({levels:[],error:"",loading:ae&&!!se}),!(!ae||!se||t))return J.current.fetchModelCapabilities(se,te).then(He=>{var pe;if(!Se)return;if(He!=null&&He.error)throw new Error(String(He.error));Te(He);const ne=(He==null?void 0:He.capabilities)||He||{},we=ne.reasoning_levels||ne.thinking_levels,fe=Array.isArray(we)?[...new Set(we.filter(le=>typeof le=="string"&&!!le.trim()))]:[];!fe.length&&ne.thinking_support===!0&&((pe=ne.thinking_control)!=null&&pe.prompt_disable_token)&&fe.push("off","auto");const $e=typeof ne.thinking_support=="boolean"?ne.thinking_support:void 0;be({levels:fe,support:$e,error:"",loading:!1})}).catch(He=>{Se&&be({levels:[],error:String((He==null?void 0:He.message)||He),loading:!1})}),()=>{Se=!1}},[te,se,ae,t]),p.useEffect(()=>Ne(!1),[te,se]);const Ve=e.inheritLabel||"Workflow / Gateway default",_t=m&&(M!=null&&M.reasoning)?`${Ve} (${M.reasoning})`:Ve,Qe=!m||e.optionsInDefaultMode!==!1,it=e.reasoningLadder?[...new Set(e.reasoningLadder.filter(Se=>typeof Se=="string"&&Se.trim()))]:null,$t=de.loading?"loading":de.levels.length||de.support===!0?"supported":de.support===!1?"unsupported":"unknown",ot=e.unknownReasoning==="allow-override"&&!!(it!=null&&it.length),mt=String(n.reasoning||"").trim();let et=[],Lt=!1;if(!it)et=de.levels.map(Se=>({value:Se,label:Se}));else if($t==="supported"||$t==="loading"){const Se=de.levels;et=[...it,...Se.filter(ne=>!it.includes(ne))].map(ne=>!Se.length||Se.includes(ne)?{value:ne,label:ne}:{value:ne,label:ne,disabled:!0,reason:"This model does not advertise it"})}else $t==="unknown"&&ot&&(Lt=!Me,et=it.map(Se=>({value:Se,label:Se})));mt&&!et.some(Se=>Se.value===mt)&&et.push({value:mt,label:`${mt} (saved)`});const ce=(ae||ot)&&(et.length>0||$t==="unknown"&&ot);return s.jsxs("div",{className:`af-pmp${i?" af-pmp--compact":""}${e.className?` ${e.className}`:""}`,"data-gateway-default":R?G.status:void 0,children:[i||c?null:s.jsxs("div",{className:"af-pmp__seg",role:"tablist","aria-label":"Provider mode",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":m,className:`af-pmp__seg-btn${m?" is-active":""}`,onClick:()=>{d(!1),e.onChange({...n,provider:"",model:"",...ae?{reasoning:""}:{}})},disabled:t,title:z,"data-default-choice":"",children:z}),s.jsx("button",{type:"button",role:"tab","aria-selected":!m,className:`af-pmp__seg-btn${m?"":" is-active"}`,onClick:()=>{d(!0)},disabled:t,children:ee})]}),G.status==="error"||G.status==="unusable"?s.jsx("div",{role:"status",className:"af-pmp__hint","data-gateway-default-problem":G.status,children:G.status==="error"?`The gateway's default could not be read: ${G.message}`:`Gateway warning: ${G.message}`}):null,h?s.jsx(Yj,{provider:L,model:K,providers:g,models:$,modelDisplayNames:S,markSaved:I.current,providerPinned:o.provider,modelPinned:o.model,disabled:t,loadingProviders:x,loadingModels:O,providerError:v||void 0,modelError:P||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:i,gatewayDefaultLabel:i?z:void 0,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:Se=>e.onChange({...n,provider:Se.provider,model:Se.model,...ae?{reasoning:""}:{}})}):s.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}),Qe&&o.reasoning?s.jsxs("div",{className:"af-pmp__reasoning",children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx("div",{className:"af-pmp__pinned","data-pinned":"reasoning",children:Ow})]}):Qe&&ce?s.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":$t,children:[s.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),s.jsx(Wr,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:_t,value:n.reasoning||"",options:[{value:"",label:_t},...et],disabled:t||de.loading||Lt,onChange:Se=>e.onChange({...n,reasoning:Se})}),$t==="unknown"&&ot?s.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[IE," ",s.jsxs("label",{className:"af-pmp__override",children:[s.jsx("input",{type:"checkbox",checked:Me,disabled:t,onChange:Se=>{Ne(Se.target.checked),!Se.target.checked&&n.reasoning&&e.onChange({...n,reasoning:""})}})," ",OE]})]}):null]}):null,Qe&&e.enableSpeculation&&o.speculation?s.jsxs("div",{className:"af-pmp__speculation",children:[s.jsx("label",{children:"MTP depth"}),s.jsx("div",{className:"af-pmp__pinned","data-pinned":"speculation",children:Ow})]}):Qe&&e.enableSpeculation?s.jsx(TE,{value:n.speculation,inheritLabel:Ve,onChange:Se=>e.onChange({...n,speculation:Se}),capabilities:je,disabled:t,loading:de.loading,hideNote:!!de.error}):null,Qe&&de.error?s.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?PE:DE,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:de.error})]})]}):null]})}function pb(...e){return e.filter(Boolean).join(" ")}function FE({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:r="Not signed in",statusTone:i="neutral",showGatewayUrl:o=!1,gatewayUrl:c="",gatewayUrlPlaceholder:l="http://127.0.0.1:8080",onGatewayUrlChange:d,userId:h,userPlaceholder:m="admin",onUserIdChange:_,token:g,tokenPlaceholder:y="Paste Gateway user token",showToken:x=!1,onTokenChange:k,onShowTokenChange:v,remember:N=!1,rememberLabel:$="Remember this browser",onRememberChange:C,loading:S=!1,submitting:D=!1,submitDisabled:O=!1,submitLabel:A="Sign in",submittingLabel:P="Signing in...",closeLabel:W="Close",signOutLabel:J="Sign out",showClose:G=!1,showSignOut:V=!1,error:R,message:M,className:I,onSubmit:L,onClose:K,onSignOut:H}){const z=S||D,ee=z||O||!String(h||"").trim()||!String(g||"").trim(),B=te=>{te.preventDefault(),!ee&&L()};return s.jsxs("form",{className:pb("af-gateway-signin",I),onSubmit:B,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:pb("af-gateway-signin__status",`af-gateway-signin__status--${i}`),children:r})}),s.jsxs("div",{className:"af-gateway-signin__form",children:[o?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:te=>d==null?void 0:d(te.target.value),placeholder:l,autoComplete:"url",disabled:z})]}):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:te=>_(te.target.value),placeholder:m,autoComplete:"username",disabled:z}),s.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),s.jsxs("div",{className:"af-gateway-signin__token-input",children:[s.jsx("input",{id:"gateway-session-token",type:x?"text":"password",value:g,onChange:te=>k(te.target.value),placeholder:y,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:z}),s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>v==null?void 0:v(!x),disabled:z,children:x?"Hide":"Show"})]}),s.jsxs("label",{className:"af-gateway-signin__checkbox",children:[s.jsx("input",{type:"checkbox",checked:!!N,onChange:te=>C==null?void 0:C(te.target.checked),disabled:z}),$]})]}),R?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:R}):null,!R&&M?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:M}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[G?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:K,disabled:z,children:W}):null,V?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(H==null?void 0:H()),disabled:z,children:J}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:ee,children:D?P:A})]})]})}function zE(e){return e==="light"?"Light":"Dark"}function BE(e){const t=e.themes&&e.themes.length?e.themes:Jj,n=e.showSwatches!==!1,r=e.variant||"panel",i=p.useMemo(()=>{const c={};for(const l of t)c[l.id]=l;return c},[t]),o=p.useMemo(()=>t.map(c=>({value:c.id,label:c.label,group:zE(c.group)})),[t]);return s.jsx(Wr,{value:e.value,options:o,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,l)=>{const d=String(l||"").trim(),h=i[d],m=(h==null?void 0:h.label)||d||e.placeholder||"Select theme…",_=(h==null?void 0:h.swatches)||null,g=!d;return s.jsxs("span",{className:"af-theme-value",children:[s.jsx("span",{className:`af-theme-label ${g?"af-theme-label--placeholder":""}`.trim(),children:m}),n&&_?s.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:_.map((y,x)=>s.jsx("span",{className:"af-theme-swatch",style:{background:y}},`${d}:${x}`))}):null]})},renderOption:(c,l)=>{const d=String(c.value||"").trim(),h=i[d],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)=>s.jsx("span",{className:"af-theme-swatch",style:{background:_}},`${d}:${g}`))}):null,l.selected?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function UE(e){const t=e.scales&&e.scales.length?e.scales:Lw,n=e.variant||"panel",r=p.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Wr,{value:e.value,options:r,placeholder:e.placeholder||"Font size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:i=>e.onChange(String(i||"").trim())})}function WE(e){const t=e.densities&&e.densities.length?e.densities:Iw,n=e.variant||"panel",r=p.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return s.jsx(Wr,{value:e.value,options:r,placeholder:e.placeholder||"Header size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:i=>e.onChange(String(i||"").trim())})}const qE=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function VE(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 qe({name:e,size:t=16,className:n,title:r,...i}){const o=r?void 0:!0,c=qE.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":o,role:r?"img":"presentation",...i,children:[r?s.jsx("title",{children:r}):null,VE(e)]})}function HE(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function GE(e){return HE(e)?!e.checked:null}let KE=0;function Fi(e){const{label:t,checked:n,onChange:r,description:i,reasonVisible:o=!0,describedBy:c,hint:l,busy:d=!1,variant:h="inline",ariaLabel:m,className:_,id:g,action:y}=e,x=String(e.unavailableReason||"").trim(),k=!!x,v=c||(g?`${g}-reason`:k?`af-switch-reason-${++KE}`:void 0),N=["af-switch",h==="row"?"af-switch--row":h==="sm"?"af-switch--sm":"",k?"af-switch--unavailable":"",_||""].filter(Boolean).join(" "),$=S=>{const D=GE({checked:n,unavailableReason:x,busy:d});if(D===null){S.preventDefault();return}r==null||r(D)},C=s.jsxs("button",{type:"button",role:"switch",id:g,className:N,"data-action":y,"aria-checked":n?"true":"false","aria-disabled":k?"true":void 0,"aria-describedby":k?v:void 0,"aria-busy":d?"true":void 0,"aria-label":m,"aria-description":i?void 0:l,title:k?l?`${x}
41
+ ${l}`:x:l,onClick:$,children:[s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsxs("span",{className:"af-switch__text",children:[s.jsx("span",{className:"af-switch__label",children:t}),i?s.jsx("span",{className:"af-switch__desc",children:i}):null]})]});return!k||c?C:s.jsxs("span",{className:h==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[C,s.jsx("span",{id:v,className:o?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:x})]})}function JE(e){const t=String(e.unavailableReason||"").trim(),n=["af-switch","af-switch--native",e.variant==="row"?"af-switch--row":"",t?"af-switch--unavailable":""].filter(Boolean).join(" "),r=t?`${e.id||e.name}-reason`:void 0,i=s.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[s.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:o=>{var c;return(c=e.onChange)==null?void 0:c.call(e,o.target.checked)},disabled:!!t,"aria-describedby":r}),s.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:s.jsx("span",{className:"af-switch__thumb"})}),s.jsx("span",{className:"af-switch__text",children:s.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?s.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[i,s.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):i}const YE=150,Zv="data-af-tip";function XE(e,t,n,r=6,i=8){let o="top",c=e.top-r-t.height;if(c<i){const h=e.bottom+r;(h+t.height<=n.height-i||n.height-e.bottom>e.top)&&(c=h,o="bottom")}let d=(e.left+e.right)/2-t.width/2;return d=Math.max(i,Math.min(d,n.width-i-t.width)),c=Math.max(i,Math.min(c,n.height-i-t.height)),{top:Math.round(c),left:Math.round(d),side:o}}let gb=0;function Zj(e){return e?String(e.getAttribute(Zv)||"").trim():""}function yy(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${Zv}]`);return!r||!t.contains(r)||!Zj(r)?null:r}function ZE(e,t={}){if(!e)throw new Error("bindAfTooltips: a root (document or element) is required");const n=e.nodeType===9?e:e.ownerDocument,r=n.defaultView||globalThis,i=typeof t.delayMs=="number"&&t.delayMs>=0?t.delayMs:YE;gb+=1;const o=n.createElement("div");o.className="af-tooltip",o.setAttribute("role","tooltip");const c=`af-tooltip-${gb}`;o.setAttribute("id",c),o.hidden=!0,(n.body||n.documentElement).appendChild(o);let l=null,d=null,h=null,m=null,_=!1,g=null;const y=()=>{h&&clearTimeout(h),h=null,d=null},x=()=>{m&&clearTimeout(m),m=null},k=()=>{if(!l)return;const I=l.getBoundingClientRect(),L=o.getBoundingClientRect(),K=XE(I,{width:L.width,height:L.height},{width:r.innerWidth,height:r.innerHeight});o.style.top=`${K.top}px`,o.style.left=`${K.left}px`,o.setAttribute("data-side",K.side)},v=()=>{if(y(),x(),!l)return;String(l.getAttribute("aria-describedby")||"").split(/\s+/).includes(c)&&(g?l.setAttribute("aria-describedby",g):l.removeAttribute("aria-describedby")),g=null,l=null,o.hidden=!0,o.textContent=""},N=I=>{y(),x(),l&&l!==I&&v();const L=Zj(I);if(!L||I.isConnected===!1)return;if(l=I,o.textContent=L,o.hidden=!1,String(I.getAttribute("aria-label")||"").trim()!==L){const H=I.getAttribute("aria-describedby");g=H&&H!==c?H:null,I.setAttribute("aria-describedby",g?`${g} ${c}`:c)}k()},$=I=>{x(),l!==I&&d!==I&&(y(),d=I,h=setTimeout(()=>{const L=d;h=null,d=null,L&&N(L)},i))},C=()=>{y(),l&&(x(),m=setTimeout(v,100))},S=I=>{try{if(typeof I.matches=="function")return I.matches(":focus-visible")}catch{}return _},D=I=>{if(I.pointerType==="touch")return;if(o.contains(I.target)){x();return}const K=yy(I.target,e);K&&$(K)},O=I=>{const K=I.relatedTarget||null;if(!(K&&(o.contains(K)||l&&l.contains(K)||d&&d.contains(K)))){if(d&&!l){y();return}l&&C()}},A=I=>{const L=I.relatedTarget||null;L&&(o.contains(L)||l&&l.contains(L))||C()},P=I=>{const L=yy(I.target,e);L&&S(L)&&$(L)},W=I=>{const L=yy(I.target,e);L&&(L===l||L===d)&&v()},J=()=>{_=!1,v()},G=I=>{if(I.key==="Escape"||I.key==="Esc"){l?(I.preventDefault(),v()):y();return}!I.metaKey&&!I.ctrlKey&&!I.altKey&&(_=!0)},V=()=>v(),R=e;R.addEventListener("pointerover",D),R.addEventListener("pointerout",O),R.addEventListener("focusin",P),R.addEventListener("focusout",W),o.addEventListener("pointerover",D),o.addEventListener("pointerout",A),n.addEventListener("pointerdown",J,!0),r.addEventListener("keydown",G,!0),r.addEventListener("scroll",V,!0),r.addEventListener("resize",V);let M=!1;return()=>{M||(M=!0,v(),R.removeEventListener("pointerover",D),R.removeEventListener("pointerout",O),R.removeEventListener("focusin",P),R.removeEventListener("focusout",W),o.removeEventListener("pointerover",D),o.removeEventListener("pointerout",A),n.removeEventListener("pointerdown",J,!0),r.removeEventListener("keydown",G,!0),r.removeEventListener("scroll",V,!0),r.removeEventListener("resize",V),o.parentNode&&o.parentNode.removeChild(o))}}const K_=new WeakMap;function QE(e){let t=K_.get(e);t||(t={count:0,release:ZE(e)},K_.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=K_.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),K_.delete(e)))}}function rf(){p.useEffect(()=>{if(!(typeof document>"u"))return QE(document)},[])}function yb(e){rf();const t=Ae.Children.only(e.children),n=String(e.content||"").trim();return n?Ae.cloneElement(t,{[Zv]:n}):t}function Qj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function e2(e){const t=e||{},n=t.connectionPath||xm,r=t.variant||"dismissable",i=p.useRef(t.onStatusChange);i.current=t.onStatusChange;const o=p.useRef(r);o.current=r;const c=p.useRef(!!t.autoOpenMidSession);c.current=!!t.autoOpenMidSession;const[l,d]=p.useState(null),[h,m]=p.useState("loading"),[_,g]=p.useState(!1),y=p.useRef(!1),x=p.useRef(!1),k=p.useRef("loading"),v=p.useRef("none"),N=p.useRef(!1),$=p.useRef(0),C=p.useCallback(M=>{var L;$.current+=1,d(M),(L=i.current)==null||L.call(i,M);const I=Qj(M);if(I)m("connected"),k.current="connected",y.current=!1,v.current="none",x.current||g(!1);else if(M!==null){const K=k.current;m("disconnected"),k.current="disconnected",K!=="disconnected"&&(v.current=N.current?"signout":K==="connected"?"mid":"boot");const H=o.current==="blocking"||v.current!=="mid"||c.current;!y.current&&H&&g(!0)}M!==null&&(x.current=I)},[]),S=p.useCallback(async()=>{const M=$.current;try{const I=await Pw(n);if($.current!==M)return;C(I)}catch{if($.current!==M)return;C(null)}},[n,C]),[D,O]=p.useState(!1),[A,P]=p.useState(null),W=p.useCallback(async()=>{O(!0),P(null),$.current+=1;let M=null;try{await tS(n)}catch(I){M=String((I==null?void 0:I.message)||I||"Sign-out request failed")}N.current=!0;try{await S()}finally{N.current=!1}return P(M),O(!1),M===null&&k.current!=="connected"},[n,S]),J=p.useRef(!1);p.useEffect(()=>{J.current||(J.current=!0,S())},[S]);const G=p.useCallback(()=>{g(!0)},[]),V=p.useCallback(()=>{const M=k.current;r==="blocking"&&M==="disconnected"||(M==="disconnected"&&(y.current=!0),g(!1))},[r]),R=p.useMemo(()=>({isOpen:_,onClose:V,blocking:r==="blocking"&&h!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:l,onStatusChange:C}),[_,V,r,h,t.appName,n,t.defaultGatewayUrl,l,C]);return{status:l,phase:h,connected:h==="connected",modalOpen:_,signingOut:D,signOutError:A,openModal:G,refresh:S,signOut:W,modalProps:R}}const t2="default";function sc(e){return typeof e=="string"?e.trim():""}function wb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0}function n2(e){var h;if(!e||!Qj(e))return null;const t=(h=e.gateway)==null?void 0:h.principal;if(!t||typeof t!="object")return null;const n=sc(t.user_id);if(!n)return null;const r={userId:n},i=sc(t.tenant_id);i&&(r.tenantId=i);const o=sc(t.runtime_id);o&&(r.runtimeId=o);const c=wb(t.roles);c&&(r.roles=c);const l=wb(t.scopes);l&&(r.scopes=l);const d=sc(t.source);return d&&(r.source=d),typeof t.admin=="boolean"&&(r.admin=t.admin),r}function eS(e){const t=sc(e.displayName)||sc(e.userId),n=sc(e.tenantId);return n&&n!==t2?`${n}/${t}`:t}function Qv(e){const t=sc(e);if(!t)return"";try{return new URL(t).host||t}catch{return t}}async function Pw(e=xm){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 s2(e,t=xm){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await n.json().catch(()=>null);if(!n.ok){const i=r&&typeof r=="object"&&r.detail?String(r.detail):`HTTP ${n.status}`;throw new Error(i)}return r}async function tS(e=xm){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 wy(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const o=JSON.parse(t);if(typeof o=="string"&&o!==t){t=o.trim();continue}}catch{}const r=t[0],i=t[t.length-1];if(r==='"'&&i==='"'||r==="'"&&i==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function nS(e){var l,d;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=(d=t.principal)==null?void 0:d.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const i=typeof e.gateway_status=="number"?e.gateway_status:null,o=Qv(e.gateway_url);if(i===0)return{label:`Gateway${o?` at ${o}`:""} did not answer — is it running?`,tone:"err"};if(i===502||i===503||i===504)return{label:`Gateway unavailable (HTTP ${i}) — try again shortly`,tone:"err"};if(i!==null&&i>=500)return{label:`Gateway error (HTTP ${i}) — try again shortly`,tone:"err"};if(i!==null&&i>=400&&i!==401&&i!==403)return{label:`Gateway answered HTTP ${i} — check the gateway URL`,tone:"err"};const c=t.error||t.detail;return typeof c=="string"&&c.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function r2(e){const t=e.connectionPath||xm,[n,r]=p.useState(!1),[i,o]=p.useState(!1),[c,l]=p.useState(null),[d,h]=p.useState(!1);p.useEffect(()=>{e.isOpen||h(!1)},[e.isOpen]);const[m,_]=p.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[g,y]=p.useState("admin"),[x,k]=p.useState(""),[v,N]=p.useState(!1),[$,C]=p.useState(!0),[S,D]=p.useState(""),[O,A]=p.useState(""),P=p.useMemo(()=>nS(c),[c]),W=R=>{var M;l(R),(M=e.onStatusChange)==null||M.call(e,R)},J=p.useRef(!1);if(p.useEffect(()=>{var M;if(!e.isOpen)return;const R=!J.current;if(J.current=!0,R&&e.initialStatus!==void 0&&e.initialStatus!==null){const I=e.initialStatus;W(I),typeof I.gateway_url=="string"&&I.gateway_url.trim()&&_(wy(I.gateway_url));const L=(M=I.gateway)==null?void 0:M.principal;L!=null&&L.user_id&&y(L.user_id);return}r(!0),D(""),Pw(t).then(I=>{var K;W(I),typeof I.gateway_url=="string"&&I.gateway_url.trim()&&_(wy(I.gateway_url));const L=(K=I.gateway)==null?void 0:K.principal;L!=null&&L.user_id&&y(L.user_id)}).catch(I=>D(`Failed to load connection status: ${String((I==null?void 0:I.message)||I)}`)).finally(()=>r(!1))},[e.isOpen]),p.useEffect(()=>{if(!e.isOpen)return;const R=M=>{M.key==="Escape"&&!M.defaultPrevented&&!e.blocking&&(M.preventDefault(),e.onClose())};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||d)return null;const G=async()=>{o(!0),D(""),A("");try{const R=wy(m);_(R);const M=await s2({gateway_url:R,gateway_user_id:g,gateway_token:x,persist:$},t);W(M),k(""),h(!0),e.onClose()}catch(R){D(String((R==null?void 0:R.message)||R))}finally{o(!1)}},V=async()=>{o(!0),D(""),A("");try{await tS(t),k("");const R=await Pw(t).catch(()=>null);W(R),A("Signed out. This browser no longer holds a gateway session.")}catch(R){D(String((R==null?void 0:R.message)||R))}finally{o(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:R=>{!e.blocking&&R.target===R.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(FE,{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:P.label,statusTone:P.tone,showGatewayUrl:!0,gatewayUrl:m,onGatewayUrlChange:R=>_(R),userId:g,onUserIdChange:y,token:x,tokenPlaceholder:c!=null&&c.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:v,onTokenChange:k,onShowTokenChange:N,remember:$,rememberLabel:"Keep this browser signed in",onRememberChange:C,loading:n,submitting:i,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(c!=null&&c.has_session),onSignOut:V,error:S,message:O,onSubmit:G})})})}function i2(){return globalThis.crypto}function o2(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 nl(){const e=i2();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return o2(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Sg(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 a2(){return nl()}function l2(){const e=[];try{if(typeof document>"u")return e;for(const t of String(document.cookie||"").split(";")){const n=t.indexOf("=");if(n<0||!t.slice(0,n).trim().endsWith("_gateway_csrf"))continue;const i=t.slice(n+1).trim();let o=i;try{o=decodeURIComponent(i)}catch{}o&&!e.includes(o)&&e.push(o)}}catch{}return e}async function c2(e){const t=e.commandsPath||wt("commands"),n=a2(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),i=e.csrfToken!==void 0?[e.csrfToken]:l2();i.length===0&&i.push("");let o=null;for(const c of i){const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",...c?{"x-abstract-csrf":c}:{}},body:r}),d=await l.json().catch(()=>null);if(!l.ok){const h=d&&typeof d=="object"&&d.detail?String(d.detail):`HTTP ${l.status}`;if(o=new Error(h),l.status===403&&d&&typeof d=="object"&&d.reason_code==="csrf_required")continue;throw o}return{accepted:!!(d!=null&&d.accepted),duplicate:!!(d!=null&&d.duplicate),seq:Number((d==null?void 0:d.seq)??0)}}throw o||new Error("Steer submit failed")}function u2(e){const[t,n]=p.useState(""),[r,i]=p.useState({kind:"idle"}),o=p.useRef(!1),c=p.useRef(0);p.useEffect(()=>{c.current+=1,i({kind:"idle"})},[e.runId]);const l=!e.disabled&&t.trim().length>0&&r.kind!=="sending",d=p.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 y;const _=t.trim();if(!_||o.current||e.disabled)return;o.current=!0;const g=c.current;i({kind:"sending"});try{const x=e.submit?await e.submit(e.runId,_):await c2({runId:e.runId,guidance:_,commandsPath:e.commandsPath});if(c.current!==g)return;if(!x.accepted&&!x.duplicate){i({kind:"error",detail:"The gateway did not accept this steer (accepted=false)."});return}i({kind:"queued",seq:x.seq,duplicate:x.duplicate}),n(""),(y=e.onSent)==null||y.call(e,{...x,guidance:_})}catch(x){c.current===g&&i({kind:"error",detail:String((x==null?void 0:x.message)||x)})}finally{o.current=!1}},m=_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&(_.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:_=>{n(_.target.value),(r.kind==="error"||r.kind==="queued")&&i({kind:"idle"})},onKeyDown:m}),s.jsx("button",{type:"button",className:"af-steer__send",disabled:!l,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}).`," ",d," ","Watch for the steer_seen ack in the run ledger."]}):r.kind==="error"?s.jsx("span",{className:"af-steer__err",children:r.detail}):s.jsx("span",{className:"af-steer__hint",children:d})})]})}const vy={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},d2=/^var\(--[a-z0-9-]+\)$/i;function f2(e,t){const n=e||"neutral";if(n==="custom"){const r=String(t||"").trim();return d2.test(r)?r:vy.neutral}return vy[n]||vy.neutral}function sS(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n||"",t.className||""].filter(Boolean).join(" ")}function rS(e){return{"--af-chip-hue":f2(e.tone,e.hue)}}function vb(e){return s.jsxs("span",{className:sS("af-chip",e,e.onRemove?"af-chip--removable":""),style:rS(e),title:e.title,children:[s.jsx("span",{className:"af-chip__label",children:e.children}),e.onRemove?s.jsx("button",{type:"button",className:"af-chip__remove","aria-label":e.removeLabel||"Remove",onClick:t=>{var n;t.stopPropagation(),(n=e.onRemove)==null||n.call(e)},children:s.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",children:[s.jsx("path",{d:"M18 6L6 18"}),s.jsx("path",{d:"M6 6l12 12"})]})}):null]})}function h2(e){return s.jsx("button",{type:"button",className:sS("af-chip",e,"af-chip--button"),style:rS(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})})}const m2='button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function _2(e,t=!1){if(!e)return null;const n=e.querySelector(".af-drawer__body")||e,r=n.querySelector("[data-autofocus]");return r||(t?e:n.querySelector("textarea:not(:disabled)")||n.querySelector(m2)||e)}function p2(){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}function xb(e){return e==="auto"?"var(--af-topbar-h, 0px)":typeof e=="number"&&Number.isFinite(e)?e:0}function g2(e){const t=e.closeOnEscape!==!1,n=p.useRef(null);p.useEffect(()=>{if(!e.open||!t)return;const c=l=>{l.key!=="Escape"||l.defaultPrevented||(l.preventDefault(),e.onClose())};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[e.open,t,e.onClose]);const r=p.useRef(null),i=e.manageFocus!==!1,o=p.useRef(!1);return p.useEffect(()=>{var h;if(!o.current){o.current=!0;return}if(!i||typeof document>"u")return;const c=n.current;if(e.open){if(r.current=document.activeElement,c&&c.contains(document.activeElement))return;const m=window.setTimeout(()=>{var _;(_=_2(c,p2()))==null||_.focus({preventScroll:!0})},0);return()=>window.clearTimeout(m)}const l=r.current;r.current=null;const d=document.activeElement;l&&l.isConnected&&(!d||d===document.body||c&&c.contains(d))&&((h=l.focus)==null||h.call(l,{preventScroll:!0}))},[e.open,i]),p.useEffect(()=>{const c=n.current;c&&(e.open?c.removeAttribute("inert"):c.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:xb(e.topOffset)}}):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:xb(e.topOffset),display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,tabIndex:-1,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})]})]})}function y2(e,t,n,r=4,i=8){let o=e.bottom+r,c=!1;if(o+t.height>n.height-i){const h=e.top-r-t.height;(h>=i||e.top>n.height-e.bottom)&&(o=h,c=!0)}let l=e.left,d=!1;return l+t.width>n.width-i&&(l=e.right-t.width,d=!0),l=Math.max(i,Math.min(l,n.width-i-t.width)),o=Math.max(i,o),{top:Math.round(o),left:Math.round(l),up:c,leftward:d}}let bb=0;function w2(e,t,n={}){if(!e||!t)throw new Error("bindAfMenu: button and menu are required");const r=n.document||e.ownerDocument,i=r.defaultView||globalThis;t.getAttribute("id")||(bb+=1,t.setAttribute("id",`af-menu-${bb}`)),e.setAttribute("aria-haspopup","menu"),e.setAttribute("aria-expanded","false"),e.setAttribute("aria-controls",String(t.getAttribute("id"))),t.setAttribute("role","menu"),t.hidden=!0;const o=()=>{const C=Array.from(t.querySelectorAll(".af-menu__item")),S=C.filter(D=>!D.hidden&&!D.hasAttribute("disabled"));for(const D of C)D.setAttribute("role","menuitem"),D.setAttribute("tabindex","-1");return S};o();let c=!1;const l=()=>{if(!c)return;const C=e.getBoundingClientRect(),S=t.getBoundingClientRect(),D=y2(C,{width:S.width,height:S.height},{width:i.innerWidth,height:i.innerHeight});t.style.top=`${D.top}px`,t.style.left=`${D.left}px`,t.setAttribute("data-placement",`${D.up?"top":"bottom"}-${D.leftward?"end":"start"}`)},d=C=>{const S=o();if(!S.length)return;const D=(C%S.length+S.length)%S.length;S[D].focus({preventScroll:!0})},h=C=>{c||(c=!0,t.hidden=!1,e.setAttribute("aria-expanded","true"),l(),d(C),r.addEventListener("pointerdown",_,!0),r.addEventListener("mousedown",_,!0),i.addEventListener("scroll",l,!0),i.addEventListener("resize",g),i.addEventListener("keydown",k,!0),n.onOpen&&n.onOpen())},m=C=>{c&&(c=!1,t.hidden=!0,e.setAttribute("aria-expanded","false"),r.removeEventListener("pointerdown",_,!0),r.removeEventListener("mousedown",_,!0),i.removeEventListener("scroll",l,!0),i.removeEventListener("resize",g),i.removeEventListener("keydown",k,!0),C&&e.focus({preventScroll:!0}),n.onClose&&n.onClose())};function _(C){const S=C.target;S&&(t.contains(S)||e.contains(S))||m(!1)}function g(){m(!1)}const y=C=>{C.preventDefault(),c?m(!0):h(0)},x=C=>{C.key==="ArrowDown"||(C.key==="Enter"||C.key===" ")&&!c?(C.preventDefault(),h(0)):C.key==="ArrowUp"&&(C.preventDefault(),h(-1))},k=C=>{if(!c||C.key!=="Escape"&&C.key!=="Esc")return;const S=C.target;S&&S!==e&&!t.contains(S)&&S!==r.body||(C.preventDefault(),m(!0))},v=C=>{if(!c)return;const D=o().indexOf(r.activeElement);C.key==="ArrowDown"?(C.preventDefault(),d(D+1)):C.key==="ArrowUp"?(C.preventDefault(),d(D<0?-1:D-1)):C.key==="Home"?(C.preventDefault(),d(0)):C.key==="End"?(C.preventDefault(),d(-1)):C.key==="Tab"&&m(!1)},N=C=>{const S=C.target,D=S&&typeof S.closest=="function"?S.closest(".af-menu__item"):null;if(!D||!t.contains(D))return;const O=r.activeElement,A=!O||O===r.body||t.contains(O);m(A)};e.addEventListener("click",y),e.addEventListener("keydown",x),t.addEventListener("keydown",v),t.addEventListener("click",N);let $=!1;return()=>{$||($=!0,m(!1),e.removeEventListener("click",y),e.removeEventListener("keydown",x),t.removeEventListener("keydown",v),t.removeEventListener("click",N))}}function v2(e){const t=p.useRef(null),n=p.useRef(null),r=e.items.filter(o=>o&&!o.hidden),i=r.length>0;return p.useEffect(()=>{if(!(!i||!t.current||!n.current))return w2(t.current,n.current)},[i]),i?s.jsxs("div",{className:`af-menu${e.className?` ${e.className}`:""}`,children:[s.jsx("button",{type:"button",ref:t,className:`af-menu__button${e.buttonClassName?` ${e.buttonClassName}`:""}`,"aria-label":e.label,title:e.title,"data-af-tip":e.tip,"aria-haspopup":"menu","aria-expanded":"false",children:e.buttonContent!==void 0?e.buttonContent:s.jsx("span",{"aria-hidden":"true",children:"⋯"})}),s.jsxs("div",{className:"af-menu__list",role:"menu",ref:n,hidden:!0,children:[e.header!==void 0&&e.header!==null?s.jsx("div",{className:"af-menu__header",role:"presentation",children:e.header}):null,r.map(o=>s.jsx("button",{type:"button",role:"menuitem",tabIndex:-1,"data-menu-id":o.id,className:`af-menu__item${o.danger?" af-menu__item--danger":""}`,onClick:()=>o.onSelect(),children:o.label},o.id))]})]}):null}const x2={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"},b2={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"}},k2={framework:x2,apps:b2},Vp=k2;function iS(){return{...Vp.framework}}function j2(){return Object.keys(Vp.apps).sort()}function S2(e,t){const n=Object.prototype.hasOwnProperty.call(Vp.apps,e)?Vp.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${j2().join(", ")})`);return{id:e,name:n.name,version:t,website:n.website,repo:n.repo,docs:n.docs,issues:n.issues,feedback:n.feedback}}async function N2(e,t){try{const n=await e(wt("about"),{method:"GET",headers:{Accept:"application/json"},signal:t});if(!n.ok)return Gh(null,`HTTP ${n.status}`);const r=await n.json().catch(()=>null);return Gh(r)}catch(n){return Gh(null,String((n==null?void 0:n.message)||n||"request failed"))}}const $2={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function Ld(e){return typeof e=="string"?e.trim():""}function Gh(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=Ld(n.abstractgateway),i=Ld(n.abstractframework);return{framework:i||null,gateway:r||null,...r&&!i?{frameworkNote:"not installed on the gateway host"}:{},...r?{}:{gatewayNote:"unavailable (the gateway did not report its version)"}}}function C2(e){const t=iS();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 E2(e){const t=e||{},n=Ld(t.framework),r=Ld(t.gateway);return[["AbstractFramework",n||Ld(t.frameworkNote)||"not reported"],["AbstractGateway",r||Ld(t.gatewayNote)||"not connected"]]}const A2='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function T2(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(A2));if(r.length===0){e.preventDefault();return}const i=r[0],o=r[r.length-1],c=!!n&&t.contains(n);e.shiftKey?(n===i||!c)&&(e.preventDefault(),o.focus()):(n===o||!c)&&(e.preventDefault(),i.focus())}function M2(e){const t=iS();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:E2(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:C2(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))}),e.extra!==void 0&&e.extra!==null?s.jsx("div",{className:"af-about-card__extra",children:e.extra}):null,s.jsx("p",{className:"af-about-card__legal",children:t.copyright})]})}function R2(e){rf();const t=p.useRef(null),n=p.useRef(null),r=p.useId(),i=p.useRef(e.onClose);return i.current=e.onClose,p.useEffect(()=>{var l;if(!e.open)return;const o=document.activeElement;(l=t.current)==null||l.focus();const c=d=>{if(!d.defaultPrevented){if(d.key==="Escape"){d.preventDefault(),i.current();return}T2(d,n.current,document.activeElement)}};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c),o&&typeof o.focus=="function"&&o.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:o=>o.stopPropagation(),children:s.jsx(M2,{identity:e.identity,versions:e.versions,extra:e.extra,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(qe,{name:"x",size:16})})})})}):null}const Cp={theme:"dark",font_scale:"md",header_density:"standard"};function L2(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Cp.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Cp.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Cp.header_density}}function I2(e){return`af_appearance_${e}_v1`}function O2(e,t){const n=I2(e),r=p.useMemo(()=>({...Cp,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[i,o]=p.useState(()=>{let c=r;try{const l=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);l&&(c=L2({...r,...JSON.parse(l)}))}catch{}try{fb(c.theme),hb({font_scale:c.font_scale,header_density:c.header_density})}catch{}return c});return p.useEffect(()=>{fb(i.theme),hb({font_scale:i.font_scale,header_density:i.header_density});try{localStorage.setItem(n,JSON.stringify(i))}catch{}},[n,i]),[i,o]}function oS(e){return p.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(BE,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(UE,{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(WE,{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 P2(e,t){return{label:t?"Disconnecting…":e==="connected"?"Disconnect":e==="loading"?"Connecting…":"Connect",title:e==="connected"?"Disconnect from gateway":e==="loading"?"Checking gateway session…":"Connect to gateway"}}function D2(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function F2(e,t){return D2(e)?{phase:e.phase,signingOut:e.signingOut===!0,connect:e.openModal,disconnect:async()=>{await e.signOut()===!0&&(t==null||t())},status:e.status,signOutError:e.signOutError||null}:{phase:e.phase,signingOut:e.signingOut===!0,connect:e.onConnect,disconnect:async()=>{e.onDisconnect()},status:e.status??null,signOutError:e.signOutError||null}}function z2(e,t){const n=Qv(t);return`Signed in as ${eS(e)}${n?` · gateway ${n}`:""}`}const xy="--af-topbar-h";function B2(e,t=!0){p.useEffect(()=>{if(!t||typeof window>"u"||typeof document>"u")return;const n=e.current;if(!n)return;const r=n.closest("[data-af-topbar], header")||n.parentElement||n,i=document.documentElement;let o="";const c=()=>{o=`${Math.max(0,Math.round(r.getBoundingClientRect().bottom))}px`,i.style.setProperty(xy,o)};c();const l=typeof ResizeObserver<"u"?new ResizeObserver(c):null;l==null||l.observe(r);const d={passive:!0,capture:!0};return window.addEventListener("resize",c),window.addEventListener("scroll",c,d),()=>{l==null||l.disconnect(),window.removeEventListener("resize",c),window.removeEventListener("scroll",c,d),o&&i.style.getPropertyValue(xy)===o&&i.style.removeProperty(xy)}},[e,t])}function U2(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function W2(e){var S,D;const t=F2(e.connection,e.onSignOut),{phase:n,signingOut:r}=t,[i,o]=p.useState(!1),[c,l]=p.useState(!1),[d,h]=p.useState(void 0),m=p.useRef(null);rf(),B2(m,e.publishHeight!==!1);const _=e.about,g=e.appearance,y=!!(g&&"value"in g),x=_&&!_.versions?_.fetch:void 0,k=p.useRef(x);k.current=x,p.useEffect(()=>{const O=k.current;if(!i||!O)return;const A=typeof AbortController<"u"?new AbortController:null;let P=!0;return h($2),N2(O,A==null?void 0:A.signal).then(W=>{P&&h(W)}),()=>{P=!1,A==null||A.abort()}},[i]);const v=P2(n,r),N=e.identity&&n==="connected"?n2(t.status):null,$=()=>void t.disconnect();let C=null;if(N&&e.identity){const O=eS(N),A=z2(N,(S=t.status)==null?void 0:S.gateway_url),P=s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:"user",size:14}),s.jsx("span",{className:"af-topbar__identity-label",children:O})]});if(e.identity==="badge")C=s.jsx("span",{className:"af-topbar__identity af-topbar__identity--badge","data-af-identity":"badge","data-af-tip":A,"aria-label":A,children:P});else{const W=U2(N.userId),J=Qv((D=t.status)==null?void 0:D.gateway_url);C=s.jsx(v2,{label:`Account: ${A}`,tip:A,className:"af-topbar__account",buttonClassName:"af-topbar__identity af-topbar__identity--menu",buttonContent:P,header:s.jsxs("span",{className:"af-topbar__account-head","data-af-identity":"menu",children:[s.jsxs("span",{className:"af-topbar__account-who",children:["Signed in as ",O]}),J?s.jsxs("span",{className:"af-topbar__account-host",children:["Gateway ",J]}):null]}),items:[{id:"copy-user-id",label:"Copy user id",onSelect:W||(()=>{}),hidden:!W},{id:"disconnect",label:"Disconnect",onSelect:$,danger:!0,hidden:r}]})}}return s.jsxs("div",{ref:m,className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.extraActions,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(qe,{name:"book",size:16})}):null,e.assistant?s.jsx("button",{type:"button",className:`af-topbar__btn af-topbar__btn--assistant${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(qe,{name:"sparkle",size:16})}):null,g?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--appearance","aria-label":g.label||"Appearance (theme and typography)","data-af-tip":g.label||"Appearance (theme and text size)","aria-haspopup":y?"dialog":void 0,onClick:()=>{"value"in g?l(!0):g.onOpen()},children:s.jsx(qe,{name:"contrast",size:16})}):null,_?s.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":_.label||`About ${_.identity.name}`,"data-af-tip":_.label||`About ${_.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var O;o(!0),(O=_.onOpen)==null||O.call(_)},children:s.jsx(qe,{name:"info",size:16})}):null,C,t.signOutError?s.jsxs("span",{className:"af-topbar__signout-error",role:"alert","data-af-tip":`Disconnect failed: ${t.signOutError}`,"aria-label":`Disconnect failed: ${t.signOutError}`,children:[s.jsx(qe,{name:"warning",size:14}),s.jsx("span",{className:"af-topbar__signout-error-label",children:"Disconnect failed"})]}):null,s.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?$:t.connect,disabled:r,title:v.title,"aria-label":v.title,children:[s.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),s.jsx("span",{className:"af-topbar__pill-label",children:v.label})]}),_?s.jsx(R2,{open:i,onClose:()=>o(!1),identity:_.identity,versions:_.versions||(_.fetch?d:void 0),extra:_.extra}):null,g&&"value"in g?s.jsx(oS,{open:c,onClose:()=>l(!1),value:g.value,onChange:g.onChange,title:g.title,note:g.note}):null]})}function Dw(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function kb(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":Dw(r)||"not set"}function q2(e,t){var n;return e.stt_provider?Dw({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?Dw(t.stt):""}function aS(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function V2(e,t,n){return`Transcribing… ${aS(e,t)}${n?` · ${n}`:""}`}const Ng=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function Hp(e){var i;const t=Sg("the microphone");if(t)return t;const n=String((e==null?void 0:e.name)||"");if(n==="NotAllowedError"||n==="SecurityError"||n==="PermissionDeniedError")return"The browser blocked the microphone. Allow it for this site (the icon left of the address), then try again.";if(n==="NotFoundError"||n==="DevicesNotFoundError")return"No microphone was found. Connect one, then try again.";if(n==="OverconstrainedError")return"The chosen microphone is not connected. Pick another one in Settings → Voice.";if(n==="NotReadableError"||n==="TrackStartError")return"Another app is using the microphone. Close it, then try again.";if(!((i=Ng())!=null&&i.getUserMedia))return"This browser cannot record audio.";const r=String((e==null?void 0:e.message)||e||"").trim();return r?`The microphone did not start: ${r.replace(/\.$/,"")}.`:"The microphone did not start."}async function lS(e){const t=Ng();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(c=>c.kind===e),i=r.some(c=>!!c.label);return{devices:r.filter(c=>c.deviceId&&c.deviceId!=="default"&&c.deviceId!=="communications").map((c,l)=>({id:String(c.deviceId),label:String(c.label||`${e==="audioinput"?"Microphone":"Speaker"} ${l+1}`)})),labelled:i}}async function H2(){const e=Ng();if(!(e!=null&&e.getUserMedia))throw new Error(Sg("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function cS(e){const t=Ng();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 $g(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function uS(){const e=$g();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function dS(e,t,n=1){const r=$g();if(!r)return()=>{};const i=new r,o=i.createMediaStreamSource(e),c=i.createAnalyser();c.fftSize=1024,o.connect(c);const l=new Float32Array(c.fftSize);let d=!0;const m=setInterval(()=>{if(!d)return;c.getFloatTimeDomainData(l);let _=0;for(let g=0;g<l.length;g+=1)_+=l[g]*l[g];t(Math.min(1,Math.sqrt(_/l.length)*4*n))},50);return()=>{var _;d=!1,clearInterval(m);try{o.disconnect()}catch{}(_=i.close)==null||_.call(i)}}const fS=.02;function jb(){return Object.assign(new Error("The recording was stopped before it began."),{name:"AbortError"})}async function hS(e){var o,c,l;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});if((o=e.signal)!=null&&o.aborted)throw jb();const n=await cS(e.deviceId);if((c=e.signal)!=null&&c.aborted)throw n.getTracks().forEach(d=>d.stop()),jb();let r=0;const i=dS(n,d=>{var h;r=Math.max(r,d),(h=e.onLevel)==null||h.call(e,d)},e.gain??1);try{const d=new t(n),h=[],m=new Promise((g,y)=>{d.ondataavailable=x=>(x==null?void 0:x.data)&&h.push(x.data),d.onstop=()=>g(),d.onerror=x=>y((x==null?void 0:x.error)||new Error("Recording failed."))});d.start(),await new Promise(g=>{var x,k;if((x=e.signal)!=null&&x.aborted)return g();const y=setTimeout(g,e.ms??3e3);(k=e.signal)==null||k.addEventListener("abort",()=>{clearTimeout(y),g()},{once:!0})}),d.stop(),await m;const _=String(d.mimeType||"audio/webm");return{blob:new Blob(h,{type:_}),peak:r,mime:_}}finally{i(),n.getTracks().forEach(d=>d.stop()),(l=e.onLevel)==null||l.call(e,0)}}async function mS(e,t={}){var i,o,c,l;if((i=t.signal)!=null&&i.aborted)return;const n=$g();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 d=e instanceof Blob?await e.arrayBuffer():e,h=await r.decodeAudioData(d.slice(0));if((o=t.signal)!=null&&o.aborted)return;if(r.state==="suspended"&&await((c=r.resume)==null?void 0:c.call(r)),r.state==="suspended")throw new Error("The browser held the sound back: press play to hear it");const m=r.createGain();m.gain.value=Kd(t.volume),m.connect(r.destination);const _=r.createBufferSource();_.buffer=h,_.connect(m),await new Promise(g=>{var x,k;const y=()=>{try{_.stop()}catch{}g()};_.onended=()=>{var v,N;(N=(v=t.signal)==null?void 0:v.removeEventListener)==null||N.call(v,"abort",y),g()},(k=(x=t.signal)==null?void 0:x.addEventListener)==null||k.call(x,"abort",y,{once:!0}),_.start()})}finally{(l=r.close)==null||l.call(r)}}async function G2(e={}){var r,i;const t=$g();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 o=n.createGain();o.connect(n.destination);const c=.3*Kd(e.volume),l=n.currentTime+.02;[660,880].forEach((d,h)=>{const m=n.createOscillator(),_=n.createGain();m.frequency.value=d,m.connect(_),_.connect(o);const g=l+h*.22;_.gain.setValueAtTime(0,g),_.gain.linearRampToValueAtTime(c,g+.02),_.gain.exponentialRampToValueAtTime(1e-4,g+.2),m.start(g),m.stop(g+.21)}),await new Promise(d=>setTimeout(d,520))}finally{(i=n.close)==null||i.call(n)}}function Kd(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}function Fw(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}async function*K2(e){var r,i,o;const t=new AbortController,n=()=>t.abort();(r=e.signal)!=null&&r.aborted?n():(i=e.signal)==null||i.addEventListener("abort",n,{once:!0});try{const 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),_=m&&typeof m=="object"&&m.detail?String(m.detail):`HTTP ${c.status}`;throw new Error(_)}if(!c.body)throw new Error("TTS stream has no body");const l=c.body.getReader(),d=new TextDecoder;let h="";for(;;){const{done:m,value:_}=await l.read();h+=m?d.decode():d.decode(_,{stream:!0}),m&&h.trim()&&(h+=`
42
+ `);let g;for(;(g=h.indexOf(`
43
+ `))>=0;){const y=h.slice(0,g).trim();if(h=h.slice(g+1),!y)continue;let x=null;try{x=JSON.parse(y)}catch{throw new Error("TTS stream returned invalid JSON.")}if(x&&x.type==="error")throw new Error(String(x.error||"TTS stream error"));const k=x&&typeof x.audio_b64=="string"?x.audio_b64:"";if(k){const v=atob(k),N=new Uint8Array(v.length);for(let $=0;$<v.length;$+=1)N[$]=v.charCodeAt($);yield N.buffer}if(x&&(x.type==="done"||x.type==="cancelled"))return}if(m)throw new Error("TTS stream ended before synthesis completed.")}}finally{(o=e.signal)==null||o.removeEventListener("abort",n),t.abort()}}function wh(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const J2=350;function Y2(){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 X2(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function Z2(){const e=window.MediaRecorder,t=r=>{var i;try{return!!((i=e==null?void 0:e.isTypeSupported)!=null&&i.call(e,r))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const r of n)if(t(r))return r;return""}async function by(e,t){var i;const n=t.slice(0),r=(i=e.decodeAudioData)==null?void 0:i.bind(e);if(typeof r!="function")throw new Error("decodeAudioData not available");try{const o=r(n);if(o&&typeof o.then=="function")return await o}catch{}return await new Promise((o,c)=>{try{r(n,o,c)}catch(l){c(l)}})}function Q2(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=o=>String.fromCharCode(t[o],t[o+1],t[o+2],t[o+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const r=new DataView(e);let i=12;for(;i+8<=t.length;){const o=n(i),c=r.getUint32(i+4,!0);if(o==="data")return t.slice(0,i+8);i+=8+c+c%2}return null}function eA(e,t){const n=new Uint8Array(t),r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length);const i=new DataView(r.buffer);return i.setUint32(4,r.length-8,!0),i.setUint32(e.length-4,n.length,!0),r.buffer}function _S(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const J_=new WeakMap;function tA(e,t){const n=e;if(!(typeof n.setSinkId!="function"||J_.get(e)===t)){J_.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>J_.delete(e))}catch{J_.delete(e)}}}function nA(e){const t=p.useRef(e);t.current=e;const n=fe=>{var $e,pe;return(pe=($e=t.current).on_error)==null?void 0:pe.call($e,fe)},r=p.useMemo(()=>X2()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),i=p.useMemo(()=>Y2()&&typeof e.transcribe=="function",[e.transcribe]),[o,c]=p.useState({key:"",status:"idle"}),l=p.useRef(o),d=p.useCallback(fe=>{l.current=fe,c($e=>$e.key===fe.key&&$e.status===fe.status?$e:fe)},[]),h=p.useRef(""),m=p.useRef(""),_=p.useRef(null),g=p.useRef(null),y=p.useRef(null),x=p.useRef(null),k=p.useRef(0),v=p.useRef(0),N=p.useRef(0),$=p.useRef(null),C=p.useRef([]),S=p.useRef(0),D=p.useRef(!0),O=p.useRef(!1),A=()=>{try{const fe=globalThis,$e=(fe==null?void 0:fe.AudioContext)||(fe==null?void 0:fe.webkitAudioContext);if(!$e)return null;if(!_.current){const ze=new $e,st=ze.createGain();st.gain.value=1,st.connect(ze.destination),_.current=ze,g.current=st}const pe=_.current,le=g.current;if(!pe||!le)return null;tA(pe,t.current.output_device_id||""),le.gain.value=Kd(t.current.volume)*(t.current.muted?0:1);try{pe.state==="suspended"&&pe.resume()}catch{}return{ctx:pe,gain:le}}catch{return null}};p.useEffect(()=>{const fe=g.current;fe&&(fe.gain.value=Kd(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const P=p.useCallback(()=>{const fe=y.current;if(y.current=null,!!fe){try{fe.onended=null}catch{}try{fe.stop()}catch{}try{fe.disconnect()}catch{}}},[]),W=p.useCallback(()=>{var fe;P(),N.current+=1,(fe=$.current)==null||fe.abort(),$.current=null,C.current=[],S.current=0,D.current=!0,O.current=!1,m.current="",h.current="",x.current=null,k.current=0,v.current=0,d({key:"",status:"idle"})},[P,d]);p.useEffect(()=>()=>{var fe,$e;W();try{(fe=g.current)==null||fe.disconnect()}catch{}try{($e=_.current)==null||$e.close()}catch{}_.current=null,g.current=null,x.current=null},[]);const J=async(fe,$e,pe)=>{const le=N.current,ze=A();if(!ze)throw new Error("TTS playback is not supported in this browser");const{ctx:st,gain:kt}=ze;try{st.state==="suspended"&&await st.resume()}catch{}if(le!==N.current)return;P();const pt=st.createBufferSource();pt.buffer=$e,pt.connect(kt);const jt=Number.isFinite(Number($e.duration))?Number($e.duration):0,ct=Math.max(0,Math.min(Number(pe||0),jt>0?Math.max(0,jt-.01):0));v.current=st.currentTime-ct,k.current=ct,y.current=pt,h.current=fe,pt.onended=()=>{y.current===pt&&(y.current=null,k.current=0,v.current=0,h.current="",d({key:"",status:"idle"}))},pt.start(0,ct),d({key:fe,status:"playing"})},G=(fe,$e)=>{if($e!==N.current)return;const pe=A();if(!pe)return;const le=C.current,ze=S.current;if(ze>=le.length){D.current&&(h.current="",k.current=0,v.current=0,d({key:"",status:"idle"}));return}const st=le[ze],{ctx:kt,gain:pt}=pe;P();const jt=kt.createBufferSource();jt.buffer=st,jt.connect(pt);const ct=Number.isFinite(Number(st.duration))?Number(st.duration):0,It=Math.max(0,Math.min(Number(k.current||0),ct>0?Math.max(0,ct-.01):0));v.current=kt.currentTime-It,y.current=jt,h.current=fe,jt.onended=()=>{$e===N.current&&y.current===jt&&(y.current=null,S.current=ze+1,k.current=0,G(fe,$e))};try{kt.state==="suspended"&&kt.resume()}catch{}jt.start(0,It),d({key:fe,status:"playing"})},V=async(fe,$e,pe)=>{var pt;const le=A();if(!le){n==null||n("This browser cannot play spoken replies.");return}P();const ze=++N.current;(pt=$.current)==null||pt.abort();const st=new AbortController;$.current=st,C.current=[],S.current=0,D.current=!1,O.current=!1,x.current=null,k.current=0,v.current=0,h.current=fe,m.current=fe,d({key:fe,status:"loading"}),n==null||n("");let kt=null;try{for await(const jt of pe($e,st.signal)){if(ze!==N.current)return;let ct;try{ct=await by(le.ctx,jt),kt||(kt=Q2(jt))}catch{if(!kt)continue;try{ct=await by(le.ctx,eA(kt,jt))}catch{continue}}if(ze!==N.current)return;C.current.push(ct),!y.current&&!O.current&&(m.current="",G(fe,ze))}if(ze!==N.current)return;if(D.current=!0,C.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),W();return}!y.current&&!O.current&&G(fe,ze)}catch(jt){if(ze!==N.current)return;n==null||n(wh("Reading aloud failed",jt)),W()}finally{$.current===st&&($.current=null)}},R=p.useCallback(async(fe,$e)=>{var It;const pe=String(fe||"").trim(),le=String($e||"").trim();if(!pe||!le)return;const ze=t.current.tts,st=t.current.tts_stream;if(typeof ze!="function"&&typeof st!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const kt=A();if(!kt){n==null||n("This browser cannot play spoken replies.");return}const pt=l.current,jt=pt.key===pe;if(jt&&pt.status==="playing"){if(y.current){const vt=Math.max(0,kt.ctx.currentTime-Number(v.current||0));k.current=vt}else k.current=0;O.current=!0,P(),d({key:pe,status:"paused"});return}if(jt&&pt.status==="paused"){if(C.current.length>0){n==null||n(""),O.current=!1,d({key:pe,status:"playing"}),G(pe,N.current);return}const vt=x.current;if(vt){n==null||n(""),O.current=!1;try{await J(pe,vt,k.current)}catch(nn){n==null||n(wh("Reading aloud failed",nn)),d({key:"",status:"idle"})}return}}if(jt&&pt.status==="loading")return;if(typeof st=="function"){await V(pe,le,st);return}P(),N.current+=1,(It=$.current)==null||It.abort(),$.current=null;const ct=N.current;C.current=[],S.current=0,D.current=!0,O.current=!1,x.current=null,k.current=0,v.current=0,h.current=pe,m.current=pe,d({key:pe,status:"loading"}),n==null||n("");try{const vt=await ze(le);if(m.current!==pe||N.current!==ct)return;const nn=await by(kt.ctx,vt);if(m.current!==pe||N.current!==ct)return;x.current=nn,k.current=0,await J(pe,nn,0)}catch(vt){if(N.current!==ct)return;m.current===pe&&(m.current="",h.current="",d({key:"",status:"idle"})),n==null||n(wh("Reading aloud failed",vt))}},[]),[M,I]=p.useState(!1),[L,K]=p.useState(!1),H=p.useRef(!1),z=p.useRef(i);z.current=i;const ee=p.useCallback(fe=>{H.current=fe,I($e=>$e===fe?$e:fe)},[]),B=p.useRef(!1),te=p.useRef(null),se=p.useRef(null),de=p.useRef([]),be=p.useRef(""),Me=p.useRef(0),Ne=p.useRef(!1),ae=p.useRef(!1),[je,Te]=p.useState(0),Ve=p.useRef(0),_t=p.useRef(null),Qe=p.useRef(0),it=p.useRef(new Set),$t=p.useRef(null),ot=p.useCallback(fe=>{const $e=Math.round(Math.min(1,Math.max(0,Number(fe)||0))*20)/20;if($e!==Qe.current){Qe.current=$e;for(const pe of Array.from(it.current))pe($e)}},[]),mt=p.useCallback(fe=>(it.current.add(fe),fe(Qe.current),()=>{it.current.delete(fe)}),[]),et=p.useRef(new Set),Lt=p.useCallback(fe=>(et.current.add(fe),()=>{et.current.delete(fe)}),[]);function ce(){var pe,le;const fe=$t.current;$t.current=null;try{fe==null||fe()}catch{}ot(0);try{(le=(pe=te.current)==null?void 0:pe.getTracks)==null||le.call(pe).forEach(ze=>{try{ze.stop()}catch{}})}catch{}te.current=null;const $e=_t.current;_t.current=null;try{$e==null||$e.close()}catch{}}const Se=p.useCallback(()=>{Me.current+=1,Ne.current=!1;const fe=se.current;if(fe){fe.onstop=null,fe.ondataavailable=null,fe.onerror=null;try{fe.stop()}catch{}}se.current=null,ce(),ee(!1),B.current=!1,K(!1),Te(0),de.current=[]},[ee]);p.useEffect(()=>()=>Se(),[Se]);async function He(fe,$e){var st,kt;if(n==null||n(""),B.current)return;const pe=Ve.current?Date.now()-Ve.current:1/0;if(!fe||!fe.size||pe<J2){Te(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 le=t.current.transcribe;if(typeof le!="function"){n==null||n("Speech to text is not available on this gateway.");return}B.current=!0;const ze=Me.current;K(!0),Te(Date.now());try{const pt=await le(fe,$e),jt=typeof pt=="string"||!pt?{text:String(pt||"")}:pt,ct=String(jt.text||"").trim();if(ze!==Me.current)return;if(ct){(kt=(st=t.current).on_transcript)==null||kt.call(st,ct,{...jt,text:ct});for(const It of Array.from(et.current))It(ct,{...jt,text:ct})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(pt){if(ze===Me.current){const jt=String((pt==null?void 0:pt.message)||pt||"").trim().replace(/\.$/,"");n==null||n(jt?`Transcription failed: ${jt}.`:"Transcription failed.")}}finally{ze===Me.current&&(B.current=!1,K(!1),Te(0))}}const ne=p.useCallback(async()=>{if(n==null||n(""),!z.current){n==null||n(Sg("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(B.current||Ne.current||H.current||se.current)return;de.current=[];const fe=Me.current;Ne.current=!0,ae.current=!1;try{const $e=await cS(t.current.input_device_id||"");if(fe!==Me.current){$e.getTracks().forEach(pt=>pt.stop());return}if(ae.current){ae.current=!1,$e.getTracks().forEach(pt=>pt.stop()),Te(0);return}te.current=$e;const pe=Number(t.current.input_gain??1);try{$t.current=dS($e,ot,Number.isFinite(pe)&&pe>0?pe:1)}catch{}const le=Z2();be.current=le;let ze=$e;const st=Number(t.current.input_gain??1);if(Number.isFinite(st)&&st>0&&st!==1&&uS()){const pt=globalThis.AudioContext||globalThis.webkitAudioContext,jt=new pt,ct=jt.createGain();ct.gain.value=st;const It=jt.createMediaStreamDestination();jt.createMediaStreamSource($e).connect(ct),ct.connect(It),_t.current=jt,ze=It.stream}const kt=le?new MediaRecorder(ze,{mimeType:le}):new MediaRecorder(ze);se.current=kt,kt.ondataavailable=pt=>{if(fe===Me.current)try{pt!=null&&pt.data&&de.current.push(pt.data)}catch{}},kt.onerror=()=>{fe===Me.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},kt.onstop=()=>{if(fe===Me.current){ee(!1),ce(),se.current=null;try{const pt=new Blob(de.current,{type:be.current||""});He(pt,be.current)}catch(pt){n==null||n(wh("The recording could not be prepared",pt))}}},kt.start(),Ve.current=Date.now(),Te(Ve.current),ee(!0)}catch($e){if(fe!==Me.current)return;ce(),se.current=null,ee(!1),Te(0),n==null||n(Hp($e))}finally{fe===Me.current&&(Ne.current=!1)}},[]),we=p.useCallback(()=>{const fe=se.current;if(Ne.current&&!fe){ae.current=!0;return}if(!(!H.current||!fe)){ee(!1);try{fe.stop()}catch($e){n==null||n(wh("The recording could not stop",$e))}}},[]);return p.useEffect(()=>{if(!M||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&Fw(t.current.capture_mode)==="toggle")return;const fe=()=>we();return window.addEventListener("pointerup",fe),window.addEventListener("pointercancel",fe),()=>{window.removeEventListener("pointerup",fe),window.removeEventListener("pointercancel",fe)}},[M]),{tts_supported:r,tts_playback:o,toggle_tts:R,stop_tts:W,voice_ptt_supported:i,voice_ptt_recording:M,voice_ptt_busy:L,start_voice_ptt_recording:ne,stop_voice_ptt_recording:we,cancel_voice_ptt_recording:Se,voice_ptt_since:je,subscribe_level:mt,voice_capture_mode:Fw(e.capture_mode),add_transcript_listener:Lt}}const sA={diary:"var(--accent)",question:"#e7b45a",dream:"#c084dd",interest:"#7bd88a",lesson:"#6ea8d8",world_model:"#5eead4"};function Sb(e){const t=String(e||"");return t.length>14?`${t.slice(0,10)}…${t.slice(-4)}`:t}function ky(e){const[t,n]=p.useState(!1),[r,i]=p.useState(null),o=p.useRef(!1),c=typeof e.entryId=="string"&&e.entryId.trim()?e.entryId.trim():null,l=e.kind&&sA[e.kind]||"var(--text-muted)",d=p.useCallback(async()=>{if(!(!c||!e.onOpen||o.current)){o.current=!0,n(!0),i(null);try{await e.onOpen(c)}catch(h){i(String((h==null?void 0:h.message)||h||"could not open"))}finally{o.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:l},"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:Sb(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 d(),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:l},"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:Sb(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 Nb=["Your voices","Engine voices","Shared voices"];function pS(e){var r,i;const t=e&&e.tags||{},n=(i=(r=e==null?void 0:e.params)==null?void 0:r.meta)==null?void 0:i.scope;return t.builtin?"Shared voices":(e==null?void 0:e.kind)==="clone"||(e==null?void 0:e.voice_kind)==="clone"?n==="library"?"Shared voices":"Your voices":"Engine voices"}function Cg(e){var t;return String((e==null?void 0:e.language)||((t=e==null?void 0:e.tags)==null?void 0:t.language_code)||"").trim().toLowerCase()}function rA(e){return Array.from(new Set(e.map(Cg).filter(Boolean))).sort()}function iA(e,t){if(!t)return!0;const n=Cg(e);if(n===t)return!0;const r=Array.isArray(e==null?void 0:e.languages)?e.languages.map(i=>String(i).toLowerCase()):[];return!n&&r.length===0?!0:r.includes(t)}const gS={en:"English",fr:"French",de:"German",es:"Spanish",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",nl:"Dutch",pl:"Polish",tr:"Turkish",ar:"Arabic",hi:"Hindi"},yS=gS,_u=e=>yS[e]||e,jy=e=>String((e==null?void 0:e.voice_id)||(e==null?void 0:e.id)||""),Y_=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 oA(e){return e?Array.isArray(e.items)?e.items:[...Array.isArray(e.profiles)?e.profiles:[],...Array.isArray(e.voices)?e.voices:[]]:[]}function wS(e,t,n){const r=String(t||"").trim();if(!r)return"";const i=oA(e).filter(c=>c&&(c.id===r||c.voice_id===r||c.profile_id===r)),o=(n?i.find(c=>(c.provider||c.engine)===n):void 0)||i[0];return String((o==null?void 0:o.label)||(o==null?void 0:o.display_name)||(o==null?void 0:o.name)||"").trim()}function vS(e){const t=String(e||"").trim();return/^[0-9a-f]{16,}$/i.test(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)}function aA(e,t){const n=wS(t,e);if(n)return n;const r=String(e||"").trim();return vS(r)?"a saved voice":r}function lA(e){var n,r,i;if(!e)return"";const t=Array.isArray(e.voice_kinds)?e.voice_kinds:[];return e.kind!=="clone"&&!t.includes("clone")?"":String(e.model||((n=e.tags)==null?void 0:n.model_id)||((i=(r=e.params)==null?void 0:r.meta)==null?void 0:i.model_id)||"").trim()}const cA=200;function uA({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:i=!0,quality:o=!0,showReset:c=!0,defaultHint:l,voiceDefaultLabel:d,createVoice:h,voiceLibrary:m,previewVoice:_,previewOn:g,recordFrom:y}){var ne,we,fe,$e,pe;const x=m||h,[k,v]=p.useState({state:"idle",error:""}),N=p.useRef(0),$=p.useRef(null),C=p.useRef(null),S=p.useRef(null),D=p.useRef(null),O=p.useRef(n);O.current=n;const[A,P]=p.useState({}),[W,J]=p.useState(""),[G,V]=p.useState(!1),[R,M]=p.useState(""),[I,L]=p.useState(0),K=p.useRef(e);K.current=e;const H=p.useRef(!0),z=()=>{var le,ze;N.current+=1,D.current!==null&&clearTimeout(D.current),D.current=null,(le=$.current)==null||le.abort(),$.current=null,(ze=C.current)==null||ze.abort(),C.current=null};p.useEffect(()=>(H.current=!0,()=>{H.current=!1,z()}),[]);const ee=le=>JSON.stringify([le.provider||"",le.model||"",le.voice||"",le.profile||""]),B=le=>`The sample did not play: ${String((le==null?void 0:le.message)||le).replace(/\.$/,"")}.`,te=(le,ze)=>{const st=new AbortController;C.current=st,v({state:"playing",error:""}),mS(le,{deviceId:(g==null?void 0:g.deviceId)||"",volume:g==null?void 0:g.volume,signal:st.signal}).then(()=>H.current&&N.current===ze&&v({state:"idle",error:""})).catch(kt=>H.current&&N.current===ze&&v({state:"idle",error:B(kt)}))},se=le=>{if(!_)return;z();const ze=N.current,st=new AbortController;$.current=st,v({state:"loading",error:""}),_(le,void 0,{signal:st.signal}).then(kt=>{!H.current||N.current!==ze||($.current=null,S.current={key:ee(le),bytes:kt},te(kt,ze))}).catch(kt=>{!H.current||N.current!==ze||($.current=null,v({state:"idle",error:B(kt)}))})},de=le=>{if(!_)return;z();const ze=N.current;if(S.current&&S.current.key===ee(le)){te(S.current.bytes,ze);return}v({state:"loading",error:""}),D.current=setTimeout(()=>{D.current=null,H.current&&N.current===ze&&se(le)},cA)},be=()=>{if(k.state!=="idle"){z(),v({state:"idle",error:""});return}const le=K.current;if(S.current&&S.current.key===ee(le)){z(),te(S.current.bytes,N.current);return}se(le)};p.useEffect(()=>{M("")},[e.provider]),p.useEffect(()=>{let le=!0;return V(!0),P({}),J(""),O.current(e.provider,e.model).then(ze=>{le&&(P(ze),J(ze.error?String(ze.error):""))}).catch(ze=>{le&&J(String((ze==null?void 0:ze.message)||ze))}).finally(()=>{le&&V(!1)}),()=>{le=!1}},[e.provider,e.model,I]);const Me=Array.isArray(A.items)?A.items:[...Array.isArray(A.profiles)?A.profiles.map(le=>({...le,voice_kind:"profile"})):[],...Array.isArray(A.voices)?A.voices.map(le=>({...le,voice_kind:"voice"})):[]],Ne=le=>JSON.stringify([le.provider||"",le.model||"",le.voice_kind==="profile"?"profile":"voice",le.id]),ae=le=>(!e.provider||!le.provider||le.provider===e.provider)&&(!e.model||!le.model||le.model===e.model),je=le=>JSON.stringify([le.provider||"",le.voice_kind==="profile"?"profile":"voice",le.id]),Te=new Map;for(const le of Me){if(!(le!=null&&le.id))continue;const ze=je(le);Te.has(ze)||Te.set(ze,new Set),Te.get(ze).add(String(le.model||""))}const Ve=le=>{var ze;return(((ze=Te.get(je(le)))==null?void 0:ze.size)||0)>1},_t=le=>Ve(le)&&!e.model?JSON.stringify([le.provider||"","",le.voice_kind==="profile"?"profile":"voice",le.id]):Ne(le),Qe=Me.find(le=>le.id===(e.profile||e.voice)&&le.voice_kind==="profile"==!!e.profile&&ae(le))||(!e.profile&&e.voice?Me.find(le=>le.id===e.voice&&le.voice_kind==="profile"&&ae(le)):void 0),it=Qe?_t(Qe):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",$t=rA(Me),ot=$t.length>1;p.useEffect(()=>{!ot&&!G&&M("")},[ot,G]);const mt=ot?R:"",et=new Set,Lt=Me.filter(le=>(le==null?void 0:le.id)&&(!e.provider||!le.provider||le.provider===e.provider)&&(!Ve(le)||!e.model||le.model===e.model||!Te.get(je(le)).has(e.model))&&(iA(le,mt)||_t(le)===it)).filter(le=>{const ze=_t(le);return et.has(ze)?!1:(et.add(ze),!0)}).map(le=>{const ze=Cg(le);return{value:_t(le),group:pS(le),label:`${le.label||le.name||le.id}${ze?` · ${_u(ze)}`:""}${!e.provider&&le.provider?` · ${le.provider}`:""}`}}).sort((le,ze)=>Nb.indexOf(le.group)-Nb.indexOf(ze.group)),ce=String(((ne=Qe==null?void 0:Qe.tags)==null?void 0:ne.description)||"").trim(),Se=lA(Qe);it&&!Lt.some(le=>le.value===it)&&Lt.unshift({value:it,group:"",label:vS(e.profile||e.voice||"")?"Saved voice (not listed)":`${e.profile||e.voice} (saved)`});const He=le=>t({...e,...le});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(Xj,{defaultHint:l,value:{provider:e.provider||"",model:e.model||""},onChange:le=>{z(),v({state:"idle",error:""}),t({...e,...le,voice:"",profile:""})},fetchProviders:async()=>{const le=await O.current();if(le.error&&!Y_(le.tts_providers||le.providers).length)throw new Error(le.error);return Y_(le.tts_providers||le.providers).map(ze=>({name:ze}))},fetchModels:async le=>{var ct,It;const ze=await O.current(le),st=((ct=ze.tts_models_by_provider)==null?void 0:ct[le])||ze.tts_models||ze.models,kt=[...Array.isArray((It=ze.tts_model_details_by_provider)==null?void 0:It[le])?ze.tts_model_details_by_provider[le]:[],...Array.isArray(st)?st.filter(vt=>vt&&typeof vt=="object"):[]],pt=new Map;for(const vt of kt){const nn=String((vt==null?void 0:vt.id)||"").trim();nn&&!pt.has(nn)&&pt.set(nn,String(vt.label||(vt.role==="cloning"?`${nn} (clones)`:nn)))}return[...new Set(Y_(st).map(vt=>String(vt).trim()).filter(Boolean))].map(vt=>({id:vt,label:pt.get(vt)||vt}))},providerLabel:"Speech provider",modelLabel:"Speech model"}),ot?s.jsxs("label",{children:["Voices that speak",s.jsx(Wr,{ariaLabel:"Voice language",placeholder:"Any language",value:R,searchable:!1,options:[{value:"",label:"Any language"},...$t.map(le=>({value:le,label:_u(le)}))],onChange:M})]}):null,s.jsxs("label",{children:["Voice / profile",s.jsxs("span",{className:"af-voice-settings__voice-row",children:[s.jsx(Wr,{ariaLabel:"AI voice",placeholder:d||"Gateway / provider default",value:it,disabled:G,options:[{value:"",label:d||"Gateway / provider default"},...Lt],onChange:le=>{let ze;if(!le)ze={voice:"",profile:""};else{const[st,kt,pt,jt]=JSON.parse(le);ze={provider:st||e.provider||"",model:kt||(st&&st!==e.provider?"":e.model)||"",voice:pt==="voice"?jt:"",profile:pt==="profile"?jt:""}}He(ze),de({...e,...ze})}}),_?s.jsx("button",{type:"button",className:"af-voice-settings__sample","data-action":"play-sample","data-state":k.state,"aria-busy":k.state==="loading","aria-label":k.state==="playing"?"Stop the sample":k.state==="loading"?"Cancel the sample":"Play a sample of this voice",title:k.state==="playing"?"Stop":k.state==="loading"?"Synthesizing… (click to cancel)":"Play a sample",disabled:G&&k.state==="idle",onClick:be,children:s.jsx("span",{"aria-hidden":"true",children:k.state==="playing"?"■":"▶"})}):null]})]}),k.error?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"sample",children:k.error}):null,ce?s.jsx("p",{className:"af-voice-settings__description",children:ce}):null,Se?s.jsxs("p",{className:"af-voice-settings__description","data-voice-note":"clone-model",children:["A cloned voice, made with ",Se,": it is always spoken with that model, whatever speech model is chosen."]}):null,G?s.jsx("p",{role:"status",children:"Loading available voices…"}):null,W?s.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",W,". Your saved choice is preserved."]}):null,!G&&!W&&e.provider&&Me.length===0&&String(A.unavailable_reason||"").trim()?s.jsx("p",{className:"af-voice-note",role:"status","data-voice-note":"unavailable",children:String(A.unavailable_reason).trim()}):null,i?s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Speaking speed",s.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:le=>He({speed:le.target.value?Number(le.target.value):void 0}),children:[s.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(le=>s.jsxs("option",{value:le,children:[le,"×"]},le))]})]}),o&&((fe=(we=A.controls)==null?void 0:we.quality_preset)!=null&&fe.supported)?s.jsxs("label",{children:["Quality",s.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:le=>He({quality_preset:le.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),Y_(A.controls.quality_preset.values).map(le=>s.jsx("option",{value:le,children:le},le))]})]}):null,(pe=($e=A.controls)==null?void 0:$e.instructions)!=null&&pe.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:le=>He({instructions:le.target.value})})]}):null]}):null,x&&(x.design||x.clone)?s.jsx(hA,{creation:x,defaultLanguage:mt,recordFrom:y,onCreated:(le,ze)=>{const st=K.current;t({...st,provider:ze||st.provider||"",model:"",voice:le,profile:""}),L(kt=>kt+1)}}):null,m!=null&&m.list?s.jsx(_A,{library:m,refreshKey:I,onChanged:()=>L(le=>le+1),onRemoved:le=>{const ze=K.current;ze.voice===le&&t({...ze,voice:""})}}):null,c?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const dA={value:"",label:"Detect from the recording"},fA=3e4;function hA({creation:e,defaultLanguage:t,onCreated:n,recordFrom:r,cloneRoute:i}){const[o,c]=p.useState(e.design?"design":"clone"),[l,d]=p.useState(""),[h,m]=p.useState(""),[_,g]=p.useState(t||"en"),[y,x]=p.useState(""),[k,v]=p.useState(null),[N,$]=p.useState(""),[C,S]=p.useState(!1),[D,O]=p.useState(!1),[A,P]=p.useState(0),[W,J]=p.useState({text:"",tone:"info"}),G=p.useRef(!1),V=p.useRef(!0),R=p.useRef(null);p.useEffect(()=>(V.current=!0,()=>{var z;V.current=!1,(z=R.current)==null||z.abort()}),[]);const M=Object.keys(yS).map(z=>({value:z,label:_u(z)})),I=o==="design"?_:y,L=()=>{if(R.current){R.current.abort();return}const z=new AbortController;R.current=z;const ee=Date.now();O(!0),J({text:"Recording — read a few sentences, then press Stop.",tone:"info"}),hS({deviceId:(r==null?void 0:r.deviceId)||"",gain:r==null?void 0:r.gain,ms:fA,signal:z.signal,onLevel:B=>V.current&&P(B)}).then(({blob:B,peak:te})=>{if(V.current){if(te<fS){J({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}v(B),J({text:`Recording ready (${Math.max(1,Math.round((Date.now()-ee)/1e3))} s).`,tone:"ok"})}}).catch(B=>{V.current&&((B==null?void 0:B.name)==="AbortError"?J({text:"Recording cancelled.",tone:"info"}):J({text:Hp(B),tone:"error"}))}).finally(()=>{R.current===z&&(R.current=null),V.current&&(O(!1),P(0))})},K=async()=>{if(!(G.current||R.current)){G.current=!0,S(!0),J({text:o==="design"?"Creating the voice from your description…":"Cloning the voice from your recording…",tone:"info"});try{const z=o==="design"?await e.design({description:l.trim(),name:h.trim()||void 0,language:_}):await e.clone(k,{name:h.trim()||void 0,reference_text:N.trim()||void 0,...y?{language:y}:{},...i!=null&&i.provider?{provider:i.provider}:{},...i!=null&&i.provider&&i.model?{model:i.model}:{}});if(!V.current)return;J({text:`Voice ready: ${z.name||z.voice_id}. It is selected above.`,tone:"ok"}),n(z.voice_id,z.engine||(o==="design"?"qwen3-tts":void 0))}catch(z){if(!V.current)return;J({text:`The voice was not created: ${String((z==null?void 0:z.message)||z).replace(/\.$/,"")}.`,tone:"error"})}finally{G.current=!1,V.current&&S(!1)}}},H=o==="design"?!!l.trim():!!k&&!D;return s.jsxs("fieldset",{className:"af-voice-create","data-voice-create":!0,children:[s.jsx("legend",{children:"Create a voice"}),s.jsxs("div",{className:"af-voice-create__modes",role:"tablist",children:[e.design?s.jsx("button",{type:"button",role:"tab","aria-selected":o==="design","data-create-mode":"design",disabled:C||D,onClick:()=>c("design"),children:"From a description"}):null,e.clone?s.jsx("button",{type:"button",role:"tab","aria-selected":o==="clone","data-create-mode":"clone",disabled:C||D,onClick:()=>c("clone"),children:"From a recording"}):null]}),o==="design"?s.jsxs("label",{children:["Describe the voice",s.jsx("textarea",{"aria-label":"Voice description",rows:3,placeholder:"A calm, warm adult female voice with a slight British accent, speaking slowly.",value:l,onChange:z=>d(z.target.value)})]}):s.jsxs(s.Fragment,{children:[s.jsxs("label",{children:["Recording",s.jsx("input",{"aria-label":"Voice recording",type:"file",accept:"audio/*",disabled:D,onChange:z=>{const ee=z.target.files&&z.target.files[0]||null;v(ee),ee&&J({text:"",tone:"info"})}})]}),s.jsxs("div",{className:"af-voice-create__record",children:[s.jsx("button",{type:"button","data-action":"record-sample",disabled:C,onClick:L,children:D?"Stop":"Record"}),D?s.jsx("div",{className:"af-voice-meter","data-voice-meter":!0,role:"meter","aria-label":"Recording level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(A*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(A*100)}%`}})}):null]}),s.jsxs("label",{children:["What the recording says (optional)",s.jsx("input",{"aria-label":"Recording transcript",value:N,onChange:z=>$(z.target.value)})]})]}),s.jsxs("label",{children:["Name",s.jsx("input",{"aria-label":"Voice name",value:h,placeholder:"My voice",onChange:z=>m(z.target.value)})]}),s.jsxs("label",{children:["Language",s.jsx(Wr,{ariaLabel:"Voice language for creation",value:I,searchable:!1,options:o==="design"?M:[dA,...M],onChange:o==="design"?g:x})]}),s.jsx("button",{type:"button","data-action":"create-voice",disabled:C||!H,onClick:K,children:C?"Creating…":"Create voice"}),W.text?s.jsx("p",{className:`af-voice-note af-voice-note--${W.tone}`,role:"status","data-voice-note":"create",children:W.text}):null]})}const mA=e=>Array.isArray(e)?e:Array.isArray(e==null?void 0:e.voices)?e.voices:[],$b=e=>String((e==null?void 0:e.message)||e||"").trim().replace(/\.$/,"");function _A({library:e,refreshKey:t,onChanged:n,onRemoved:r}){const[i,o]=p.useState([]),[c,l]=p.useState({loading:!0,error:""}),[d,h]=p.useState(null),[m,_]=p.useState(""),[g,y]=p.useState(""),[x,k]=p.useState({text:"",tone:"info"}),[v,N]=p.useState(0),$=p.useRef(e);$.current=e;const C=p.useRef(!1),S=p.useRef(!0);p.useEffect(()=>(S.current=!0,()=>{S.current=!1}),[]),p.useEffect(()=>{const A=$.current.list;if(!A)return;let P=!0;return l(W=>({loading:!0,error:W.error})),A().then(W=>{P&&(o(mA(W).filter(J=>{var G;return jy(J)&&!((G=J==null?void 0:J.tags)!=null&&G.builtin)})),l({loading:!1,error:""}))}).catch(W=>P&&l({loading:!1,error:`The voices could not be listed: ${$b(W)}.`})),()=>{P=!1}},[t,v]);const D=(A,P,W,J)=>{C.current||(C.current=!0,y(A),k({text:"",tone:"info"}),P().then(()=>{S.current&&(k({text:W,tone:"ok"}),h(null),_(""),J==null||J(),N(G=>G+1),n==null||n())}).catch(G=>S.current&&k({text:`${$b(G)||"The gateway refused"}.`,tone:"error"})).finally(()=>{C.current=!1,S.current&&y("")}))},O=A=>String(A.name||A.label||jy(A));return s.jsxs("fieldset",{className:"af-voice-library","data-voice-library":!0,children:[s.jsx("legend",{children:"Manage voices"}),c.loading&&!i.length?s.jsx("p",{role:"status",children:"Loading your voices…"}):null,c.error?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"library",children:c.error}):null,!c.loading&&!c.error&&!i.length?s.jsx("p",{className:"af-voice-library__empty",children:"No voices of your own yet."}):null,i.length?s.jsx("ul",{className:"af-voice-library__list",children:i.map(A=>{const P=jy(A),W=pS(A)==="Shared voices",J=Cg(A),G=String(A.engine||A.provider||""),V=g===P;return s.jsxs("li",{className:"af-voice-library__item","data-voice-id":P,children:[(d==null?void 0:d.id)===P?s.jsxs("span",{className:"af-voice-library__edit",children:[s.jsx("input",{"aria-label":`New name for ${O(A)}`,value:d.name,onChange:R=>h({id:P,name:R.target.value})}),s.jsx("button",{type:"button","data-action":"save-voice-name",disabled:V||!d.name.trim(),onClick:()=>D(P,()=>$.current.rename(P,{name:d.name.trim()}),`Renamed to ${d.name.trim()}.`),children:"Save"}),s.jsx("button",{type:"button","data-action":"cancel-voice-name",disabled:V,onClick:()=>h(null),children:"Cancel"})]}):s.jsxs("span",{className:"af-voice-library__name",children:[O(A),s.jsx("span",{className:"af-voice-library__meta",children:[W?"Shared":"Yours",J?_u(J):"",G].filter(Boolean).join(" · ")})]}),m===P?s.jsxs("span",{className:"af-voice-library__confirm",role:"group","aria-label":`Delete ${O(A)}?`,children:["Delete ",O(A),"?",s.jsx("button",{type:"button","data-action":"confirm-delete-voice",disabled:V,onClick:()=>D(P,()=>$.current.remove(P),`${O(A)} was deleted.`,()=>r==null?void 0:r(P)),children:"Delete"}),s.jsx("button",{type:"button","data-action":"keep-voice",disabled:V,onClick:()=>_(""),children:"Keep"})]}):(d==null?void 0:d.id)!==P?s.jsxs("span",{className:"af-voice-library__actions",children:[e.rename?s.jsx("button",{type:"button","data-action":"rename-voice",disabled:!!g,onClick:()=>h({id:P,name:O(A)}),children:"Rename"}):null,e.remove?s.jsx("button",{type:"button","data-action":"delete-voice",disabled:!!g,onClick:()=>_(P),children:"Delete"}):null,e.share&&!W?s.jsx("button",{type:"button","data-action":"share-voice",disabled:!!g,onClick:()=>D(P,()=>$.current.share(P),`${O(A)} is shared with everyone.`),children:"Share"}):null]}):null]},P)})}):null,x.text?s.jsx("p",{className:`af-voice-note af-voice-note--${x.tone}`,role:"status","data-voice-note":"library-action",children:x.text}):null]})}const Sy=wt("automations"),pA=wt("trigger-sources"),gA=wt("me/email"),yA=wt("me/email/accounts"),wA=wt("triggers/connections"),vA=wt("automations/schedule-preview");class Cb 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 xA(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const r=n;if(typeof r.reason_code=="string"&&r.reason_code&&typeof r.message=="string"){const i={status:e,code:r.reason_code,message:r.message};return typeof r.field=="string"&&(i.field=r.field),typeof r.command_id=="string"&&(i.command_id=r.command_id),i}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function Ny(e){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&t.set(r,String(i));const n=t.toString();return n?`?${n}`:""}function bA(){return nl()}function kA(e){const t=e.newId??bA,n=i=>`${Sy}/${encodeURIComponent(i)}`;async function r(i,o,c){const l={accept:"application/json",...e.headers?e.headers():{}},d={method:i,headers:l};c!==void 0&&(l["content-type"]="application/json",d.body=JSON.stringify(c));const h=await e.fetch(Xv(e.baseUrl,o),d),m=await h.text();let _,g=!1;if(m)try{_=JSON.parse(m),g=!0}catch{g=!1}if(!h.ok)throw new Cb(xA(h.status,_));if(!g||_===null||typeof _!="object")throw new Cb({status:h.status,code:"invalid_response",message:`The gateway answered ${i} ${o} with a body that is not a JSON object.`});return _}return{listAutomations:(i={})=>r("GET",`${Sy}${Ny({status:i.status,cursor:i.cursor,limit:i.limit})}`),getAutomation:i=>r("GET",n(i)),createAutomation:i=>r("POST",Sy,i),reviseAutomation:(i,o)=>r("PATCH",n(i),{command_id:o.command_id??t(),...o.expected_revision!==void 0?{expected_revision:o.expected_revision}:{},changes:o.changes}),sendAutomationCommand:(i,o)=>r("POST",`${n(i)}/commands`,{command_id:o.command_id??t(),type:o.type,...o.payload!==void 0?{payload:o.payload}:{}}),listOccurrences:(i,o={})=>r("GET",`${n(i)}/occurrences${Ny({cursor:o.cursor,limit:o.limit})}`),discuss:(i,o)=>r("POST",`${n(i)}/discuss`,{request_id:o.request_id??t(),occurrence_index:o.occurrence_index,prompt:o.prompt}),markSeen:(i,o)=>r("POST",`${n(i)}/seen`,{attention_cursor:o}),listAttention:(i,o={})=>r("GET",`${n(i)}/attention${Ny({cursor:o.cursor,limit:o.limit})}`),listTriggerSources:()=>r("GET",pA),getMyEmail:()=>r("GET",gA),listTriggerConnections:()=>r("GET",wA),listMailboxes:()=>r("GET",yA),previewSchedule:i=>r("POST",vA,{trigger:i})}}function xS(e){const t=e==null?void 0:e._runtime,n=Array.isArray(t==null?void 0:t.allowed_tools)?t.allowed_tools:null,r=Array.isArray(e==null?void 0:e.tools)?e.tools:n;return Array.isArray(r)?r.filter(i=>typeof i=="string"&&(!n||n.includes(i))):null}function bS(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 jA(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const i of t)i in e&&(n[i]=e[i]);const r=e._runtime;if(r&&typeof r=="object"){const i={};for(const o of["allowed_tools","provider","model","thinking","speculation","stream"])o in r&&(i[o]=r[o]);Object.keys(i).length&&(n._runtime=i)}return n}function zw(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const SA={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},NA={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.`},$A="Next scheduled run: {time}.",CA="Growing context: later runs see this run in their history.",EA={run_now:{name:"playCircle"}},AA={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.",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."},TA={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."},ex={labels:SA,hints:NA,run_now_next_run_line:$A,run_now_growing_line:CA,icons:EA,email:AA,schedule:TA},Ep={manual:"By hand",schedule:"On a schedule",something:"When something arrives",main_mailbox:"your main mailbox"};function bm(e){const t=String(e||"");return t.startsWith("feed")?"feed":t.startsWith("webhook")?"webhook":"other"}function kS(e,t){const n=bm(t);return n==="feed"?`When ${e} has a new item`:n==="webhook"?`When ${e} is called`:`When ${e} sends something`}function jS(e){if(!e)return"";const t=e.config??{};return(typeof t.connection_id=="string"?t.connection_id:typeof e.connection_id=="string"?e.connection_id:"").trim()}function uc(e){if(!e)return!1;const t=String(e.source_id||"");return!(t==="schedule"||t==="manual"||!t)}function Eg(e,t){const n=typeof e=="string"?e.trim():"",r=!n||n==="self"?"default":n,i=(t??[]).find(o=>o.account_id===r)??(r==="default"?(t??[]).find(o=>o.primary):void 0);return i!=null&&i.address?i.address:r==="default"?Ep.main_mailbox:r}function tx(e,t){const n=jS(e);return n?(t??[]).find(r=>r.connection_id===n)??null:null}function MA(e,t,n){var c;if(!e||!uc(e))return"";const r=String(e.source_id||"");if(r.startsWith("email"))return Eg((c=e.config)==null?void 0:c.account,n);const i=tx(e,t);if(i!=null&&i.label)return i.label;const o=bm(r);return o==="feed"?"A feed":o==="webhook"?"A webhook":"A connection"}function km(e,t,n,r){var l;const i=typeof(r==null?void 0:r.trigger_text)=="string"?r.trigger_text.trim():"";if(i)return i;if(!e)return"";const o=String(e.source_id||"");if(o==="schedule"){const d=r==null?void 0:r.schedule_rule_text;return typeof d=="string"&&d.trim()?d.trim():Ep.schedule}if(o==="manual")return Ep.manual;if(o.startsWith("email"))return`When mail arrives in ${Eg((l=e.config)==null?void 0:l.account,n)}`;if(jS(e)){const d=tx(e,t),h=bm(o),m=(d==null?void 0:d.label)||(h==="feed"?"a feed":h==="webhook"?"a webhook":"a connection");return kS(m,o)}return Ep.something}const RA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function $y(e,t){const n=new Date(e),r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(n),i=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(n),[,o,c]=r.split("-"),l=`${Number(c)} ${RA[Number(o)-1]??o}`;return{day:r,clock:i,label:l}}function LA(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;try{return new Intl.DateTimeFormat("en-GB",{timeZone:t}),t}catch{return null}}function Qh(e,t={}){if(!e)return"";const n=Date.parse(e);if(Number.isNaN(n))return"";const r=LA(t.timeZone),i=r??"UTC",o=r?"":" UTC",c=t.nowMs??Date.now(),l=$y(n,i),d=$y(c,i).day,h=$y(c-864e5,i).day;return l.day===d?`${t.style==="day"?"today ":""}${l.clock}${o}`:l.day===h?`yesterday ${l.clock}${o}`:`${l.label} ${l.clock}${o}`}function Ka(e){return typeof e=="string"?e.trim():""}function X_(e){return e?`: “${e}”`:""}function Z_(e,t,n){return`${e} ${e===1?t:n}`}function IA(e,t={}){var m,_,g;if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,r=Ka(n.type),i=/^abstract\.(.+)\.v(\d+)$/.exec(r),o=i?i[1]:"";if(!o||o==="schedule"||o==="manual")return null;const c=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:{},l=Qh(Ka(n.time),{timeZone:t.timeZone,nowMs:t.nowMs});let d="",h="";if(o.startsWith("email")){const y=Array.isArray(c.messages)?c.messages:[],x=typeof c.count=="number"?c.count:y.length;if(!x)return null;d=Eg((_=(m=t.trigger)==null?void 0:m.config)==null?void 0:_.account,t.mailboxes),h=`${Z_(x,"new message","new messages")}${X_(Ka((g=y[0])==null?void 0:g.subject))}`}else{const y=Array.isArray(c.events)?c.events:[],x=typeof c.count=="number"?c.count:y.length;if(!x)return null;const k=y[0]&&typeof y[0]=="object"?y[0]:{},v=k.data&&typeof k.data=="object"&&!Array.isArray(k.data)?k.data:{},N=Ka(c.connection_id)||Ka(n.connectionid),$={source_id:o,config:{connection_id:N}},C=tx(N?$:t.trigger,t.connections),S=bm(o);d=(C==null?void 0:C.label)||MA(N?$:t.trigger??$,t.connections,t.mailboxes);const D=O=>{var A;return!!O&&typeof O=="object"&&((A=O.data)==null?void 0:A.test)===!0};y.length&&y.every(D)?h=x===1?"Test event":`${x} test events`:S==="webhook"?h=`${Z_(x,"call","calls")}${X_(Ka(k.subject))}`:S==="feed"?h=`${Z_(x,"new item","new items")}${X_(Ka(v.title)||Ka(k.subject))}`:h=`${Z_(x,"new event","new events")}${X_(Ka(k.subject))}`}return{source:d,what:h,at:l,text:[d,h,l].filter(Boolean).join(" · ")}}const OA=/^([1-9][0-9]*)([smhd])$/,PA={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function jm(e){if(typeof e!="string")return null;const t=OA.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function DA(e){const t=jm(e);if(!t)return`every ${e}`;const[n,r]=PA[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function Bw(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 nx(e,t,n){return km(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function SS(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const FA={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},$n=ex.email,NS="email.received",$S=1,zA="1h",BA="60s",CS=60,sx=100,Uw=1e3,Eb=200,Ab=200,Tb=50;function Ag(e){return!!e&&e.source_id===NS&&e.source_version===$S}function Tg(e){return!!e&&e.effective_enabled===!0}function ES(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 UA=/[\s<>,;:"()[\]]/;function Ww(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!UA.test(t)}function WA(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const AS={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function rx(e){return e?zA:BA}function TS(e){const t=jm(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function Cy(e,t,n,r,i){const o=ES(e);if(!o.length)return null;const c=o.filter(l=>!n(l));return c.length&&i.push(`${t}: ${c.join(", ")} ${c.length===1?"is not":"are not"} ${r}.`),o.length>Eb&&i.push(`${t}: at most ${Eb} entries.`),o}function qA(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=rx(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&&(TS(n.every)??0)<CS&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=sx:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>Uw?t.push(`At most this many emails per run: a whole number from 1 to ${Uw}.`):n.max_batch=e.maxBatch;const r={},i=Cy(e.fromIn,$n.from_in,Ww,"an email address",t);i&&(r.from_in=i);const o=Cy(e.fromDomainIn,$n.from_domain_in,WA,"a domain like example.com",t);o&&(r.from_domain_in=o);const c=Cy(e.toIn,$n.to_in,Ww,"an email address",t);c&&(r.to_in=c);const l=e.subjectContains.trim();return l&&(l.length>Ab||/[\r\n]/.test(l)?t.push(`${$n.subject_contains}: one line of at most ${Ab} characters.`):r.subject_contains=l),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 MS(e){const t=e,n=t.filter??{},r=["when an email arrives"],i=[...n.from_in??[],...n.from_domain_in??[]];i.length&&r.push(`from ${i.join(", ")}`),n.to_in&&n.to_in.length&&r.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&r.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&r.push("with attachments"),n.has_attachment===!1&&r.push("without attachments");const o=typeof t.every=="string"?t.every:rx(t.uses_model!==!1);r.push(`checked ${DA(o)}`);const c=typeof t.max_batch=="number"?t.max_batch:sx;return r.push(`up to ${c} per run`),r.join(" · ")}const Kh={mode:"self",addresses:""};function qw(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=ES(e.addresses).filter(i=>i!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const r=n.filter(i=>!Ww(i));return r.length&&t.push(`${$n.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Tb&&t.push(`At most ${Tb-1} addresses.`),{recipients:["self",...n],errors:t}}function VA(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function HA(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function RS(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function LS(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function GA(e){return LS(e)?"In the console and by email":"In the console"}const yo={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},KA=new Set(["running","waiting","backoff"]);function JA(e,t=[]){return e.current_occurrence!=null}function IS(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 OS(e,t){var n;return e.next_run_at&&e.next_run_local?`${qS(e.next_run_local,e.time_zone)} (${YA(e.next_run_at,t)})`:e.status==="paused"?"none while paused":e.status==="active"&&e.trigger&&uc(e.trigger)?Mb.event:e.status==="active"&&((n=e.trigger)==null?void 0:n.source_id)==="manual"?Mb.manual:"none scheduled"}const Mb={event:"when something new arrives",manual:"when someone presses Run now"};function YA(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const r=Math.round((n-t)/6e4);if(r<=0)return"due now";if(r<60)return`in ${r} min`;const i=Math.floor(r/60);return i<24?`in ${i} h${r%60?` ${r%60} min`:""}`:`in ${Math.floor(i/24)} d${i%24?` ${i%24} h`:""}`}function em(e,t=[],n=!1){const r=new Set(e.capabilities),i=e.status,o=JA(e,t),c=(m,_,g)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(m)?i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:_?{enabled:!0}:{enabled:!1,reason:g}:{enabled:!1,reason:"Not permitted for this automation."},l=i==="active"||i==="paused",d=i==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:l?r.has(d)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:c("pause",i==="active",i==="paused"?"Already paused.":"The automation has ended."),resume:c("resume",i==="paused",i==="active"?"Already running on schedule.":"The automation has ended."),run_now:c("run_now",l&&!o,o?"An occurrence is in progress.":"The automation has ended."),stop_current:c("stop_current",o,"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."}:i!=="archived"?{enabled:!1,reason:"Not archived."}:r.has("unarchive")?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."},discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:r.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function XA(e){return e.status==="active"?yo.pause:yo.resume}function ZA(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 QA(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=ZA(t),r=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,i=n==="failed"?`Failed after ${r}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,o=t.status==="completed"&&t.attempts>1?`completed after ${r}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:i,statusText:o,canDiscuss:!KA.has(t.status)}})}function eT(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function PS(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 tT={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 Gp(e){return{title:tT[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function ix(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 DS(e,t){var o,c,l;const n=e.trigger,r=n.source_id==="schedule"||Ag(n)?n.config.every:void 0,i=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof r=="string"?r:null,calendar:rT(n)?lT(n.config):null,context:e.context_mode,growingMaxTokens:Number(((c=(o=t==null?void 0:t.context)==null?void 0:o.growing)==null?void 0:c.max_tokens)??e.growing_max_tokens??tm),prompt:typeof i=="string"?i:null,toolApproval:t?t.policy.tool_approval:null,tools:xS(t==null?void 0:t.target.input_data),notifyEmail:t?LS(t.notify):null,emailRecipients:t?VA((l=t.notify)==null?void 0:l.recipients):null}}function nT(e,t,n){var d;const r=[],i={},o=t.title.trim();o?o.length>120?r.push("Title is at most 120 characters."):o!==e.title&&(i.title=o):r.push("Title is required.");const c=DS(e,n);if(t.every!==c.every&&t.every!==null){const h=Ag(e.trigger);if(!jm(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(h&&(TS(t.every)??0)<CS)r.push("The check interval is at least 60 seconds.");else{const m={...e.trigger.config,every:t.every};h&&delete m.start_at,i.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=ox(t.calendar);if(!h.config)r.push(...h.errors);else{const m=e.trigger.config,_={...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}:{}};i.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:_}}}const l=t.context==="growing"?t.growingMaxTokens??c.growingMaxTokens:c.growingMaxTokens;if(zS(l)||r.push(FS),(t.context!==e.context_mode||l!==c.growingMaxTokens)&&(i.context=BS(t.context,l)),n&&typeof c.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==c.prompt.trim()){const h=t.prompt.trim();h?i.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=i.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};i.target={...h,input_data:bS(h.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==c.toolApproval&&(i.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const h=qw(t.notifyEmail?t.emailRecipients??Kh:c.emailRecipients??Kh),m=qw(c.emailRecipients??Kh).recipients;h.errors.length?r.push(...h.errors):(t.notifyEmail!==c.notifyEmail||JSON.stringify(h.recipients)!==JSON.stringify(m))&&(i.notify=RS(t.notifyEmail,h.recipients))}if(r.length)return{errors:r};if(n&&t.target&&zw(t.target)!==zw(n.target)){const h=((d=i.target)==null?void 0:d.input_data)||n.target.input_data;i.target={...t.target,input_data:jA(h)}}return Object.keys(i).length?i:null}const tm=5e4,sT="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.",FS="Max growing context must be a positive whole number of tokens.";function zS(e){return Number.isSafeInteger(e)&&e>0}function BS(e,t){return{mode:e,...t!==tm?{growing:{max_tokens:t}}:{}}}const fs=ex.schedule,Kp=["mon","tue","wed","thu","fri","sat","sun"],US=["daily","weekly","monthly"],WS=2;function rT(e){return e.source_id==="schedule"&&e.source_version===WS}const iT=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function qS(e,t){if(!e)return"";const n=iT.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function oT(e,t="account"){return(t==="account"?fs.time_zone_line:fs.time_zone_line_automation).replace("{time_zone}",e)}const aT=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function VS(e){return US.includes(e.kind)}function ox(e){const t=[];if(aT.test(e.at)||t.push(fs.error_at),e.kind==="weekly"){const n=Kp.filter(r=>e.days.includes(r));return n.length||t.push(fs.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(fs.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 lT(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)?Kp.filter(r=>t.days.includes(r)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const cT=[{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 HS(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 uT(e){const t=e.trim().split(`
56
+ `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const dT=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function Rb(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=HS(e.until);r?n.until=r:t.push("Stop at must be a date and time (UTC).")}return n}function fT(e){const t=[],n=e.when;if(n.kind==="once"){const l=(n.at||"").trim().slice(0,16);return dT.test(l)?{config:{kind:"once",at:l},errors:t}:{config:null,errors:[fs.error_once]}}if(VS(n)){const l=ox(n),d=Rb(e,l.errors);return l.config&&!l.errors.length?{config:{...l.config,...d},errors:[]}:{config:null,errors:l.errors}}const r=n.amount;let i=null;!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):i=`${r}${n.unit}`;let o=null;e.startAt&&(o=HS(e.startAt),o||t.push("First run must be a date and time (UTC)."));const c=Rb(e,t);return t.length||!i?{config:null,errors:t}:{config:{kind:"every",every:i,...o?{start_at:o}:{},...c},errors:t}}function GS(e){const t=fT(e);return t.config?{trigger:{source_id:"schedule",source_version:WS,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function hT(e){return e.kind==="every"||e.kind==="once"||VS(e)}function KS(e,t){const n=[];t.target||n.push("Choose what to run.");const r=e.prompt.trim();r||n.push("Write the task to run.");const i=(e.title??"").trim()||uT(r);i.length>120&&n.push("Title is at most 120 characters.");const o=e.trigger==="email",c=o?qA(e.email??AS):null,l=o?null:GS(e);n.push(...c?c.errors:l.errors);const d=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?qw(e.emailRecipients):null;d&&n.push(...d.errors);const h=e.growingMaxTokens??tm;if(e.context==="growing"&&!zS(h)&&n.push(FS),n.length||!t.target)return{ok:!1,errors:n};const m={...t.target,input_data:{...t.target.input_data??{},prompt:r}},_={request_id:t.requestId,title:i,target:m,trigger:c?{source_id:NS,source_version:$S,config:c.config}:l.trigger,context:BS(e.context,e.context==="growing"?h:tm),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(_.notify=RS(!0,d==null?void 0:d.recipients)),{ok:!0,body:_}}const mT="Tools run without asking (you approve them now by creating this automation)";function _T(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 pT(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 JS={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class gT{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||yT(n.error))&&this.open.delete(t)}}function yT(e){return ix(e)&&e.status>0&&e.code!=="invalid_response"}function wT(){return nl()}class vT{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 Lb(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 xT="08:00",bT=["mon"],YS={at:xT,days:[...bT],day:1};function ax(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 lx(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function Ib(e){return lx(YS,e)}const kT=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function XS(e){const t=e.value,n=r=>{if(t.kind!=="weekly")return;const i=t.days.includes(r);e.onChange({...t,days:Kp.filter(o=>o===r?!i:t.days.includes(o))})};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":fs.days_legend,children:[s.jsx("span",{children:fs.days_legend}),Kp.map(r=>s.jsx(h2,{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:fs.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:fs.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:kT.map(r=>s.jsx("option",{value:r,children:r==="last"?fs.last_day:r},r))})]}):null,s.jsx("label",{htmlFor:`${e.idBase}-at`,children:fs.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":fs.time_label,onChange:r=>e.onChange({...t,at:r.target.value.slice(0,5)})})]})]})}function jT(e){return s.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[s.jsx(yb,{content:fs.time_zone_hint,children:s.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:oT(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?s.jsxs(s.Fragment,{children:[" · ",s.jsx(yb,{content:fs.time_zone_change_hint,children:s.jsx("button",{type:"button",className:"af-auto__link af-schedule__tz-change",onClick:e.onOpenPreferences,children:fs.time_zone_change})})]}):null]})}function ST(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function ZS(e,t,n=250){const r=e?JSON.stringify(e):"",[i,o]=p.useState({phase:"idle"}),c=p.useRef(0),l=p.useRef(t);return l.current=t,p.useEffect(()=>{const d=++c.current;if(!r){o({phase:"idle"});return}o({phase:"loading"});const h=setTimeout(()=>{l.current(JSON.parse(r)).then(m=>{c.current===d&&o({phase:"ok",description:m})},m=>{c.current===d&&o({phase:"error",message:ST(m)})})},n);return()=>clearTimeout(h)},[r,n]),i}function Vw(e){const t=e.state;return t.phase==="ok"?s.jsxs(s.Fragment,{children:[e.showZone===!1?null:s.jsx(jT,{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"?fs.describing:e.incompleteText??fs.incomplete})}function Ob(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 Hw(e){const t=e.disabled===!0,n=p.useMemo(()=>Ob([...e.options||[],...e.value||[]]),[e.options,e.value]),r=p.useMemo(()=>Ob(e.value||[]),[e.value]),[i,o]=p.useState(!1),[c,l]=p.useState(""),d=p.useMemo(()=>{const _=c.trim().toLowerCase();return _?n.filter(g=>g.toLowerCase().includes(_)):n},[n,c]),h=p.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:()=>o(_=>!_),disabled:t||!n.length,"aria-expanded":i,children:[i?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?s.jsx("div",{className:"af_multi_select_chips",children:r.map(_=>s.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${_}`,className:"af_multi_select_chip",title:_,onClick:()=>{if(t)return;const g=new Set(h);g.delete(_),e.onChange(Array.from(g.values()))},children:[_,t?null:s.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},_))}):null,i?s.jsxs("div",{className:"af_multi_select_panel",children:[s.jsx("input",{className:"mono",value:c,onChange:_=>l(String(_.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),s.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${m}px`},children:[d.map(_=>{const g=h.has(_);return s.jsxs("label",{className:`af_multi_select_item mono ${g?"checked":""}`,children:[s.jsx("input",{type:"checkbox",checked:g,disabled:t,onChange:y=>{const x=new Set(h);y.target.checked?x.add(_):x.delete(_),e.onChange(Array.from(x.values()))}}),s.jsx("span",{children:_})]},_)}),d.length?null:s.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function QS(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 the flow's default tools"]}),e.value!==null?s.jsx(Hw,{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 eN="@default",tN="No workflows available for this app — ask your admin.",nN={shared:"Shared",mine:"Mine"};class Gl extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function NT(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 $T(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function CT(e,t={}){return e===null?$T(t):NT(e,t)}function Di(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Hs(e){return typeof e=="string"?e.trim():""}const Q_="update the gateway";function ET(e,t){var l,d;const n=Di(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=Di(n[t]);if(!r)return{status:"unavailable",reason:Hs((d=Di((l=Di(e.default_agent_workflows_unavailable))==null?void 0:l[t]))==null?void 0:d.reason)||`no default workflow for ${t}`};const i=Hs(r.bundle_id),o=Hs(r.flow_id);if(!i||!o)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const c=Hs(r.bundle_version);return{status:"ok",name:Hs(r.name)||o,bundleId:i,bundleVersion:c,flowId:o,workflowId:Hs(r.workflow_id)||`${i}${c?`@${c}`:""}:${o}`}}function AT(e,t,n={}){var l,d;const r=Di(e);if(!r)throw new Gl("The gateway's workflow list is not a JSON object.");const i=Hs(r.executable_for);if(t===null){if(i)throw new Gl(`Asked for every workflow, the gateway listed only ${i}.`)}else if(i!==t)throw new Gl(i?`The gateway listed workflows for ${i}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${Q_}.`);if(!Array.isArray(r.items))throw new Gl("The gateway's workflow list has no items.");const o=[];for(const h of r.items){const m=Di(h),_=Hs(m==null?void 0:m.bundle_id);if(!m||!_)throw new Gl("The gateway listed a workflow without a bundle id.");const g=Di(m.owner),y=Hs(g==null?void 0:g.kind);if(y!=="gateway"&&y!=="user")throw new Gl(`The gateway did not say who owns ${_} (owner missing): ${Q_}.`);if(typeof m.shipped!="boolean")throw new Gl(`The gateway did not say whether ${_} ships with it (shipped missing): ${Q_}.`);const x=Hs(m.bundle_version),k=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const v of k){const N=Di(v),$=Hs(N==null?void 0:N.flow_id);if(!N||!$)continue;const C=Array.isArray(N.interfaces)?N.interfaces.map(Hs).filter(Boolean):[],S=IT((l=Di(m.automation_defaults))==null?void 0:l[$]),D=N.triggerable===!0||!!S;if(t===null){if(!C.length&&!D)continue}else if(!C.includes(t))throw new Gl(`The gateway offered ${_}:${$}, which does not declare ${t}: ${Q_}.`);o.push({value:Hs(N.workflow_id)||`${_}${x?`@${x}`:""}:${$}`,bundleId:_,bundleVersion:x,flowId:$,name:Hs(N.name)||Hs((d=Di(m.metadata))==null?void 0:d.name)||_,description:Hs(N.description)||Hs(m.description),registryScope:Hs(m.registry_scope)||"private",group:y==="user"?"mine":"shared",shipped:m.shipped,interfaces:C,...t===null?{showInterfaces:!0}:{},...S?{automationTrigger:S}:{},...D?{triggerable:!0}:{}})}}const c=n.defaultInterface??t;return{interfaceId:t,entries:o,gatewayDefault:c?ET(r,c):{status:"unavailable",reason:"no interface named for the gateway default"}}}function TT(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:nN[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const MT={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function RT(e){return MT[e]??e}function LT(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?!e.interfaces.length&&e.automationTrigger?[km(e.automationTrigger),n].filter(Boolean).join(" · "):[[...new Set(e.interfaces.map(RT))].join(", "),n].filter(Boolean).join(" · "):n}function IT(e){var o;const t=Di((o=Di(e))==null?void 0:o.trigger),n=Hs(t==null?void 0:t.source_id);if(!t||!n||typeof t.source_version!="number")return;const r=Di(t.config)??{},i=Hs(t.connection_id);return{source_id:n,source_version:t.source_version,config:r,...i?{connection_id:i}:{}}}function OT(e){return e.value}function PT(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function DT(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 FT(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:eN,name:"Gateway default",detail:PT((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const i of TT(n))for(const o of i.entries)r.push({key:o.value,value:o.value,name:o.name,detail:LT(o,n),title:OT(o),group:i.id,entry:o});return r}async function zT(e,t,n){var o;const r=await fetch(Xv(e,wt(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),i=await r.json().catch(()=>null);if(!r.ok){const c=((o=i==null?void 0:i.detail)==null?void 0:o.message)||(i==null?void 0:i.message)||(typeof(i==null?void 0:i.detail)=="string"?i.detail:"");throw new Error(c||`The gateway answered ${r.status}.`)}return i}function BT(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 sN(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:i=!0,gatewayBaseUrl:o,reloadKey:c}=e,l=p.useRef(e.request);l.current=e.request;const[d,h]=p.useState(0),[m,_]=p.useState({status:"idle",data:null,error:""});p.useEffect(()=>{if(!i){_({status:"idle",data:null,error:""});return}const y=new AbortController;_(v=>({...v,status:"loading",error:""}));const x=CT(t,{allVersions:r});return(l.current?l.current(x,{signal:y.signal}):zT(o,x,y.signal)).then(v=>{y.signal.aborted||_({status:"ready",data:AT(v,t,{defaultInterface:n}),error:""})}).catch(v=>{y.signal.aborted||_({status:"error",data:null,error:BT(v)})}),()=>y.abort()},[t,n,r,i,o,c,d]);const g=p.useCallback(()=>h(y=>y+1),[]);return{...m,reload:g}}function UT(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,r=window.innerHeight,i=Math.min(Math.max(t.width,300),440,n-32),o=Math.max(16,Math.min(t.left,n-16-i)),c=r-t.bottom-16;return c>=220||c>=t.top?{position:"fixed",left:o,width:i,top:t.bottom+4,maxHeight:Math.max(160,c)}:{position:"fixed",left:o,width:i,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function rN(...e){return e.filter(Boolean).join(" ")}function iN(e){const t=sN({interfaceId:e.interfaceId,defaultInterface:e.defaultInterface,request:e.request,gatewayBaseUrl:e.gatewayBaseUrl,allVersions:e.allVersions,enabled:e.workflows?!1:e.enabled!==!1}),n=e.workflows??t,r=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),i=p.useId().replace(/:/g,""),o=`${i}-list`,[c,l]=p.useState(!1),[d,h]=p.useState(-1),m=p.useRef(null),_=p.useRef(null),[g,y]=p.useState({}),x=e.entryDetail,k=p.useMemo(()=>FT(n.data,r).map(P=>{const W=P.entry&&x?x(P.entry):null;return W?{...P,detail:W}:P}),[n.data,r,x]),v=k.find(P=>P.value===e.value),N=v?{name:v.name,detail:v.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading flows…",detail:""}:{name:e.value===eN?"Gateway default":"Choose a flow",detail:""},$=String(e.unavailableReason||"").trim(),C=!$&&n.status==="ready",S=p.useCallback(()=>{l(!1),h(-1)},[]),D=p.useCallback(()=>{if(!C)return;y(UT(_.current)),l(!0);const P=k.findIndex(W=>W.value===e.value);h(P>=0?P:0)},[C,k,e.value]),O=p.useCallback(P=>{var W;S(),P.value!==e.value&&e.onChange(P.value,P.entry),(W=_.current)==null||W.focus()},[S,e]);p.useEffect(()=>{if(!c)return;const P=J=>{m.current&&!m.current.contains(J.target)&&S()},W=()=>S();return document.addEventListener("mousedown",P),document.addEventListener("touchstart",P),window.addEventListener("resize",W),()=>{document.removeEventListener("mousedown",P),document.removeEventListener("touchstart",P),window.removeEventListener("resize",W)}},[c,S]),p.useEffect(()=>{var W;if(!c||d<0)return;const P=typeof document<"u"?document.getElementById(`${i}-opt-${d}`):null;(W=P==null?void 0:P.scrollIntoView)==null||W.call(P,{block:"nearest"})},[c,d,i]);const A=P=>{if(!c){["Enter"," ","ArrowDown","ArrowUp"].includes(P.key)&&(P.preventDefault(),D());return}if(P.key==="Escape"){P.preventDefault(),S();return}if(P.key==="Tab"){S();return}if(P.key==="Enter"||P.key===" "){P.preventDefault(),d>=0&&k[d]&&O(k[d]);return}const W=DT(P.key,d,k.length);W!==null&&(P.preventDefault(),h(W))};return s.jsxs("div",{ref:m,className:rN("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[s.jsxs("button",{ref:_,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${i}-value`,"aria-haspopup":"listbox","aria-expanded":c,"aria-controls":o,"aria-activedescendant":c&&d>=0?`${i}-opt-${d}`:void 0,"aria-disabled":C?void 0:!0,title:$||void 0,onClick:()=>c?S():D(),onKeyDown:A,children:[s.jsxs("span",{className:"af-workflow-picker__value",id:`${i}-value`,children:[s.jsx("span",{className:"af-workflow-picker__name",children:N.name}),N.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:N.detail}):null]}),s.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),c?s.jsx(WT,{id:o,idBase:i,rows:k,value:e.value,highlight:d,ariaLabel:e.ariaLabel||"Workflow",style:g,onHighlight:h,onChoose:O}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&k.every(P=>!P.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:tN}):null]})}function WT(e){const t=(o,c)=>s.jsxs("div",{id:`${e.idBase}-opt-${c}`,role:"option","aria-selected":o.value===e.value,"data-value":o.value,title:o.title,className:rN("af-workflow-picker__option",c===e.highlight&&"af-workflow-picker__option--highlighted",o.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(c),onMouseDown:l=>l.preventDefault(),onClick:()=>e.onChoose(o),children:[s.jsx("span",{className:"af-workflow-picker__name",children:o.name}),o.detail?s.jsx("span",{className:"af-workflow-picker__detail",children:o.detail}):null]},o.key),n=e.rows.map((o,c)=>({row:o,index:c})),r=n.filter(o=>o.row.group===null),i=["shared","mine"].map(o=>({g:o,items:n.filter(c=>c.row.group===o)})).filter(o=>o.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(o=>t(o.row,o.index)),i.map(({g:o,items:c})=>s.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${o}`,"data-group":o,children:[s.jsx("div",{id:`${e.idBase}-g-${o}`,className:"af-workflow-picker__group",role:"presentation",children:nN[o]}),c.map(l=>t(l.row,l.index))]},o)),i.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:tN}):null]})}function qT(e){const t=zw(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Flow"}),s.jsx(iN,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:VT(t,e.options)},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})})]})}function VT(e,t){var d,h,m;const n=((h=(d=t.workflows)==null?void 0:d.data)==null?void 0:h.entries)??[],r=n.find(_=>_.value===e);if(r)return r.name;const i=e.indexOf("@"),o=e.lastIndexOf(":"),c=i>0?e.slice(0,i):o>0?e.slice(0,o):e,l=o>0?e.slice(o+1):"";return((m=n.find(_=>_.bundleId===c&&(!l||_.flowId===l)))==null?void 0:m.name)||c||e}async function HT(e,t){var g,y;const n=e.flow_id==="@default"?(y=(g=t.workflows)==null?void 0:g.data)==null?void 0:y.gatewayDefault:null,r="bundle_ref"in e?e.bundle_ref:(n==null?void 0:n.status)==="ok"?`${n.bundleId}@${n.bundleVersion}`:"",i=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!r||!i||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const o=r.lastIndexOf("@"),c=o<0?r:r.slice(0,o),l=o<0?"":r.slice(o+1),d=await t.request(`bundles/${encodeURIComponent(c)}/flows/${encodeURIComponent(i)}/input_schema${l?`?bundle_version=${encodeURIComponent(l)}`:""}`,{signal:new AbortController().signal}),h=(d==null?void 0:d.input_data_schema)||d;if(!h||typeof h!="object"||!h.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const m={...d.defaults||{}};for(const[x,k]of Object.entries(h.properties))k&&"default"in k&&(m[x]=k.default);Object.assign(m,e.input_data||{});const _=(Array.isArray(h.required)?h.required:[]).filter(x=>m[x]===void 0);if(_.length)throw new Error(`This workflow needs additional inputs: ${_.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:m}}function oN(e){if(Tg(e.status))return null;const t=$n.not_set_up,n=$n.open_my_email,r=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,i=e.status&&e.status.admin_disabled&&typeof e.status.admin_disabled.cause=="string"?e.status.admin_disabled.cause:"";return s.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[r,e.onOpenMyEmail?s.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,i?s.jsxs("span",{className:"af-email__cause",children:[" (",i,")"]}):null]})}function GT(e){const t=e.value,n=l=>e.onChange({...t,...l}),r=l=>`${e.idBase}-email-${l}`,i=jm(rx(t.usesModel)),o=t.every??(i&&i.unit==="s"?{amount:Math.max(1,Math.round(i.amount/60)),unit:"m"}:{amount:i?i.amount:1,unit:i?i.unit:"h"}),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:$n.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:String(o.amount),disabled:c,"aria-label":"Check interval amount",name:"email_every_amount",onChange:l=>n({every:{amount:Number(l.target.value),unit:o.unit}})}),s.jsxs("select",{value:o.unit,disabled:c,"aria-label":"Check interval unit",name:"email_every_unit",onChange:l=>n({every:{amount:o.amount,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.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:$n.interval_rule}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[s.jsx("span",{children:$n.max_batch_label}),s.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:Uw,step:1,disabled:c,value:String(t.maxBatch??sx),onChange:l=>n({maxBatch:l.target.value.trim()===""?null:Number(l.target.value)})})]}),s.jsx("p",{className:"af-auto__hint",children:$n.max_batch_hint}),s.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:c,children:[s.jsx("legend",{children:$n.filters_legend}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[s.jsx("span",{children:$n.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:l=>n({fromIn:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[s.jsx("span",{children:$n.from_domain_in}),s.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:l=>n({fromDomainIn:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[s.jsx("span",{children:$n.to_in}),s.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:l=>n({toIn:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[s.jsx("span",{children:$n.subject_contains}),s.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:l=>n({subjectContains:l.target.value})})]}),s.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[s.jsx("span",{children:$n.has_attachment}),s.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:l=>n({hasAttachment:l.target.value}),children:[s.jsx("option",{value:"any",children:$n.has_attachment_any}),s.jsx("option",{value:"yes",children:$n.has_attachment_yes}),s.jsx("option",{value:"no",children:$n.has_attachment_no})]})]}),s.jsx("p",{className:"af-auto__hint",children:$n.list_hint})]})]})}function KT(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(Fi,{variant:"row",action:"notify-email",label:$n.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:[$n.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:$n.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"})})," ",$n.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"})})," ",$n.recipients_list]}),e.recipients.mode==="list"?s.jsx("textarea",{name:"email_recipient_list","aria-label":$n.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:$n.recipients_hint})]}):null]})}const JT={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function aN(e){const t=String(e.status),n=JT[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:FA[t]??t}),n?s.jsx(qe,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const Pb="Discuss this run",Mg=e=>s.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function YT(e){return ix(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function XT(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(Ae.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function ZT(e,t){const n=e.trigger,r=t.find(i=>i.id===n.source_id&&i.version===n.source_version);return r?"available"in r&&r.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${r.unavailable_reason?`: ${r.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function QT(e){const t=e.summary,n=IS(t),r=ZT(t,e.triggerSources),i=OS(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(aN,{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:"Flow"}),s.jsx("dd",{"data-fact":"workflow",children:e.workflowLabel})]}):null,s.jsx("dt",{children:"When"}),s.jsxs("dd",{"data-fact":"trigger",children:[nx(t.trigger,t,{connections:e.triggerConnections,mailboxes:e.mailboxes}),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:SS(t.context_mode)}),n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Now"}),s.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,s.jsx("dt",{children:"Next run"}),s.jsx("dd",{"data-fact":"next",children:i}),s.jsx("dt",{children:"Runs"}),s.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root&&e.onOpenWorkspace?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Files"}),s.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children: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 files",onClick:()=>{var o;return(o=e.onOpenWorkspace)==null?void 0:o.call(e,t.automation_id)},children:[s.jsx(qe,{name:"folder",size:14,className:"af-auto__path-icon"}),s.jsx("span",{children:"Browse its files"})]})})]}):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:PS(t)})]})]})}function eM(e){var c,l;const t=e.definition,n=e.renderText??Mg,r=t.target.input_data.prompt,i=t.policy.retry,o=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(qe,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),s.jsx(qe,{name:"file",size:14}),s.jsx("span",{className:"af-auto__definition-title",children:"Details"})]}),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," · ",nx(t.trigger,e.served,{connections:e.triggerConnections,mailboxes:e.mailboxes}),Ag(t.trigger)?s.jsx("div",{className:"af-auto__hint","data-def":"email_rule",children:MS(t.trigger.config)}):null,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:[SS(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:o==="ask"?"Ask before each tool call (ask)":o==="auto"?"Run without asking (auto)":String(o)}),s.jsx("dt",{children:"Notify"}),s.jsx("dd",{"data-def":"notify",children:GA(t.notify)}),(l=t.notify)!=null&&l.channels.includes("email")?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Recipients"}),s.jsx("dd",{"data-def":"email_recipients",children:HA(t.notify.recipients)})]}):null,s.jsx("dt",{children:"Retries"}),s.jsxs("dd",{"data-def":"retry",children:[i.max_attempts," ",i.max_attempts===1?"attempt":"attempts",", backoff ",i.backoff.initial," ×",i.backoff.factor," up to ",i.backoff.max]}),t.workspace_root?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Folder"}),s.jsx("dd",{"data-def":"workspace",children:s.jsx(XT,{path:t.workspace_root})})]}):null,s.jsx("dt",{children:"Revision"}),s.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Sm=ex,wa=Sm.labels,Go={active:"play",pause:"pause",resume:"play",run_now:Sm.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},Gw=Sm.hints,tM=Sm.run_now_next_run_line,nM=Sm.run_now_growing_line;function Jp(e,t){const n=[Gw[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(tM.replace("{time}",qS(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(nM)),n.join(`
58
+ `)}function sM(e,t,n){const r=new Map;for(const c of t){const l=e[c];if(l.enabled)continue;const d=l.reason??"Not available now.";r.set(d,[...r.get(d)??[],c])}const i=[],o={};return[...r.entries()].forEach(([c,l],d)=>{const h=`${n}-why-${d}`;i.push({id:h,text:`${l.map(m=>wa[m]).join(", ")}: ${c}`});for(const m of l)o[m]=h}),{lines:i,describedBy:o}}function Ur(e){return s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:e.icon,size:14,className:"af-auto__btn-icon"}),s.jsx("span",{children:e.label})]})}function rM(e){const t=em(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",i=sM(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),o=(c,l,d)=>{const h=Jp(c,e.summary);return s.jsx("button",{type:"button",className:`af-auto__btn${d!=null&&d.danger?" af-auto__btn--danger":""}`,"data-action":(d==null?void 0:d.action)??c,disabled:!t[c].enabled,title:t[c].enabled?h:`${t[c].reason}
59
+ ${h}`,"aria-description":h,"aria-describedby":i.describedBy[c],"aria-pressed":d==null?void 0:d.pressed,onClick:l,children:s.jsx(Ur,{icon:Go[c],label:(d==null?void 0:d.label)??wa[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(Fi,{className:"af-auto__switch",action:"active",label:wa.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:i.describedBy.active,busy:e.busy,hint:Jp("active",e.summary),onChange:()=>e.onCommand(XA(e.summary))},"active"),o("run_now",()=>e.onCommand(yo.run_now)),o("stop_current",()=>e.onCommand(yo.stop_current)),o("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?o("unarchive",()=>e.onCommand(yo.unarchive)):o("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),s.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?s.jsxs(s.Fragment,{children:[s.jsx(qe,{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(qe,{name:"x",size:12})}):null]}):null})]}),i.lines.length?s.jsxs("p",{className:"af-auto__reasons",children:[s.jsx(qe,{name:"info",size:12,className:"af-auto__reasons-icon"}),i.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(yo.archive),children:s.jsx(Ur,{icon:"archive",label:"Archive"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:s.jsx(Ur,{icon:"x",label:"Keep it"})})]})]}):null]})}const Db=[["m","minutes"],["h","hours"],["d","days"]];function iM(e,t){const n=v=>{const N=e.elements.namedItem(v);return N&&typeof N.value=="string"?N.value:null},r=n("every_amount"),i=n("every_unit"),o=r!==null&&i!==null?`${r.trim()}${i}`:t.every,c=e.elements.namedItem("context"),l=c&&(c.value==="growing"||c.value==="independent")?c.value:t.context,d=n("prompt"),h=e.elements.namedItem("tool_approval"),m=h&&(h.value==="auto"||h.value==="ask")?h.value:t.toolApproval??null,_=e.elements.namedItem("notify_email"),g=_&&typeof _.checked=="boolean"?_.checked:t.notifyEmail??null,y=e.elements.namedItem("email_recipients"),x=n("email_recipient_list"),k=y&&(y.value==="self"||y.value==="list")?{mode:y.value,addresses:x??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:o,context:l,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:d??t.prompt??null,toolApproval:m,notifyEmail:g,emailRecipients:k}}function oM(e){var O;const t=DS(e.summary,e.definition),[n,r]=p.useState(),[i,o]=p.useState(t.tools??null),[c,l]=p.useState(t.context),[d,h]=p.useState(!!t.notifyEmail),[m,_]=p.useState(((O=t.calendar)==null?void 0:O.kind)??null),[g,y]=p.useState(t.calendar?Ib(t.calendar):null),x=m&&g?ax(m,g):null,k=(()=>{if(!x)return null;const A=ox(x);if(!A.config)return null;const P=e.summary.trigger.config.time_zone;return{source_id:e.summary.trigger.source_id,source_version:e.summary.trigger.source_version,config:{...A.config,...typeof P=="string"?{time_zone:P}:{}}}})(),v=ZS(k,e.previewSchedule),N=t.every?jm(t.every):null,$=N&&N.unit==="s"?[["s","seconds"],...Db]:Db,C=`af-auto-revise-${e.summary.automation_id}`,S=Tg(e.emailStatus),D=Ag(e.summary.trigger);return s.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${C}-heading`,onSubmit:A=>{A.preventDefault(),e.onSubmit({...iM(A.currentTarget,t),...x?{calendar:x}:{},...n?{target:n}:{},...e.availableTools!==void 0?{tools:i}:{}})},onKeyDown:A=>{A.key==="Escape"&&e.onCancel&&(A.preventDefault(),e.onCancel())},children:[e.heading===null?s.jsx("span",{id:`${C}-heading`,hidden:!0,children:"Edit automation"}):s.jsxs("h3",{className:"af-auto__form-title",id:`${C}-heading`,children:[s.jsx(qe,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?s.jsx(qT,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,s.jsxs("label",{className:"af-auto__field",htmlFor:`${C}-title`,children:[s.jsx("span",{children:"Title"}),s.jsx("input",{id:`${C}-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:`${C}-prompt`,children:[s.jsx("span",{children:"Task"}),s.jsx("textarea",{id:`${C}-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:D?$n.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:$.map(([A,P])=>s.jsx("option",{value:A,children:P},A))})]}),D?s.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:$n.interval_rule}):null]}):x?s.jsxs("fieldset",{className:"af-auto__field","data-field":"calendar",children:[s.jsx("legend",{children:fs.legend}),s.jsx("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:US.map(A=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`${C}-calendar-kind`,value:A,checked:x.kind===A,disabled:e.busy,onChange:()=>_(A)})," ",fs[`kind_${A}`]]},A))}),s.jsx(XS,{value:x,onChange:A=>y(P=>lx(P??Ib(A),A)),idBase:C,disabled:e.busy}),s.jsx(Vw,{state:v,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:()=>l("independent")})," Independent — each run starts fresh"]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>l("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:sT})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(QS,{availableTools:e.availableTools,value:i,onChange:o,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"}),S?null:s.jsx(oN,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(JE,{variant:"row",action:"notify-email",name:"notify_email",label:$n.notify_label,defaultChecked:!!t.notifyEmail,onChange:h,unavailableReason:!S&&!t.notifyEmail?"Connect a mailbox first.":null}),s.jsxs("p",{className:"af-auto__hint",children:[$n.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),s.jsx("div",{hidden:!d,children:s.jsxs("fieldset",{className:"af-auto__field",disabled:!d,"data-field":"email-recipients",children:[s.jsx("legend",{children:$n.recipients_legend}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",$n.recipients_self]}),s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!S&&t.emailRecipients.mode!=="list"})," ",$n.recipients_list]}),s.jsx("textarea",{name:"email_recipient_list","aria-label":$n.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!S&&t.emailRecipients.mode!=="list"}),s.jsx("p",{className:"af-auto__hint",children:$n.recipients_hint})]})})]}):null,s.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; runs that a new schedule would have had in the past are not made up."}),e.errors.length?s.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(A=>s.jsx("li",{children:A},A))}):null,s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:s.jsx(Ur,{icon:"check",label:e.submitLabel??"Save changes"})}),e.onCancel?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:s.jsx(Ur,{icon:"x",label:"Cancel"})}):null]})]})}function aM(e,t){const n=typeof t=="string"?t.trim():"",r=typeof e=="string"?e:"",i=r.indexOf(`
61
+ `);if(!n||i<0||!r.startsWith("["))return null;const o=r.slice(i+1);return o===n||o.startsWith(`${n}
62
+ `)?n:null}function lM(e){var n;const t=String(((n=e.trigger)==null?void 0:n.source_id)||"");return t==="schedule"?"on schedule":t==="manual"?"run by hand":t.startsWith("email")?"new mail":t?"something arrived":""}const cM="What the agent received";function Kw(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function uM(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),i=e.renderText??Mg,o=c=>s.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[s.jsx("span",{className:"af-auto-wait__kind",children:JS[t.kind]??"Waiting"}),t.prompt?i(t.prompt):s.jsxs("span",{children:[" ",c]})]});if(t.kind==="tool_approval"){const c=_T(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:[o("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((l,d)=>s.jsxs("li",{"data-tool":l.name,children:[s.jsx("code",{className:"af-auto-wait__tool",children:l.name}),s.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(l.arguments,null,2)})]},l.call_id??`${l.name}:${d}`))}):s.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:s.jsx(Ur,{icon:"check",label:"Approve"})}),s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:s.jsx(Ur,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:c=>{var d;c.preventDefault();const l=pT(Kw(c.currentTarget,"payload"));l.ok?r({payload:l.payload}):(d=e.onWaitError)==null||d.call(e,l.error)},children:[o("The run waits for an event."),s.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),s.jsx("div",{className:"af-auto__row",children:s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:s.jsx(Ur,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?s.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:c=>{c.preventDefault();const l=Kw(c.currentTarget,"response");l&&r({response:l})},children:[o("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(Ur,{icon:"send",label:"Answer"})})]})]}):s.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[o("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 dM(e){const{row:t,tone:n,badge:r,statusText:i}=e.view,o=`af-auto-occ-${t.run_id}`,c=e.renderText??Mg,l=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,d=e.discuss.enabled?e.view.canDiscuss?null:"Available once this run finishes.":e.discuss.reason??"Not available.",h=(v,N)=>e.renderTurn?e.renderTurn({kind:v,role:v==="trigger"?"user":"assistant",text:N,index:t.index,runId:t.run_id}):c(N),m=e.renderTurn?" af-auto-turn--card":"",_=typeof e.task=="string"?e.task.trim():"",g=aM(t.user_turn,_)!==null,y=lM(t),x=Qh(t.fired_at,{timeZone:e.timeZone,nowMs:e.nowMs,style:"day"}),k=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":`${o}-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:`${o}-h`,title:`${t.trigger.summary} · fired ${Bw(t.fired_at)}`,children:[s.jsxs("span",{className:"af-auto-turn__index",children:["Run #",t.index]}),y?` · ${y}`:"",x?` · ${x}`:""]}),e.eventCard?s.jsxs("div",{className:"af-auto-event","data-event-card":"true",children:[s.jsx(qe,{name:"inbox",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto-event__text",children:[s.jsx("strong",{className:"af-auto-event__source",children:e.eventCard.source}),e.eventCard.what?s.jsxs("span",{children:[" · ",e.eventCard.what]}):null,e.eventCard.at?s.jsxs("span",{className:"af-auto-turn__muted",children:[" · ",e.eventCard.at]}):null]})]}):null,(g?_:t.user_turn).trim()?s.jsx("div",{className:"af-auto-turn__text",children:h("trigger",g?_:t.user_turn)}):null,g?s.jsxs("details",{className:"af-auto-received","data-received":"true",children:[s.jsx("summary",{children:cM}),s.jsx("div",{className:"af-auto-received__body",children:c(t.user_turn)})]}):null]}),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:i}),t.finished_at?s.jsxs("span",{title:Bw(t.finished_at),children:[" · ",Qh(t.finished_at,{timeZone:e.timeZone,nowMs:e.nowMs,style:"day"})]}):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:k}),t.artifacts.length?s.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(v=>s.jsxs("li",{children:[e.onOpenResource?s.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var N;return(N=e.onOpenResource)==null?void 0:N.call(e,{kind:"artifact",url:v.url,name:v.name,mimeType:v.mime_type,runId:t.run_id})},children:[s.jsx(qe,{name:"file",size:13,className:"af-auto__btn-icon"})," ",v.name]}):s.jsx("span",{className:"af-auto-artifact__name",children:v.name})," ",s.jsx("span",{className:"af-auto-turn__muted",children:v.mime_type})]},v.artifact_id))}):null,t.waits.map(v=>s.jsx(uM,{wait:v,busy:e.busy,idBase:o,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${v.run_id}:${v.wait_key}`))]}),s.jsxs("div",{className:"af-auto-occ__foot",children:[s.jsxs("details",{className:"af-auto-occ__details",children:[s.jsx("summary",{children:"Run details"}),s.jsxs("dl",{className:"af-auto__facts",children:[s.jsx("dt",{children:"Run"}),s.jsx("dd",{children:s.jsx("code",{children:t.run_id})}),s.jsx("dt",{children:"Attempts"}),s.jsx("dd",{children:t.attempts})]}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:s.jsx(Ur,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var v;return(v=e.onOpenResource)==null?void 0:v.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:s.jsx(Ur,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var v;return(v=e.onOpenWorkspace)==null?void 0:v.call(e,t.run_id)},children:s.jsx(Ur,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?s.jsxs("form",{className:"af-auto-discuss","aria-label":`${Pb}, from run ${t.index}`,onSubmit:v=>{v.preventDefault();const N=Kw(v.currentTarget,"prompt");N&&e.onDiscussSubmit(t.index,N)},children:[s.jsxs("p",{className:"af-auto__hint",children:["Starts a new conversation from run #",t.index," with the automation's whole history (runs 1–",t.index,"). It works in its own folder; the automation's files can be read but not changed (by the file tools; shell commands are not sandboxed), and nothing is written back into the automation."]}),s.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),s.jsxs("div",{className:"af-auto__row",children:[s.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:s.jsx(Ur,{icon:"send",label:"Start discussion"})}),s.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:s.jsx(Ur,{icon:"x",label:"Cancel"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!l,title:Gw.discuss,"aria-description":Gw.discuss,"aria-describedby":d?`${o}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:s.jsx(Ur,{icon:Go.discuss,label:Pb})}),d?s.jsx("span",{className:"af-auto__reasons",id:`${o}-discuss-why`,children:d}):null]})]})]})}const fM=5e3,hM={[yo.pause]:"Automation paused.",[yo.resume]:"Automation active.",[yo.run_now]:"Run requested.",[yo.stop_current]:"Stop requested.",[yo.unarchive]:"Unarchived: it is paused until you make it active."};function mM(e){var Me,Ne;const{summary:t,busy:n}=e,r=e.renderText??Mg,i=p.useId(),o=p.useRef(null),[c,l]=p.useState(!1),d=e.editOpen!==void 0,m=em(t,e.occurrences,!1).revise.enabled&&(d?e.editOpen===!0:c),_=p.useRef(null);m?(!_.current||_.current.summary.automation_id!==t.automation_id)&&(_.current={summary:t,definition:e.definition}):_.current=null;const g=_.current,y=p.useRef(e.onEditOpenChange);y.current=e.onEditOpenChange;const x=ae=>{var je;d||l(ae),(je=y.current)==null||je.call(y,ae)},[k,v]=p.useState([]),[N,$]=p.useState(!1),[C,S]=p.useState(null),[D,O]=p.useState(null),[A,P]=p.useState(null);p.useEffect(()=>{if(!A)return;const ae=setTimeout(()=>P(null),fM);return()=>clearTimeout(ae)},[A]),p.useEffect(()=>{var je;if(!m)return;v([]);const ae=Lb(o.current,['.af-auto__revise [name="title"]']);ae==null||ae.focus(),(je=ae==null?void 0:ae.scrollIntoView)==null||je.call(ae,{block:"nearest"})},[m,t.automation_id]);const[W,J]=p.useState(null);p.useEffect(()=>{var ae;W&&((ae=Lb(o.current,[...W,".af-auto__notice",".af-auto__title"]))==null||ae.focus(),J(null))},[W]);const G=p.useRef(null);G.current||(G.current=new gT(e.newId??wT));const V=G.current,R=ae=>O(YT(ae)),M=(ae,je,Te)=>{O(null),P(null),je(V.idFor(ae)).then(Ve=>{V.settle(ae,{ok:!0}),Te(Ve)},Ve=>{V.settle(ae,{ok:!1,error:Ve}),R(Ve)})},I=eT(t),L=p.useRef(e.onSeen);L.current=e.onSeen;const K=p.useRef(null);K.current||(K.current=new vT),p.useEffect(()=>{const ae=K.current,je=I?`${t.automation_id}|${I}`:null;if(!I||!ae.next(je,t))return;const Te=t;L.current(I).then(()=>ae.succeeded(je),Ve=>{ae.failed(je,Te),R(Ve)})});const H=em(t,e.occurrences,n),z=QA(e.occurrences),ee=(Ne=(Me=e.definition)==null?void 0:Me.target.input_data)==null?void 0:Ne.prompt,B=ae=>e.occurrenceEvents&&ae in e.occurrenceEvents?IA(e.occurrenceEvents[ae],{trigger:t.trigger,connections:e.triggerConnections,mailboxes:e.mailboxes,timeZone:t.time_zone,nowMs:e.nowMs}):null,te=t.occurrence_count-e.occurrences.length,se=D??e.error??null,de=se?Gp(se):null,be=t.attention;return s.jsxs("section",{ref:o,className:`af-auto${e.className?` ${e.className}`:""}`,...e.hideHeader?{"aria-label":t.title}:{"aria-labelledby":i},"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[e.hideHeader?null:s.jsxs(s.Fragment,{children:[s.jsx(QT,{summary:t,workflowLabel:e.workflowName,triggerSources:e.triggerSources,titleId:i,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}),s.jsx(rM,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:m,notice:A,onDismissNotice:()=>P(null),idBase:`${i}-ctl`,onCommand:ae=>M(`command:${ae}`,je=>e.onCommand(ae,void 0,{command_id:je}),()=>{ae===yo.archive?($(!1),P("Archive requested."),J(['[data-action="archive"]'])):P(hM[ae]??"Command sent.")}),onToggleRevise:()=>{v([]),x(!m)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),J(['[data-action="archive"]'])}})]}),m&&g?s.jsx(oM,{summary:g.summary,definition:g.definition,busy:n,errors:k,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,previewSchedule:e.previewSchedule,onCancel:()=>{x(!1),J(['[data-action="edit"]'])},onSubmit:ae=>{const je=g.summary,Te=nT(je,ae,g.definition);if(Te===null){v(["Nothing changed."]);return}if("errors"in Te){v(Te.errors);return}v([]),M(`revise:${je.revision}:${JSON.stringify(Te)}`,async Ve=>{const _t=ae.target&&Te.target?{...Te,target:await(e.prepareTarget?e.prepareTarget(Te.target):HT(Te.target,e.workflowPickerOptions))}:Te;return e.onRevise(_t,je.revision,{command_id:Ve})},()=>{P("Saved; applies from the next run."),x(!1),J(['[data-action="edit"]'])})}}):e.definition?s.jsx(eM,{definition:e.definition,renderText:r,served:t,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}):null,de?s.jsxs("div",{className:"af-auto__error",role:"alert","data-code":se==null?void 0:se.code,children:[s.jsx(qe,{name:"error",size:14,className:"af-auto__btn-icon"}),s.jsxs("span",{className:"af-auto__error-text",children:[s.jsx("strong",{children:de.title})," ",s.jsx("span",{children:de.detail})]}),D?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:()=>O(null),children:s.jsx(qe,{name:"x",size:12})}):null]}):null,be.items.length||be.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[be.items.map(ae=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ae.kind}`,"data-cursor":ae.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${ae.kind==="failure"?"failed":"notified"}`,children:ae.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:ae.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ae.index," · ",Bw(ae.at)]}),ae.body?s.jsx("div",{className:"af-auto__attention-body",children:r(ae.body)}):null]},ae.cursor)),be.waits.map(ae=>s.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[s.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":ae.kind,children:JS[ae.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",ae.index]}),ae.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(ae.prompt)}):null]},`${ae.run_id}:${ae.wait_key}`))]})}):null,te>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(Ur,{icon:"history",label:`Load earlier runs (${te} more)`})}):null,z.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Runs",children:z.map(ae=>{const je=`[data-index="${ae.row.index}"]`;return s.jsx(dM,{view:ae,busy:n,eventCard:B(ae.row.run_id),task:typeof ee=="string"?ee:void 0,timeZone:t.time_zone,nowMs:e.nowMs,discuss:H.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?Te=>{var Ve;O(null);try{Promise.resolve((Ve=e.onOpenResource)==null?void 0:Ve.call(e,Te)).catch(R)}catch(_t){R(_t)}}:void 0,discussOpen:C===ae.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(Te,Ve,_t)=>{O(null),e.onAnswerWait(Te,Ve,_t).then(()=>P("Answer sent."),R)},onWaitError:Te=>O({status:0,code:"invalid_payload",message:Te}),onDiscussOpen:S,onDiscussCancel:()=>{S(null),J([`${je} [data-action="discuss"]`])},onDiscussSubmit:(Te,Ve)=>M(`discuss:${Te}:${Ve}`,_t=>e.onDiscuss(Te,Ve,{request_id:_t}),()=>{S(null),P("Discussion started in a new conversation."),J([`${je} [data-action="discuss"]`])})},ae.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No runs yet."})]})}const lN=72;function _M(e,t=lN){const n=Math.max(1,Math.floor(t)),r=new Array(n).fill(0),i=e.length;if(!i)return r;const o=i/n;let c=0;for(let l=0;l<n;l+=1){const d=Math.floor(l*o),h=Math.max(d+1,Math.floor((l+1)*o));let m=0;for(let _=d;_<h&&_<i;_+=1){const g=Math.abs(Number(e[_])||0);g>m&&(m=g)}r[l]=m,m>c&&(c=m)}return c<=0?r:r.map(l=>l/c)}function ep(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"--:--";const t=Math.floor(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=String(t%60).padStart(2,"0");return n>0?`${n}:${String(r).padStart(2,"0")}:${i}`:`${r}:${i}`}function pM(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function gM(e,t){const[n,r]=p.useState({peaks:t??null,note:""});return p.useEffect(()=>{if(t){r({peaks:t,note:""});return}let i=!0;r({peaks:null,note:""});const o=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!o||typeof fetch!="function"){r({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let c=null;try{const l=await(await fetch(e)).arrayBuffer();c=new o;const d=await c.decodeAudioData(l);i&&r({peaks:_M(d.getChannelData(0)),note:""})}catch(l){i&&r({peaks:null,note:`Waveform unavailable: ${l instanceof Error?l.message:String(l)}`})}finally{c&&c.close().catch(()=>{})}})(),()=>{i=!1}},[e,t]),n}function Rg(e){const t=p.useRef(null),n=p.useRef(null),[r,i]=p.useState(!1),[o,c]=p.useState(0),[l,d]=p.useState(null),[h,m]=p.useState(""),{peaks:_,note:g}=gM(e.src,e.peaks),y=_??new Array(lN).fill(0),x=l&&l>0?Math.min(1,o/l):0,k=e.name?`Audio ${e.name}`:"Audio",v=p.useCallback(()=>{const S=t.current;S&&(S.paused?S.play().catch(D=>m(D instanceof Error?D.message:String(D))):S.pause())},[]),N=p.useCallback(S=>{const D=t.current;!D||!Number.isFinite(S)||(D.currentTime=S,c(S))},[]),$=S=>{var O;const D=(O=n.current)==null?void 0:O.getBoundingClientRect();!D||!l||N(pM(S-D.left,D.width,l))},C=S=>{if(!l)return;const D=S.key==="ArrowRight"||S.key==="ArrowUp"?5:S.key==="ArrowLeft"||S.key==="ArrowDown"?-5:0;D?(S.preventDefault(),N(Math.min(l,Math.max(0,o+D)))):S.key==="Home"?(S.preventDefault(),N(0)):S.key==="End"?(S.preventDefault(),N(l)):(S.key===" "||S.key==="Enter")&&(S.preventDefault(),v())};return s.jsxs("div",{className:`af-audio${e.className?` ${e.className}`:""}`,"data-playing":r?"true":"false",children:[s.jsx("audio",{ref:t,src:e.src,preload:"metadata",onPlay:()=>i(!0),onPause:()=>i(!1),onEnded:()=>i(!1),onTimeUpdate:S=>c(S.currentTarget.currentTime),onLoadedMetadata:S=>d(Number.isFinite(S.currentTarget.duration)?S.currentTarget.duration:null),onDurationChange:S=>d(Number.isFinite(S.currentTarget.duration)?S.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 ${k}`:`Play ${k}`,title:r?"Pause":"Play",onClick:v,children:s.jsx(qe,{name:r?"pause":"play",size:16})}),s.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${k}`,"aria-valuemin":0,"aria-valuemax":Math.round(l??0),"aria-valuenow":Math.round(o),"aria-valuetext":`${ep(o)} of ${ep(l)}`,title:g||void 0,"data-waveform":_?"decoded":"flat",onKeyDown:C,onPointerDown:S=>{var D,O;(O=(D=S.currentTarget).setPointerCapture)==null||O.call(D,S.pointerId),$(S.clientX)},onPointerMove:S=>{S.buttons&1&&$(S.clientX)},children:s.jsx("svg",{viewBox:`0 0 ${y.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:y.map((S,D)=>{const O=Math.max(1.5,S*30),A=(D+.5)/y.length<=x;return s.jsx("rect",{className:A?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:D*2+.3,y:16-O/2,width:1.4,height:O,rx:.6},D)})})}),s.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[ep(o)," / ",ep(l)]}),h?s.jsx("p",{className:"af-audio__error",role:"alert",children:h}):null]})}const pu=e=>new Set(e.split(/\s+/).filter(Boolean)),yM=pu("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"),wM=pu("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"),vM=pu("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),xM=pu("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"),Fb=pu("true false null yes no on off"),bM={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:yM},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:wM},shell:{line:["#"],strings:['"',"'"],keywords:vM},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:xM},data:{line:["#"],strings:['"',"'"],keywords:Fb},json:{line:[],strings:['"'],keywords:Fb},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:pu("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:pu("")}},kM={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 cx(e){const t=String(e||"").trim().toLowerCase(),n=t.split("/").pop()||t;if(n==="dockerfile"||n==="makefile")return"shell";const r=n.lastIndexOf("."),i=r>=0?n.slice(r+1):n;return kM[i]||""}const jM=e=>e>="0"&&e<="9",SM=e=>/[A-Za-z_$]/.test(e),zb=e=>/[A-Za-z0-9_$]/.test(e);function cN(e,t){const n=String(e??""),r=bM[t];if(!r)return n?[{kind:"plain",text:n}]:[];const i=[];let o="";const c=(d,h)=>{if(h){if(d==="plain"){o+=h;return}o&&i.push({kind:"plain",text:o}),o="",i.push({kind:d,text:h})}};let l=0;for(;l<n.length;){const d=n[l];if(r.line.find(m=>n.startsWith(m,l))){const m=n.indexOf(`
63
+ `,l),_=m===-1?n.length:m;c("comment",n.slice(l,_)),l=_;continue}if(r.block&&n.startsWith(r.block[0],l)){const m=n.indexOf(r.block[1],l+r.block[0].length),_=m===-1?n.length:m+r.block[1].length;c("comment",n.slice(l,_)),l=_;continue}if(r.strings.includes(d)){const m=r.triple&&n.startsWith(d.repeat(3),l)?d.repeat(3):"";if(m){const y=n.indexOf(m,l+3),x=y===-1?n.length:y+3;c("string",n.slice(l,x)),l=x;continue}let _=l+1;for(;_<n.length&&n[_]!==d&&(d==="`"||n[_]!==`
64
+ `);)_+=n[_]==="\\"?2:1;const g=Math.min(n.length,_+1);c("string",n.slice(l,g)),l=g;continue}if(jM(d)&&!(l>0&&zb(n[l-1]))){let m=l+1;for(;m<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[m]);)m+=1;c("number",n.slice(l,m)),l=m;continue}if(SM(d)){let m=l+1;for(;m<n.length&&zb(n[m]);)m+=1;const _=n.slice(l,m),g=t==="sql"?r.keywords.has(_.toLowerCase()):r.keywords.has(_);c(g?"keyword":"plain",_),l=m;continue}c("plain",d),l+=1}return o&&i.push({kind:"plain",text:o}),i}function tp({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:i}){const o=cx(t),c=cN(e,o),l=n?String(e??"").split(`
65
+ `).length:0;return s.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${r?` ${r}`:""}`,"data-language":o||"text","aria-label":i,style:n?{"--af-code-gutter":`${String(l).length+1}ch`}:void 0,children:s.jsx("code",{children:n?NM(c).map((d,h)=>s.jsxs("span",{className:"af-code__line","data-line":h+1,children:[d.map((m,_)=>Bb(m,_)),`
66
+ `]},h)):c.map((d,h)=>Bb(d,h))})})}function Bb(e,t){return e.kind==="plain"?s.jsx(Ae.Fragment,{children:e.text},t):s.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function NM(e){const t=[[]];for(const n of e)n.text.split(`
67
+ `).forEach((i,o)=>{o>0&&t.push([]),i&&t[t.length-1].push({kind:n.kind,text:i})});return t}const uN=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Dh=6e4,Fh=60*Dh,np=24*Fh;function Nm(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)?Nm(Number(t)):Date.parse(t)}function Ub(e){return e<10?`0${e}`:String(e)}function Wb(e,t){const n=Nm(e);if(!Number.isFinite(n))return"";const r=new Date(n),i=r.getFullYear()===new Date(t).getFullYear();return`${uN[r.getMonth()]} ${r.getDate()}${i?"":`, ${r.getFullYear()}`}`}function ux(e){const t=Nm(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${uN[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${Ub(n.getHours())}:${Ub(n.getMinutes())}`}function Yp(e,t){const n=Nm(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const o=-r;if(o<Dh)return"due now";if(o<Fh)return`in ${Math.round(o/Dh)} min`;if(o<np)return`in ${Math.round(o/Fh)} h`;const c=Math.round(o/np);return c<7?`in ${c} ${c===1?"day":"days"}`:Wb(n,t)}if(r<Dh)return"just now";if(r<Fh)return`${Math.floor(r/Dh)} min ago`;if(r<np)return`${Math.floor(r/Fh)} h ago`;const i=Math.floor(r/np);return i===1?"yesterday":i<7?`${i} days ago`:Wb(n,t)}const $M=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),CM=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),EM=new Set("mp4 m4v webm mov ogv mkv".split(" ")),AM=new Set("mts cts".split(" ")),TM=new Set(["video/mp2t"]),MM=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function RM(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function Xp(e,t=""){const n=RM(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":$M.has(n)?"image":CM.has(n)?"audio":EM.has(n)?"video":cx(e)||AM.has(n)?"code":MM.has(n)?"text":r.startsWith("image/")&&r!=="image/svg+xml"?"image":r.startsWith("audio/")?"audio":r.startsWith("video/")&&!TM.has(r)?"video":r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function Jw(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function Lg(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 LM(e){const t=e.kind??Xp(e.name,e.contentType),n=Lg(e.sizeBytes),r=e.modified!==void 0?Yp(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(qe,{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:ux(e.modified),dateTime:new Date(Nm(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(qe,{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(qe,{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(IM,{kind:t,p:e})]})})]})}function IM({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(vh,{});case"audio":return t.url?s.jsx(Rg,{src:t.url,name:t.name}):s.jsx(vh,{});case"video":return t.url?s.jsx("video",{className:"af-file-viewer__image af-file-viewer__video",src:t.url,controls:!0,playsInline:!0,preload:"metadata","aria-label":t.name}):s.jsx(vh,{});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(vh,{});case"markdown":return t.renderMarkdown?s.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):s.jsx(tp,{text:n,language:""});case"json":{let r=n,i="";try{r=JSON.stringify(JSON.parse(n),null,2)}catch{i=t.partialNote?"":"Not valid JSON; shown as text."}return s.jsxs(s.Fragment,{children:[i?s.jsx("p",{className:"af-file-viewer__muted",children:i}):null,s.jsx(tp,{text:r,language:"json"})]})}case"code":return s.jsx(tp,{text:n,language:t.name});case"text":return s.jsx(tp,{text:n,language:"",lineNumbers:!1});default:return s.jsx(vh,{})}}function vh(){return s.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function zh(e){const t=p.useId(),n=`${e.id||t}-title`;return s.jsxs("section",{className:`af-settings-group${e.variant==="flat"?" af-settings-group--flat":""}${e.className?` ${e.className}`:""}`,"aria-labelledby":n,id:e.id,children:[s.jsxs("div",{className:"af-settings-group__head",children:[s.jsx("h3",{className:"af-settings-group__title",id:n,children:e.title}),e.aside?s.jsx("span",{className:"af-settings-group__aside",children:e.aside}):null]}),e.help?s.jsx("p",{className:"af-settings-group__help",children:e.help}):null,s.jsx("div",{className:"af-settings-group__rows",children:e.children})]})}function oc(e){const t=e.htmlFor?"label":"span";return s.jsxs("div",{className:`af-setting-row${e.stack?" af-setting-row--stack":""}${e.className?` ${e.className}`:""}`,"data-setting":e.setting,children:[s.jsxs("div",{className:"af-setting-row__label",children:[s.jsx(t,{className:"af-setting-row__name",...e.htmlFor?{htmlFor:e.htmlFor}:{},children:e.label}),e.help?s.jsx("span",{className:"af-setting-row__help",children:e.help}):null]}),e.children!==void 0||e.trailing?s.jsxs("div",{className:"af-setting-row__control",children:[e.children,e.trailing?s.jsx("span",{className:"af-setting-row__trailing",children:e.trailing}):null]}):null]})}function qb(e){const t=!!e.overrideSummary,n=p.useId(),r=t?`${e.overrideSummary}${e.overrideOwner?` — ${e.overrideOwner}`:""}`:`Gateway default${e.defaultSummary?` · ${e.defaultSummary}`:""}`;return s.jsxs("div",{className:"af-override","data-setting":e.setting,"data-overridden":t?"true":"false",children:[s.jsx(oc,{label:e.label,help:e.help,trailing:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"change","aria-expanded":e.open,"aria-controls":n,disabled:e.disabled,onClick:e.onToggle,children:e.open?"Done":"Change"}),t&&e.onReset?s.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"use-default",disabled:e.disabled,onClick:e.onReset,children:"Use gateway default"}):null]}),children:s.jsx("span",{className:"af-override__summary",title:r,children:r})}),s.jsx("div",{className:"af-override__editor",id:n,hidden:!e.open,children:e.open?e.children:null})]})}const qn={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."},ni=qn;function OM(e){return e==="any_except_denied"?ni.postureAnyExceptDenied:ni.postureAllowedOnly}function PM(e){return e==="any_except_denied"?ni.postureAnyExceptDeniedHelp:ni.postureAllowedOnlyHelp}function Vb(e){return e==="ro"?ni.accessRead:e==="deny"?ni.accessDenied:ni.accessReadWrite}function DM(e){return e==="gateway"?ni.gatewayHelp:e==="account"?ni.accountHelp:e==="session"?ni.sessionHelp:ni.runHelp}const Hb={deny:0,ro:1,rw:2},Ey=["rw","ro","deny"];function FM(e){if(e===null)return{allowed:[...Ey],reasons:{}};const t=e==="deny"?ni.capRefused:ni.capReadOnly,n=Ey.filter(i=>Hb[i]<=Hb[e]),r={};for(const i of Ey)n.includes(i)||(r[i]=t);return{allowed:n,reasons:r}}function zM(e,t){const{policy:n}=t,r=t.effective;if(e==="gateway"?typeof n.summary!="string":!r)throw new Error(e==="gateway"?"The gateway workspace policy has no summary line.":`A ${e}-level workspace chooser needs the gateway's effective workspaces.`);const i=e!=="gateway"&&n.configured===!1,o=t.can_edit===!1,c=new Map(((r==null?void 0:r.folders)??[]).map(y=>[y.path,y.cap])),l=r,d=i?l.folders.map(y=>({path:y.path,mode:y.mode})):n.folders,h=i?l.posture:n.posture,m=i?l.default_mode??n.default_mode:n.default_mode,_=!i&&!o,g=d.map(y=>{const x=e==="gateway"?null:c.get(y.path)??null,{allowed:k,reasons:v}=FM(x);return{path:y.path,mode:y.mode,cap:x,allowed:k,reasons:v,builtin:!1,editable:_}});if(e==="gateway")for(const y of n.builtin_refused??[])g.push({path:y,mode:"deny",cap:null,allowed:[],reasons:{},builtin:!0,editable:!1});return{level:e,posture:h,following:i,rows:g,everythingElse:h==="any_except_denied"?{mode:m,editable:_}:null,canAdd:_,gatewayLine:e==="gateway"?null:`${ni.gatewayPrefix} ${l.gateway_summary}`,summary:e==="gateway"?n.summary:l.summary,locked:o}}function BM(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function $m(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 UM(e,t,n,r){return $m(e,{...t,folders:t.folders.map(i=>i.path===n?{path:n,mode:r}:i)})}function WM(e,t,n){return $m(e,{...t,posture:n})}function qM(e,t,n){return $m(e,{...t,default_mode:n})}function VM(e,t,n,r){const i=String(n).trim();return $m(e,{...t,folders:[...t.folders,{path:i,mode:BM(e,t.posture)}]})}function HM(e,t,n){return $m(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function GM(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 KM(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function JM(e="me",t=Zh){return`${KM(t)}/workspace/effective/${encodeURIComponent(e)}`}const Gb=e=>e==="ro"||e==="rw"||e==="deny",YM=e=>e==="ro"||e==="rw",XM=e=>e==="allowed_only"||e==="any_except_denied",Kb="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function ZM(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(Kb);if(!(XM(t.posture)&&(YM(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"&&Gb(r.mode)&&Gb(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${Kb}`);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 nm(e,t="me",n=Zh){const r=JM(t,n);return async(i,o)=>ZM(await e(r,{method:"POST",body:o?{workspace:i,session:o}:{workspace:i}}))}function Ig(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;const t=e&&typeof e=="object"?e:{},n=t.detail;return n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:typeof t.message=="string"?t.message:""}function Jb(e){const t=Ig(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${ni.notSaved}`}const QM=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function eR(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 dN(e){rf();const t=e.idPrefix||"af-workspace",[n,r]=p.useState(null),[i,o]=p.useState({}),[c,l]=p.useState(null),[d,h]=p.useState(""),[m,_]=p.useState(null),g=String(e.unavailableReason||"").trim(),y=e.level,x=e.level==="run"?eR(e.value,e.effective):e.state,k=e.level==="run"?e.effective:e.state,v=m&&m.base===k?m.value:x,N=v?zM(y,v):null,$=I=>{if(e.level==="run"){const L=e,K=I.configured===!1?null:{posture:I.posture,default_mode:I.default_mode,folders:I.folders};return Promise.resolve(L.onChange(K))}return e.save(I)};async function C(I,L){if(n!==null||g)return!1;r(I),l(null),o(K=>{const H={...K};return delete H[I],H});try{const K=await $(L);return QM(K)&&_({base:k,value:K}),l(I),!0}catch(K){return o(H=>({...H,[I]:Jb(K)})),!1}finally{r(null)}}const S=I=>i[I]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:i[I]}):c===I?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:qn.saved}):null,D=(I,L)=>s.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":I,"data-af-tip":L,tabIndex:L?0:void 0,children:Vb(I)}),O=(I,L,K,H,z)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":I,"data-workspace":z,"data-access":L,children:K.map(ee=>{const B=!!ee.reason||!!g;return s.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":L===ee.value?"true":"false","aria-disabled":B?"true":void 0,"data-af-tip":ee.reason||void 0,"data-action":`${z}-${ee.value}`,onClick:()=>B||n!==null||ee.value===L?void 0:H(ee.value),children:ee.text},ee.value)})}),A=I=>{if(I.builtin)return D("deny",qn.builtinRefused);if(!I.editable||!v)return D(I.mode);const L=v.policy;return s.jsxs(s.Fragment,{children:[O(`${qn.accessLabel} ${I.path}`,I.mode,["rw","ro","deny"].map(K=>({value:K,text:Vb(K),reason:I.reasons[K]})),K=>void C(I.path,UM(y,L,I.path,K)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${qn.remove} ${I.path}`,"data-af-tip":`${qn.remove} ${I.path}`,"aria-disabled":g||n!==null?"true":void 0,onClick:()=>g||n!==null?void 0:void C(I.path,HM(y,L,I.path)),children:s.jsx(qe,{name:"x",size:16})})]})};async function P(I){if(!v||!N||!N.canAdd)return;const L=I.trim();L&&await C("add",VM(y,v.policy,L))&&h("")}async function W(){if(!e.choose||n!==null||g)return;let I;try{I=await e.choose()}catch(L){o(K=>({...K,add:Jb(L)}));return}I&&await P(I)}const J=N?N.rows.filter(I=>I.mode!=="deny"):[],G=N?N.rows.filter(I=>I.mode==="deny"):[],V=I=>s.jsxs("li",{className:"af-workspace__row","data-workspace":I.builtin?"builtin":"row","data-path":I.path,"data-mode":I.mode,"data-cap":I.cap??void 0,children:[s.jsx("code",{className:"af-workspace__path",children:I.path}),s.jsx("span",{className:"af-workspace__controls",children:A(I)}),S(I.path)]},`${I.builtin?"builtin:":""}${I.path}`),R=y==="account"?qn.followGateway:qn.useDefault,M=y==="account"?qn.followGatewayHelp:qn.useDefaultHelp;return s.jsx(zh,{id:t,className:`af-workspace af-workspace--${y}${e.className?` ${e.className}`:""}`,title:y==="gateway"?qn.gatewayTitle:qn.title,help:DM(y),children:e.loadError?s.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!N||!v?s.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:qn.loading}):s.jsxs("div",{className:"af-workspace__body","data-level":y,"data-following":N.following?"true":"false",children:[N.gatewayLine?s.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:N.gatewayLine}):null,g?s.jsx("p",{className:"af-workspace__note",id:`${t}-blocked`,"data-workspace":"blocked",children:g}):null,y!=="gateway"?s.jsxs("div",{className:"af-workspace__follow","data-workspace":"follow",children:[s.jsx(Fi,{variant:"row",label:R,description:M,checked:N.following,busy:n==="follow",unavailableReason:g||(N.locked?qn.locked:null),reasonVisible:!1,describedBy:g?`${t}-blocked`:void 0,action:y==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:I=>void C("follow",GM(v,I))}),S("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:OM(N.posture)}):O(qn.postureLabel,N.posture,[{value:"allowed_only",text:qn.postureAllowedOnly},{value:"any_except_denied",text:qn.postureAnyExceptDenied}],I=>void C("posture",WM(y,v.policy,I)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:PM(N.posture)}),S("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":qn.title,"data-workspace":"list",children:[J.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:qn.allowedTitle}):null,J.map(V),G.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:qn.deniedTitle}):null,G.map(V),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:qn.everythingElse}),s.jsx("span",{className:"af-workspace__controls",children:N.everythingElse.editable?O(`${qn.accessLabel} ${qn.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:qn.accessReadWrite},{value:"ro",text:qn.accessRead}],I=>void C("everything-else",qM(y,v.policy,I)),"workspace-default"):D(N.everythingElse.mode)}),S("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":qn.addPlaceholder,placeholder:qn.addPlaceholder,value:d,disabled:!!g||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:I=>h(I.target.value),onKeyDown:I=>{I.key==="Enter"?(I.preventDefault(),P(d)):I.key==="Escape"&&(I.preventDefault(),h(""),o(L=>{const K={...L};return delete K.add,K}))}}),s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!g||!d.trim()||n!==null,onClick:()=>void P(d),children:qn.add}),e.choose?s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!g||n!==null,onClick:()=>void W(),children:qn.choose}):null,S("add")]}):null]}),N.posture==="allowed_only"&&!J.length?s.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:qn.emptyAllowed}):null,y==="session"||y==="run"?s.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:qn.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 Ay=e=>`${Math.round(e*100)} %`,tR="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function nR(e){var O,A,P;const t=!!e.unavailableReason,n=e.outputSelectable??_S(),r=p.useId(),[i,o]=p.useState({devices:[],labelled:!0}),[c,l]=p.useState({text:"",tone:"info"}),d=p.useRef(!0);p.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const h=e.value,m=W=>e.onChange({...h,...W}),_=Kd(h.reply_volume),g=h.reply_muted===!0,y=e.showMute!==!1||g,x=e.listDevices||lS,k=p.useRef(x);k.current=x;const v=()=>{n&&k.current("audiooutput").then(W=>d.current&&o(W)).catch(()=>d.current&&o({devices:[],labelled:!1}))};p.useEffect(()=>{t||v()},[n,t,e.devicesKey]);const N=()=>{l({text:"Playing a short chime…",tone:"info"}),G2({deviceId:n&&h.output_device||"",volume:_}).then(()=>{if(!d.current)return;const W="Chime played. Heard nothing? Pick another output or raise the volume.";l({text:g?`${W} Replies are muted: unmute them to hear them.`:W,tone:"ok"})}).catch(W=>d.current&&l({text:`The speaker test failed: ${String((W==null?void 0:W.message)||W).replace(/\.$/,"")}.`,tone:"error"}))},$=h.output_device||"",C=[{value:"",label:"System default"},...i.devices.map(W=>({value:W.id,label:W.label})),...$&&!i.devices.some(W=>W.id===$)?[{value:$,label:"Saved speaker (not connected)"}]:[]],S=((O=e.labels)==null?void 0:O.device)||"Output device",D=((A=e.labels)==null?void 0:A.volume)||"Reply volume";return s.jsxs("div",{className:`af-voice-output${e.className?` ${e.className}`:""}`,"data-voice-output":!0,children:[s.jsx(oc,{label:S,setting:"output-device",help:n?void 0:tR,trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:t,onClick:N,children:((P=e.labels)==null?void 0:P.test)||"Test"}),children:s.jsx(Wr,{ariaLabel:S,placeholder:"System default",value:n?$:"",options:C,disabled:t||!n,searchable:!1,onOpen:v,onChange:W=>m({output_device:W})})}),c.text?s.jsx("p",{className:`af-voice-note af-voice-note--${c.tone}`,role:"status","data-voice-note":"speaker",children:c.text}):null,s.jsxs(oc,{label:D,setting:"reply-volume",htmlFor:r,trailing:y?s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"mute-replies",disabled:t,onClick:()=>m({reply_muted:!g}),children:g?"Unmute":"Mute"}):void 0,children:[s.jsx("input",{id:r,className:"af-voice-range",type:"range",min:0,max:100,step:5,value:Math.round(_*100),disabled:t,"aria-valuetext":g?`Muted (${Ay(_)})`:Ay(_),onChange:W=>m({reply_volume:Number(W.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value","data-voice-volume":g?"muted":"on",children:g?"Muted":Ay(_)})]})]})}function sR(e){const[t,n]=p.useState(0),r=e==null?void 0:e.subscribe_level;return p.useEffect(()=>{if(!r){n(0);return}return r(i=>n(Math.min(1,Math.max(0,Number(i)||0))))},[r]),t}function rR(e){const t=sR(e.level===void 0?e.source:null),n=Math.min(1,Math.max(0,e.level===void 0?t:Number(e.level)||0)),r=e.inline?"span":"div";return s.jsx(r,{className:`af-voice-meter${e.className?` ${e.className}`:""}`,"data-voice-meter":!0,"data-voice-meter-source":e.origin||"live",role:"meter","aria-label":e.label||"Microphone level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(n*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(n*100)}%`}})})}const Ty=e=>`${Math.round(e*100)} %`;function fN(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function iR(e){var G,V,R;const t=!!e.unavailableReason,n=p.useId(),[r,i]=p.useState({devices:[],labelled:!0}),[o,c]=p.useState(""),[l,d]=p.useState({phase:"idle",message:"",tone:"info"}),[h,m]=p.useState(0),_=p.useRef(!0);p.useEffect(()=>(_.current=!0,()=>{_.current=!1}),[]);const g=uS(),y=e.value,x=M=>e.onChange({...y,...M}),k=fN(y.input_gain),v=e.listDevices||lS,N=p.useRef(v);N.current=v;const $=()=>{N.current("audioinput").then(M=>_.current&&i(M)).catch(()=>_.current&&i({devices:[],labelled:!1}))};p.useEffect(()=>{t||$()},[t]);const C=()=>{c(""),H2().then(()=>{var M;$(),(M=e.onDevicesChanged)==null||M.call(e)}).catch(M=>_.current&&c(Hp(M)))},S=()=>{d({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),hS({deviceId:y.input_device||"",ms:3e3,gain:k,onLevel:M=>_.current&&m(M)}).then(async({blob:M,peak:I})=>{var L,K,H;if(_.current){if(I<fS){d({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}d({phase:"playing",message:"Playing it back…",tone:"info"}),await mS(M,{deviceId:((L=e.playOn)==null?void 0:L.deviceId)||"",volume:(K=e.playOn)==null?void 0:K.volume}),_.current&&(d({phase:"idle",message:`The microphone works (peak level ${Ty(I)}).`,tone:"ok"}),$(),(H=e.onDevicesChanged)==null||H.call(e))}}).catch(M=>_.current&&d({phase:"idle",message:Hp(M),tone:"error"}))},D=y.input_device||"",O=[{value:"",label:"System default"},...r.devices.map(M=>({value:M.id,label:M.label})),...D&&!r.devices.some(M=>M.id===D)?[{value:D,label:"Saved microphone (not connected)"}]:[]],A=l.phase!=="idle",P=l.phase==="recording",W=((G=e.labels)==null?void 0:G.device)||"Input device",J=((V=e.labels)==null?void 0:V.gain)||"Input level";return s.jsxs("div",{className:`af-voice-input${e.className?` ${e.className}`:""}`,"data-voice-input":!0,children:[s.jsx(oc,{label:W,setting:"input-device",trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:t||A,onClick:S,children:l.phase==="recording"?"Recording…":l.phase==="playing"?"Playing…":((R=e.labels)==null?void 0:R.test)||"Test"}),children:s.jsx(Wr,{ariaLabel:W,placeholder:"System default",value:D,options:O,disabled:t,searchable:!1,onOpen:$,onChange:M=>x({input_device:M})})}),s.jsx(rR,{source:P?null:e.levelSource,level:P?h:e.level,origin:P?"test":"live"}),l.message?s.jsx("p",{className:`af-voice-note af-voice-note--${l.tone}`,role:"status","data-voice-note":"microphone",children:l.message}):null,!r.labelled&&!t?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:C,children:"Show names"})]}):null,o?s.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:o}):null,g?s.jsxs(oc,{label:J,setting:"input-gain",htmlFor:n,help:"Raises a quiet microphone.",children:[s.jsx("input",{id:n,className:"af-voice-range",type:"range",min:50,max:150,step:10,value:Math.round(k*100),disabled:t,"aria-valuetext":Ty(k),onChange:M=>x({input_gain:Number(M.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:Ty(k)})]}):null]})}const oR=["provider","model","voice","profile","speed","quality_preset","instructions"];function aR(e){const t={};for(const n of oR){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function lR(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 cR=[{value:"",label:"Detect automatically"},...Object.keys(gS).map(e=>({value:e,label:_u(e)}))],uR=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function dR(e,t){const n=e.profile||e.voice||"",r=n?String(t||"").trim()||aA(n):"";return[e.provider,e.model,r].filter(Boolean).join(" · ")}function fR(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const hR=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],Yb=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 mR(e){var Te,Ve,_t,Qe,it,$t,ot,mt,et,Lt;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,r=e.rows||{},i=p.useRef(e.fetchCatalog);i.current=e.fetchCatalog;const o=p.useRef(e.fetchDefaults);o.current=e.fetchDefaults;const c=p.useRef(e.fetchLanguages);c.current=e.fetchLanguages;const[l,d]=p.useState({}),[h,m]=p.useState({value:null,failed:!1}),_=e.defaults!==void 0?{value:e.defaults,failed:!1}:h,g=e.defaults!==void 0,[y,x]=p.useState(""),[k,v]=p.useState(0),[N,$]=p.useState(null),C=e.outputSelectable??_S(),S=e.value,D=e.nested?"flat":"card",O=ce=>e.onChange({...S,...ce}),A=Kd(S.reply_volume),P=fN(S.input_gain),W=r.tts!==!1&&!e.ttsSlot,J=r.stt!==!1,G=W||J||!!e.ttsSlot,V=e.voiceLibrary||e.createVoice;p.useEffect(()=>{if(n)return;let ce=!0;return i.current().then(Se=>ce&&d(Se||{})).catch(()=>ce&&d({})),g||o.current().then(Se=>ce&&m({value:Se||{},failed:!1})).catch(()=>ce&&m({value:null,failed:!0})),()=>{ce=!1}},[n,g]);const R=S.profile||S.voice||"",[M,I]=p.useState({id:"",name:""}),L=y==="tts";p.useEffect(()=>{if(n||!R||!W)return;let ce=!0;return i.current(S.provider||void 0,S.model||void 0).then(Se=>ce&&I({id:R,name:wS(Se,R,S.provider||void 0)})).catch(()=>ce&&I({id:R,name:""})),()=>{ce=!1}},[n,R,S.provider,S.model,W,L]);const K=dR(S,M.id===R?M.name:""),H=S.stt_provider||((Ve=(Te=_.value)==null?void 0:Te.stt)!=null&&Ve.configured?String(_.value.stt.provider||""):""),z=!!e.fetchLanguages;p.useEffect(()=>{const ce=c.current;if(n||!ce||r.microphone===!1)return;let Se=!0;return ce("stt",H||void 0).then(He=>Se&&$(Array.isArray(He)?He.map(ne=>String(ne).toLowerCase()).filter(Boolean):[])).catch(()=>Se&&$(null)),()=>{Se=!1}},[n,z,H,r.microphone]);const ee=kb(_.value,"tts",_.failed),B=kb(_.value,"stt",_.failed),te=[(_t=_.value)==null?void 0:_t.tts,(Qe=_.value)==null?void 0:Qe.stt].map(ce=>ce&&!ce.configured?ce.note:"").filter(Boolean),se=[(it=_.value)==null?void 0:it.tts,($t=_.value)==null?void 0:$t.stt].map(ce=>{var Se;return ce&&ce.configured?String(((Se=ce.hint)==null?void 0:Se.sentence)||"").trim():""}).filter(Boolean),de=!!((mt=(ot=l.controls)==null?void 0:ot.quality_preset)!=null&&mt.supported),be={deviceId:C&&S.output_device||"",volume:A},Me=N&&N.length?[{value:"",label:"Detect automatically"},...N.map(ce=>({value:ce,label:_u(ce)}))]:[...cR],Ne=S.stt_language||"";Ne&&!Me.some(ce=>ce.value===Ne)&&Me.push({value:Ne,label:`${_u(Ne)} (saved)`});const ae=Fw(S.capture_mode??((et=e.captureDefaults)==null?void 0:et.capture_mode)),je=S.auto_send??((Lt=e.captureDefaults)==null?void 0:Lt.auto_send)??!1;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,G?s.jsxs(zh,{variant:D,title:"Engines",help:"Which engines speak and listen.",children:[e.ttsSlot?s.jsx("div",{className:"af-voice-section__tts-slot","data-voice-slot":"tts",children:e.ttsSlot}):null,W?s.jsx(qb,{label:"Text → speech",setting:"tts",defaultSummary:ee,overrideSummary:K,overrideOwner:t,open:y==="tts",onToggle:()=>x(y==="tts"?"":"tts"),onReset:()=>O({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(uA,{value:S,onChange:ce=>e.onChange({...S,...ce}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:V,previewVoice:e.previewVoice?(ce,Se,He)=>e.previewVoice({...S,...ce},Se,He):void 0,previewOn:be,recordFrom:{deviceId:S.input_device||"",gain:P}})}):null,J?s.jsx(qb,{label:"Speech → text",setting:"stt",defaultSummary:B,overrideSummary:fR(S),overrideOwner:t,open:y==="stt",onToggle:()=>x(y==="stt"?"":"stt"),onReset:()=>O({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(Xj,{value:{provider:S.stt_provider||"",model:S.stt_model||""},onChange:ce=>O({stt_provider:ce.provider,stt_model:ce.model}),fetchProviders:async()=>{const ce=await i.current();return Yb(ce.stt_providers).map(Se=>({name:Se}))},fetchModels:async ce=>{var He;const Se=await i.current(ce);return Yb(((He=Se.stt_models_by_provider)==null?void 0:He[ce])||Se.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}):null,_.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,te.map(ce=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:ce},ce)),se.map(ce=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:ce},ce))]}):null,r.output!==!1?s.jsx(zh,{variant:D,title:"Output",children:s.jsx(nR,{value:S,onChange:e.onChange,listDevices:e.listDevices,outputSelectable:C,showMute:r.mute===!0,unavailableReason:e.unavailableReason,devicesKey:k})}):null,r.microphone!==!1?s.jsxs(zh,{variant:D,title:"Microphone",children:[s.jsx(iR,{value:S,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:be,onDevicesChanged:()=>v(ce=>ce+1),unavailableReason:e.unavailableReason}),s.jsx(oc,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:s.jsx(Wr,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:Ne,options:Me,disabled:n,searchable:!1,onChange:ce=>O({stt_language:ce})})}),r.capture===!0?s.jsxs(s.Fragment,{children:[s.jsx(oc,{label:"Microphone button",setting:"capture-mode",children:s.jsx(Wr,{ariaLabel:"Microphone button",value:ae,options:uR,disabled:n,searchable:!1,onChange:ce=>O({capture_mode:ce==="toggle"?"toggle":"hold"})})}),s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"auto-send",children:s.jsx(Fi,{label:"Send what you say automatically",description:"Off: what you say lands in the message box for you to review.",variant:"row",checked:je,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ce=>O({auto_send:ce})})})]}):null]}):null,r.replies!==!1?s.jsxs(zh,{variant:D,title:"Replies",children:[s.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:s.jsx(Fi,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:S.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ce=>O({read_aloud:ce})})}),s.jsx(oc,{label:"Voice latency",setting:"latency",help:de?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:s.jsx(Wr,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:de&&S.quality_preset||"",options:hR,disabled:n||!de,searchable:!1,onChange:ce=>O({quality_preset:ce})})})]}):null]})}function Og(e){const t=String(e??"").trim();if(!t||!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return null;try{return JSON.parse(t)}catch{return null}}function _R(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function pR(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),r=String(e.ts||"").trim(),i=[t];return n&&i.push(n),r&&i.push(r),i.join(" · ")}function gR(e){return e.endsWith(`
68
+ `)?e:`${e}
69
+ `}function yR(e){return String(e||"").trimStart().startsWith("```")}function hN(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const i of e){const o=pR(i);r.push(`## ${o}`,"");const c=String(i.content||""),l=Og(c);l!==null&&!yR(c)?r.push("```json",_R(l).trimEnd(),"```",""):r.push(gR(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(`
70
+ `).trimEnd()}
71
+ `}async function il(e){var n;const t=String(e||"");if(!t)return!1;try{if(typeof navigator<"u"&&typeof((n=navigator.clipboard)==null?void 0:n.writeText)=="function")return await navigator.clipboard.writeText(t),!0}catch{}try{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-9999px",document.body.appendChild(r),r.select();const i=document.execCommand("copy")===!0;return document.body.removeChild(r),i}catch{return!1}}function mN(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),r=String(e.mime||"text/plain;charset=utf-8"),i=new Blob([n],{type:r}),o=URL.createObjectURL(i),c=document.createElement("a");c.href=o,c.download=t,document.body.appendChild(c),c.click(),c.remove(),window.setTimeout(()=>URL.revokeObjectURL(o),1e3)}const wR=3,vR=Number.MAX_SAFE_INTEGER;function _N(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pN(e){return Array.isArray(e)}function xR(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Id({kind:e,children:t}){return s.jsx("span",{className:`pc-json-token ${e}`,children:t})}function bR(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,i]=p.useState(!n||e.expansionMode==="unfolded");return p.useEffect(()=>{n&&i(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?s.jsxs("span",{className:`pc-json-string ${r?"open":"collapsed"}`,children:[s.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>i(o=>!o),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?s.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):s.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>i(!0),"aria-label":"Expand string value",children:[s.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),s.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):s.jsx(Id,{kind:"string",children:t})}function kR(e,t,n){return e===null?s.jsx(Id,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(bR,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?s.jsx(Id,{kind:"number",children:String(e)}):typeof e=="boolean"?s.jsx(Id,{kind:"boolean",children:e?"true":"false"}):s.jsx(Id,{kind:"string",children:JSON.stringify(String(e))})}function jR(e){return pN(e)?e.length===1?"1 item":`${e.length} items`:_N(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function gN(e){const{label:t,value:n,depth:r,collapseAfterDepth:i,expansionMode:o,expansionVersion:c,trailingComma:l}=e,d=r*14,h=_N(n),m=pN(n),_=h||m,g=r<i,[y,x]=p.useState(g);p.useEffect(()=>{x(g)},[g,c]);const k=t?s.jsxs(s.Fragment,{children:[s.jsx(Id,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!_)return s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[k,kR(n,o,c),l?",":""]});const v=m?"[":"{",N=m?"]":"}",$=jR(n),C=y?`${v}`:`${v}…${N}${$?` (${$})`:""}`,S=m?n.map((D,O)=>({key:String(O),label:void 0,value:D})):Object.entries(n).map(([D,O])=>({key:D,label:D,value:O}));return s.jsxs("details",{className:"pc-json-viewer__details",open:y,onToggle:D=>x(D.currentTarget.open),children:[s.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:d},children:[k,s.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:y?"▾":"▸"}),s.jsx("span",{className:"pc-json-viewer__punct",children:C}),!y&&l?s.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),y?s.jsx("div",{className:"pc-json-viewer__children",children:S.length===0?s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),l?",":""]}):s.jsxs(s.Fragment,{children:[S.map((D,O)=>{const A=O===S.length-1;return s.jsx(gN,{label:D.label,value:D.value,depth:r+1,collapseAfterDepth:i,expansionMode:o,expansionVersion:c,trailingComma:!A},`${r}:${t||"root"}:${D.key}`)}),s.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:d},children:[s.jsx("span",{className:"pc-json-viewer__punct",children:N}),l?",":""]})]})}):null]})}function SR(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 hr(e){const{value:t,className:n,showCopy:r=!0}=e,[i,o]=p.useState({mode:"folded",version:0}),[c,l]=p.useState("idle"),d=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):wR,h=i.mode==="unfolded"?vR:d,m=p.useMemo(()=>typeof t=="string"?SR(t):t,[t]),_=p.useMemo(()=>xR(t),[t]),g=["pc-json-viewer",n].filter(Boolean).join(" ");p.useEffect(()=>{o(x=>({mode:"folded",version:x.version+1}))},[m]);const y=()=>{o(x=>({mode:x.mode==="unfolded"?"folded":"unfolded",version:x.version+1}))};return s.jsxs("div",{className:g,children:[s.jsxs("div",{className:"pc-json-viewer__toolbar",children:[s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:y,"aria-expanded":i.mode==="unfolded",children:i.mode==="unfolded"?"Fold all":"Unfold all"}),r?s.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void il(_).then(x=>{l(x?"copied":"failed"),window.setTimeout(()=>l("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(gN,{value:m,depth:0,collapseAfterDepth:h,expansionMode:i.mode,expansionVersion:i.version,trailingComma:!1})})]})}function NR({code:e,lang:t}){const[n,r]=p.useState("idle"),i=p.useRef(null);p.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]);const o=cN(e,cx(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 il(e);r(c?"copied":"failed"),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r("idle"),900)},children:s.jsx(qe,{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:o.map((c,l)=>c.kind==="plain"?s.jsx(Ae.Fragment,{children:c.text},l):s.jsx("span",{className:`af-code__${c.kind}`,children:c.text},l))})})]})}function xh(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],i=n.toLowerCase();let o=0;for(;o<n.length;){let c=-1,l="";for(let m=0;m<t.needlesLower.length;m++){const _=t.needlesLower[m];if(!_)continue;const g=i.indexOf(_,o);if(g===-1)continue;const y=t.needles[m]||"";y&&(c===-1||g<c||g===c&&y.length>l.length)&&(c=g,l=y)}if(c===-1||!l){r.push(n.slice(o));break}c>o&&r.push(n.slice(o,c));const d=t.hits===0&&t.id?t.id:void 0,h=n.slice(c,c+l.length);r.push(s.jsx("span",{id:d,className:t.className,children:h},`hl:${t.hits}`)),t.hits+=1,o=c+l.length}return r}function yN(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Yw="http://same-origin.invalid/";function $R(e){try{const t=new URL(e,Yw);return t.protocol==="http:"&&t.origin===new URL(Yw).origin}catch{return!1}}function wN(e){const t=String(e||"").trim();return yN(t)??(t&&$R(t)?t:void 0)}let au=null;function CR(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??Yw;let i,o;try{i=new URL(r).origin,o=new URL(t,r)}catch{return!1}return o.protocol!=="http:"&&o.protocol!=="https:"?!1:o.origin===i}function vN(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 Xb(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function Qa(e,t){const n=[],r=String(e??"");let i=0,o="";const c=()=>{if(o){for(const l of xh(o,t))n.push(l);o=""}};for(;i<r.length;){const l=r[i];if(l==="!"&&r[i+1]==="["){const d=r.indexOf("]",i+2);if(d!==-1&&r[d+1]==="("){const h=r.indexOf(")",d+2);if(h!==-1){const m=r.slice(i+2,d),_=wN(r.slice(d+2,h));if(_&&au&&!au(_)){c(),n.push(vN(`img:${i}`,_,m)),i=h+1;continue}if(_){c(),n.push(s.jsxs("span",{className:"pc-md_image_inline",children:[s.jsx("img",{className:"pc-md_img",src:_,alt:m,loading:"lazy"}),m?s.jsx("span",{className:"pc-md_img_caption",children:t?xh(m,t):m}):null]},`img:${i}`)),i=h+1;continue}}}}if(l==="["){const d=r.indexOf("]",i+1);if(d!==-1&&r[d+1]==="("){const h=r.indexOf(")",d+2);if(h!==-1){const m=r.slice(i+1,d),_=yN(r.slice(d+2,h));if(_){c(),n.push(s.jsx("a",{className:"pc-md_link",href:_,target:_.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:Qa(m,t)},`link:${i}`)),i=h+1;continue}}}}if(l==="`"){const d=r.indexOf("`",i+1);if(d!==-1){c();const h=r.slice(i+1,d);n.push(s.jsx("code",{children:t?xh(h,t):h},`code:${i}`)),i=d+1;continue}}if(l==="_"&&!Xb(r[i-1])){const d=r[i+1]==="_"?"__":"_",h=d.length;if(r[i+h]&&!/\s/.test(r[i+h])&&r[i+h]!=="_"){let m=r.indexOf(d,i+h);for(;m!==-1&&(/\s/.test(r[m-1]||" ")||Xb(r[m+h])||h===1&&r[m+1]==="_");)m=r.indexOf(d,m+1);if(m!==-1&&m>i+h){c();const _=r.slice(i+h,m),g=Qa(_,t);n.push(h===2?s.jsx("strong",{children:g},`ubold:${i}`):s.jsx("em",{children:g},`uem:${i}`)),i=m+h;continue}}}if(l==="*"&&r[i+1]==="*"){const d=r.indexOf("**",i+2);if(d!==-1){c();const h=r.slice(i+2,d);n.push(s.jsx("strong",{children:t?xh(h,t):h},`bold:${i}`)),i=d+2;continue}}if(l==="*"&&r[i+1]!=="*"){const d=r.indexOf("*",i+1);if(d!==-1){c();const h=r.slice(i+1,d);n.push(s.jsx("em",{children:t?xh(h,t):h},`em:${i}`)),i=d+1;continue}}o+=l,i+=1}return c(),n}function ER(e){return String(e??"").replace(/\r\n/g,`
72
+ `).replace(/\r/g,`
73
+ `).split(`
74
+ `)}function Ap(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 AR(e){const t=[];for(const i of e){const o=Ap(i);o?t.push(o):t.length>0&&i.trim()&&(t[t.length-1].content+=` ${i.trim()}`)}const n=[],r=[];for(const i of t){for(;r.length>0&&i.indent<r[r.length-1].indent;)r.pop();let o=r.length>0?r[r.length-1]:null;if(o&&i.indent>o.indent){const c=o.node.items,l=c[c.length-1];if(l){const d={ordered:i.ordered,start:i.start,items:[]};l.children.push(d),r.push({indent:i.indent,node:d}),o=r[r.length-1]}}else if(o&&o.node.ordered!==i.ordered){r.pop();const c=r.length>0?r[r.length-1]:null,l={ordered:i.ordered,start:i.start,items:[]};if(c){const d=c.node.items,h=d[d.length-1];h?h.children.push(l):c.node.items.push({content:"",children:[l]})}else n.push(l);r.push({indent:i.indent,node:l}),o=r[r.length-1]}if(!o){const c={ordered:i.ordered,start:i.start,items:[]};n.push(c),r.push({indent:i.indent,node:c}),o=r[r.length-1]}o.node.items.push({content:i.content,children:[]})}return n}function xN(e,t,n){const r=e.items.map((i,o)=>s.jsxs("li",{children:[Qa(i.content,t),i.children.map((c,l)=>xN(c,t,`${n}:${o}:${l}`))]},`${n}:li:${o}`));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 TR(e,t,n){return AR(e).map((r,i)=>xN(r,t,`${n}:${i}`))}function Zb(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 Qb(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 e0=/^(#{1,5})\s+(.*)$/;function t0(e){return e.trim().startsWith("```")}function n0(e){return e.trimStart().startsWith(">")}function Ni(e){const t=au;au=e.images==="link"?e.inlineImage||CR:null;try{return MR(e)}finally{au=t}}function MR({text:e,className:t,highlight:n,highlights:r,highlightClassName:i,highlightId:o}){const c=ER(e),l=[],d=[];Array.isArray(r)&&d.push(...r),typeof n=="string"&&n.trim()&&d.push(n);const h=Array.from(new Set(d.map(y=>String(y??"").trim()).filter(Boolean))).filter(y=>y.length>=4),m=h.length?{needles:h,needlesLower:h.map(y=>y.toLowerCase()),className:i||"pc-md_hl",id:o,hits:0}:null;let _=0;for(;_<c.length;){const y=String(c[_]??"");if(!y.trim()){_+=1;continue}const x=y.trim();if(/^([-_*])(\s*\1){2,}$/.test(x)){l.push(s.jsx("hr",{className:"pc-md_hr"},`hr:${_}`)),_+=1;continue}const k=y.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(k){const $=wN(k[2]||"");if($&&au&&!au($)){l.push(s.jsx("p",{className:"pc-md_p",children:vN(`img:${_}`,$,k[1]||"")},`p:${_}`)),_+=1;continue}if($){const C=k[1]||"";l.push(s.jsxs("figure",{className:"pc-md_figure",children:[s.jsx("img",{className:"pc-md_img",src:$,alt:C,loading:"lazy"}),C?s.jsx("figcaption",{children:Qa(C,m)}):null]},`figure:${_}`)),_+=1;continue}}if(t0(y)){const C=y.trim().replace(/```/g,"").trim(),S=[];for(_+=1;_<c.length&&!String(c[_]??"").trim().startsWith("```");)S.push(String(c[_]??"")),_+=1;_<c.length&&(_+=1);const D=S.join(`
75
+ `);l.push(s.jsx(NR,{code:D,lang:C},`pre:${_}`));continue}const v=y.match(e0);if(v){const $=v[1].length,C=v[2]||"",S=Qa(C,m);$===1?l.push(s.jsx("h1",{children:S},`h1:${_}`)):$===2?l.push(s.jsx("h2",{children:S},`h2:${_}`)):$===3?l.push(s.jsx("h3",{children:S},`h3:${_}`)):$===4?l.push(s.jsx("h4",{children:S},`h4:${_}`)):l.push(s.jsx("h5",{children:S},`h5:${_}`)),_+=1;continue}if(n0(y)){const $=[];for(;_<c.length&&String(c[_]??"").trimStart().startsWith(">");){const S=String(c[_]??"").trimStart();$.push(S.replace(/^>\s?/,"")),_+=1}l.push(s.jsx("blockquote",{className:"pc-md_quote",children:$.map((C,S)=>s.jsxs(Ae.Fragment,{children:[Qa(C,m),S<$.length-1?s.jsx("br",{}):null]},`q:${_}:${S}`))},`quote:${_}`));continue}if(y.includes("|")&&_+1<c.length&&Qb(String(c[_+1]??""))){const $=Zb(y),C=Math.max(1,$.length),S=[];for(_+=2;_<c.length;){const D=String(c[_]??"");if(!D.trim()||!D.includes("|"))break;const O=Zb(D),A=[];for(let P=0;P<C;P++)A.push(O[P]??"");S.push(A),_+=1}l.push(s.jsx("div",{className:"pc-md_table_wrap",children:s.jsxs("table",{className:"pc-md_table",children:[s.jsx("thead",{children:s.jsx("tr",{children:$.slice(0,C).map((D,O)=>s.jsx("th",{children:Qa(D,m)},`th:${_}:${O}`))})}),s.jsx("tbody",{children:S.map((D,O)=>s.jsx("tr",{children:D.map((A,P)=>s.jsx("td",{children:Qa(A,m)},`td:${_}:${O}:${P}`))},`tr:${_}:${O}`))})]})},`table:${_}`));continue}if(Ap(y)){const $=[];for(;_<c.length;){const C=String(c[_]??"");if(!C.trim()||C.trimStart().startsWith("```"))break;if(Ap(C)||/^\s{2,}\S/.test(C)){$.push(C),_+=1;continue}break}l.push(s.jsx(Ae.Fragment,{children:TR($,m,`list:${_}`)},`list:${_}`));continue}const N=[];for(;_<c.length&&String(c[_]??"").trim()&&!(N.length>0&&Ap(String(c[_]??"")));){const $=String(c[_]??"");if(N.length>0&&(e0.test($)||t0($)||n0($))||N.length>0&&$.includes("|")&&_+1<c.length&&Qb(String(c[_+1]??"")))break;N.push($),_+=1}l.push(s.jsx("p",{className:"pc-md_p",children:N.map(($,C)=>s.jsxs(Ae.Fragment,{children:[Qa($,m),C<N.length-1?s.jsx("br",{}):null]},`pl:${_}:${C}`))},`p:${_}`))}const g=["pc-md",t].filter(Boolean).join(" ");return s.jsx("div",{className:g,children:l})}function bN(e){const t=String(e.text??""),n=p.useMemo(()=>Og(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?s.jsx("div",{className:r,children:s.jsx(hr,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?s.jsx("div",{className:r,children:e.renderMarkdown(t)}):s.jsx("div",{className:r,children:s.jsx(Ni,{text:t,images:e.images,inlineImage:e.inlineImage})})}const RR=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),LR=new Set(["application/pdf","application/json","text/plain","text/markdown","text/csv","text/tab-separated-values","text/x-python","text/javascript","application/javascript","text/css","text/x-c","text/x-shellscript","text/x-typescript","image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","video/mp4","video/webm","video/quicktime","audio/mpeg","audio/mp4","audio/aac","audio/wav","audio/x-wav","audio/ogg","audio/webm","audio/flac"]);function kN(e){const t=String(e??"");if(!t.trim())return!1;try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/",r=new URL(t,n).protocol;return r==="blob:"||r==="data:"}catch{return!0}}function IR(e,t){const n=String(t||"").split("/").pop()||"",r=n.lastIndexOf(".");if(r>0&&RR.has(n.slice(r+1).toLowerCase()))return!1;const i=String(e||"").split(";",1)[0].trim().toLowerCase();return!i||i==="text/html"||i.includes("xml")?!1:LR.has(i)}function OR(e){const t=n=>!!n&&(!kN(n)||IR(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}const s0=1024*1024,PR="1 MiB",DR=25*1024*1024,jN=(e,t)=>`${wt(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function FR(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 zR(e,t,n){var h;const r=new TextDecoder;let i="",o=0;const c=(h=e.body)==null?void 0:h.getReader();if(c){for(;o<t;){const{done:m,value:_}=await c.read();if(m)break;const g=_.subarray(0,t-o);o+=g.length,i+=r.decode(g,{stream:!0})}await c.cancel().catch(()=>{})}else i=(await e.text()).slice(0,t),o=i.length;const l=FR(e)??n,d=l!==void 0?l>o:o>=t;return{text:i,received:o,total:l,partial:d}}function BR(e){return`Showing the first ${PR} of ${e!==void 0?Lg(e):"a file of unknown size"}; download for the rest.`}function UR(e){try{return decodeURIComponent(e)}catch{return e}}function WR(e,t,n){const r=`${wt(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,i=n.split("/").slice(0,-1),o=d=>{if(/^[a-z][a-z0-9+.-]*:/i.test(d)||d.startsWith("/")||d.startsWith("#"))return null;const h=[...i];for(const m of d.split(/[?#]/,1)[0].split("/"))if(!(!m||m==="."))if(m===".."){if(!h.length)return null;h.pop()}else h.push(UR(m));return h.length?jN(t,h.join("/")):null},c=d=>{let h="",m=0;for(;m<d.length;){if(d[m]==="!"&&d[m+1]==="["){const _=d.indexOf("]",m+2);if(_!==-1&&d[_+1]==="("){const g=d.indexOf(")",_+2);if(g!==-1){const y=d.slice(m+2,_),x=d.slice(_+2,g).trim(),k=x.startsWith(r)?x:o(x);h+=k?`![${y}](${k})`:`[image: ${y||x}](${x})`,m=g+1;continue}}}h+=d[m],m+=1}return h};let l=!1;return e.split(`
76
+ `).map(d=>/^\s*(```|~~~)/.test(d)?(l=!l,d):l?d:c(d)).join(`
77
+ `)}function qR(e,t,n,r){const[i,o]=p.useState({status:"idle"});return p.useEffect(()=>{if(!n||!t){o({status:"idle"});return}const c=new AbortController;let l="";const d=Xp(n.name);if(d==="binary"){o({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((d==="image"||d==="audio"||d==="video"||d==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>DR){o({status:"error",kind:d,message:`Too large to preview (${Lg(n.size_bytes)}); use Download.`});return}o({status:"loading",kind:d});const h=Jw(d);return(async()=>{var m;try{const _=await e(jN(t,n.path),{signal:c.signal,...h?{headers:{Range:`bytes=0-${s0-1}`}}:{}});if(!_.ok)throw new Error(`Preview failed (HTTP ${_.status}): ${await _.text().catch(()=>"")||_.statusText||"no reason given"}`);const g=_.headers.get("content-type")||"",y=Xp(n.name,g);if(Jw(y)){const x=await zR(_,s0,n.size_bytes);if(c.signal.aborted)return;o({status:"ready",kind:y,contentType:g,text:y==="markdown"?WR(x.text,t,n.path):x.text,partial:x.partial,total:x.total});return}if(y==="image"||y==="audio"||y==="video"||y==="pdf"){const x=await _.blob();if(c.signal.aborted)return;l=URL.createObjectURL(x.type?x:new Blob([x],{type:y==="pdf"?"application/pdf":g})),o({status:"ready",kind:y,contentType:g,url:l,partial:!1});return}await((m=_.body)==null?void 0:m.cancel().catch(()=>{})),c.signal.aborted||o({status:"ready",kind:"binary",contentType:g,partial:!1})}catch(_){c.signal.aborted||o({status:"error",kind:d,message:String((_==null?void 0:_.message)||_)})}})(),()=>{c.abort(),l&&URL.revokeObjectURL(l)}},[e,t,n==null?void 0:n.path,n==null?void 0:n.name,n==null?void 0:n.size_bytes,r]),i}function SN(e){const{markdownImages:t,inlineImage:n,renderMarkdown:r,...i}=e;return s.jsx(LM,{...i,nowMs:e.nowMs??Date.now(),renderMarkdown:r||(o=>s.jsx(Ni,{text:o,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}function VR(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:BR(e.total)}:{}}}function Bh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zl(e){return typeof e=="string"?e.trim():""}function HR(e){var i;const t=Bh(e);if(!t)return null;const n=Bh(t.sandbox);if(n&&Zl(n.kind))return n;const r=Bh((i=Bh(t.output))==null?void 0:i.sandbox);return r&&Zl(r.kind)?r:null}function Xw(e){const t=HR(e);if(!t)return null;const n=Zl(t.kind),r=Zl(t.label)||n,i=Number.isFinite(Number(t.builtin_refused))?Math.max(0,Math.trunc(Number(t.builtin_refused))):0;if(n==="none")return{state:"refused",kind:n,label:r,line:`Sandbox: ${r} — refused`,rows:[],builtinRefused:0};const o=[],c=Zl(t.private_workspace);c&&o.push({path:c,mode:"Read & write",private:!0});for(const d of Array.isArray(t.allowed)?t.allowed:[]){const h=Bh(d),m=Zl(h==null?void 0:h.path);m&&o.push({path:m,mode:Zl(h==null?void 0:h.mode)==="ro"?"Read-only":"Read & write"})}for(const d of Array.isArray(t.refused)?t.refused:[]){const h=Zl(d);h&&o.push({path:h,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:r,line:`Sandbox: ${r}`,rows:[],builtinRefused:0};const l=o.length;return{state:"sandboxed",kind:n,label:r,line:`Sandbox: ${r} · ${l} ${l===1?"workspace":"workspaces"} enforced`,rows:o,builtinRefused:i}}function NN({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}const My=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,ki=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"";function GR(e){const t=ki(e==null?void 0:e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=My(e==null?void 0:e.policy),r=My(n==null?void 0:n.set_by),i=ki(r==null?void 0:r.user_id)||ki(r==null?void 0:r.client),o=typeof(n==null?void 0:n.revision)=="number"?n.revision:void 0,c={decision:t,...ki(e==null?void 0:e.source)?{source:ki(e==null?void 0:e.source)}:{},...o!==void 0?{revision:o}:{},...i?{setBy:i}:{},...ki(n==null?void 0:n.set_at)?{setAt:ki(n==null?void 0:n.set_at)}:{}},l=(Array.isArray(e==null?void 0:e.tool_calls)?e.tool_calls:[]).map(d=>My(d)).filter(d=>!!(d&&ki(d.call_id))).map(d=>({callId:ki(d.call_id),name:ki(d.name),...ki(d.matched)?{matched:ki(d.matched)}:{}}));return l.length?{provenance:c,calls:l}:null}function Zp(e){if(e.decision==="denied")return"Denied by this chat's policy";const t=e.setAt?ux(e.setAt):"",r=[e.setBy?`set by ${e.setBy}`:"",t?`at ${t}`:""].filter(Boolean).join(" ");return`Allowed by this chat's policy${r?` (${r})`:""}`}function r0(e){const t=new Map;for(const n of e||[]){const r=ki(n==null?void 0:n.name);if(!r)continue;const i=ki(n==null?void 0:n.reason).replace(/_/g," ")||"not stored";t.set(i,[...t.get(i)||[],r])}return t.size?`Not covered: ${[...t].map(([n,r])=>`${r.join(", ")} (${n})`).join("; ")}`:""}const Cr="not reported",ei=e=>e===void 0?Cr:Math.round(e).toLocaleString(),zr=e=>{if(e===void 0)return Cr;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`},$N=e=>e===void 0?Cr:`${Math.round(e).toLocaleString()} tok/s`,KR=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",lu=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,JR=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function YR(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 Qp(e){const t=[],n=(e.models||[]).map(JR),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 XR(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:ei(e.inputTokens)},{label:"Output",value:ei(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:ei(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:ei(e.totalTokens)}),n.push({heading:`Usage · ${lu(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const o=e.cachedTokens||0,c=e.fedTokens||0,l=[{label:"Reused from cache",value:`${ei(o)}${o+c?` (${KR(o,o+c)})`:""}`},{label:"Newly processed",value:ei(e.fedTokens)},{label:"Outcome",value:YR(t.map(d=>d.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Cr},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Cr}];e.measuredCacheCalls!==e.llmCalls&&l.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:l})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Cr}]});const i=t.filter(o=>o.inputTokens!==void 0);return i.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${ei(i[0].inputTokens)} tokens`}]}):i.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${ei(i[0].inputTokens)} → ${ei(i[i.length-1].inputTokens)} tokens`}],note:"Each call re-sends the conversation, so the input total counts the context once per call."}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Input","Cached","New","Output","Cache"],rows:t.map((o,c)=>[String(c+1),ei(o.inputTokens),o.cachedTokens===void 0?"—":ei(o.cachedTokens),o.fedTokens===void 0?"—":ei(o.fedTokens),ei(o.outputTokens),o.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Cr:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:Qp(e)}}function sp(e,t,n,r){if(e===void 0)return Cr;const i=[zr(e)];return t!==void 0&&i.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${$N(n)}`:""}`),i.join(" · ")}function ZR(e){var h,m,_;const t=e.modelCalls||[],n=[],r=e.durationMs,i=[{label:"Wall clock",value:zr(r)}];if(i.push({label:"Model",value:e.genTimeMs===void 0?Cr:`${zr(e.genTimeMs)} · ${lu(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),i.push({label:"Tools",value:e.toolTimeMs!==void 0?`${zr(e.toolTimeMs)} · ${lu(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Cr:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const g=r-e.genTimeMs-(e.toolTimeMs||0);i.push({label:"Orchestration",value:g>=0?zr(g):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:i});const o=[],c=e.ttftCalls||0,l=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?o.push({label:c&&c===l?"Prefill (TTFT)":"Prefill",value:sp(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:c===l?"measured time to first token":c?`TTFT measured on ${c} of ${l}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?o.push({label:"Prefill",value:sp(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?o.push({label:"Prefill",value:`${zr(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${$N(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):o.push({label:"Prefill",value:Cr}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&o.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),o.push({label:"Generation",value:e.generationPhaseMs!==void 0?sp(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):sp(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&o.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:o});const d=e.speculation;if(d){const g=(d.draftKinds||[]).map(x=>x.toUpperCase()).join(", "),y=[{label:"Mode",value:`${d.used?"on":"off"}${g?` · ${g}`:""}${(h=d.modes)!=null&&h.length?` (${d.modes.join(", ")})`:""}`,hint:d.calls!==e.llmCalls||d.used!==d.calls?`used on ${d.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:d.acceptanceRate===void 0?Cr:`${Math.round(d.acceptanceRate*100)}% · ${ei(d.acceptedTokens)} of ${ei(d.draftedTokens)} drafted`}];((m=d.draftLengths)!=null&&m.length||d.rounds!==void 0)&&y.push({label:"Draft length",value:`${(_=d.draftLengths)!=null&&_.length?`${d.draftLengths.join("/")} tok/round`:Cr}${d.rounds!==void 0?` · ${d.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:y})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${zr(e.toolTimeMs)} · ${lu(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${zr(e.slowestToolBatch.ms)} · ${CN(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((g,y)=>[String(y+1),g.promptMs===void 0?"—":`${zr(g.promptMs)}${g.promptSource==="rate"?"*":""}`,g.promptNewTokensPerSecond===void 0?"—":Math.round(g.promptNewTokensPerSecond).toLocaleString(),g.generationMs===void 0?"—":zr(g.generationMs),g.generationTokensPerSecond===void 0?"—":Math.round(g.generationTokensPerSecond).toLocaleString(),g.cacheOutcome||"—"])},note:t.some(g=>g.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?Cr:`${zr(r)} wall clock`,sections:n,footer:Qp(e)}}function CN(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${lu(e.calls,"call")} (${e.tools.join(", ")})`}function QR(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:Qp(e)};const r=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&r.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&r.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:r});const i=Object.entries(e.toolBreakdown||{}).sort((l,d)=>d[1].calls-l[1].calls||l[0].localeCompare(d[0]));i.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:i.map(([l,d])=>[l,d.calls.toLocaleString(),d.failed.toLocaleString(),d.ms!==void 0?`${zr(d.ms)}${d.sharedBatches?" +shared":""}`:d.sharedBatches?"shared":Cr])},note:i.some(([,l])=>l.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const o=i.filter(([,l])=>l.errors&&Object.keys(l.errors).length);o.length&&t.push({heading:"Failures",rows:o.map(([l,d])=>({label:l,value:Object.entries(d.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?Cr:`${zr(e.toolTimeMs)} · ${lu(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&c.push({label:"Slowest batch",value:`${zr(e.slowestToolBatch.ms)} · ${CN(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:`${lu(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:Qp(e)}}function Ry(e,t){return e==="tokens"?XR(t):e==="time"?ZR(t):QR(t)}function eL(e){const t=e.detail;return s.jsxs("div",{ref:e.panelRef,id:e.id,role:"tooltip",className:`pc-stat-detail pc-stat-detail--${t.kind}`,style:e.style,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,children:[s.jsxs("div",{className:"pc-stat-detail-head",children:[s.jsx("span",{className:"pc-stat-detail-title",children:t.title}),s.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var r;return s.jsxs("div",{className:"pc-stat-detail-section",children:[s.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(r=n.rows)!=null&&r.length?s.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(i=>s.jsxs(Ae.Fragment,{children:[s.jsx("dt",{children:i.label}),s.jsxs("dd",{children:[s.jsx("span",{className:i.value===Cr?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:i.value}),i.hint?s.jsx("span",{className:"pc-stat-detail-hint",children:i.hint}):null]})]},i.label))}):null,n.table?s.jsxs("table",{className:"pc-stat-detail-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:n.table.columns.map(i=>s.jsx("th",{scope:"col",children:i},i))})}),s.jsx("tbody",{children:n.table.rows.map((i,o)=>s.jsx("tr",{children:i.map((c,l)=>s.jsx("td",{children:c},l))},o))})]}):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 Ja=8;function tL(e){const[t,n]=p.useState(!!e.defaultOpen),[r,i]=p.useState(null),o=p.useRef(null),c=p.useRef(null),l=p.useRef(null),d=`pc-stat-${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,h=p.useCallback(()=>{l.current!==null&&window.clearTimeout(l.current),l.current=null},[]),m=p.useCallback(()=>{h(),n(!0)},[h]),_=p.useCallback(()=>{h(),l.current=window.setTimeout(()=>n(!1),120)},[h]);p.useEffect(()=>h,[h]),p.useLayoutEffect(()=>{if(!t){i(null);return}const k=()=>{const v=o.current,N=c.current;if(!v||!N)return;const $=v.getBoundingClientRect(),C=N.offsetWidth,S=N.offsetHeight,D=window.innerWidth,O=window.innerHeight,A=$.top-Ja-S,P=$.bottom+Ja,W=A>=Ja?A:P+S<=O-Ja?P:Math.max(Ja,O-Ja-S),J=Math.min(Math.max(Ja,$.left),Math.max(Ja,D-Ja-C));i({top:W,left:J})};return k(),window.addEventListener("resize",k),window.addEventListener("scroll",k,!0),()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k,!0)}},[t]),p.useEffect(()=>{if(!t)return;const k=v=>{v.key==="Escape"&&n(!1)};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]);const g=typeof e.onClick=="function",y=g?"button":"span",x=t?s.jsx(eL,{detail:e.detail,id:d,panelRef:c,onMouseEnter:h,onMouseLeave:_,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(y,{ref:o,...g?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",g?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?d:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:m,onMouseLeave:_,onFocus:m,onBlur:()=>n(!1),onKeyDown:k=>{k.key==="Escape"&&n(!1)},onClick:g?()=>{var k;return(k=e.onClick)==null?void 0:k.call(e)}:void 0,children:[e.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),x&&typeof document<"u"?jg.createPortal(x,document.body):x]})}function EN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function nL(e){const t=EN(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),i=["command","query","url","file_path","path","pattern","name"].map(o=>n.find(([c])=>c===o)).find(Boolean)||n[0];return i?{label:i[0].replace(/_/g," "),value:typeof i[1]=="string"?i[1]:JSON.stringify(i[1])??""}:{label:"",value:""}}function AN({tool:e,showCopy:t=!0}){const[n,r]=p.useState(!1),i=EN(e.arguments),o=nL(e.arguments),c=["file path","path"].includes(o.label)&&o.value.length>60?`${o.value.split(/[\\/]/).pop()} · ${o.value.slice(0,24)}…`:o.value,l=e.error&&/^File ['"].+['"] does not exist\.?$/.test(e.error)?"File not found. Expand for the exact path.":e.error&&e.error.length>180?`${e.error.slice(0,100)}…${e.error.slice(-70)}`:e.error,d={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},h=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,m=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i):null;return s.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[s.jsxs("summary",{className:"pc-tool-activity__summary",children:[s.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:s.jsx(qe,{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:o.value,children:o.value?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pc-tool-activity__key",children:o.label}),c]}):"No parameters"}),s.jsx("span",{className:"pc-tool-activity__status",children:d[e.status]}),e.policy?s.jsx("span",{className:"pc-tool-activity__policy","data-policy":e.policy.decision,title:Zp(e.policy),children:e.policy.decision==="denied"?"Denied by this chat's policy":"Allowed by this chat's policy"}):null,Number.isFinite(h)&&h>=0?s.jsxs("span",{className:"pc-tool-activity__duration","data-approval-wait":e.approvalWait?"":void 0,title:e.approvalWait?"Timed from request to result: includes the wait for your decision.":void 0,children:[zr(h),e.approvalWait?" incl. approval wait":""]}):null,s.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:s.jsx(qe,{name:"chevronRight",size:13})}),e.error?s.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:l}):null]}),s.jsxs("div",{className:"pc-tool-activity__detail",children:[e.policy?s.jsxs("p",{className:"pc-tool-activity__policy-line","data-policy":e.policy.decision,children:[Zp(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,s.jsx(NN,{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 il(JSON.stringify(e,null,2))),children:[s.jsx(qe,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),m?s.jsx("dl",{className:"pc-tool-activity__parameters",children:m.map(([_,g])=>s.jsxs(Ae.Fragment,{children:[s.jsx("dt",{children:_}),s.jsx("dd",{children:g&&typeof g=="object"?s.jsx(hr,{value:g}):s.jsx("code",{children:typeof g=="string"?g:JSON.stringify(g)})})]},_))}):e.arguments===void 0?s.jsx("p",{children:"Arguments are unavailable in this ledger."}):s.jsx(hr,{value:i}),e.output!==void 0?s.jsxs(s.Fragment,{children:[s.jsx("h4",{children:"Result"}),typeof e.output=="string"?s.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):s.jsx("div",{className:"pc-tool-activity__output",children:s.jsx(hr,{value:e.output})})]}):null]})]})}function TN({tools:e,showCopy:t}){const n=r=>e.filter(i=>i.status===r).length;return s.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[s.jsxs("div",{className:"pc-tool-group__heading",children:[s.jsx(qe,{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(AN,{tool:r,showCopy:t},r.id))]})}function sL(e){const t=e.totalTokens!==void 0?Ry("tokens",e):null,n=Ry("tools",e),r=e.durationMs!==void 0?Ry("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(`
78
+ `)}]:[],...r?[{label:zr(e.durationMs),detail:r}]:[]]}function rL(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 iL=new Set(["blob:","data:","http:","https:"]);function eg(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return iL.has(new URL(t,n).protocol)?t:void 0}catch{return}}function MN(e,t){return kN(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function oL({item:e,onOpen:t,markdown:n}){const[r,i]=p.useState(!1),o=eg(e.src),c=String(e.name||e.label||"").trim()||"File",l=OR({href:e.href?eg(e.href):void 0,src:o,contentType:e.contentType,name:e.name||e.label}),d=Xp(c,e.contentType),h=Jw(d),m=typeof e.text=="string";if(!o&&!l&&!m)return null;const _=Lg(e.size),g=String(e.label||"").trim()||c;return s.jsxs("figure",{className:"pc-chat-media__item pc-chat-media__item--file","data-file-kind":d,children:[s.jsxs("div",{className:"pc-chat-media__file-row",children:[s.jsx(qe,{name:"file",size:14}),s.jsx("span",{className:"pc-chat-media__file-name",title:c,children:g}),_?s.jsx("span",{className:"pc-chat-media__file-size",children:_}):null,t?s.jsx("button",{type:"button",className:"pc-chat-media__file-open","data-action":"open-file",onClick:()=>t({...e,src:o||"",...l?{href:l}:{href:void 0}}),children:"Open"}):s.jsx("button",{type:"button",className:"pc-chat-media__file-open","data-action":"toggle-file","aria-expanded":r,onClick:()=>i(y=>!y),children:r?"Close":"Open"}),l?s.jsx("a",{className:"pc-chat-media__link",...MN(l,String(e.name||"").trim()||g),children:"Raw file"}):null]}),r&&!t?s.jsx(SN,{className:"pc-chat-media__viewer",name:c,kind:d,contentType:e.contentType,sizeBytes:e.size,status:h&&!m?"error":"ready",error:h&&!m?l?"No preview text was supplied for this file; open the raw file.":"No preview text was supplied for this file.":void 0,markdownImages:n.images||"link",...n.inlineImage?{inlineImage:n.inlineImage}:{},...n.renderMarkdown?{renderMarkdown:n.renderMarkdown}:{},...m?{text:e.text}:{},...o&&!h?{url:o}:{},onClose:()=>i(!1)}):null]})}function aL({item:e,onOpenFile:t,markdown:n}){const[r,i]=p.useState(!1);if(e.kind==="file")return s.jsx(oL,{item:e,onOpen:t,markdown:n||{}});const o=eg(e.src),c=e.href?eg(e.href):void 0,l=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!l||!o&&!c)return null;const d=l==="image"?"Image":l==="video"?"Video":"Audio",h=String(e.label||"").trim()||`Generated ${d.toLowerCase()}`,m=()=>i(!0);return s.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${l}`,children:[o&&l==="image"?s.jsx("img",{className:"pc-chat-media__image",src:o,alt:h,loading:"lazy",onError:m}):null,o&&l==="video"?s.jsx("video",{className:"pc-chat-media__video",src:o,controls:!0,playsInline:!0,preload:"metadata","aria-label":h,onError:m}):null,o&&l==="audio"?s.jsx(Rg,{className:"pc-chat-media__audio",src:o,name:h}):null,l==="audio"&&String(e.transcript||"").trim()?s.jsxs("details",{className:"pc-chat-media__transcript",children:[s.jsx("summary",{children:"Transcript"}),s.jsx("p",{className:"pc-chat-media__transcript-text",children:String(e.transcript).trim()})]}):null,r?s.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[d," could not be decoded by this browser",c?"; open the raw file with the link.":"."]}):null,c?s.jsx("figcaption",{className:"pc-chat-media__caption",children:s.jsx("a",{className:"pc-chat-media__link",...MN(c,String(e.name||"").trim()||h),children:h})}):null]})}function lL(e){return e==="loading"?{icon:"loader",title:"Generating audio…",spinning:!0}:e==="playing"?{icon:"pause",title:"Pause",spinning:!1}:e==="paused"?{icon:"play",title:"Resume",spinning:!1}:{icon:"speaker",title:"Speak (TTS)",spinning:!1}}function dx(e){var D,O;const t=e.message,n=p.useMemo(()=>rL(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),i=p.useMemo(()=>{if(!r)return"";const A=new Date(r);return Number.isFinite(A.getTime())?A.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[o,c]=p.useState("idle"),l=p.useRef(null);p.useEffect(()=>()=>{l.current!==null&&window.clearTimeout(l.current)},[]);const d=t.live,h=!d&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),m=h&&((D=e.getSpeakState)==null?void 0:D.call(e,t))||"idle",_=lL(m),g=e.showCopy!==!1,y=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],x=t.statistics,k=t.stats,v=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(k)?k:x?sL(x):[],[e.stats,k,x]),N=Array.isArray(t.media)?t.media:[],$=String(d?d.reasoning||"":t.reasoning||""),C=!!String(t.content||"").trim();if(t.toolActivity)return s.jsx(AN,{tool:t.toolActivity,showCopy:e.showCopy});const S=e.renderFooter?e.renderFooter(t):null;if(((O=e.variant)==null?void 0:O.call(e,t))==="hint"||t.kind==="tool_policy_decision"){const A=String(t.level||"").trim().toLowerCase();return s.jsxs("div",{className:["pc-chat-hint",A==="warn"||A==="error"?`pc-chat-hint--${A}`:"",e.className].filter(Boolean).join(" "),role:"note","data-variant":"hint",children:[s.jsx("span",{className:"pc-chat-hint__text",children:String(t.content||"")}),S!=null&&S!==!1?s.jsx("div",{className:"pc-chat-footer",children:S}):null]})}return s.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,d?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...d?{"aria-busy":!0}:{},children:[s.jsxs("div",{className:"pc-chat-header",children:[s.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:s.jsx(qe,{name:n.icon,size:14})}),s.jsx("span",{className:"pc-chat-role",children:n.label}),d?s.jsxs("span",{className:"pc-chat-live-indicator",title:d.label?`Pending: ${d.label}`:"The reply is still being written",children:[s.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),d.label||"streaming"]}):null,d!=null&&d.caption?s.jsx("span",{className:"pc-chat-live-caption",children:d.caption}):null,s.jsx("span",{className:"pc-chat-header-spacer"}),i?s.jsx("span",{className:"pc-chat-time",children:i}):null,s.jsxs("div",{className:"pc-chat-header-actions",children:[h?s.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":_.title,title:_.title,"data-speak-state":m,onClick:()=>{var A;return(A=e.onSpeakToggle)==null?void 0:A.call(e,t)},children:s.jsx(qe,{name:_.icon,size:22,className:_.spinning?"pc-chat-speak-spinner":void 0},_.icon)}):null,g?s.jsx("button",{className:`pc-chat-icon-btn ${o!=="idle"?`pc-chat-icon-btn--${o}`:""}`.trim(),type:"button","aria-label":"Copy message",title:o==="idle"?"Copy":o==="copied"?"Copied":"Copy failed",onClick:async()=>{const A=await il(String(t.content||""));c(A?"copied":"failed"),l.current!==null&&window.clearTimeout(l.current),l.current=window.setTimeout(()=>c("idle"),900)},children:s.jsx(qe,{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,C||!d&&!N.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(bN,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,N.length?s.jsx("div",{className:"pc-chat-media",children:N.slice(0,24).map((A,P)=>s.jsx(aL,{item:A,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},A.id||`${A.kind}:${A.src}:${P}`))}):null,y.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:y.slice(0,24).map((A,P)=>{const W=String(A.label||"").trim()||"attachment",J=String(A.target||"").trim(),G=String(A.title||"").trim(),V=!!A.disabled||typeof A.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:G||W,onClick:V?void 0:A.onClick,disabled:V,children:[s.jsx(qe,{name:"paperclip",size:14}),J?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${J}`,children:J}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:W})]},A.id||`${W}:${P}`)})}):null,v.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:v.slice(0,12).map((A,P)=>{const W=String(A.label||"").trim();if(!W)return null;if(A.detail)return s.jsx(tL,{label:W,detail:A.detail,icon:A.icon,onClick:A.onClick},A.id||`${W}:${P}`);const J=String(A.title||"").trim(),G=typeof A.onClick=="function",V=G?"button":"span";return s.jsxs(V,{...G?{type:"button"}:{},className:["pc-chat-stat",G?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:J||void 0,onClick:G?()=>{var R;return(R=A.onClick)==null?void 0:R.call(A)}:void 0,children:[A.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:A.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:W})]},A.id||`${W}:${P}`)})}):null,S!=null&&S!==!1?s.jsx("div",{className:"pc-chat-footer",children:S}):null]})}function cL(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function fx(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=p.useRef(null),i=p.useRef(null),[o,c]=p.useState(!0),l=p.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),d=p.useMemo(()=>{var _;const m=[];for(const g of l){const y=m[m.length-1];g.toolActivity&&((_=y==null?void 0:y[0])!=null&&_.toolActivity)&&y[0].runId===g.runId?y.push(g):m.push([g])}return m},[l]);p.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const _=()=>{c(cL(m,t))};return m.addEventListener("scroll",_,{passive:!0}),_(),()=>m.removeEventListener("scroll",_)},[n,t]);const h=p.useMemo(()=>{let m=0;for(const _ of l)if(m+=String(_.content??"").length,Array.isArray(_.media))for(const g of _.media)m+=String((g==null?void 0:g.src)??"").length+1;return`${l.length}:${m}:${String(e.afterKey??"")}`},[l,e.afterKey]);return p.useEffect(()=>{if(!n||!o)return;const m=r.current;m&&(m.scrollTop=m.scrollHeight)},[n,o,h]),p.useEffect(()=>{if(!n)return;const m=r.current;if(!m)return;const _=()=>{o&&(m.scrollTop=m.scrollHeight)};return m.addEventListener("load",_,!0),m.addEventListener("loadedmetadata",_,!0),()=>{m.removeEventListener("load",_,!0),m.removeEventListener("loadedmetadata",_,!0)}},[n,o]),s.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[l.length?null:e.empty||null,d.map((m,_)=>{var x;const g=m[0],y=String(g.id||"")||String(g.ts||"")+":"+String(g.role||"")+":"+_;return g.toolActivity?s.jsx(TN,{tools:m.map(k=>k.toolActivity),showCopy:(x=e.messageProps)==null?void 0:x.showCopy},y):s.jsx(dx,{message:g,...e.messageProps||{}},y)}),e.after,s.jsx("div",{ref:i})]})}const hx=Ae.forwardRef(function(t,n){const r=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,i=!!t.disabled,o=!!t.busy,c=!i&&!o&&!!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:l=>t.onChange(l.target.value),rows:r,style:{"--pc-composer-rows":String(r)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:i,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:l=>{l.key!=="Enter"||l.shiftKey||l.nativeEvent.isComposing||l.keyCode===229||(l.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:o?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function Uh(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function i0(e){var r;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let i=0;i<t.length;i+=1)((r=t[i])==null?void 0:r.kind)==="file"&&(n+=1);return n>0?n:null}function o0(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function mx(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let o=0;o<r.length;o+=1){const c=r[o];if(!c||c.kind!=="file")continue;const l=typeof c.webkitGetAsEntry=="function"?c.webkitGetAsEntry():null,d=typeof c.getAsFile=="function"?c.getAsFile():null;l!=null&&l.isDirectory?n.push(l.name||(d==null?void 0:d.name)||"folder"):d&&t.push(d)}return{files:t,folders:n}}const i=e==null?void 0:e.files;if(i)for(let o=0;o<i.length;o+=1)i[o]&&t.push(i[o]);return{files:t,folders:n}}function RN(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 uL={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function bh(e){return String(e).padStart(2,"0")}function dL(e,t,n){const r=String(e||"").trim();if(r&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(r))return r;const i=uL[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",o=`${n.getFullYear()}-${bh(n.getMonth()+1)}-${bh(n.getDate())} at ${bh(n.getHours())}.${bh(n.getMinutes())}.${bh(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${o}.${i}`}function LN(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}=mx(e);return r.map(i=>{const o=dL(i.name,i.type,t);return o===i.name?i:new File([i],o,{type:i.type,lastModified:i.lastModified})})}class fL{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 Wh="llm.delta",Ed="llm.delta_end";function hL(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jc(e){return typeof e=="string"&&e.trim()!==""}function mL(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function IN(e){return"reason"in e}function ON(e,t){const n=hL(e),r=n==null?void 0:n.kind,i=t||(typeof r=="string"&&r?r:n&&"reason"in n?Ed:Wh),o=d=>{throw new Error(`Malformed ${i} event from the gateway: ${d}`)};if(t!==void 0&&t!==Wh&&t!==Ed&&o(`unknown event name ${JSON.stringify(t)}`),!n)return o("the payload is not an object");r!==void 0&&r!==Wh&&r!==Ed&&o(`unknown kind ${JSON.stringify(r)}`),r!==void 0&&t!==void 0&&r!==t&&o(`kind ${JSON.stringify(r)} does not match the event name`),Jc(n.run_id)||o("run_id is missing"),Jc(n.call_id)||o("call_id is missing"),mL(n.seq)||o("seq is not a non-negative integer");const c=t||r?(t||r)===Ed:"reason"in n;n.root_run_id!==void 0&&!Jc(n.root_run_id)&&o("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!Jc(n.parent_run_id)&&o("parent_run_id is neither a run id nor null");const l={run_id:n.run_id,...Jc(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...Jc(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))||o(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&o("detail is not a string"),{kind:Ed,...l,reason:n.reason,...Jc(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&o("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&o(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&o("snapshot is not a boolean"),{kind:Wh,...l,text:n.text,channel:n.channel,snapshot:n.snapshot})}function _L(e,t){if(e!==Wh&&e!==Ed)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 ON(n,e)}const pL={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 gL(e){return`This reply is not streamed: ${e?pL[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const _x=e=>wt(`runs/${encodeURIComponent(e)}/workspace`);function yL(e){return _x(e)}function wL(e,t){return`${_x(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function vL(e,t){return`${_x(e)}/content?${new URLSearchParams({path:t})}`}async function of(e,t){let n="";try{const r=await e.text();try{const i=JSON.parse(r),o=(i==null?void 0:i.detail)??(i==null?void 0:i.error)??(i==null?void 0:i.message);n=typeof o=="string"?o:o&&typeof o.message=="string"?o.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function xL(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 i=n.entries.map((c,l)=>{const d=c&&typeof c=="object"?c:{};return(typeof d.name!="string"||typeof d.path!="string"||d.type!=="file"&&d.type!=="dir")&&r(`entry ${l+1} lacks a name, path or file/dir type`),d}),o=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:i,truncated:n.truncated,...o?{hidden:o}:{}}}async function bL(e,t,n){const r=await e(yL(t),{signal:n});if(!r.ok)throw await of(r,"The workspace is not available");const i=await r.json();if(!i||typeof i.workspace_root!="string"||typeof i.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return i}async function kL(e,t,n,r){const i=await e(wL(t,n),{signal:r});if(!i.ok)throw await of(i,"The folder could not be listed");return xL(await i.json(),n)}async function jL(e,t,n,r){const i=await e(vL(t,n),{signal:r});if(!i.ok)throw await of(i,"The file could not be read");return await i.blob()}async function SL(e,t,n,r){const i=await bL(e,t,r);return{where:i,listing:i.exists?await kL(e,t,n,r):null}}function NL(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((r,i)=>n.push({label:r,path:t.slice(0,i+1).join("/")})),n}function PN(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 $L(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function CL(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 EL=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function AL(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return EL.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 DN(e,t,n){const r=n==="open"?AL(e.type):{mode:"download"},i=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,o=URL.createObjectURL(i);if(r.mode==="open")window.open(o,"_blank","noopener");else{const c=document.createElement("a");c.href=o,c.download=t,document.body.appendChild(c),c.click(),c.remove()}window.setTimeout(()=>URL.revokeObjectURL(o),6e4)}async function TL(e,t,n){const r=await e(ME(t),{signal:n.signal});if(!r.ok)throw await of(r,`${n.name} could not be read`);DN(await r.blob(),n.name,n.mode??"open")}function ML(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function RL(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 LL(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function FN(e){var V;const{fetchGateway:t,runId:n}=e,[r,i]=p.useState({runId:n,path:""}),o=r.runId===n?r.path:"",[c,l]=p.useState(null),[d,h]=p.useState(""),[m,_]=p.useState(""),[g,y]=p.useState(!!n),[x,k]=p.useState(""),[v,N]=p.useState(!1),[$,C]=p.useState(0),[S,D]=p.useState(null),O=S&&S.runId===n&&!e.onSelectFile?S.entry:null,A=qR(t,n,O,`${e.refreshKey??""}:${$}`);p.useEffect(()=>{if(!n)return;const R=new AbortController;return y(!0),h(""),(async()=>{try{const M=await SL(t,n,o,R.signal);R.signal.aborted||l({runId:n,...M})}catch(M){R.signal.aborted||h(String((M==null?void 0:M.message)||M))}finally{R.signal.aborted||y(!1)}})(),()=>R.abort()},[t,n,o,$,e.refreshKey]),p.useEffect(()=>_(""),[n]);const P=c&&c.runId===n?c:null,W=p.useCallback(async R=>{k(R.path),h("");try{DN(await jL(t,n,R.path),R.name,"download")}catch(M){h(String((M==null?void 0:M.message)||M))}finally{k("")}},[t,n]),J=(P==null?void 0:P.where.workspace_root)||"",G=e.nowMs??Date.now();return s.jsx(IL,{title:e.title,note:e.note,where:(P==null?void 0:P.where)??null,path:o,listing:(P==null?void 0:P.listing)??null,error:d,notice:m,loading:g,fileBusy:x,selectedPath:e.onSelectFile?e.selectedPath:O==null?void 0:O.path,className:e.className,nowMs:G,openingFolder:v,onNavigate:R=>{D(null),i({runId:n,path:R})},onRefresh:()=>C(R=>R+1),onFile:R=>void W(R),onSelectFile:e.onSelectFile??(R=>D({runId:n,entry:R})),onClose:e.onClose,onCopyPath:J?()=>{(e.copyText||LL)(J).then(R=>_(R?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&RL(P==null?void 0:P.where)?()=>{N(!0),_(""),e.onOpenFolder().then(()=>_("Folder opened on this machine.")).catch(R=>_(`Open folder failed: ${String((R==null?void 0:R.message)||R)}`)).finally(()=>N(!1))}:void 0,preview:O?s.jsx(SN,{name:O.name,path:O.path,sizeBytes:O.size_bytes,modified:O.mtime,nowMs:G,...VR(A),actions:(V=e.fileActions)==null?void 0:V.call(e,O),onDownload:()=>void W(O),onClose:()=>D(null)}):null})}function IL(e){var o,c,l,d;const t=e.listing?CL(e.listing):"",n=(c=(o=e.where)==null?void 0:o.host)==null?void 0:c.hostname,r=((l=e.where)==null?void 0:l.workspace_root)||"",i=e.nowMs??Date.now();return s.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":r||void 0,children:[s.jsxs("header",{className:"pc-ws__head",children:[s.jsxs("span",{className:"pc-ws__title",children:[s.jsx(qe,{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(qe,{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(qe,{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:ML(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(qe,{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(qe,{name:"copy",size:14})}):null,n&&((d=e.where.host)==null?void 0:d.caller_is_this_machine)!==!0?s.jsxs("span",{className:"pc-ws__muted",children:[" on ",n]}):null]}):null,e.note?s.jsx("div",{className:"pc-ws__muted",children:e.note}):null,e.notice?s.jsx("div",{className:"pc-ws__muted",role:"status",children:e.notice}):null,e.error?s.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.preview?s.jsx("div",{className:"pc-ws__preview",children:e.preview}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:NL(e.path).map((h,m,_)=>m===_.length-1?s.jsx("span",{"aria-current":"page",children:h.label},h.path):s.jsxs(Ae.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:$L(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(qe,{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(qe,{name:"file",size:14})," ",s.jsx("span",{className:"pc-ws__label",children:h.name})]}):s.jsxs("span",{className:"pc-ws__name",children:[s.jsx(qe,{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:PN(h.size_bytes)}),h.mtime!==void 0&&Yp(h.mtime,i)?s.jsx("time",{className:"pc-ws__time",title:ux(h.mtime),"data-meta":"modified",children:Yp(h.mtime,i)}):null]}),e.onFile?s.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"download-file",disabled:e.fileBusy===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(qe,{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 OL={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},zN="docs";function PL(e){return wt(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Ly(e){return`${String(e||"app")}-docs-assistant:${nl()}`}function DL(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}),{...OL,session_id:e.sessionId,kind:zN,input_data:t}}function BN(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 FL(e){const t=e&&typeof e=="object"?e:{},n=l=>typeof l=="number"&&Number.isFinite(l)&&l>0?Math.trunc(l):0,r=n(t.dropped_messages);if(!r)return"";const i=n(t.replayed_messages),o=n(t.dropped_tokens),c=n(t.max_tokens);return`Earlier messages not replayed: ${r.toLocaleString("en-US")}${o?` (~${o.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${i.toLocaleString("en-US")} message${i===1?"":"s"}`+(c?` (history window: the most recent ${c.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*zL(e,t){const n=e.getReader(),r=new TextDecoder;let i="";const o=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",o,{once:!0});try{for(;;){const{value:c,done:l}=await n.read();if(l)break;i+=r.decode(c,{stream:!0}).replace(/\r\n/g,`
79
+ `);let d=i.indexOf(`
80
+
81
+ `);for(;d>=0;){const h=i.slice(0,d);i=i.slice(d+2);let m="message";const _=[];for(const g of h.split(`
82
+ `))g.startsWith("event:")?m=g.slice(6).trim():g.startsWith("data:")&&_.push(g.slice(5).replace(/^ /,""));_.length&&(yield{event:m,data:_.join(`
83
+ `)}),d=i.indexOf(`
84
+
85
+ `)}}}finally{t==null||t.removeEventListener("abort",o)}}function BL(e,t){return new Promise((n,r)=>{if(t.aborted)return r(new DOMException("Aborted","AbortError"));const i=setTimeout(()=>{t.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",o,{once:!0})})}async function rc(e,t){if(!e.ok)throw await of(e,t);return e.json()}function UL(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(i,o)=>{var x;const{fetchGateway:c,source:l}=e;if(r===null){const k=await c(PL(l.app),{signal:o.signal,headers:{Accept:"application/json"}}),v=await rc(k,`The ${l.name} documentation could not be read, so nothing was asked`),N=typeof(v==null?void 0:v.text)=="string"?v.text:"";if(!N.trim())throw new Error(`The gateway returned an empty ${l.name} documentation corpus, so nothing was asked.`);r=N}const d=String(r),h=[];for(const k of o.files||[]){const v=new FormData;v.append("session_id",o.sessionId),v.append("file",k,k.name||"upload.bin"),v.append("filename",k.name||"upload.bin"),k.type&&v.append("content_type",k.type);const N=await rc(await c(wt("attachments/upload"),{method:"POST",body:v,signal:o.signal}),`"${k.name}" could not be attached`),$=N==null?void 0:N.attachment;if(!$||typeof $.$artifact!="string"||!$.$artifact)throw new Error(`"${k.name}" could not be attached: the gateway returned no attachment reference.`);h.push($)}const m=await rc(await c(wt("runs/start"),{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(DL({question:i,docs:d,appName:l.name,sessionId:o.sessionId,attachments:h}))}),"The docs-qa workflow could not start"),_=String((m==null?void 0:m.run_id)||"");if(!_)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const g=new AbortController,y=()=>g.abort();o.signal.addEventListener("abort",y,{once:!0}),o.onText&&(async()=>{var k;try{const v=await c(wt(`runs/${encodeURIComponent(_)}/ledger/stream?after=0`),{signal:g.signal,headers:{Accept:"text/event-stream"}});if(!v.ok||!v.body)return;let N="",$="";for await(const C of zL(v.body,g.signal)){const S=_L(C.event,C.data);!S||IN(S)||S.channel!=="content"||S.run_id!==_||(S.call_id!==N&&(N=S.call_id,$=""),$=S.snapshot?S.text:$+S.text,(k=o.onText)==null||k.call(o,$))}}catch{}})();try{const k=Date.now()+n;for(;;){await BL(t,o.signal);const v=await rc(await c(wt(`runs/${encodeURIComponent(_)}`),{signal:o.signal}),"The docs-qa run could not be read"),N=String((v==null?void 0:v.status)||"").toLowerCase();if(N==="completed"){(x=o.onHistory)==null||x.call(o,(v==null?void 0:v.session_history)??null);const $=BN(v);if(!$)throw new Error(`The docs-qa run ${_} completed without an answer.`);return $}if(N==="failed"||N==="cancelled"){const $=v==null?void 0:v.error,C=typeof $=="string"?$:typeof($==null?void 0:$.message)=="string"?$.message:"";throw new Error(`The docs-qa run ${N}${C?`: ${C}`:""}.`)}if(N==="waiting")throw new Error(`The docs-qa run ${_} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=k)throw new Error(`The docs-qa run ${_} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{o.signal.removeEventListener("abort",y),g.abort()}}}async function WL(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:zN,limit:"500",include_ledger_len:"false"}),i=await rc(await e(wt(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),o=`${String(t||"app")}-docs-assistant:`,c=new Map;for(const d of Array.isArray(i==null?void 0:i.items)?i.items:[]){const h=String((d==null?void 0:d.session_id)||"");if(!h.startsWith(o)||!(d!=null&&d.run_id))continue;const m=c.get(h)||{runs:[],updatedAt:""};m.runs.push({id:String(d.run_id),created:String(d.created_at||"")});const _=String(d.updated_at||d.created_at||"");_>m.updatedAt&&(m.updatedAt=_),c.set(h,m)}const l=[...c.entries()].sort((d,h)=>d[1].updatedAt<h[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(l.map(async([d,h])=>{var g;const m=h.runs.sort((y,x)=>y.created<x.created?-1:1).map(y=>y.id);let _="";try{const y=await rc(await e(wt(`runs/${encodeURIComponent(m[0])}/input_data`),{signal:n.signal}),"");_=String(((g=y==null?void 0:y.input_data)==null?void 0:g.prompt)||"").trim()}catch{_=""}return{sessionId:d,title:_||"Untitled question",updatedAt:h.updatedAt,runIds:m}}))}async function qL(e,t,n,r){var o;const i=[];for(const c of t.runIds){const[l,d]=await Promise.all([rc(await e(wt(`runs/${encodeURIComponent(c)}/input_data`),{signal:r}),"A past question could not be read"),rc(await e(wt(`runs/${encodeURIComponent(c)}`),{signal:r}),"A past answer could not be read")]),h=String(((o=l==null?void 0:l.input_data)==null?void 0:o.prompt)||"").trim();h&&i.push({id:`u-${c}`,role:"user",content:h,ts:String((d==null?void 0:d.created_at)||"")||void 0});const m=BN(d),_=String((d==null?void 0:d.status)||"").toLowerCase();i.push(m?{id:`a-${c}`,role:"assistant",title:n,content:m,ts:String((d==null?void 0:d.updated_at)||"")||void 0}:{id:`a-${c}`,role:"assistant",title:n,level:"warn",content:_==="completed"?"This answer was empty.":`No answer: the run is ${_||"unknown"}.`})}return i}function VL(e){const[t,n]=p.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:[Yp(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(qe,{name:"archive",size:16})})]})},r.sessionId))}):s.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const HL=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function GL(e){const t=p.useRef(null),[n,r]=p.useState(!1),i=!!e.blockedNotice,o=!!e.busy,c=e.files||[],l=typeof e.onAddFiles=="function"&&!i,d=s.jsxs("div",{className:"pc-docs-assistant__empty",children:[s.jsxs("p",{className:"pc-docs-assistant__empty-text",children:["Ask anything about ",e.source.name,"."]}),e.suggestions&&e.suggestions.length?s.jsx("div",{className:"pc-docs-assistant__suggestions",children:e.suggestions.map(h=>s.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:o||i,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;!l||!Uh((m=h.dataTransfer)==null?void 0:m.types)||(h.preventDefault(),r(!0))},onDragLeave:()=>r(!1),onDrop:h=>{var _,g;if(!l)return;h.preventDefault(),r(!1);const m=mx(h.dataTransfer);m.files.length&&((_=e.onAddFiles)==null||_.call(e,m.files)),m.folders.length&&((g=e.onNotice)==null||g.call(e,RN(m.folders)))},children:[s.jsx(fx,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:d,messageProps:{showCopy:!0}}),i?s.jsx("div",{className:"pc-docs-assistant__blocked",role:"status",children:e.blockedNotice}):null,e.notice?s.jsx("div",{className:"pc-docs-assistant__notice",role:"status",children:e.notice}):null,s.jsx("div",{className:"pc-docs-assistant__composer",children:s.jsx(hx,{value:e.draft,onChange:e.onDraftChange,onSubmit:e.onSend,placeholder:e.placeholder||`Ask about ${e.source.name}…`,ariaLabel:`Question about ${e.source.name}`,disabled:i,busy:o,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:h=>{var _;if(!l)return;const m=LN(h.clipboardData);m.length&&(h.preventDefault(),(_=e.onAddFiles)==null||_.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(qe,{name:"paperclip",size:14}),s.jsx("span",{className:"pc-chat-attachment-name",children:h.name}),e.onRemoveFile&&!o?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(qe,{name:"x",size:12})}):null]},h.id))}):null,actions:s.jsxs(s.Fragment,{children:[l?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:o,onClick:()=>{var h;return(h=t.current)==null?void 0:h.click()},children:s.jsx(qe,{name:"paperclip",size:16})}),s.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:h=>{var _;const m=Array.from(h.currentTarget.files||[]);h.currentTarget.value="",m.length&&((_=e.onAddFiles)==null||_.call(e,m))}})]}):null,o&&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(qe,{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 rp(){return new Date().toISOString()}function KL(e){rf();const{source:t}=e,n=p.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=p.useMemo(()=>e.ask||UL({fetchGateway:(R,M)=>n.current(R,M),source:t}),[e.ask,t.app,t.name]),i=p.useRef(Ly(t.app)),[o,c]=p.useState([]),l=p.useRef(o);l.current=o;const[d,h]=p.useState(""),[m,_]=p.useState([]),[g,y]=p.useState(!1),[x,k]=p.useState(""),v=p.useRef(null),[N,$]=p.useState(!1),[C,S]=p.useState({state:"loading",items:[]});p.useEffect(()=>()=>{var R;return(R=v.current)==null?void 0:R.abort()},[]);const D=p.useCallback(async()=>{S(R=>({...R,state:"loading"}));try{const R=await WL((M,I)=>n.current(M,I),t.app);S({state:"ready",items:R})}catch(R){S({state:"error",items:[],error:String((R==null?void 0:R.message)||R)})}},[t.app]),O=p.useCallback(async R=>{var M;(M=v.current)==null||M.abort(),S(I=>({...I,state:"loading"}));try{const I=await qL((L,K)=>n.current(L,K),R,t.name);i.current=R.sessionId,c(I),k(""),$(!1),S(L=>({...L,state:"ready"}))}catch(I){S(L=>({...L,state:"error",error:String((I==null?void 0:I.message)||I)}))}},[t.name]),A=p.useCallback(async R=>{try{const M=await n.current(wt(`sessions/${encodeURIComponent(R.sessionId)}/archive`),{method:"POST"});if(!M.ok)throw await of(M,"The conversation could not be archived");i.current===R.sessionId&&(i.current=Ly(t.app),c([])),S(I=>({...I,items:I.items.filter(L=>L.sessionId!==R.sessionId)}))}catch(M){S(I=>({...I,state:"error",error:String((M==null?void 0:M.message)||M)}))}},[t.app]);p.useEffect(()=>{var R;e.connected||(R=v.current)==null||R.abort()},[e.connected]),p.useEffect(()=>()=>{for(const R of m)R.preview&&URL.revokeObjectURL(R.preview)},[]);const P=p.useCallback(R=>{k(""),_(M=>[...M,...R.map(I=>({id:nl(),file:I,preview:HL.test(I.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(I):void 0}))])},[]),W=p.useCallback(async R=>{const M=String(R||"").trim();if(!M||g||!e.connected)return;const I=m;h(""),_([]),k("");const L=I.filter(de=>de.preview).map(de=>({kind:"image",src:de.preview,label:de.file.name})),K=I.map(de=>({id:de.id,label:de.file.name,title:de.file.name,disabled:!0})),H={id:`u-${nl()}`,role:"user",content:M,ts:rp(),...L.length?{media:L}:{},...K.length?{attachments:K}:{}},z=`a-${nl()}`,ee=[...l.current,H],B={id:z,role:"assistant",title:t.name,content:"",ts:rp(),live:{callId:z,reasoning:"",label:"answering"}};c([...ee,B]),y(!0);const te=new AbortController;v.current=te;const se=de=>c([...ee,de]);try{const de=await r(M,{signal:te.signal,sessionId:i.current,files:I.map(be=>be.file),onText:be=>{te.signal.aborted||se({...B,content:be,live:{callId:z,reasoning:"",label:"streaming"}})},onHistory:be=>k(FL(be))});te.signal.aborted||se({id:z,role:"assistant",title:t.name,content:de,ts:rp()})}catch(de){const be=te.signal.aborted;se({id:z,role:"assistant",title:t.name,level:be?"warn":"error",content:be?"Stopped. Nothing more will be shown for this question.":String((de==null?void 0:de.message)||de||"The docs assistant failed."),ts:rp()})}finally{v.current===te&&(v.current=null),y(!1)}},[r,g,m,e.connected,t.name]),J=()=>{var R;(R=v.current)==null||R.abort(),i.current=Ly(t.app),c([]),_([]),h(""),k("")},G=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||g,onClick:()=>{const R=!N;$(R),R&&D()},children:s.jsx(qe,{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:!o.length&&!d&&!m.length&&!N,onClick:()=>{J(),$(!1)},children:s.jsx(qe,{name:"compose",size:16})})]}),V=s.jsxs(s.Fragment,{children:[N?s.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:s.jsx(VL,{items:C.items,state:C.state,error:C.error,nowMs:Date.now(),activeSessionId:i.current,onOpen:R=>void O(R),onArchive:R=>void A(R)})}):null,s.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:s.jsx(GL,{source:t,messages:o,draft:d,onDraftChange:h,onSend:()=>void W(d),onStop:()=>{var R;return(R=v.current)==null?void 0:R.abort()},busy:g,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:m.map(R=>({id:R.id,name:R.file.name})),onAddFiles:P,onNotice:k,onRemoveFile:R=>_(M=>{const I=M.find(L=>L.id===R);return I!=null&&I.preview&&URL.revokeObjectURL(I.preview),M.filter(L=>L.id!==R)}),notice:x,suggestions:e.suggestions,onSuggestion:R=>void W(R),placeholder:e.placeholder})})]});return{headerActions:G,body:V}}function JL(e){const{headerActions:t,body:n}=KL(e);return s.jsx(g2,{open:e.open,onClose:e.onClose,label:"Docs assistant",title:s.jsxs("span",{className:"pc-docs-assistant__title",children:[s.jsx(qe,{name:"book",size:16}),"Docs assistant"]}),width:e.width||420,topOffset:e.topOffset,manageFocus:e.manageFocus===!0,className:`pc-docs-assistant-drawer${e.className?` ${e.className}`:""}`,headerActions:t,children:n})}const a0="replay_view_v1",YL=["version","root_run_id","workflow","session_id","status","display_status","cursor","interaction","open_waits","usage","warnings"],l0=["runs","messages","activities","artifacts"],UN=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function WN(e){return e==null?"None":e===!0?"True":e===!1?"False":String(e)}function XL(e){const t=typeof e=="boolean"?Number(e):e;if(typeof t=="number"&&Number.isInteger(t)){const n=String(Math.abs(t));return t<0?`-${n.padStart(11,"0")}`:n.padStart(12,"0")}return WN(e)}function c0(e,t){if(e===t)return 0;const n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){const i=e.charCodeAt(r),o=t.charCodeAt(r);if(i===o)continue;const c=l=>l>=55296&&l<=57343;return c(i)||c(o)?(e.codePointAt(r)??i)-(t.codePointAt(r)??o):i-o}return e.length-t.length}function Zw(e,t){return WN(e==="runs"?t.run_id:t.id)}function Qw(e,t){return[(Array.isArray(t.order)&&t.order.length?t.order:[]).map(XL),Zw(e,t)]}function qN(e,t){const n=Math.min(e[0].length,t[0].length);for(let r=0;r<n;r+=1){const i=c0(e[0][r],t[0][r]);if(i)return i}return e[0].length!==t[0].length?e[0].length-t[0].length:c0(e[1],t[1])}function ZL(e,t){return qN(Qw("messages",e),Qw("messages",t))}function ev(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return e===t||e==null&&t==null;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>ev(n,t[r]));if(e&&t&&typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(i=>UN(t,i)&&ev(e[i],t[i]))}return!1}function QL(e,t){const n=e&&Object.keys(e).length?{...e}:Object.fromEntries(l0.map(r=>[r,[]]));for(const r of YL)UN(t,r)&&(n[r]=t[r]);for(const r of l0){const i=t[r],o=Array.isArray(n[r])&&n[r].length?n[r]:[];if(!Array.isArray(i)||!i.length){n[r]=o;continue}const c=[...o],l=new Map(c.map((h,m)=>[Zw(r,h),m]));let d=!1;for(const h of i){const m=Zw(r,h),_=l.get(m);_===void 0?(l.set(m,c.length),c.push(h),d=!0):(ev(c[_].order??null,h.order??null)||(d=!0),c[_]=h)}if(d){const h=c.map(m=>({it:m,key:Qw(r,m)}));h.sort((m,_)=>qN(m.key,_.key)),n[r]=h.map(m=>m.it)}else n[r]=c}return n}let eI=class{constructor(){this.lastEventId="",this.buffer="",this.event="",this.data=[],this.pendingCr=!1}push(t){const n=[];let r=t;for(this.pendingCr&&r.startsWith(`
86
+ `)&&(r=r.slice(1)),this.pendingCr=!1,this.buffer+=r;;){const i=/\r\n|\n|\r/.exec(this.buffer);if(!i)break;if(i[0]==="\r"&&i.index===this.buffer.length-1){const c=this.buffer.slice(0,i.index);this.buffer="",this.pendingCr=!0,this.line(c,n);break}const o=this.buffer.slice(0,i.index);this.buffer=this.buffer.slice(i.index+i[0].length),this.line(o,n)}return n}line(t,n){if(t===""){this.data.length&&n.push({event:this.event||"message",data:this.data.join(`
87
+ `),...this.id!==void 0?{id:this.id}:{}}),this.event="",this.data=[],this.id=void 0;return}if(t.startsWith(":"))return;const r=t.indexOf(":"),i=r<0?t:t.slice(0,r);let o=r<0?"":t.slice(r+1);o.startsWith(" ")&&(o=o.slice(1)),i==="event"?this.event=o:i==="data"?this.data.push(o):i==="id"&&!o.includes("\0")&&(this.id=o,this.lastEventId=o)}};class tI{constructor(){this.view=null,this.lastEventId=null,this.terminal=!1}adopt(t,n){var r,i,o;return this.view&&u0((r=t.cursor)==null?void 0:r.runs,(i=this.view.cursor)==null?void 0:i.runs)?!1:(this.view=t,this.lastEventId=nI(n)||((o=t.cursor)==null?void 0:o.token)||null,!0)}apply(t){var i,o,c,l;if(t.event==="done")return this.terminal=!0,"done";if(t.event!=="view"&&t.event!=="delta")return"ignored";const n=JSON.parse(t.data);if(t.event==="view")return this.view=n,this.lastEventId=t.id||((i=this.view.cursor)==null?void 0:i.token)||null,"view";if(!this.view)throw new Error("replay view: a delta arrived before any view (reconnect without Last-Event-ID).");const r=t.id||((o=n.cursor)==null?void 0:o.token)||null;return r&&r===this.lastEventId?"duplicate":u0((c=n.cursor)==null?void 0:c.runs,(l=this.view.cursor)==null?void 0:l.runs)?"stale":(this.view=QL(this.view,n),this.lastEventId=r,"delta")}}function nI(e){return String(e||"").trim().replace(/^W\//,"").replace(/^"|"$/g,"")}function u0(e,t){if(!e||!t)return!1;let n=!1;for(const[r,i]of Object.entries(t)){const o=e[r];if(typeof o!="number"){i>0&&(n=!0);continue}if(o>i)return!1;o<i&&(n=!0)}for(const[r,i]of Object.entries(e))if(!(r in t)&&i>0)return!1;return n}class sI extends Error{constructor(t,n){super(`This gateway does not serve the replay view (GET runs/{id}/view answered ${t}${n?`: ${n}`:""}); AbstractGateway 0.17.0 or later serves it.`),this.name="ReplayViewUnavailableError",this.status=t}}const Tp=200;async function Iy(e){let t="";try{const r=await e.text();try{const i=JSON.parse(r);t=typeof i.detail=="string"?i.detail:r}catch{t=r}}catch{t=""}if(e.status===405||e.status===404&&t.trim()==="Not Found")return new sI(e.status,t.trim());const n=new Error(t||`Gateway answered ${e.status}`);return n.status=e.status,n.detail=t,n}const d0=e=>`runs/${encodeURIComponent(e)}/view`;function rI(e){const t=e.fetch;return{...e.advertised!==void 0?{advertised:e.advertised}:{},async getView(n,r={}){const i={Accept:"application/json"};r.ifNoneMatch&&(i["If-None-Match"]=r.ifNoneMatch);const o=r.at?`?at=${encodeURIComponent(r.at)}`:"",c=await t(`${d0(n)}${o}`,{method:"GET",headers:i,...r.signal?{signal:r.signal}:{}}),l=c.headers.get("etag");if(c.status===304)return{notModified:!0,etag:l,bytes:0};if(!c.ok)throw await Iy(c);const d=new Uint8Array(await c.arrayBuffer()),h=JSON.parse(new TextDecoder().decode(d));if((h==null?void 0:h.version)!==a0)throw new Error(`Unsupported replay view version ${JSON.stringify(h==null?void 0:h.version)} (this client reads ${a0}).`);return{notModified:!1,view:h,etag:l,bytes:d.byteLength}},async listSessionTurns(n,r={}){const i=`include_session=true&include_subruns=false&ledger_max_items=1&detail=replay&session_turn_limit=${Tp+1}`,o=await t(`runs/${encodeURIComponent(n)}/history_bundle?${i}`,{method:"GET",headers:{Accept:"application/json"},...r.signal?{signal:r.signal}:{}});if(!o.ok)throw await Iy(o);const c=await o.json(),l=c.session&&typeof c.session=="object"?c.session:null,d=Array.isArray(l==null?void 0:l.turns)?l.turns:[],h=new Set,m=[];for(const _ of d){const g=typeof(_==null?void 0:_.run_id)=="string"?_.run_id:"";!g||h.has(g)||(h.add(g),m.push({run_id:g,...typeof _.created_at=="string"?{created_at:_.created_at}:{}}))}return m},async streamView(n,r){var m;const i={Accept:"text/event-stream"};r.lastEventId&&(i["Last-Event-ID"]=r.lastEventId);const o=await t(`${d0(n)}/stream`,{method:"GET",headers:i,signal:r.signal});if(!o.ok)throw await Iy(o);if(!o.body)throw new Error("The replay view stream has no body.");(m=r.onOpen)==null||m.call(r);const c=new eI,l=new TextDecoder,d=o.body.getReader();let h=0;try{for(;;){const{done:_,value:g}=await d.read();if(_)break;h+=g.byteLength;for(const y of c.push(l.decode(g,{stream:!0})))if(r.onFrame(y),y.event==="done")return{bytes:h}}for(const _ of c.push(l.decode()))r.onFrame(_)}finally{try{await d.cancel()}catch{}}return{bytes:h}}}}const yn=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"",gu=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,f0=new Set(["completed","failed","cancelled"]),iI=new Set(["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"]);function VN(e){const t={...e.details||{}};e.kind==="tool_approval"&&(t.kind="tool_approval",t.tool_calls=Array.isArray(e.tool_calls)?e.tool_calls:[]);const n=e.kind==="ask_user"?"user":e.kind==="event"?"event":"tool_approval",r={wait_key:e.wait_key,reason:n,details:t};return e.prompt!=null&&(r.prompt=e.prompt),Array.isArray(e.choices)&&(r.choices=e.choices),typeof e.allow_free_text=="boolean"&&(r.allow_free_text=e.allow_free_text),{runId:e.run_id,wait:r,...e.step_id?{stepId:e.step_id}:{},kind:e.kind,...e.command?{command:e.command}:{}}}function oI(e,t){const n=yn(e.status||t.status).toLowerCase();return n==="completed"?"completed":n==="waiting"?"waiting":n==="running"||n==="started"||n==="pending"?"running":"failed"}function aI(e){const t=gu(e.policy_decision),n=yn(t==null?void 0:t.decision);if(n!=="auto_approved"&&n!=="denied")return;const r=gu(t==null?void 0:t.set_by),i=yn(r==null?void 0:r.user_id)||yn(r==null?void 0:r.client);return{decision:n,...yn(e.decided_by)?{source:yn(e.decided_by)}:{},...yn(e.matched)?{matched:yn(e.matched)}:{},...typeof(t==null?void 0:t.revision)=="number"?{revision:t.revision}:{},...i?{setBy:i}:{},...yn(t==null?void 0:t.set_at)?{setAt:yn(t==null?void 0:t.set_at)}:{}}}function lI(e,t){if(typeof e.error=="string"&&e.error.trim())return e.error.trim();const n=gu(e.error);if(n)return yn(n.message)||yn(n.detail)||JSON.stringify(n);if(t==="denied")return"Denied";if(t==="cancelled")return"Cancelled"}function cI(e){return(Array.isArray(e.tool_calls)?e.tool_calls:[]).map((n,r)=>{var d;const i=oI(n,e),o=yn(n.status||e.status).toLowerCase(),c=aI(n),l=i==="failed"?lI(n,o):void 0;return{id:`${e.id}:${yn(n.id)||r}`,runId:e.run_id,name:yn(n.name)||"tool",...n.arguments!==void 0?{arguments:n.arguments}:{},...n.output!==void 0?{output:n.output}:{},status:i,...i==="completed"?{success:!0}:i==="failed"?{success:!1}:{},...l?{error:l}:{},...yn(e.started_at)?{startedAt:yn(e.started_at)}:{},...yn(e.ended_at)?{endedAt:yn(e.ended_at)}:{},...((d=e.wait)==null?void 0:d.kind)==="tool_approval"&&e.wait.outcome?{approvalWait:!0}:{},...yn(n.id)?{callId:yn(n.id)}:{},...c?{policy:c}:{}}})}function HN(e){return{id:`tool:${e.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:e.runId,toolActivity:e,content:JSON.stringify({tool:e.name,status:e.status,arguments:e.arguments,output:e.output,error:e.error},null,2),ts:e.endedAt||e.startedAt}}function uI(e){const t=yn(e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=gu(e.policy),r=gu(n==null?void 0:n.set_by),i=yn(r==null?void 0:r.user_id)||yn(r==null?void 0:r.client),o={decision:t,...yn(e.source)?{source:yn(e.source)}:{},...typeof(n==null?void 0:n.revision)=="number"?{revision:n.revision}:{},...i?{setBy:i}:{},...yn(n==null?void 0:n.set_at)?{setAt:yn(n==null?void 0:n.set_at)}:{}};return{id:`policy:${e.id}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",runId:e.run_id,content:Zp(o),ts:yn(e.started_at)||void 0}}function dI(e){const t=gu(e.usage)||{},n=new Set;let r=0,i=0,o=1/0,c=-1/0;for(const h of e.activities||[]){const m=Date.parse(yn(h.started_at)),_=Date.parse(yn(h.ended_at));if(Number.isFinite(m)&&(o=Math.min(o,m)),Number.isFinite(_)&&(c=Math.max(c,_)),h.kind==="llm"&&(i+=1),h.kind==="tool")for(const g of h.tool_calls||[]){if(r+=1,yn(g.status)!=="completed"||!iI.has(yn(g.name)))continue;const y=gu(g.arguments)||{},x=yn(y.destination)||yn(y.destination_path)||yn(y.file_path)||yn(y.path)||yn(y.filename);x&&n.add(x)}}const l=h=>typeof h=="number"&&Number.isFinite(h)?h:void 0,d={llmCalls:l(t.llm_calls)??i,toolCalls:r,changedFiles:[...n]};return l(t.input_tokens)!==void 0&&(d.inputTokens=l(t.input_tokens)),l(t.output_tokens)!==void 0&&(d.outputTokens=l(t.output_tokens)),l(t.total_tokens)!==void 0&&(d.totalTokens=l(t.total_tokens)),Number.isFinite(o)&&Number.isFinite(c)&&(d.durationMs=Math.max(0,c-o)),d}function fI(e,t){const n=Array.isArray(e.order)&&typeof e.order[0]=="string"&&e.order[0]?e.order[0]:void 0,r=yn(e.level).toLowerCase();return{id:e.id,role:e.role,kind:e.kind,content:e.text,runId:e.run_id,...n?{ts:n}:{},...e.role==="system"?{title:"Workflow",level:r==="error"?"error":r==="warn"||r==="warning"?"warn":"info"}:{},...Array.isArray(e.artifact_ids)&&e.artifact_ids.length?{artifactIds:[...e.artifact_ids]}:{},...t?{statistics:t}:{}}}function h0(e){const t=e.root_run_id,n=dI(e),r=e.interaction?VN(e.interaction):null,i=e.interaction?`${e.interaction.run_id}:${e.interaction.step_id||""}:question`:"",o=(e.messages||[]).find(y=>y.id===`${t}:final`),c=o?o.repeats||o.id:"",l=[];for(const y of e.messages||[])y.kind==="final"&&y.repeats||y.kind==="question"&&y.id===i||l.push({order:y.order,id:y.id,message:fI(y,y.id===c?n:void 0)});const d=[],h=[],m=[];for(const y of e.activities||[])if(y.kind==="tool"){const x=cI(y);d.push(...x),x.forEach((k,v)=>l.push({order:[...y.order||[],v],id:`${y.id}:${v}`,message:HN(k)}))}else if(y.kind==="tool_policy"){const x=uI(y);x&&l.push({order:y.order,id:y.id,message:x})}else if(y.kind==="llm")for(const x of y.step_ids||[])(f0.has(y.status)?m:h).push(`${y.run_id}:${x}`);l.sort((y,x)=>ZL(y,x));const _=new Map((e.runs||[]).map(y=>[y.run_id,yn(y.status).toLowerCase()])),g=yn(e.status).toLowerCase()||"unknown";return{messages:l.map(y=>y.message),tools:d,interaction:f0.has(g)?null:r,status:g,displayStatus:yn(e.display_status),openLlmCalls:h,endedLlmCalls:m,runStatus:_,statistics:n}}const ss=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Mp=e=>Array.isArray(e)?e.map(ss):[],Mn=e=>typeof e=="string"?e:"",kh=e=>Mn(e.runtime_call_id||e.call_uid),Ya=e=>Mn(e.call_id||e.id);function hI(e){if(e.status!=="waiting")return!1;const t=e.result&&typeof e.result=="object"?e.result.wait:null,n=t&&typeof t.details=="object"?t.details:null;return(n==null?void 0:n.mode)==="approval_required"||(n==null?void 0:n.kind)==="tool_approval"||String((t==null?void 0:t.wait_key)||"").startsWith("tool_approval:")}function GN(e,t){const n=t.record,r=ss(n.effect);if(r.type!=="tool_calls")return[];const i=ss(n.result),o=Mp(ss(r.payload).tool_calls),c=o.length||n.status!=="waiting"?o:Mp(ss(ss(i.wait).details).tool_calls),l=Mp(i.results),d=c.length?c:l,h=[];return d.forEach((m,_)=>{let g=kh(m)?l.filter(O=>kh(O)===kh(m)):[];!g.length&&Ya(m)&&c.filter(O=>Ya(O)===Ya(m)).length===1&&(g=l.filter(O=>Ya(O)===Ya(m)));const y=c.length?g.length===1?g[0]:c.length===l.length?l[_]:{}:m,x=kh(m)||kh(y)||`${Mn(n.idempotency_key)||Mn(n.step_id)||t.cursor}:${_}`,k=`${t.runId}:${x}`,v=e.get(k),N=Mn(m.name||y.name)||(v==null?void 0:v.name);if(!N)return;const $=n.status==="completed"||n.status==="failed",C=n.status==="failed"||y.success===!1||!!y.error,S=m.arguments??y.arguments??(v==null?void 0:v.arguments),D={...v,id:k,runId:t.runId,name:N,arguments:S,status:$?C?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof y.success=="boolean"?{success:y.success}:{},...y.output!==void 0||y.result!==void 0?{output:y.output??y.result}:{},...y.error?{error:String(y.error)}:{},...Xw(y)?{sandbox:Xw(y)}:{},...Ya(m)||Ya(y)?{callId:Ya(m)||Ya(y)}:{},...v!=null&&v.approvalWait||hI(n)?{approvalWait:!0}:{},startedAt:(v==null?void 0:v.startedAt)||Mn(n.started_at)||void 0,endedAt:$&&Mn(n.ended_at)||(v==null?void 0:v.endedAt)};v&&["completed","failed"].includes(v.status)&&!$||(e.set(k,D),h.push(D))}),h}function Ad(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function ya(e,t){for(const n of t){const r=e==null?void 0:e[n];if(r==null||r===""||typeof r=="boolean")continue;const i=Number(r);if(Number.isFinite(i)&&i>=0)return Math.trunc(i)}}function KN(e){if(typeof e=="string")try{return ss(JSON.parse(e))}catch{return{}}return ss(e)}function wd(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function mI(e){return ya(e,["reasoning_tokens","thinking_tokens"])??ya(ss(e.completion_tokens_details),["reasoning_tokens"])??ya(ss(e.output_tokens_details),["reasoning_tokens"])}function _I(e){const t=ss(typeof e=="string"&&e.trim().startsWith("{")?KN(e):e);return Mn(t.error_class)}function pI(e){const t=new Map;for(const n of e){const r=n.record;if(ss(r.effect).type!=="emit_event")continue;const i=ss(r.result);if(Mn(i.name)!=="abstract.progress")continue;const o=ss(i.payload);if(Mn(o.kind)!=="llm"||!Mn(o.step_id))continue;const c=`${Mn(o.run_id)||n.runId}:${Mn(o.step_id)}`,l=t.get(c)||{},d=Ad(o.ttft_s);d!==void 0&&(l.ttftS=d),l.provider=l.provider||Mn(o.provider)||void 0,l.model=l.model||Mn(o.model)||void 0,t.set(c,l)}return t}function Oy(e){var k,v,N,$;const t=new Map,n=new Set,r=new Set,i={llmCalls:0,toolCalls:0,changedFiles:[]};let o=1/0,c=-1/0,l=!1,d=0,h=0,m=0;const _=pI(e),g=[],y=new Set;for(const C of e){const S=C.record,D=`${C.runId}:${S.step_id||C.cursor}:${S.status}`;if(n.has(D))continue;n.add(D);for(const ae of[S.started_at,S.ended_at]){const je=Date.parse(Mn(ae));Number.isFinite(je)&&(o=Math.min(o,je),c=Math.max(c,je))}for(const ae of GN(t,C))ae.status==="waiting"&&y.add(ae.id);if(ss(S.effect).type!=="llm_call"||S.status!=="completed")continue;i.llmCalls+=1;const O=ss(S.result),A=ss(O.output),P=ss(O.usage||O.token_usage||O.tokens||A.usage||A.token_usage||A.tokens),W=ya(P,["input_tokens","prompt_tokens","prompt","input","in"]),J=ya(P,["output_tokens","completion_tokens","completion","output","out"]),G=ya(P,["total_tokens","total"])??(W!==void 0||J!==void 0?(W||0)+(J||0):void 0);G!==void 0&&(W===void 0||J===void 0||W+J!==G)&&(l=!0),W!==void 0&&(i.inputTokens=(i.inputTokens||0)+W),J!==void 0&&(i.outputTokens=(i.outputTokens||0)+J),G!==void 0&&(i.totalTokens=(i.totalTokens||0)+G);const V=Ad(O.gen_time??A.gen_time);V!==void 0&&(i.genTimeMs=(i.genTimeMs||0)+V,i.timedCalls=(i.timedCalls||0)+1);const R=ss(O.metadata||A.metadata),M=ss(R.performance),I=Ad(M.prompt_tokens_per_second),L=Ad(M.generation_tokens_per_second),K=ss(R.prompt_cache),H=Ad(K.cached_tokens),z=Ad(K.fed_tokens);if(I!==void 0||L!==void 0){if(i.measuredSpeedCalls=(i.measuredSpeedCalls||0)+1,I!==void 0&&I>0&&(i.promptTokensPerSecond=(i.promptTokensPerSecond||0)+I,W!==void 0)){const ae=W/I*1e3;i.prefillMs=(i.prefillMs||0)+ae,z!==void 0&&(d+=z,h+=ae)}L!==void 0&&L>0&&(i.generationTokensPerSecond=(i.generationTokensPerSecond||0)+L,J!==void 0&&(i.decodeMs=(i.decodeMs||0)+J/L*1e3))}if(H!==void 0||z!==void 0){i.measuredCacheCalls=(i.measuredCacheCalls||0)+1,i.cachedTokens=(i.cachedTokens||0)+(H||0),i.fedTokens=(i.fedTokens||0)+(z||0);const ae=Mn(K.outcome);if(ae){const je=i.cacheOutcomes||[];je.includes(ae)||je.push(ae),i.cacheOutcomes=je}}const ee=Mn(S.step_id)||void 0,B=ee&&_.get(`${C.runId}:${ee}`)||{},te=ss(O.route),se={runId:C.runId};ee&&(se.stepId=ee),Mn(S.started_at)&&(se.startedAt=Mn(S.started_at));const de=Mn(O.model||A.model)||Mn(te.model)||B.model,be=Mn(te.provider)||Mn(ss(R._provider_request).provider)||B.provider||Mn(O.provider);de&&(se.model=de),be&&(se.provider=be),de&&(i.models=wd(i.models,de)),be&&(i.providers=wd(i.providers,be)),(G===void 0||W!==void 0&&J!==void 0&&W+J===G)&&(W!==void 0&&(se.inputTokens=W),J!==void 0&&(se.outputTokens=J)),G!==void 0&&(se.totalTokens=G);const Me=mI(P);Me!==void 0&&(se.reasoningTokens=Me,i.reasoningTokens=(i.reasoningTokens||0)+Me),H!==void 0&&(se.cachedTokens=H),z!==void 0&&(se.fedTokens=z),Mn(K.outcome)&&(se.cacheOutcome=Mn(K.outcome)),Mn(K.backend)&&(se.cacheBackend=Mn(K.backend),i.cacheBackends=wd(i.cacheBackends,se.cacheBackend)),V!==void 0&&(se.genTimeMs=V),I!==void 0&&I>0&&(se.promptTokensPerSecond=I),L!==void 0&&L>0&&(se.generationTokensPerSecond=L),B.ttftS!==void 0?(se.ttftMs=B.ttftS*1e3,se.promptMs=se.ttftMs,se.promptSource="ttft",i.ttftMs=(i.ttftMs||0)+se.ttftMs,i.ttftCalls=(i.ttftCalls||0)+1):se.promptTokensPerSecond!==void 0&&W!==void 0&&(se.promptMs=W/se.promptTokensPerSecond*1e3,se.promptSource="rate"),se.promptMs!==void 0&&(i.promptPhaseMs=(i.promptPhaseMs||0)+se.promptMs,i.promptPhaseCalls=(i.promptPhaseCalls||0)+1,z!==void 0&&se.promptMs>0&&(se.promptNewTokensPerSecond=z/(se.promptMs/1e3),i.promptPhaseNewTokens=(i.promptPhaseNewTokens||0)+z,m+=se.promptMs)),se.ttftMs!==void 0&&V!==void 0&&V>=se.ttftMs?se.generationMs=V-se.ttftMs:se.generationTokensPerSecond!==void 0&&J!==void 0&&(se.generationMs=J/se.generationTokensPerSecond*1e3),se.generationMs!==void 0&&J!==void 0&&(i.generationPhaseMs=(i.generationPhaseMs||0)+se.generationMs,i.generationPhaseTokens=(i.generationPhaseTokens||0)+J);const Ne=ss(R.speculation);if(Object.keys(Ne).length){const ae={};Mn(Ne.mode)&&(ae.mode=Mn(Ne.mode)),typeof Ne.used=="boolean"&&(ae.used=Ne.used),Mn(Ne.draft_kind)&&(ae.draftKind=Mn(Ne.draft_kind));const je=ya(Ne,["accepted_tokens"]),Te=ya(Ne,["drafted_tokens"]),Ve=ya(Ne,["rounds"]),_t=ya(Ne,["num_draft_tokens"]);je!==void 0&&(ae.acceptedTokens=je),Te!==void 0&&(ae.draftedTokens=Te),je!==void 0&&Te&&(ae.acceptanceRate=je/Te),Ve!==void 0&&(ae.rounds=Ve),_t!==void 0&&(ae.draftLength=_t),se.speculation=ae;const Qe=i.speculation||(i.speculation={calls:0,used:0});Qe.calls+=1,ae.used&&(Qe.used+=1),ae.mode&&(Qe.modes=wd(Qe.modes,ae.mode)),ae.draftKind&&(Qe.draftKinds=wd(Qe.draftKinds,ae.draftKind)),je!==void 0&&Te!==void 0&&(Qe.acceptedTokens=(Qe.acceptedTokens||0)+je,Qe.draftedTokens=(Qe.draftedTokens||0)+Te),Ve!==void 0&&(Qe.rounds=(Qe.rounds||0)+Ve),_t!==void 0&&(Qe.draftLengths=wd(Qe.draftLengths,_t))}g.push(se)}g.length&&(g.every(C=>C.startedAt)&&g.sort((C,S)=>Date.parse(C.startedAt)-Date.parse(S.startedAt)),i.modelCalls=g),m>0&&i.promptPhaseNewTokens!==void 0&&(i.promptPhaseTokensPerSecond=i.promptPhaseNewTokens/(m/1e3)),i.generationPhaseMs&&i.generationPhaseTokens!==void 0&&(i.generationPhaseTokensPerSecond=i.generationPhaseTokens/(i.generationPhaseMs/1e3)),(k=i.speculation)!=null&&k.draftedTokens&&(i.speculation.acceptanceRate=(i.speculation.acceptedTokens||0)/i.speculation.draftedTokens),i.measuredSpeedCalls&&(i.promptTokensPerSecond!==void 0&&(i.promptTokensPerSecond/=i.measuredSpeedCalls),i.generationTokensPerSecond!==void 0&&(i.generationTokensPerSecond/=i.measuredSpeedCalls)),h>0&&(i.prefillNewTokens=d,i.prefillNewTokensPerSecond=d/(h/1e3));const x=new Map;for(const C of t.values()){if(C.status==="waiting"){i.toolsWaiting=(i.toolsWaiting||0)+1;continue}if(C.status==="running"){i.toolsRunning=(i.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(C.status))continue;i.toolCalls+=1;const S=C.status==="failed";S&&(i.toolsFailed=(i.toolsFailed||0)+1);const D=i.toolBreakdown||(i.toolBreakdown={}),O=D[C.name]||(D[C.name]={calls:0,failed:0});if(O.calls+=1,S){O.failed+=1;const G=_I(C.output);G&&((O.errors||(O.errors={}))[G]=(((v=O.errors)==null?void 0:v[G])||0)+1)}const A=Date.parse(Mn(C.startedAt)),P=Date.parse(Mn(C.endedAt));if(Number.isFinite(A)&&Number.isFinite(P)&&P>=A){const G=`${C.runId}|${C.startedAt}|${C.endedAt}`,V=x.get(G)||{ms:P-A,calls:0,names:new Map,waited:!1};V.calls+=1,V.names.set(C.name,(V.names.get(C.name)||0)+1),y.has(C.id)&&(V.waited=!0),x.set(G,V)}if(C.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(C.name))continue;const W=KN(C.arguments),J=Mn(W.destination||W.destination_path||W.file_path||W.path||W.filename);J&&r.add(J)}for(const C of x.values()){i.toolBatches=(i.toolBatches||0)+1,i.toolTimeMs=(i.toolTimeMs||0)+C.ms,C.waited&&(i.toolTimeIncludesApproval=!0);const S=[...C.names.keys()].sort();(!i.slowestToolBatch||C.ms>i.slowestToolBatch.ms)&&(i.slowestToolBatch={ms:C.ms,calls:C.calls,tools:S});const D=(N=i.toolBreakdown)==null?void 0:N[S[0]];if(S.length===1&&D)D.ms=(D.ms||0)+C.ms;else for(const O of S){const A=($=i.toolBreakdown)==null?void 0:$[O];A&&(A.sharedBatches=(A.sharedBatches||0)+1)}}return i.changedFiles=[...r],l&&(delete i.inputTokens,delete i.outputTokens),Number.isFinite(o)&&Number.isFinite(c)&&(i.durationMs=Math.max(0,c-o)),{tools:[...t.values()],statistics:i}}function gI(e){const t=ss(ss(e).ledgers);return Object.entries(t).flatMap(([n,r])=>Mp(ss(r).items).map((i,o)=>({runId:n,cursor:Number(i.cursor)||o+1,record:Object.keys(ss(i.record)).length?ss(i.record):i})))}const m0=e=>`${e} ${e===1?"file":"files"}`;function yI(e){const t=e.filter(i=>i.state==="queued"||i.state==="uploading").length;if(t)return`Wait for ${m0(t)} to finish uploading.`;const n=e.filter(i=>i.state==="failed"||i.state==="refused");if(!n.length)return null;const r=n.some(i=>i.state==="failed");return n.length===1?`"${n[0].name}" was not attached. ${r?"Retry or remove":"Remove"} it before sending.`:`${m0(n.length)} were not attached. ${r?"Retry or remove":"Remove"} them before sending.`}const wI=new Set(["blob:","data:","http:","https:"]);function vI(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return wI.has(new URL(t,n).protocol)?t:void 0}catch{return}}function xI(e){const t=typeof e.size=="number"?PN(e.size):"";if(e.state==="queued")return{meta:`Waiting${t?` · ${t}`:""}`,state:"waiting to upload"};if(e.state==="uploading")return{meta:`Uploading${t?` · ${t}`:""}`,state:"uploading"};if(e.state==="attached")return{meta:t,state:"attached"};const n=String(e.error||"").trim()||(e.state==="refused"?"Refused":"Upload failed");return{meta:n,state:`not attached: ${n}`}}function bI(e){const t=Array.isArray(e.items)?e.items:[];return t.length?s.jsx("div",{className:"pc-attachment-chips",role:"list","aria-label":"Attached files",children:t.map(n=>{const r=n.state==="queued"||n.state==="uploading",{meta:i,state:o}=xI(n),c=vI(n.thumbnailUrl);return s.jsxs("div",{role:"listitem",tabIndex:0,className:`pc-attachment-chip is-${n.state}`,"data-state":n.state,"aria-label":`${n.name}, ${o}`,"aria-busy":r||void 0,children:[s.jsx("span",{className:"pc-attachment-chip__icon","aria-hidden":"true",children:c?s.jsx("img",{className:"pc-attachment-chip__thumb",src:c,alt:"",loading:"lazy"}):r?s.jsx("span",{className:"pc-attachment-chip__spinner"}):n.state==="attached"?s.jsx(qe,{name:"paperclip",size:13}):s.jsx(qe,{name:"warning",size:13})}),s.jsxs("span",{className:"pc-attachment-chip__body",children:[s.jsx("span",{className:"pc-attachment-chip__name",title:n.name,children:n.name}),i?s.jsx("span",{className:"pc-attachment-chip__meta",children:i}):null]}),n.state==="failed"&&e.onRetry?s.jsxs("button",{type:"button",className:"pc-attachment-chip__action pc-attachment-chip__retry","data-action":"retry","aria-label":`Retry ${n.name}`,title:"Retry upload",disabled:e.disabled,onClick:()=>{var l;return(l=e.onRetry)==null?void 0:l.call(e,n.id)},children:[s.jsx(qe,{name:"refresh",size:12}),s.jsx("span",{children:"Retry"})]}):null,e.onRemove?s.jsx("button",{type:"button",className:"pc-attachment-chip__action","data-action":"remove","aria-label":`Remove ${n.name}`,title:`Remove ${n.name}`,disabled:e.disabled,onClick:()=>{var l;return(l=e.onRemove)==null?void 0:l.call(e,n.id)},children:s.jsx(qe,{name:"x",size:12})}):null]},n.id)})}):null}function kI(e,t){var n,r;if(e.kind==="ask-user"){if(t.kind==="choice"||t.kind==="free-text")return e.onSubmit(t.answer);if(t.kind==="skip"&&e.onSkip)return e.onSkip();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();if(t.kind==="approve-session"&&e.onApproveForSession)return e.onApproveForSession();if(t.kind==="deny-chat"){const i=(n=e.denyOptions)==null?void 0:n.find(o=>o.key===t.key);if(i)return i.onDeny()}if(t.kind==="approve-kind"){const i=(r=e.approveKinds)==null?void 0:r.find(o=>o.kind===t.toolset);if(i)return i.onApprove()}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")}const Td={deny:"Deny",allowOnce:"Allow once",allowForChat:"Allow for this chat",allowAll:"Allow all enabled tools",allowKindForChat:e=>`Allow all ${e} tools for this chat`,allowForRun:"Allow for this run",localChatPolicyNote:"Allowed for this chat in this browser only — the gateway cannot store chat policies.",localRunPolicyNote:"Allowed until this run ends, in this browser only — the gateway cannot store chat policies.",denyToolForChat:e=>`Always deny ${e} in this chat`,denyKindForChat:e=>`Always deny ${e} tools in this chat`,denyForChatNote:"Always deny applies to every run of this chat, automations and runs that read other people's text included, until the policy is reset; a request shown before it is refused even if approved later.",noScopeNote:"The gateway did not say where this grant applies.",unavailablePolicyNote:e=>`Allow for this chat is unavailable: ${e||"the gateway's capabilities could not be read."} Allow once still works.`,decideLater:"Decide later",submit:"Submit",skip:"Continue without answering",keepWaiting:"Keep waiting",sendEvent:"Send event"};function _0(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function jI(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"})]})}const Vo=Td;function SI(e){var V,R,M;const t=e.interaction,n=e.variant==="card",[r,i]=p.useState(""),[o,c]=p.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[l,d]=p.useState(null),[h,m]=p.useState(!1),[_,g]=p.useState(""),[y,x]=p.useState(null),k=`${t.kind}:${t.id}`,v=p.useRef(k),N=p.useRef(!1),$=p.useRef(!1),C=p.useRef(!0),S=p.useRef(0);v.current!==k&&(v.current=k,N.current=!1,$.current=!1,S.current+=1);const D=!!e.disabled||l!==null||h||N.current||$.current,O=async(I,L)=>{var z;if(e.disabled||N.current||$.current)return;const K=k,H=++S.current;N.current=!0,x(null),g(""),d(I);try{const ee=await L();if(!C.current||v.current!==K||S.current!==H)return;$.current=!0,m(!0);const B=ee&&typeof ee=="object"&&typeof ee.outcomeNote=="string"?String(ee.outcomeNote):"";g(`Response sent. Waiting for the workflow to continue.${B?` ${B}`:""}`)}catch(ee){if(!C.current||v.current!==K||S.current!==H)return;x({submission:I,message:_0(ee)}),g("The action failed. You can try again."),(z=e.onError)==null||z.call(e,ee)}finally{if(!C.current||v.current!==K||S.current!==H)return;N.current=!1,d(null)}},A=async I=>{var K;if(e.disabled||N.current||$.current)return;const L=k;try{if(await I(),!C.current||v.current!==L)return;x(null),g(t.kind==="tool-approval"?"Left for later. Nothing was sent; the run keeps waiting for this decision.":"Left for later. Nothing was sent; the run keeps waiting for your answer.")}catch(H){if(!C.current||v.current!==L)return;g(`Could not leave this for later: ${_0(H)}`),(K=e.onError)==null||K.call(e,H)}};p.useEffect(()=>{i(""),c(t.kind==="event-wait"&&t.initialPayload||""),x(null),d(null),m(!1),g("")},[k]),p.useEffect(()=>(C.current=!0,()=>{C.current=!1,S.current+=1,N.current=!1}),[]);const P=()=>{y&&O(y.submission,()=>kI(t,y.submission))},W=t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required"),J=(I,L)=>I?s.jsx("button",{type:"button",className:"pc-workflow-interaction__defer","data-decision":"defer",disabled:D,onClick:()=>void A(I),children:L}):null;let G;if(t.kind==="ask-user")G=s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(V=t.choices)!=null&&V.length?s.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(I=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice","data-decision":"choice",disabled:D||I.disabled,onClick:()=>void O({kind:"choice",answer:I.id},()=>t.onSubmit(I.id)),children:[s.jsx("span",{children:I.label}),I.description?s.jsx("small",{children:I.description}):null]},I.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:r,onChange:I=>i(I.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:n?1:2,disabled:D,onKeyDown:I=>{I.key!=="Enter"||I.shiftKey||I.nativeEvent.isComposing||I.keyCode===229||(I.preventDefault(),r.trim()&&O({kind:"free-text",answer:r},()=>t.onSubmit(r)))}},`${k}:text`),s.jsx("button",{type:"button",className:"pc-btn","data-decision":"submit",disabled:D||!r.trim(),onClick:()=>void O({kind:"free-text",answer:r},()=>t.onSubmit(r)),children:(l==null?void 0:l.kind)==="free-text"?"Sending…":t.submitLabel||Vo.submit})]}):null,t.onSkip||t.onDefer?s.jsxs("div",{className:"pc-workflow-interaction__buttons pc-workflow-interaction__buttons--secondary",children:[J(t.onDefer,t.deferLabel||Vo.keepWaiting),t.onSkip?s.jsx("button",{type:"button",className:"pc-workflow-interaction__skip","data-decision":"skip",disabled:D,onClick:()=>void O({kind:"skip"},t.onSkip),children:(l==null?void 0:l.kind)==="skip"?"Continuing…":t.skipLabel||Vo.skip}):null]}):null]});else if(t.kind==="tool-approval"){const I=String(t.disabledReason||"").trim(),L=D||!!I,K=[!I&&t.onApproveForSession&&t.approveForSessionDescription?t.approveForSessionDescription:"",!I&&t.onApproveAll&&t.approveAllDescription?t.approveAllDescription:""].filter(Boolean),H=K.length?String(t.broadScopeSummary||"").trim():"";G=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?n?s.jsxs("details",{className:"pc-workflow-interaction__review",children:[s.jsx("summary",{children:"Review"}),s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail})]}):s.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,s.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[J(t.onDefer,t.deferLabel||Vo.decideLater),s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:D,onClick:()=>void O({kind:"deny"},t.onDeny),children:(l==null?void 0:l.kind)==="deny"?"Denying…":t.denyLabel||Vo.deny}),s.jsx("button",{type:"button",className:"pc-btn","data-decision":"approve",disabled:D,onClick:()=>void O({kind:"approve"},t.onApprove),children:(l==null?void 0:l.kind)==="approve"?"Allowing…":t.approveLabel||Vo.allowOnce}),t.onApproveForSession?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session","data-decision":"approve-session",disabled:L,title:I||t.approveForSessionDescription||void 0,onClick:()=>void O({kind:"approve-session"},t.onApproveForSession),children:(l==null?void 0:l.kind)==="approve-session"?"Allowing…":t.approveForSessionLabel||Vo.allowForChat}):null,(t.approveKinds||[]).map(z=>s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session pc-workflow-interaction__allow-kind","data-decision":"approve-kind","data-kind":z.kind,disabled:L,title:I||t.approveForSessionDescription||void 0,onClick:()=>void O({kind:"approve-kind",toolset:z.kind},z.onApprove),children:(l==null?void 0:l.kind)==="approve-kind"&&l.toolset===z.kind?"Allowing…":z.label||Vo.allowKindForChat(z.kind)},z.kind)),t.onApproveAll?s.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all","data-decision":"approve-all",disabled:L,title:I||t.approveAllDescription||void 0,onClick:()=>void O({kind:"approve-all"},t.onApproveAll),children:(l==null?void 0:l.kind)==="approve-all"?"Allowing…":t.approveAllLabel||Vo.allowAll}):null]}),H?s.jsx("p",{className:"pc-workflow-interaction__scope","data-scope-summary":"",children:H}):null,t.remember?s.jsxs("label",{className:"pc-workflow-interaction__remember",children:[s.jsx("input",{type:"checkbox",checked:t.remember.checked,disabled:D,onChange:z=>t.remember.onChange(z.target.checked)}),s.jsx("span",{children:t.remember.label})]}):null,t.deniedNote?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note","data-denied-note":"",children:t.deniedNote}):null,(R=t.denyOptions)!=null&&R.length?s.jsxs("details",{className:"pc-workflow-interaction__more","data-more":"",children:[s.jsx("summary",{children:"More"}),s.jsx("p",{className:"pc-workflow-interaction__scope",children:Vo.denyForChatNote}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:t.denyOptions.map(z=>s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny-chat","data-key":z.key,disabled:D,onClick:()=>void O({kind:"deny-chat",key:z.key},z.onDeny),children:(l==null?void 0:l.kind)==="deny-chat"&&l.key===z.key?"Denying…":z.label},z.key))})]}):null,t.policySummary?s.jsx("p",{className:"pc-workflow-interaction__scope","data-policy-summary":"",children:t.policySummary}):null,t.scopeNote?s.jsx("p",{className:"pc-workflow-interaction__scope-note",role:"note","data-scope-note":"",children:t.scopeNote}):null,t.notCovered?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note","data-not-covered":"",children:t.notCovered}):null,I&&(t.onApproveAll||t.onApproveForSession||(M=t.approveKinds)!=null&&M.length)?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note",children:I}):null,H&&K.length?s.jsxs("details",{className:"pc-workflow-interaction__scope-details","data-scope-details":"",children:[s.jsx("summary",{children:"What the broader choices allow"}),K.map(z=>s.jsx("p",{className:"pc-workflow-interaction__scope",children:z},z))]}):K.map(z=>s.jsx("p",{className:"pc-workflow-interaction__scope",children:z},z))]})}else G=s.jsxs("div",{className:"pc-workflow-interaction__body",children:[s.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),s.jsxs("label",{className:"pc-workflow-interaction__entry",children:[s.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),s.jsx("textarea",{value:o,onChange:I=>c(I.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:n?1:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:D},`${k}:payload`)]}),s.jsx("div",{className:"pc-workflow-interaction__buttons",children:s.jsx("button",{type:"button",className:"pc-btn","data-decision":"send-event",disabled:D,onClick:()=>void O({kind:"event",payload:o},()=>t.onSend(o)),children:(l==null?void 0:l.kind)==="event"?"Sending…":t.sendLabel||Vo.sendEvent})})]});return s.jsxs("section",{className:["pc-workflow-interaction",n?"pc-workflow-interaction--card":""].filter(Boolean).join(" "),"data-variant":n?"card":"panel","aria-labelledby":`pc-workflow-interaction-${k}`,children:[s.jsxs("div",{className:"pc-workflow-interaction__heading",children:[s.jsx(qe,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:n?14:16}),s.jsxs("div",{children:[s.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${k}`,children:W}),t.description?s.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),G,y?s.jsx(jI,{message:y.message,onRetry:P,disabled:D}):null,s.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:_})]})}function vd(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function NI(e){var ne;rf();const[t,n]=p.useState(!1),[r,i]=p.useState(!1),[o,c]=p.useState(!1),[l,d]=p.useState(null),[h,m]=p.useState(()=>{var we,fe;return((fe=(we=e.steer)==null?void 0:we.modes)==null?void 0:fe[0])||"guide"}),[_,g]=p.useState(null),[y,x]=p.useState("idle"),k=p.useRef(null),v=p.useRef(!0),N=p.useRef(!1),$=p.useRef(!1),C=p.useRef(!1),S=p.useRef(0),D=p.useRef(0),O=p.useRef(0);p.useEffect(()=>(v.current=!0,()=>{var we;v.current=!1,S.current+=1,D.current+=1,O.current+=1,N.current=!1,$.current=!1,C.current=!1,(we=k.current)==null||we.abort(),k.current=null}),[]);const A=!!e.blockedNotice,P=!!e.disabled||A,W=!!e.busy||t,J=t||!!e.busy&&!e.sendWhileBusy,G=e.stopState||null,V=(G==null?void 0:G.phase)==="stopping",R=e.steer&&typeof e.steer.onSteer=="function"?e.steer:null,M=R?(ne=R.modes)!=null&&ne.length?R.modes:["guide"]:[],I=M.includes(h)?h:M[0]||"guide",L=!!R&&!!e.busy,K=Array.isArray(e.attachmentItems)?e.attachmentItems:[];p.useEffect(()=>{g(null)},[!!e.busy]);const H=typeof e.onFiles=="function",z=p.useRef(null),[ee,B]=p.useState(null),[te,se]=p.useState(""),de=p.useRef(e.onFiles);de.current=e.onFiles;const be=p.useRef(P);be.current=P;const Me=async(we,fe)=>{const $e=de.current;if($e){if(be.current){d({action:"attach",message:"attachments are unavailable right now."});return}if(fe.length)d({action:"attach",message:RN(fe)});else if(we.length)d(null);else{d({action:"attach",message:"the drop contained no files."});return}if(we.length){se(`Attaching ${we.length} ${we.length===1?"file":"files"}…`);try{await $e(we)}catch(pe){v.current&&d({action:"attach",message:vd(pe)})}}}},Ne=p.useRef(Me);Ne.current=Me,p.useEffect(()=>{if(!H||typeof window>"u")return;const we=new fL;let fe=0;const $e=ct=>!!(z.current&&ct instanceof Node&&z.current.contains(ct)),pe=()=>{we.reset(),fe&&window.clearInterval(fe),fe=0,B(null)},le=()=>{fe||(fe=window.setInterval(()=>{we.active(Date.now())||pe()},250))},ze=ct=>{var nn;if(!Uh((nn=ct.dataTransfer)==null?void 0:nn.types))return;we.enter(Date.now());const It=$e(ct.target),vt=i0(ct.dataTransfer);B(wn=>wn&&wn.over===It&&wn.count===(vt??wn.count)?wn:{count:vt??(wn==null?void 0:wn.count)??null,over:It}),le()},st=ct=>{var vt;if(!Uh((vt=ct.dataTransfer)==null?void 0:vt.types))return;ct.preventDefault(),we.over(Date.now());const It=$e(ct.target);ct.dataTransfer&&(ct.dataTransfer.dropEffect=It&&!be.current?"copy":"none"),B(nn=>nn&&nn.over===It?nn:{count:(nn==null?void 0:nn.count)??i0(ct.dataTransfer),over:It}),le()},kt=ct=>{var It;Uh((It=ct.dataTransfer)==null?void 0:It.types)&&(we.leave(Date.now())||pe())},pt=ct=>{var On;if(!Uh((On=ct.dataTransfer)==null?void 0:On.types))return;const It=$e(ct.target),vt=ct.defaultPrevented&&!It;if(ct.preventDefault(),pe(),vt)return;if(!It){d({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:nn,folders:wn}=mx(ct.dataTransfer);Ne.current(nn,wn)},jt=ct=>{ct.key==="Escape"&&we.depth>0&&pe()};return window.addEventListener("dragenter",ze),window.addEventListener("dragover",st),window.addEventListener("dragleave",kt),window.addEventListener("drop",pt),window.addEventListener("dragend",pe),window.addEventListener("blur",pe),window.addEventListener("keydown",jt),()=>{window.removeEventListener("dragenter",ze),window.removeEventListener("dragover",st),window.removeEventListener("dragleave",kt),window.removeEventListener("drop",pt),window.removeEventListener("dragend",pe),window.removeEventListener("blur",pe),window.removeEventListener("keydown",jt),fe&&window.clearInterval(fe)}},[H]);const ae=we=>{if(!H||P)return;const fe=LN(we.clipboardData);fe.length&&(we.preventDefault(),Me(fe,[]))},je=ee?s.jsxs("div",{className:["pc-workflow-chat__dropzone",ee.over?"is-over":"",P?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[s.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:s.jsx(qe,{name:"paperclip",size:18})}),s.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[s.jsx("strong",{children:P?"Attachments are unavailable right now":o0(ee.count)}),P?null:s.jsx("span",{children:ee.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,Te=ee?P?"Attachments are unavailable right now":o0(ee.count):te,Ve=async we=>{if(!R)return;const fe=I,$e=++S.current;N.current=!0,d(null),g(null),n(!0);try{const pe=await R.onSteer(we,fe);if(!v.current||S.current!==$e)return;if(!(pe!=null&&pe.accepted)&&!(pe!=null&&pe.duplicate)){d({action:"steer",message:"the gateway did not accept this message (accepted=false)."});return}g({mode:fe,...typeof pe.seq=="number"?{seq:pe.seq}:{},duplicate:!!pe.duplicate}),e.onDraftChange("")}catch(pe){v.current&&S.current===$e&&d({action:"steer",message:vd(pe)})}finally{v.current&&S.current===$e&&(N.current=!1,n(!1))}},_t=async()=>{const we=String(e.draft||"");if(P||N.current||!we.trim())return;if(L)return void Ve(we);if(!e.sendWhileBusy&&e.busy)return;const fe=K.length?yI(K):null;if(fe){d({action:"send",message:fe});return}const $e=++S.current,pe=new AbortController;k.current=pe,N.current=!0,d(null),g(null),n(!0);try{await e.onSend(we,{signal:pe.signal})}catch(le){v.current&&S.current===$e&&!pe.signal.aborted&&d({action:"send",message:vd(le)})}finally{k.current===pe&&(k.current=null),v.current&&S.current===$e&&(N.current=!1,n(!1))}},Qe=async()=>{if(P||$.current||!e.onCancel)return;const we=++D.current;$.current=!0,d(null),i(!0);const $e=k.current||new AbortController;$e.abort(new DOMException("Stopped by the user","AbortError"));try{await e.onCancel($e.signal)}catch(pe){v.current&&D.current===we&&d({action:"cancel",message:vd(pe)})}finally{v.current&&D.current===we&&($.current=!1,i(!1))}},it=async()=>{if(P||C.current||!e.onAttach)return;const we=++O.current;C.current=!0,d(null),c(!0);try{await e.onAttach()}catch(fe){v.current&&O.current===we&&d({action:"attach",message:vd(fe)})}finally{v.current&&O.current===we&&(C.current=!1,c(!1))}},$t=()=>{l&&((l.action==="send"||l.action==="steer")&&_t(),l.action==="cancel"&&Qe(),l.action==="attach"&&it())},ot=e.toolbar||null,mt=we=>hN((Array.isArray(e.messages)?e.messages:[]).filter(fe=>!fe.toolActivity&&!fe.live&&String(fe.content||"").trim()),we?{heading:we}:void 0),et=async we=>{if(!P){d(null);try{await we()}catch(fe){v.current&&d({action:"toolbar",message:vd(fe)})}}},Lt=async()=>{const we=await il(mt());v.current&&(x(we?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>v.current&&x("idle"),1200))},ce=ot?s.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[ot.onNewSession?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:P,onClick:()=>void et(ot.onNewSession),children:[s.jsx(qe,{name:"plus",size:14}),s.jsx("span",{children:"New chat"})]}):null,ot.onClear?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:P,onClick:()=>void et(ot.onClear),children:[s.jsx(qe,{name:"trash",size:14}),s.jsx("span",{children:"Clear"})]}):null,ot.copyTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"copy",onClick:()=>void Lt(),children:[s.jsx(qe,{name:y==="copied"?"check":"copy",size:14}),s.jsx("span",{children:y==="copied"?"Copied":y==="failed"?"Copy failed":"Copy"})]}):null,ot.exportTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const we=ot.exportTranscript;mN({filename:we.filename,text:mt(we.heading),mime:"text/markdown;charset=utf-8"})},children:[s.jsx(qe,{name:"download",size:14}),s.jsx("span",{children:"Export"})]}):null]}):null,Se=I==="queue"?"Queue":"Steer",He=_?_.mode==="queue"?`Queued for the next turn${typeof _.seq=="number"?` (seq ${_.seq})`:""}.`:`${_.duplicate?"Already queued":"Queued"}${typeof _.seq=="number"?` (seq ${_.seq})`:""}. ${R!=null&&R.parked?"The run is waiting: your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary."}`:"";return s.jsxs("section",{ref:z,className:["pc-workflow-chat",ee?"pc-workflow-chat--dragging":"",ee!=null&&ee.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||ce?s.jsxs("header",{className:["pc-workflow-chat__header",ce?"pc-workflow-chat__header--toolbar":""].filter(Boolean).join(" "),children:[e.header?s.jsx("div",{className:"pc-workflow-chat__header-main",children:e.header}):null,ce]}):null,s.jsx("div",{className:"pc-workflow-chat__transcript",children:s.jsx(fx,{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(SI,{interaction:e.interaction,disabled:P}):null,A?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${A?"blocked":""}`})}),l?s.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[s.jsxs("span",{children:["Could not"," ",l.action==="send"?"send this message":l.action==="steer"?I==="queue"?"queue this message":"steer the run":l.action==="attach"?"attach a file":l.action==="toolbar"?"complete that action":"stop the run",": ",l.message]}),l.action!=="toolbar"?s.jsx("button",{type:"button",onClick:$t,disabled:P,children:"Try again"}):null]}):null,s.jsxs("div",{className:"pc-workflow-chat__composer",children:[s.jsx(hx,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void _t(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:P,busy:L?t:J,sendLabel:L?Se:e.sendLabel,busyLabel:L?I==="queue"?"Queueing…":"Steering…":e.busyLabel,rows:2,leading:e.attachments||K.length?s.jsxs("div",{className:"pc-workflow-chat__attachments",children:[K.length?s.jsx(bI,{items:K,onRemove:e.onRemoveAttachment,onRetry:e.onRetryAttachment,disabled:P}):null,e.attachments]}):null,overlay:je,onPaste:H?ae: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:P||o,onClick:()=>void it(),children:[s.jsx(qe,{name:"paperclip",size:16}),s.jsx("span",{children:o?"Attaching…":"Attach"})]}):null,e.composerExtras,L&&M.length>1?s.jsx("span",{className:"pc-workflow-chat__steer-modes",role:"group","aria-label":"While the run is busy",children:M.map(we=>s.jsx("button",{type:"button",className:"pc-workflow-chat__steer-mode","data-steer-mode":we,"aria-pressed":I===we,disabled:P||t,onClick:()=>m(we),children:we==="queue"?"Queue next turn":"Guide this run"},we))}):null,W&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:P||r||V,onClick:()=>void Qe(),children:[s.jsx(qe,{name:"x",size:14}),s.jsx("span",{children:r||V?"Stopping…":"Stop"})]}):G?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${G.phase}`,role:"status","aria-live":"polite",children:G.label}):null]})}),R?s.jsx("div",{className:"pc-workflow-chat__steer-status",role:"status","aria-live":"polite",children:He}):null,H?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:Te}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function $I(e){return e.source==="replay_view"?"Live view from the gateway (replay view)":e.source==="ledger_fold"?`Rebuilt in this client from the run ledger${e.sourceReason?`: ${e.sourceReason}`:""}`:""}function CI(e){return e.toolApprovalGranted?null:e.interaction}const Py={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Jt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Et(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function qh(e){return Array.isArray(e)?e:[]}function EI(e){const t=Jt(e);return!!(t&&(t.code==="revision_conflict"||t.reason_code==="revision_conflict"||t.status===409||t.name==="SessionToolPolicyConflict"))}function bi(e){return Et(e==null?void 0:e.status).toLowerCase()||"unknown"}function os(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function _o(e){const t=Jt(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function AI(e){const t=Jt(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Dy(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Jt(n);if(!r)return n;const i={};for(const o of Object.keys(r).sort())i[o]=t(r[o]);return i};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function tv(e){if(typeof e=="string")return e.trim();const t=Jt(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return""}function xd(e){const t=tv(e);if(t)return t;if(!Jt(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function p0(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const i=Et(e[r]);if(i)return i}const t=Jt(e.context);for(const r of["task","message"]){const i=Et(t==null?void 0:t[r]);if(i)return i}const n=qh(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const i=Jt(n[r]);if(Et(i==null?void 0:i.role).toLowerCase()!=="user")continue;const o=Et(i==null?void 0:i.content);if(o)return o}return""}function JN(e){const t=Jt(e.result);return Jt(t==null?void 0:t.wait)}function Fy(e){return e?Et(e.reason)==="subworkflow"||Et(e.wait_key).startsWith("subworkflow:"):!1}function g0(e,t){return!!(e&&e.runId===t.runId&&Et(e.wait.wait_key)===Et(t.wait.wait_key))}function nv(e){return Jt(e.effect)||{}}function TI(e,t){return Et(e.run_id)||t}function y0(e){return Et(e.ended_at)||Et(e.started_at)||void 0}function w0(e){const t=new Set,n=h=>{const m=Et(h);m&&t.add(m)},r=Jt(e.result);n(r==null?void 0:r.sub_run_id),n(r==null?void 0:r.subRunId),n(r==null?void 0:r.child_run_id);const i=nv(e),o=Jt(i.payload);Et(i.type)==="start_subworkflow"&&(n(o==null?void 0:o.sub_run_id),n(o==null?void 0:o.subRunId),n(o==null?void 0:o.child_run_id));const c=JN(e),l=Jt(c==null?void 0:c.details);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 d=Et(c==null?void 0:c.wait_key);return d.startsWith("subworkflow:")&&n(d.slice(12)),[...t]}const zy=new WeakMap,MI=/^(live|live-end|stream-unavailable):/;function RI(e){return!!(e&&typeof e=="object"&&e.name==="ReplayViewUnavailableError")}function v0(e){const t=String(e||""),n=t.indexOf("~");return n<0?"":t.slice(n+1)}const jh=()=>({sessionId:"",transport:null,order:[],created:new Map,turns:new Map});class LI{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Py},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,this.sessionToolPolicy=null,this.sessionPolicyUnavailableReason="",this.sessionPolicyState=null,this.sessionPolicyClamped=[],this.toolPolicyByCall=new Map,this.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds=new Set,this.viewTerminalRuns=new Set,this.viewStreamEnded=!1,this.viewEarlier={messages:[],tools:[]},this.viewTurnCache=jh();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,this.sessionToolPolicy=n.sessionToolPolicy||null,this.sessionToolPolicy||(this.sessionPolicyUnavailableReason=Et(n.sessionToolPolicyUnavailableReason)),this.snapshot=this.withSessionPolicy({...Py})}sessionPolicyMode(){var t;return((t=this.sessionToolPolicy)==null?void 0:t.supported)===!0?"gateway":!this.sessionToolPolicy&&this.sessionPolicyUnavailableReason?"unavailable":"local-fallback"}sessionPolicyStatus(){const t=this.sessionPolicyMode();return{mode:t,...t==="unavailable"?{reason:this.sessionPolicyUnavailableReason}:{},clamped:this.sessionPolicyClamped,policy:this.sessionPolicyState}}setSessionToolPolicyClient(t,n={}){const r=t?"":Et(n.reason);if(t===this.sessionToolPolicy&&r===this.sessionPolicyUnavailableReason)return;const i=!!(t&&this.sessionToolPolicy&&t.sessionId===this.sessionToolPolicy.sessionId);this.sessionToolPolicy=t,this.sessionPolicyUnavailableReason=r,i||(this.sessionPolicyState=null,this.sessionPolicyClamped=[]),this.set({...this.snapshot})}gatewayPolicy(){const t=this.sessionToolPolicy;if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);if(!t||t.supported!==!0)throw new Error("This gateway cannot store chat tool policies (session_tool_policy is not supported).");return t}adoptSessionPolicy(t){var n,r;this.sessionPolicyState=t,this.sessionPolicyClamped=Array.isArray(t==null?void 0:t.clamped)?t.clamped.filter(i=>i&&typeof i=="object"):[],this.set({...this.snapshot}),(r=(n=this.options).onSessionPolicy)==null||r.call(n,t,this.sessionPolicyClamped)}async loadSessionPolicy(){const t=await this.gatewayPolicy().get();return this.adoptSessionPolicy(t),t}requireRootSession(t){var r,i;const n=Et((r=this.snapshot.run)==null?void 0:r.session_id)||Et((i=this.runStates.get(this.rootRunId))==null?void 0:i.session_id);if(!n)throw new Error("This chat's session is not known yet: the policy is written to the root run's session.");if(n!==t.sessionId)throw new Error(`The tool policy client is bound to session ${t.sessionId}, but this chat's root run belongs to session ${n}: the policy is written to the root run's session.`)}async currentRevision(t){var i;if(typeof((i=this.sessionPolicyState)==null?void 0:i.revision)=="number")return this.sessionPolicyState.revision;const n=await this.loadSessionPolicy();if(typeof(n==null?void 0:n.revision)=="number")return n.revision;const r=t.revision;return typeof r=="number"?r:void 0}async policyWriteError(t){if(EI(t))return await this.loadSessionPolicy().catch(()=>null),new Error("Someone changed this chat's policy; re-read it before deciding again (it was refreshed).");const n=t instanceof Error?t.message:String(t);return new Error(`This chat's policy was not changed: ${n}`)}requireTarget(t){const n=this.requireInteraction();if(os(this.snapshot.status))throw new Error("This run has already ended.");if(n.runId!==t.runId||Et(n.wait.wait_key)!==t.waitKey||t.stepId!==void 0&&n.stepId!==t.stepId)throw new Error("This approval request has changed. Review the current request before deciding.");if(!this.isToolApproval(n))throw new Error("This is not a tool approval request.");return n}async writeThenAnswer(t,n,r,i=[]){this.requireTarget(t);const o=this.gatewayPolicy();this.requireRootSession(o);const c=[...new Set(i.map(h=>Et(h)).filter(Boolean))];let l={};if(n.deny){const h=await this.currentRevision(o);if(typeof h!="number")throw new Error("This chat's policy was not changed: the gateway did not return a policy revision to guard the deny with.");l={if_revision:h}}let d;try{d=await o.merge({...n,...c.length?{ask:c}:{},...l,client:n.client||"panel-chat"})}catch(h){throw await this.policyWriteError(h)}this.sessionToolPolicy===o&&this.adoptSessionPolicy(d);try{await this.approve(r,t)}catch(h){const m=h instanceof Error?h.message:String(h);throw new Error(`This chat's tool policy was saved, but this request was not answered: ${m} The policy does not answer requests that were already waiting.`)}return d}async approveAllForSession(t,n={}){const r=this.sessionPolicyMode();if(r==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);return r!=="gateway"?(await this.allowAllToolsForRun(t),null):this.writeThenAnswer(t,{approve:{all:!0,...typeof n.maxRiskRank=="number"?{max_risk_rank:n.maxRiskRank}:{}}},!0,n.ask)}approveKindForSession(t,n,r={}){return this.writeThenAnswer(t,{approve:{kinds:[n]}},!0,r.ask)}denyKindForSession(t,n,r={}){return this.writeThenAnswer(t,{deny:{kinds:[n]}},!1,r.ask)}denyToolForSession(t,n,r={}){return this.writeThenAnswer(t,{deny:{tools:[n]}},!1,r.ask)}async resetSessionPolicy(){if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason}`);if(this.sessionPolicyMode()!=="gateway"){this.revokeToolApproval();return}const t=this.gatewayPolicy();this.requireRootSession(t);const n=await this.currentRevision(t);if(typeof n!="number")throw new Error("This chat's policy was not reset: the gateway did not return a policy revision to guard the reset with.");try{await t.reset(n)}catch(r){throw await this.policyWriteError(r)}this.adoptSessionPolicy(null)}withSessionPolicy(t){const n=this.sessionPolicyMode(),{sessionPolicyReason:r,...i}=t;return{...i,sessionPolicyMode:n,...n==="unavailable"?{sessionPolicyReason:this.sessionPolicyUnavailableReason}:{},sessionPolicy:this.sessionPolicyState,sessionPolicyClamped:this.sessionPolicyClamped}}withSource(t){const{source:n,sourceReason:r,...i}=t;return this.source?{...i,source:this.source.source,...this.source.reason?{sourceReason:this.source.reason}:{}}:i}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.toolPolicyByCall.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.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds.clear(),this.viewTerminalRuns.clear(),this.viewStreamEnded=!1,this.viewEarlier={messages:[],tools:[]},this.set({...Py})}dispose(){this.reset(),this.viewTurnCache=jh(),this.subscribers.clear()}async load(t){const n=Et(t);if(this.reset(),!n)return;const r=++this.generation,i=new AbortController;this.controller=i,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{if(await this.loadView(n,r,i.signal)||!this.live(r))return;this.set({...this.snapshot});const[o,c]=await Promise.all([this.transport.getRun(n,i.signal),this.transport.getHistory(n,i.signal)]);if(!this.live(r))return;const l=Jt(o),d=Jt(l==null?void 0:l.waiting),h=bi(l);if(await this.ingestHistory(c,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:l,status:h,loading:!1,...d&&!os(h)?{interaction:this.interactionWith({runId:n,wait:d})}:{}}),l&&this.updateRunState(n,l),d)for(const m of w0({result:{wait:d}}))m!==n&&this.catchUpAndWatch(m,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(o){!i.signal.aborted&&this.live(r)&&this.fail(o)}}async sendCommand(t,n={}){var m,_;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=Et(n.wait_key),i=t==="resume"?r?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!i)throw new Error("No workflow run is loaded");const o=t==="resume"&&r&&((m=this.snapshot.interaction)==null?void 0:m.stepId)||"",c=`${i}\0${t}\0${o}\0${Dy(n)}`;let l=this.commandIds.get(c);l||(l=this.newCommandId(),this.commandIds.set(c,l));const d=this.generation,h=(_=this.controller)==null?void 0:_.signal;try{const g=await this.transport.submitCommand({command_id:l,run_id:i,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},h);if(!this.live(d))return g;const y=Jt(g);if(y&&y.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Et(y.detail)||"Gateway did not accept the command");return this.commandIds.delete(c),this.viewFold?["pause","resume","cancel"].includes(t)&&this.refreshViewRun(d):i===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(i,d),g}catch(g){throw this.live(d)&&this.fail(g,!1),g}}resume(t,n){const r=this.requireInteraction();if(n&&(r.runId!==n.runId||Et(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This question has changed. Review the current question before answering.");return this.sendCommand("resume",{wait_key:Et(r.wait.wait_key),payload:{response:t}})}answerEvent(t,n){const r=this.requireInteraction();if(n&&(r.runId!==n.runId||Et(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This wait has changed. Review the current one before answering.");if(!r.command)throw new Error("This wait has no resume command (it does not come from the replay view): send the event instead.");return this.sendCommand("resume",{wait_key:Et(r.wait.wait_key),payload:t})}approve(t,n){const r=this.requireInteraction();if(os(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||Et(r.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&r.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(r,this.toolApprovalPolicy.enabledTools))throw new Error("This request includes an unavailable or unselected tool. It cannot be authorized. Deny this request or stop the run and change Tools settings.");const i=this.generation;return this.sendCommand("resume",{wait_key:Et(r.wait.wait_key),payload:{approved:!!t}}).then(o=>{if(!this.live(i))return o;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})),o})}async approveWithPolicyChange(t,n){const r=this.generation,i=this.approvalEpoch;if(!this.isToolApproval(this.requireInteraction()))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(r)||i!==this.approvalEpoch||this.toolApprovalStopped||os(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,r=this.approvalEpoch,i=this.requireInteraction();if(!this.isToolApproval(i))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||r!==this.approvalEpoch||os(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${i.stepId?`:${i.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){Dy(t)!==Dy(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}:${Et(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&Fy(t.wait)&&!Fy(n.wait)?n:n&&g0(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Jt(n.waiting);if(!r||bi(n)!=="waiting"||Fy(r)||os(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Et(r.wait_key)}`))return;const i=this.interactionWith({runId:t,wait:r}),o=this.snapshot.interaction;o&&g0(o,i)&&o.stepId===i.stepId||this.set({...this.snapshot,interaction:i})}coveredByStandingPermission(t,n){var r;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||os(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:!!Et(n.wait.wait_key)}present(t){const n=t.interaction,r=n?this.occurrenceKey(n):"",i=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(r)||!this.approvedWaits.has(r)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!i&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let o=!1;const c=t.messages.map(l=>{var m;const d=l.toolActivity;if(!d||((m=this.toolActivities.get(d.id))==null?void 0:m.status)!=="waiting")return l;const h=i&&d.runId===(n==null?void 0:n.runId)?"running":"waiting";return d.status===h?l:(o=!0,this.toolMessage({...d,status:h}))});return{...t,toolApprovalGranted:i,...o?{messages:c}:{}}}toolCallsMatch(t,n){var i;const r=qh((i=Jt(t.wait.details))==null?void 0:i.tool_calls);return r.length>0&&r.every(o=>{var l;const c=Et((l=Jt(o))==null?void 0:l.name);return!!c&&n.includes(c)})}isToolApproval(t){const n=Jt(t.wait.details);return(n==null?void 0:n.mode)==="approval_required"||(n==null?void 0:n.kind)==="tool_approval"}autoApproveCurrentWait(){const t=this.snapshot.interaction;if(!this.coveredByStandingPermission(this.snapshot,t))return;const n={runId:t.runId,waitKey:Et(t.wait.wait_key),stepId:t.stepId},r=this.occurrenceKey(t);if(this.approvedWaits.has(r))return;this.approvedWaits.add(r),this.grantedToolWaits.add(r);const i=this.generation,o=this.approvalEpoch;this.approve(!0,n).catch(c=>{if(this.live(i)){if(this.grantedToolWaits.delete(r),o!==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(!Et(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(this.withSource(this.withSessionPolicy(t)));for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async loadView(t,n,r){const i=this.transport.replayView,o=m=>(this.live(n)&&(this.source={source:"ledger_fold",reason:m}),!1);if(!i)return o("this app's transport does not read the replay view");if(i.advertised===!1)return o("the gateway does not advertise the replay view");const c=zy.get(i);if(typeof c=="string")return o(c);let l,d;try{[l,d]=await Promise.all([i.getView(t,{signal:r}),this.transport.getRun(t,r)])}catch(m){if(!RI(m))throw m;const _=m instanceof Error?m.message:"the gateway does not serve the replay view";return zy.set(i,_),o(_)}if(zy.set(i,!0),!this.live(n))return!0;if(l.notModified)throw new Error("The gateway answered 304 to a replay view read without If-None-Match.");this.source={source:"replay_view"},this.viewRun=Jt(d);const h=new tI;return h.adopt(l.view,l.etag),this.viewFold=h,this.viewDigest=v0(h.lastEventId),this.adoptView(),this.followView(t,n),this.followLiveReplies(t,n),await this.loadEarlierTurns(t,Et(l.view.session_id),n,r),!0}async loadEarlierTurns(t,n,r,i){var N;const o=this.transport.replayView;if(!o||!n)return;const c=($,C)=>({id:$,role:"system",level:"warn",title:"History",content:C});if(!o.listSessionTurns){this.viewEarlier={messages:[c(`history:${n}:unlisted`,"Earlier turns of this conversation are not shown: this app's replay view transport cannot list the conversation's turns (createReplayViewTransport provides listSessionTurns).")],tools:[]},this.adoptView();return}const l=this.viewTurnCache.sessionId===n&&this.viewTurnCache.transport===o?this.viewTurnCache:{...jh(),sessionId:n,transport:o};this.viewTurnCache=l;const d=($,C=new Map,S=[])=>{const D=$.map(O=>l.turns.get(O)||C.get(O)).filter(O=>!!O);this.viewEarlier={messages:[...S,...D.flatMap(O=>O.messages)],tools:D.flatMap(O=>O.tools)}},h=l.order.indexOf(t);let m,_=!1;if(h>=0&&l.order.slice(0,h).every($=>l.turns.has($)))m=l.order.slice(0,h);else{const $=Et((N=this.viewRun)==null?void 0:N.created_at),C=$?l.order.filter(O=>l.turns.has(O)&&l.created.has(O)&&l.created.get(O)<$):[];C.length&&(d(C),this.adoptView());let S;try{S=await o.listSessionTurns(t,{signal:i})}catch(O){if(!this.live(r))return;if(_o(O))throw this.viewTurnCache=jh(),O;d(C,new Map,[c(`history:${n}:unlisted`,`Earlier turns of this conversation could not be listed: ${O instanceof Error?O.message:String(O)}`)]),this.adoptView();return}if(!this.live(r))return;_=S.length>Tp,_&&(S=S.slice(S.length-Tp));for(const O of S)O.created_at&&l.created.set(O.run_id,O.created_at);l.order=S.map(O=>O.run_id);const D=l.order.indexOf(t);m=D>=0?l.order.slice(0,D):l.order.filter(O=>O!==t)}const g=new Map,y=m.filter($=>!l.turns.has($));let x=0;const k=async()=>{for(;this.live(r);){const $=y[x++];if(!$)return;try{const C=await o.getView($,{signal:i});if(C.notModified||!C.view)throw new Error("the gateway answered without a view");const S=h0(C.view);os(S.status)?l.turns.set($,{messages:S.messages,tools:S.tools}):g.set($,{messages:[...S.messages,c(`history:${$}:open`,`This earlier turn is still ${S.status||"running"}; open it to follow or answer it.`)],tools:S.tools})}catch(C){if(!this.live(r))return;if(_o(C))throw this.viewTurnCache=jh(),C;g.set($,{messages:[c(`history:${$}:unavailable`,`An earlier turn could not be restored (${$.slice(0,8)}): ${C instanceof Error?C.message:String(C)}`)],tools:[]})}}};if(await Promise.all(Array.from({length:Math.min(4,y.length)},()=>k())),!this.live(r))return;const v=_?[c(`history:${n}:limit`,`Only the last ${Tp} turns of this conversation are shown.`)]:[];d(m,g,v),this.adoptView()}adoptView(){var h,m,_;const t=(h=this.viewFold)==null?void 0:h.view;if(!t)return;const n=h0(t);os(n.status)&&t.session_id&&this.viewTurnCache.sessionId===t.session_id&&this.viewTurnCache.turns.set(t.root_run_id,{messages:n.messages,tools:n.tools}),this.toolActivities=new Map([...this.viewEarlier.tools,...n.tools].map(g=>[g.id,g]));for(const g of n.endedLlmCalls)this.closedLiveCalls.has(g)||this.closeLiveReply(g);for(const g of t.messages||[])g.role!=="assistant"||this.viewAssistantIds.has(g.id)||(this.viewAssistantIds.add(g.id),this.closeLiveRepliesOfRun(g.run_id));for(const[g,y]of n.runStatus)!os(y)||this.viewTerminalRuns.has(g)||(this.viewTerminalRuns.add(g),this.endLiveRepliesOfRun(g,y));this.openLlmSteps=new Set(n.openLlmCalls);const r=os(n.status),i=this.snapshot.messages.filter(g=>MI.test(String(g.id||""))),o={...this.viewRun||{},run_id:t.root_run_id,status:n.status,...t.session_id?{session_id:t.session_id}:{}};let c=n.interaction;const l=this.snapshot.interaction;if(c&&l&&l.runId===c.runId&&Et(l.wait.wait_key)===Et(c.wait.wait_key)&&l.stepId!==c.stepId&&(l.stepId===void 0||c.stepId===void 0)){const{stepId:g,...y}=c;c=l.stepId===void 0?y:{...y,stepId:l.stepId}}this.set({...this.snapshot,view:t,run:o,status:n.status,displayStatus:r?"":n.displayStatus,messages:[...this.viewEarlier.messages,...n.messages,...i],interaction:c,loading:!1,...r?{autoApproveTools:!1}:{}}),(this.stopRequested||this.forcedStop)&&this.recomputeStop();const d=v0((m=this.viewFold)==null?void 0:m.lastEventId);d!==this.viewDigest&&Object.keys(((_=t.cursor)==null?void 0:_.runs)||{}).length<=32&&(this.viewDigest=d,this.refreshViewRun(this.generation))}async followView(t,n){const r=this.transport.replayView,i=this.viewFold;if(!r||!i)return;let o=0;for(;this.live(n)&&this.viewFold===i&&!i.terminal;){this.set({...this.snapshot,connection:o?"reconnecting":"connecting"});try{if(await r.streamView(t,{lastEventId:i.lastEventId,signal:this.controller.signal,onOpen:()=>{this.live(n)&&this.set({...this.snapshot,connection:"connected",error:null})},onFrame:c=>{if(!this.live(n)||this.viewFold!==i)return;o=0;const l=i.apply(c);(l==="view"||l==="delta")&&this.adoptView()}}),!this.live(n))return;if(i.terminal)break;o+=1}catch(c){if(!this.live(n))return;if(o+=1,this.fail(c,!1),_o(c)){this.set({...this.snapshot,connection:"disconnected"});return}}if(o>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(o-1)))}if(this.viewStreamEnded=!0,!(!this.live(n)||this.viewFold!==i)){if(i.terminal||os(this.snapshot.status)){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Replay view stream reconnect limit reached. Reconnect the workflow to continue."})}}async followLiveReplies(t,n){var i,o,c;let r=0;try{for(;this.live(n)&&this.viewFold&&!this.viewStreamEnded&&!os(this.snapshot.status);){const l=Number((c=(o=(i=this.viewFold.view)==null?void 0:i.cursor)==null?void 0:o.runs)==null?void 0:c[t])||0;this.dropLiveRepliesVia(t);try{if(await this.transport.streamLedger(t,l,()=>{},this.controller.signal,void 0,d=>{this.live(n)&&(r=0,this.ingestDelta(t,d))}),!this.live(n))return;r+=1}catch(d){if(!this.live(n))return;if(r+=1,_o(d)){this.fail(d);return}}if(r>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async refreshView(t){var o;const n=this.transport.replayView,r=this.viewFold;if(!n||!r)return;const i=await n.getView(this.rootRunId,{ifNoneMatch:r.lastEventId?`"${r.lastEventId}"`:null,signal:(o=this.controller)==null?void 0:o.signal});!this.live(t)||this.viewFold!==r||i.notModified||r.adopt(i.view,i.etag)&&this.adoptView()}async refreshViewRun(t){var n;try{const r=Jt(await this.transport.getRun(this.rootRunId,(n=this.controller)==null?void 0:n.signal));if(!r||!this.live(t)||!this.viewFold)return;this.viewRun=r,this.adoptView()}catch(r){this.live(t)&&this.fail(r,!1)}}async catchUpAndWatch(t,n){var r;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const i=Jt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));if(!this.live(n))return;i&&this.updateRunState(t,i)}catch(i){if(!this.live(n))return;if(_o(i))throw i;this.fail(i,!1)}if(await this.catchUp(t,n),!this.live(n)||os(bi(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(i){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw i;if(_o(i)){this.fail(i);return}const o=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,o),this.fail(i,!1),o>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(o-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var r;for(let i=0;i<100&&this.live(n);i+=1){const o=this.cursors.get(t)||0,c=await this.transport.getLedger(t,o,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const l=Jt(c),d=Array.isArray(c)?c:qh(l==null?void 0:l.items);for(const m of d)this.ingestItem(t,m);const h=Number(l==null?void 0:l.next_after);if(!d.length||!Number.isFinite(h)||h<=o)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 i;let r=0;for(;this.live(n)&&!os(bi(this.runStates.get(t)||null));){const o=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let c=!1;const l=()=>{!this.live(n)||c||(c=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,o,h=>{this.live(n)&&(l(),this.ingestItem(t,h))},this.controller.signal,l,h=>{this.live(n)&&(l(),this.ingestDelta(t,h))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const d=Jt(await this.transport.getRun(t,(i=this.controller)==null?void 0:i.signal));if(!this.live(n))return;d&&this.updateRunState(t,d),r+=1}catch(c){if(!this.live(n))return;if(r+=1,this.fail(c,!1),_o(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(os(bi(this.runStates.get(t)||null))){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Ledger stream reconnect limit reached. Reconnect the workflow to continue."})}}async ingestHistory(t,n,r){const i=Jt(t);if(!i)return;const o=Jt(i.session),c=qh(o==null?void 0:o.turns).map(Jt).filter(h=>!!h);if(await this.hydrateHistoricalSessionRuns(c,n,r),!this.live(r))return;for(const h of c){const m=Et(h==null?void 0:h.run_id)||n;this.ingestSessionTurn(h,n,m!==n&&this.historicalRuns.get(m)||null)}const l=`turn:${n}:user`;if(!this.seenMessages.has(l)){const h=p0(Jt(i.input_data));h&&this.addMessage({id:l,role:"user",content:h})}const d=Jt(i.ledgers);if(d)for(const[h,m]of Object.entries(d)){const _=Jt(m);for(const g of qh(_==null?void 0:_.items))this.ingestItem(h,g)}}ingestSessionTurn(t,n,r){if(!t)return;const i=Et(t.run_id)||n,o=Jt(t.input_data)||Jt(t.input)||{},c=Et(t.prompt)||p0(o);c&&this.addMessage({id:`turn:${i}:user`,role:"user",content:c,ts:Et(t.created_at)||void 0});const l=this.historicalRunFailures.get(i);if(l){const _=Et(t.answer)||tv(t.output),g=l.missing?"is unavailable because the run no longer exists":"could not be restored",y=_?` Saved reply (not verified as the final result): ${_}`:"";this.addMessage({id:`history:${i}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${g}.${y}`});return}const h=(r&&os(bi(r))?xd(r.output):"")||(r?Et(t.answer)||tv(t.output):""),m=this.historicalEvidence.get(i);for(const _ of(m==null?void 0:m.tools)||[])this.upsertTool(_);h&&this.addRunAssistantMessage(i,{id:`final:${i}`,role:"assistant",content:h,runId:i,statistics:m==null?void 0:m.statistics,ts:Et(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const i=[...new Set(t.map(d=>Et(d.run_id)).filter(d=>d&&d!==n&&!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)))];if(!i.length||!this.live(r))return;let o=0,c=!1;const l=async()=>{var d,h,m;for(;!c&&this.live(r);){const _=i[o++];if(!_)return;try{const g=Jt(await this.transport.getRun(_,(d=this.controller)==null?void 0:d.signal));if(!this.live(r))return;if(g){this.historicalRuns.set(_,g);try{const y=await this.transport.getHistory(_,(h=this.controller)==null?void 0:h.signal);if(!this.live(r))return;this.historicalEvidence.set(_,Oy(gI(y)))}catch(y){if(!this.live(r))return;if(_o(y))throw y;this.fail(new Error(`Earlier turn activity could not be restored: ${y instanceof Error?y.message:String(y)}`),!1)}}else this.historicalRuns.set(_,null),this.historicalRunFailures.set(_,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(g){if(!this.live(r))return;const y=AI(g)===404;this.historicalRuns.set(_,null),this.historicalRunFailures.set(_,{missing:y,detail:g instanceof Error?g.message:Et((m=Jt(g))==null?void 0:m.detail)||"request failed"}),_o(g)&&(c=!0,this.fail(g))}}};if(await Promise.all(Array.from({length:Math.min(4,i.length)},()=>l())),c&&this.live(r))for(const d of i)!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)&&(this.historicalRuns.set(d,null),this.historicalRunFailures.set(d,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=Jt(n),i=Jt(r==null?void 0:r.record)||r;if(!i)return;const o=TI(i,t),c=Number(r==null?void 0:r.cursor),l=Number.isFinite(c)&&c>0?c:(this.cursors.get(o)||0)+1,d=`${o}:${l}`;if(!this.seenRecords.has(d)){if(this.seenRecords.add(d),this.cursors.set(o,Math.max(this.cursors.get(o)||0,l)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:l,record:i,runId:o}]}),this.foldRecord(o,i,d),this.snapshot.messages.some(h=>h.id===`final:${this.rootRunId}`)){const h=Oy(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 w0(i))h!==o&&this.catchUpAndWatch(h,this.generation)}}foldRecord(t,n,r){var m,_,g;const i=nv(n),o=Et(i.type).toLowerCase(),c=Jt(n.result),l=Et(n.status).toLowerCase(),d=y0(n);if(this.foldStopEvidence(t,n,o,l),["llm_call","tool_calls"].includes(o)&&["started","running"].includes(l)){const y=Date.parse(d||"");(!Number.isFinite(y)||y>=this.displayStatusAt)&&(Number.isFinite(y)&&(this.displayStatusAt=y),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(o==="answer_user"&&l==="completed"){const y=xd(c)||xd(Jt(i.payload));y&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:y,ts:d})}if(o==="emit_event"&&l==="completed"){const y=Jt(i.payload)||{},x=Jt(c),k=Et(y.name)||Et(x==null?void 0:x.name),v=y.payload!==void 0?y.payload:x==null?void 0:x.payload;if(["abstract.message","abstractcode.message"].includes(k)){const N=xd(v);if(N){const $=Et((m=Jt(v))==null?void 0:m.level).toLowerCase(),C=$==="error"?"error":["warn","warning"].includes($)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:N,level:C,ts:d})}}if(["abstract.status","abstractcode.status"].includes(k)){const N=Jt(v),$=N?N.status??N.text??N.value:v,C=Date.parse(d||"");!os(this.snapshot.status)&&typeof $=="string"&&(!Number.isFinite(C)||C>=this.displayStatusAt)&&(Number.isFinite(C)&&(this.displayStatusAt=C),this.set({...this.snapshot,displayStatus:$.trim()}))}if(k==="abstract.tool_policy_decision"){const N=GR(Jt(v));if(N){this.addMessage({id:`policy:${t}:${r}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",content:Zp(N.provenance),ts:d});for(const $ of N.calls){const C={...N.provenance,...$.matched?{matched:$.matched}:{}};this.toolPolicyByCall.set(`${t}:${$.callId}`,C);for(const S of this.toolActivities.values())S.runId===t&&S.callId===$.callId&&this.upsertTool(S)}}}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(k)){const N=xd(v);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:d})}}const h=JN(n);if(l==="waiting"&&h&&!os(this.snapshot.status)&&!os(bi(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Et(h.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:h,...Et(n.step_id)?{stepId:Et(n.step_id)}:{}})})),o==="tool_calls")for(const y of GN(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(y);if(o==="resume"&&(c==null?void 0:c.resumed)===!0){const y=Et((_=Jt(i.payload))==null?void 0:_.wait_key);y&&this.resolvedWaits.add(`${t}:${y}`),((g=this.snapshot.interaction)==null?void 0:g.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,i){let o=!1;if(r==="llm_call"){const c=Et(n.step_id);if(c){const l=`${t}:${c}`;i==="started"?(this.openLlmSteps.add(l),o=!0):["completed","failed","cancelled","waiting"].includes(i)&&(o=this.openLlmSteps.delete(l)||o),["completed","failed","cancelled"].includes(i)&&this.closeLiveReply(l)}}if(r==="emit_event"&&i==="completed"){const c=Jt(nv(n).payload)||{},l=Jt(n.result),d=Et(c.name)||Et(l==null?void 0:l.name),h=Jt(c.payload!==void 0?c.payload:l==null?void 0:l.payload);d==="abstract.status"&&Et(h==null?void 0:h.killed_by)==="kill_switch"&&(this.forcedStop=h,o=!0)}o&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:Et(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(t=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const n=this.snapshot.stop||null;((n==null?void 0:n.phase)!==(t==null?void 0:t.phase)||(n==null?void 0:n.label)!==(t==null?void 0:t.label))&&this.set({...this.snapshot,stop:t}),(t==null?void 0:t.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(t){var n;if(!this.stopFollowing){this.stopFollowing=!0;try{let r=500,i=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(r),!this.live(t))return;const o=this.viewFold?[]:[this.rootRunId,...[...this.watchedRuns].filter(l=>l!==this.rootRunId)];let c=!1;if(this.viewFold)try{await this.refreshView(t)}catch(l){c=!0,this.live(t)&&(this.fail(l,!1),i=this.snapshot.error)}for(const l of o)try{await this.catchUp(l,t)}catch(d){c=!0,this.live(t)&&(this.fail(d,!1),i=this.snapshot.error)}!c&&i&&this.snapshot.error===i&&(this.set({...this.snapshot,error:null}),i=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=Et(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){const n=t.callId?this.toolPolicyByCall.get(`${t.runId}:${t.callId}`):void 0;return HN(n?{...t,policy:n}:t)}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(o=>o.id===n.id);if(r<0){this.addMessage(n);return}const i=[...this.snapshot.messages];i[r]=n,this.set({...this.snapshot,messages:i})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const r=`answer:${t}:`,i=`final:${t}`;this.snapshot.messages.some(o=>o.role==="assistant"&&o.content===n.content&&(o.id===i||String(o.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=ON(n)}catch(d){this.fail(d,!1);return}const i=`${r.run_id}:${r.call_id}`;if(IN(r)){if(r.reason==="unavailable"){this.noteStreamUnavailable(r);return}if(r.reason==="cancelled"&&r.detail==="reinvoked"){this.closeLiveReply(i,"restarted");return}this.closeLiveReply(i,r.reason==="completed"?void 0:r.reason);return}if(this.closedLiveCalls.has(i)||this.runEnded(r.run_id)||this.runEnded(this.rootRunId))return;const o=this.liveReplies.get(i)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},c=r.channel==="reasoning"?"reasoning":"text",l=o.seq[r.channel];if(r.snapshot){if(r.seq<l)return;o[c]=r.text}else{if(r.seq<=l)return;o[c]+=r.text}o.seq[r.channel]=r.seq,o.via=t,this.liveReplies.set(i,o),this.liveDirty.add(i),this.scheduleLiveRender()}runEnded(t){var r,i;const n=(r=this.viewFold)==null?void 0:r.view;return n?os(String(((i=n.runs.find(o=>o.run_id===t))==null?void 0:i.status)||""))||t===this.rootRunId&&os(String(n.status||"")):os(bi(this.runStates.get(t)||null))}scheduleLiveRender(){if(this.liveRenderTimer)return;const t=this.lastLiveRender+this.liveRenderIntervalMs-Date.now();if(t<=0){this.renderLiveReplies();return}this.liveRenderTimer=setTimeout(()=>{this.liveRenderTimer=null,this.renderLiveReplies()},t)}renderLiveReplies(){if(this.lastLiveRender=Date.now(),!this.liveDirty.size)return;const t=[...this.snapshot.messages];for(const n of this.liveDirty){const r=this.liveReplies.get(n);if(!r)continue;const i=this.liveMessage(r),o=t.findIndex(c=>c.id===i.id);o<0?t.push(i):t[o]=i,this.shownLiveCalls.add(n)}this.liveDirty.clear(),this.set({...this.snapshot,messages:t})}liveMessage(t){const n=t.runId!==this.rootRunId;return{id:`live:${t.runId}:${t.callId}`,role:"assistant",content:t.text,runId:t.runId,live:{callId:t.callId,reasoning:t.reasoning,...n?{caption:`sub-agent · ${t.nodeId||t.runId}`}:{}}}}closeLiveReply(t,n){this.closedLiveCalls.add(t);const r=this.liveReplies.get(t);if(!r){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const i=`live:${r.runId}:${r.callId}`,o=this.snapshot.messages.findIndex(l=>l.id===i);if(o<0)return;const c=[...this.snapshot.messages];if(n==="restarted"){const l=this.restartNote(t);this.seenMessages.add(String(l.id)),c[o]=l}else if(n){const l=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(l),c[o]={id:l,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(o,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:gL(t.detail)})}closeLiveRepliesOfRun(t){for(const n of[...this.liveReplies.values()])n.runId===t&&this.closeLiveReply(`${n.runId}:${n.callId}`)}closeLiveRepliesVia(t,n){for(const r of[...this.liveReplies.values()])(r.via===t||r.runId===t)&&this.closeLiveReply(`${r.runId}:${r.callId}`,n)}endLiveRepliesOfRun(t,n){const r=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const i of[...this.liveReplies.values()])this.closeLiveReply(`${i.runId}:${i.callId}`,r);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,r);for(const i of[...this.closedLiveCalls])i.startsWith(`${t}:`)&&this.closedLiveCalls.delete(i);for(const i of[...this.shownLiveCalls])i.startsWith(`${t}:`)&&this.shownLiveCalls.delete(i)}dropLiveRepliesVia(t){const n=new Set;for(const[r,i]of this.liveReplies)i.via===t&&(this.liveReplies.delete(r),this.liveDirty.delete(r),n.add(`live:${i.runId}:${i.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(r=>!n.has(String(r.id)))})}fail(t,n=!0){var r,i,o;_o(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(i=(r=this.options).onAuthError)==null||i.call(r,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:Et((o=Jt(t))==null?void 0:o.detail)||String(t),..._o(t)?{autoApproveTools:!1}:{},...n?{connection:"disconnected"}:{}})}newCommandId(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();if(t&&typeof t.getRandomValues=="function"){const n=t.getRandomValues(new Uint8Array(16));n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n,i=>i.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var o;if(this.runStates.set(t,n),os(bi(n))&&this.endLiveRepliesOfRun(t,bi(n)),t!==this.rootRunId){os(bi(n))&&((o=this.snapshot.interaction)==null?void 0:o.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=bi(n),i=os(r);if(i){const c=xd(n.output);c&&this.upsertFinal(t,c,y0(n))}this.set({...this.snapshot,run:n,status:r,...i?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),i||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,r){this.closeLiveRepliesOfRun(t);const i=`final:${t}`;this.seenMessages.add(i);const o={id:i,role:"assistant",content:n,ts:r,runId:t,statistics:Oy(this.snapshot.records).statistics},c=this.snapshot.messages.findIndex(d=>d.id===i||String(d.id||"").startsWith(`answer:${t}:`)&&d.content===n);if(c<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,o]});return}const l=[...this.snapshot.messages];l[c]=o,this.set({...this.snapshot,messages:l})}async refreshRunState(t,n){var r;try{const i=Jt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));i&&this.live(n)&&this.updateRunState(t,i)}catch(i){this.live(n)&&this.fail(i,!1)}}async pollRootLifecycle(t,n){var r;for(;this.live(n)&&this.rootRunId===t&&!os(bi(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||os(bi(this.runStates.get(t)||null)))return;try{const i=Jt(await this.transport.getRun(t,(r=this.controller)==null?void 0:r.signal));i&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,i)}catch(i){if(!this.live(n))return;if(_o(i)){this.fail(i);return}this.fail(i,!1)}}}waitForRetry(t){var i;const n=(i=this.controller)==null?void 0:i.signal;if(!n||n.aborted)return Promise.resolve();const r=n;return new Promise(o=>{const c=setTimeout(d,t),l=()=>{clearTimeout(c),d()};function d(){r.removeEventListener("abort",l),o()}r.addEventListener("abort",l,{once:!0})})}}function II(e){const t=p.useMemo(()=>new LI(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=p.useSyncExternalStore(i=>t.subscribe(i),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return p.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),p.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function Yc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fr(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function x0(e){return["session","workflow","run","global"].includes(e)?e:null}function Yl(e){return{scope:Fr(e==null?void 0:e.scope).toLowerCase(),name:Fr(e==null?void 0:e.name)||Fr(e==null?void 0:e.event_name),scopeId:Fr(e==null?void 0:e.scope_id)||Fr(e==null?void 0:e.scopeId),sessionId:Fr(e==null?void 0:e.session_id)||Fr(e==null?void 0:e.sessionId),workflowId:Fr(e==null?void 0:e.workflow_id)||Fr(e==null?void 0:e.workflowId),runId:Fr(e==null?void 0:e.run_id)||Fr(e==null?void 0:e.runId)}}function OI(e,t){const n=e.wait,r=Fr(n.wait_key),i=[Yl(n),Yl(Yc(n.details))];for(const o of t){if(o.runId!==e.runId)continue;const c=o.record,l=Yc(c.result),d=Yc(l==null?void 0:l.wait),h=Yc(c.effect),m=Yc(h==null?void 0:h.payload);Fr(d==null?void 0:d.wait_key)!==r&&Fr(m==null?void 0:m.wait_key)!==r||i.push(Yl(c),Yl(m),Yl(Yc(m==null?void 0:m.details)),Yl(d),Yl(Yc(d==null?void 0:d.details)))}return i}function By(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function YN(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function PI(e,t,n){if(!n)return null;const r=`evt:${t}:${n}:`;if(!e.startsWith(r))return null;const i=e.slice(r.length);return i?YN(t,n,i):null}function DI(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=Fr(e.wait.wait_key),i=/^evt:(session|workflow|run|global):/.exec(r);if(!i)return{target:null,error:"The gateway did not provide a canonical event wait key."};const o=x0(i[1]);if(!o)return{target:null,error:"The event wait uses an unsupported scope."};const c=OI(e,Array.isArray(t)?t:[]),l=new Map;for(const g of c){const y=x0(g.scope);if(!y||!g.name)continue;if(y!==o)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const x=`evt:${y}:`,k=`:${g.name}`;if(!r.startsWith(x)||!r.endsWith(k)||r.length<=x.length+k.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const v=r.slice(x.length,-k.length),N=By(y,g);if(N&&N!==v)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const $=YN(y,v,g.name);l.set(`${$.scope}\0${$.scopeId}\0${$.name}`,$)}if(l.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(l.size===1)return{target:[...l.values()][0]};const d=new Set;o==="run"&&d.add(e.runId),o==="global"&&d.add("global");for(const g of c){const y=By(o,g);y&&d.add(y)}if(Fr(n==null?void 0:n.run_id)===e.runId){const g=Yl(n||null),y=By(o,g);y&&d.add(y)}const m=[...d].map(g=>PI(r,o,g)).filter(g=>!!g),_=new Map(m.map(g=>[`${g.scope}\0${g.scopeId}\0${g.name}`,g]));return _.size===1?{target:[..._.values()][0]}:_.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 XN(e){return s.jsx(bN,{text:e,images:"link"})}const FI={trigger:"Trigger",answer:"Automation"};function b0(e,t){return s.jsx(dx,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:FI[e.kind],runId:e.runId},images:"link"})}function zI(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function BI(e,t,n={}){var h;if(!e)return null;const r=zI(e)?VN(e):e,i=r.wait,o=`${r.runId}:${i.wait_key}:${r.stepId||""}`,c=i.details||{};if(c.mode==="approval_required"||c.kind==="tool_approval"){const m=Array.isArray(c.tool_calls)?c.tool_calls:[],_={runId:r.runId,waitKey:String(i.wait_key||""),stepId:r.stepId},g=[...new Set(m.map(O=>String((O==null?void 0:O.name)||"tool")))],y=n.onPermissionsAll,x=n.onAllowForSession,k=String(n.approveAllScope||"").trim(),v=((h=n.remember)==null?void 0:h.call(n,g))||void 0,N=Td,$=x?{approveForSessionLabel:N.allowForChat,approveForSessionDescription:"Allow for this chat approves this batch and the enabled tools for the rest of this chat. Unchecked tools stay unavailable; questions still need your answer.",onApproveForSession:async()=>{let O;await t.approveWithPolicyChange(_,()=>{O=x()}),O&&await O.catch(A=>{throw new Error(`This batch was allowed, but "Allow for this chat" could not be turned on: ${A instanceof Error?A.message:String(A)}`)})}}:{};let C=$,S=[];const D=n.sessionPolicy;if(D){const O=t.approveAllForSession,A=t.approveKindForSession,P=t.denyToolForSession,W=t.denyKindForSession,J=t.sessionPolicyStatus;if(typeof O!="function"||typeof A!="function"||typeof P!="function"||typeof W!="function"||typeof J!="function")throw new Error("presentInteraction: sessionPolicy needs a WorkflowSessionController (approveAllForSession, approveKindForSession, denyToolForSession, denyKindForSession, sessionPolicyStatus).");const G=J.call(t),V=D.ask?[...D.ask]:void 0,R=(K,H)=>{var ee;const z=String(((ee=K==null?void 0:K.scope)==null?void 0:ee[H])||"").trim();return z?`Applies: ${z}`:N.noScopeNote},M=K=>({outcomeNote:[r0(K==null?void 0:K.clamped),R(K,"approve")].filter(Boolean).join(" ")}),I=K=>({outcomeNote:`${N.denyForChatNote} ${R(K,"deny")}`}),L=r0(G.clamped);if(G.mode==="unavailable")C={scopeNote:N.unavailablePolicyNote(G.reason||"")};else if(G.mode==="gateway"){const K=[...new Set(m.map(B=>{var te;return String((B==null?void 0:B.toolset)||"").trim()||String(((te=D.toolsetOf)==null?void 0:te.call(D,String((B==null?void 0:B.name)||"")))||"").trim()}).filter(Boolean))],H=(V||[]).map(B=>String(B).trim()).filter(Boolean),z=H.length?`Tools set to Ask keep asking: ${H.join(", ")}.`:"Nothing is set to Ask, so tools that reach destinations the model picks (fetch_url, browser_probe, send_email) are included.",ee=G.policy;S=ee?g.filter(B=>Object.prototype.hasOwnProperty.call(ee.deny||{},B)):[],C={approveForSessionLabel:N.allowForChat,approveForSessionDescription:K.length?`Each of ${(()=>{const B=[`“${N.allowForChat}” (every tool)`,...K.map(te=>`“${N.allowKindForChat(te)}” (that toolset only)`)];return`${B.slice(0,-1).join(", ")} or ${B[B.length-1]}`})()} approves this batch and stores a policy for this chat on the gateway: the later tool calls it covers, in every run of this chat, run without asking, until the policy is reset. ${z} Tools the gateway does not authorize stay uncovered.`:`“${N.allowForChat}” approves this batch and stores a policy for this chat on the gateway: later tool calls of every run of this chat run without asking, until the policy is reset. ${z} Tools the gateway does not authorize stay uncovered.`,broadScopeSummary:`The broader choices keep allowing later tool calls of this chat until the policy is reset. ${z}`,onApproveForSession:async()=>M(await O.call(t,_,{...D.maxRiskRank!==void 0?{maxRiskRank:D.maxRiskRank}:{},...V?{ask:V}:{}})),approveKinds:K.map(B=>({kind:B,label:N.allowKindForChat(B),onApprove:async()=>M(await A.call(t,_,B,V?{ask:V}:{}))})),denyOptions:[...g.map(B=>({key:`tool:${B}`,label:N.denyToolForChat(B),onDeny:async()=>I(await P.call(t,_,B,V?{ask:V}:{}))})),...K.map(B=>({key:`kind:${B}`,label:N.denyKindForChat(B),onDeny:async()=>I(await W.call(t,_,B,V?{ask:V}:{}))}))],...S.length?{deniedNote:`Denied by this chat's policy: ${S.join(", ")}. The gateway refuses ${S.length===1?"it":"them"} even if allowed once.`}:{},...ee?{policySummary:`This chat's policy: ${Object.keys(ee.approve||{}).length} tools allowed without asking, ${Object.keys(ee.deny||{}).length} denied. ${R(ee,"approve")}`}:{},...L?{notCovered:L}:{}}}else C=x?{...$,scopeNote:N.localChatPolicyNote}:{approveForSessionLabel:N.allowForRun,onApproveForSession:async()=>{await O.call(t,_,{})},scopeNote:N.localRunPolicyNote}}return{id:o,kind:"tool-approval",title:`${m.length||"Requested"} ${m.length===1?"action needs":"actions need"} permission`,toolName:g.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(TN,{tools:m.map((O,A)=>({id:String((O==null?void 0:O.call_id)||(O==null?void 0:O.id)||A),runId:r.runId,name:(O==null?void 0:O.name)||"Tool",arguments:O==null?void 0:O.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(hr,{value:m.length?m:c})]})]}),approveLabel:Td.allowOnce,denyLabel:Td.deny,approveAllLabel:y?Td.allowAll:void 0,approveAllDescription:y?`Sets permissions: all${k?` ${k}`:""}, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.`:void 0,...y?{broadScopeSummary:`“${Td.allowAll}” changes your tool permissions for future turns too.`}:{},...C,...n.approveAllDisabledReason?{disabledReason:n.approveAllDisabledReason}:{},...v?{remember:v}:{},...n.onDefer?{onDefer:n.onDefer}:{},onApproveAll:y?async()=>{await t.approveWithPolicyChange(_,()=>{y()})}:void 0,onApprove:async()=>(await t.approve(!0,_),S.length?{outcomeNote:`The gateway refuses ${S.join(", ")}: denied by this chat's policy.`}:void 0),onDeny:async()=>{await t.approve(!1,_)}}}const l={runId:r.runId,waitKey:String(i.wait_key||""),stepId:r.stepId};if(i.reason==="user"||i.reason==="ask_user")return{id:o,kind:"ask-user",title:"A question for you",prompt:String(i.prompt||c.prompt||"How would you like to continue?"),allowFreeText:i.allow_free_text!==!1,choices:(Array.isArray(i.choices)?i.choices:[]).map(m=>typeof m=="object"&&m!==null?{id:String(m.value??m.id??m.label),label:String(m.label??m.text??m.value??m.id),description:m.description}:{id:String(m),label:String(m)}),onSubmit:async m=>{await t.resume(m,l)},...n.allowSkip?{onSkip:async()=>{await t.resume("",l)}}:{},...n.onDefer?{onDefer:n.onDefer}:{}};const d=String(i.wait_key||"");if(i.reason==="event"||d.startsWith("evt:")){if(r.command){const x=t.answerEvent;if(typeof x!="function")throw new Error("presentInteraction: an event wait from the replay view needs a WorkflowSessionController (answerEvent).");const k={runId:r.runId,waitKey:d,stepId:r.stepId};return{id:o,kind:"event-wait",title:"Waiting for your input",eventName:d,prompt:String(i.prompt||"This workflow is waiting for an event."),description:Array.isArray(i.choices)&&i.choices.length?`Expected: ${i.choices.map(v=>String(typeof v=="object"&&v!==null?v.label??v.value??"":v)).join(", ")}`:"The data you send resumes this wait.",initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send",onSend:async v=>{await x.call(t,JSON.parse(v||"{}"),k)}}}const _=DI(r,n.records||[],n.currentRun??null),g=_.target,y=(g==null?void 0:g.name)||"";return{id:o,kind:"event-wait",title:g?"Waiting for an event":"Event routing unavailable",eventName:y,prompt:String(i.prompt||`This workflow will continue when “${y||"its trigger"}” arrives.`),description:g?"You can also send the expected event here.":`This event cannot be sent safely. ${_.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async x=>{if(!g)throw new Error(_.error);const k=JSON.parse(x||"{}"),v={name:g.name,scope:g.scope,payload:k};g.scope==="session"?v.session_id=g.scopeId:g.scope==="workflow"?v.workflow_id=g.scopeId:g.scope==="run"&&(v.run_id=g.scopeId),await t.emitEvent(v)}}}return null}const UI={app:"observer",name:"AbstractObserver"},WI=["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 qI(e){const t=p.useRef(e.gateway);t.current=e.gateway;const n=(r,i)=>t.current.fetch_gateway(r,i);return s.jsx(JL,{open:e.open,onClose:e.onClose,source:UI,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:WI})}function VI(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 HI(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 GI(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const KI='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function JI(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function YI(e){const[t,n]=p.useReducer(VI,!1),r=p.useRef(null),i=p.useRef(null),o=p.useRef(!1);return p.useEffect(()=>{n({type:"page_change"})},[e.page]),p.useEffect(()=>{n({type:"layout_change"})},[e.is_drawer]),p.useEffect(()=>{var c;if(t){o.current=!0;const l=i.current,d=(l==null?void 0:l.querySelector(".shell_nav_item.active"))||(l==null?void 0:l.querySelector(".shell_nav_item"));d==null||d.focus();const h=m=>{if(m.key==="Escape"){n({type:"escape",default_prevented:m.defaultPrevented,other_modal_open:JI(i.current)});return}if(m.key!=="Tab"||!i.current)return;const _=Array.from(i.current.querySelectorAll(KI)).filter(y=>y.offsetParent!==null||y===document.activeElement),g=GI(_.length,_.indexOf(document.activeElement),m.shiftKey);g>=0&&(m.preventDefault(),_[g].focus())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)}o.current&&(o.current=!1,(c=r.current)==null||c.focus())},[t]),{open:t,set_open:c=>n({type:c?"open":"close"}),toggle_ref:r,sidebar_ref:i,attrs:HI(e.is_drawer,t)}}function XI(e,t){return[...e.filter(n=>!n.local_error),t].map(n=>({role:n.role,content:n.content}))}function ip(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.trunc(e):0}function ZI(e){const t=ip(e==null?void 0:e.dropped_messages);if(!e||t<=0)return null;const n=ip(e.replayed_messages),r=ip(e.dropped_tokens),i=ip(e.max_tokens),o=[`Earlier messages not replayed: ${t.toLocaleString("en-US")}${r?` (~${r.toLocaleString("en-US")} tokens)`:""}.`,`The model read the newest ${n.toLocaleString("en-US")} message${n===1?"":"s"}`+(i?` (history window: the most recent ${i.toLocaleString("en-US")} tokens of whole messages).`:".")];return e.oversize_turn_kept&&o.push("Your latest message alone is larger than the window; it was sent whole."),o.join(" ")}function QI(e){const t=ZI(e.history);return t?s.jsx(dx,{message:{role:"system",level:"info",title:"History",content:t}}):null}const eO="api/local/reveal",tO="sw.js",sv="#run/";function nO(e){return`${sv}${encodeURIComponent(String(e||"").trim())}`}function ZN(e){const t=String(e||"");if(!t.startsWith(sv))return"";const n=t.slice(sv.length).split("?")[0];if(!n||n.includes("/"))return"";try{return decodeURIComponent(n).trim()}catch{return""}}function sO(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function rO(e){const t=ZN(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 l=c.split("/").filter(Boolean);return l.length?l[l.length-1].trim():""},i=r(String(e.hash||"").replace(/^#/,""));if(n(i))return i;const o=r(String(e.pathname||""));return n(o)?o:""}const iO={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"},oO=new Set(["wait","resume","memory","model","node"]),aO=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),lO={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 cO(e){const t=String(e||"").trim();return t?iO[t]||"other":"node"}function uO(e,t,n){return n?!1:e==="event"?aO.has(String(t||"").trim()):oO.has(e)}const dO=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 fO(e){const t=new TextEncoder().encode(e),n=t.length*8,r=t.length+9+63>>6<<6,i=new Uint8Array(r);i.set(t),i[t.length]=128;const o=new DataView(i.buffer);o.setUint32(r-8,Math.floor(n/4294967296)),o.setUint32(r-4,n>>>0);const c=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),l=new Uint32Array(64);for(let d=0;d<r;d+=64){for(let N=0;N<16;N++)l[N]=o.getUint32(d+N*4);for(let N=16;N<64;N++){const $=l[N-15],C=l[N-2],S=($>>>7|$<<25)^($>>>18|$<<14)^$>>>3,D=(C>>>17|C<<15)^(C>>>19|C<<13)^C>>>10;l[N]=l[N-16]+S+l[N-7]+D>>>0}let[h,m,_,g,y,x,k,v]=c;for(let N=0;N<64;N++){const $=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7),C=y&x^~y&k,S=v+$+C+dO[N]+l[N]>>>0,D=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),O=h&m^h&_^m&_,A=D+O>>>0;v=k,k=x,x=y,y=g+S>>>0,g=_,_=m,m=h,h=S+A>>>0}c[0]=c[0]+h>>>0,c[1]=c[1]+m>>>0,c[2]=c[2]+_>>>0,c[3]=c[3]+g>>>0,c[4]=c[4]+y>>>0,c[5]=c[5]+x>>>0,c[6]=c[6]+k>>>0,c[7]=c[7]+v>>>0}return Array.from(c,d=>d.toString(16).padStart(8,"0")).join("")}const rv="$slim";function hO(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[rv]&&typeof e[rv]=="object")}function mO(e){const t=new Map;for(const n of e||[]){if(!n||typeof n!="object"||String(n.status||"")!=="started")continue;const r=String(n.step_id||""),i=n.effect&&typeof n.effect=="object"?n.effect.payload:null;r&&i&&typeof i=="object"&&!t.has(r)&&t.set(r,i)}return t}function _O(e,t){const n=[];for(const r of t)if(r==="system"){if(typeof e.system_prompt!="string"||!e.system_prompt)return null;n.push({role:"system",content:e.system_prompt})}else if(r==="messages"){if(!Array.isArray(e.messages))return null;for(const i of e.messages)i&&typeof i=="object"&&n.push({...i})}else if(r==="prompt"){if(typeof e.prompt!="string"||!e.prompt)return null;n.push({role:"user",content:e.prompt})}else return null;return n}function pO(e,t){const n=e&&e[rv];if(!n||typeof n!="object")return{state:"missing",reason:"not a $slim marker"};const r=t.get(String(n.step_id||""));if(!r)return{state:"missing",reason:"its started record is not in the loaded ledger"};let i;if(n.kind==="started_payload_field"){const c=String(n.field||"");if(!(c in r))return{state:"missing",reason:`the started record has no "${c}" field`};i=r[c]}else if(n.kind==="started_messages_layout"){if(i=Array.isArray(n.layout)?_O(r,n.layout.map(String)):null,!i)return{state:"missing",reason:"the started record cannot rebuild these messages"}}else return{state:"missing",reason:`unknown $slim kind "${String(n.kind||"")}"`};if(Array.isArray(n.appendix)&&n.appendix.length){if(!Array.isArray(i))return{state:"missing",reason:"appendix on a non-list value"};const c=i.map(d=>d&&typeof d=="object"?{...d}:d),l=[...n.appendix].sort((d,h)=>Number((d==null?void 0:d.at)??-1)-Number((h==null?void 0:h.at)??-1));for(const d of l){const h=Number(d==null?void 0:d.at);if(!Number.isInteger(h)||h<0||h>c.length)return{state:"missing",reason:"appendix position out of range"};c.splice(h,0,d.item)}i=c}return fO(JSON.stringify(i))!==String(n.sha256||"")?{state:"unverified",value:i,reason:"checksum differs from the record"}:{state:"resolved",value:i}}function gO(e,t){const n=[],r=[],i=(o,c,l)=>{if(l>14)return o;if(hO(o)){const d=pO(o,t);return d.state==="missing"?(n.push({path:c,reason:d.reason}),o):(d.state==="unverified"&&r.push({path:c,reason:d.reason}),d.value)}if(Array.isArray(o)){let d=null;return o.forEach((h,m)=>{const _=i(h,`${c}[${m}]`,l+1);_!==h&&((d??(d=[...o]))[m]=_)}),d??o}if(o&&typeof o=="object"){let d=null;for(const h of Object.keys(o)){const m=i(o[h],c?`${c}.${h}`:h,l+1);m!==o[h]&&((d??(d={...o}))[h]=m)}return d??o}return o};return{value:i(e,"",0),unresolved:n,unverified:r}}function k0(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?t:null}function QN(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function yO(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&QN(e).some(n=>n&&n.success===!1):!1}function wO(e){var n;const t=String((e==null?void 0:e.idempotency_key)||"").trim();return String(((n=e==null?void 0:e.effect)==null?void 0:n.type)||"")==="tool_calls"&&t?`idem:${t}`:String((e==null?void 0:e.step_id)||"")}function Pg(e,t){var h,m,_,g,y,x;const n=String(t||"").trim(),r=(e||[]).filter(k=>k&&k.record&&String(k.run_id||k.record.run_id||"").trim()===n).sort((k,v)=>(k.cursor||0)-(v.cursor||0)),i=mO(r.map(k=>k.record)),o=new Map,c=[];for(const k of r){const v=k.record,$=wO(v)||`cursor:${k.cursor}`;let C=o.get($);C||(C={cursor:k.cursor,started:null,latest:v,latest_cursor:k.cursor},o.set($,C),c.push($)),String(v.status||"")==="started"&&!C.started&&(C.started=v),k.cursor>=C.latest_cursor&&(C.latest=v,C.latest_cursor=k.cursor)}let l=0;const d=[];for(const k of c){const v=o.get(k),N=gO(v.latest,i),$=N.value,C=String(((h=$==null?void 0:$.effect)==null?void 0:h.type)||((_=(m=v.started)==null?void 0:m.effect)==null?void 0:_.type)||"").trim(),S=cO(C),D=S==="event"?String(((y=(g=$==null?void 0:$.effect)==null?void 0:g.payload)==null?void 0:y.name)||"").trim():"";S==="llm_call"&&(l+=1);const O=yO($,S),A=String(((x=v.started)==null?void 0:x.started_at)||($==null?void 0:$.started_at)||""),P=String(($==null?void 0:$.ended_at)||""),W=k0(A),J=k0(P);d.push({id:`${n}:${k}`,run_id:n,step_id:String(($==null?void 0:$.step_id)||""),node_id:String(($==null?void 0:$.node_id)||""),kind:S,effect_type:C,event_name:D,status:String(($==null?void 0:$.status)||""),cursor:v.cursor,started_at:A,ended_at:P,duration_ms:W!==null&&J!==null?Math.max(0,J-W):null,started:v.started,record:$,failed:O,housekeeping:uO(S,D,O),cycle:l,unresolved:N.unresolved,unverified:N.unverified})}return d}function vO(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 xO={view:"cycles",only:"all",all_steps:!1,q:""};function bO(e,t,n){const r=String(t.q||"").trim().toLowerCase();return e.filter(i=>!(t.only==="llm"&&i.kind!=="llm_call"||t.only==="tools"&&i.kind!=="tool"||t.only==="failed"&&!i.failed||t.only==="all"&&!t.all_steps&&i.housekeeping||r&&!n(i).includes(r)))}const kO=["all","llm","tools","failed"];function j0(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{...xO};const r=new URLSearchParams(t.slice(n+1)),i=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:kO.includes(i)?i:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function jO(e,t){const n=String(e||"").split("?")[0],r=new URLSearchParams;t.view!=="cycles"&&r.set("view",t.view),t.only!=="all"&&r.set("only",t.only),t.all_steps&&r.set("all","1"),t.q.trim()&&r.set("q",t.q);const i=r.toString();return i?`${n}?${i}`:n}function Bd(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(`
88
+ `):e==null?"":JSON.stringify(e,null,2)}function e1(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function t1(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:e1(t.arguments??((r=t.function)==null?void 0:r.arguments))}}):[]}function S0(e){const t={role:String((e==null?void 0:e.role)||"?"),content:Bd(e==null?void 0:e.content)},n=t1(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 N0(e){const t=Number(e);return Number.isFinite(t)&&e!==null&&e!==void 0?t:null}const SO={"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 Cm(e){var x,k,v,N,$,C,S;const t=e.record||{},n=((k=(x=e.started)==null?void 0:x.effect)!=null&&k.payload&&typeof e.started.effect.payload=="object"?e.started.effect.payload:(v=t==null?void 0:t.effect)==null?void 0:v.payload)||{},r=t!=null&&t.result&&typeof t.result=="object"?t.result:{},i=r.usage||r.token_usage||{},o=[],c=e.unverified.map(D=>`${D.path}: ${D.reason}`);for(const D of e.unresolved){const O=SO[D.path];O&&o.push(`${O}: ${D.reason}`)}const l=($=(N=r==null?void 0:r.metadata)==null?void 0:N._provider_request)==null?void 0:$.payload;let d="",h=[],m="";if(l&&Array.isArray(l.messages)){m="sent";for(const D of l.messages)String((D==null?void 0:D.role)||"")==="system"&&!h.length?d+=(d?`
89
+
90
+ `:"")+Bd(D.content):h.push(S0(D))}else(Array.isArray(n.messages)||typeof n.prompt=="string")&&(m="payload",h=(Array.isArray(n.messages)?n.messages:[]).map(S0),typeof n.prompt=="string"&&n.prompt.trim()&&h.push({role:"user",content:n.prompt}));!d&&typeof n.system_prompt=="string"&&(d=n.system_prompt);const g=(Array.isArray(n.tools)?n.tools:Array.isArray(l==null?void 0:l.tools)?l.tools:[]).filter(D=>D&&typeof D=="object").map(D=>{const O=D.function&&typeof D.function=="object"?D.function:D;return{name:String(O.name||"?"),description:String(O.description||""),schema:O.parameters??O.input_schema??null}}),y=(C=r==null?void 0:r.metadata)!=null&&C._provider_request&&typeof r.metadata._provider_request=="object"?r.metadata._provider_request:{};return{provider:String(n.provider||r.provider||y.provider||(l==null?void 0:l.provider)||""),model:String(n.model||r.model||y.model||(l==null?void 0:l.model)||""),tokens_in:N0(i.prompt_tokens??i.input_tokens),tokens_out:N0(i.completion_tokens??i.output_tokens),system:d,messages:h,messages_source:m,tools:g,response:Bd(r.content??r.response??""),tool_calls:t1(r.tool_calls),reasoning:Bd(r.reasoning??((S=r==null?void 0:r.metadata)==null?void 0:S.reasoning)??""),missing:o,unverified:c}}function Em(e){var i,o,c,l;const t=((o=(i=e.record)==null?void 0:i.effect)==null?void 0:o.payload)||((l=(c=e.started)==null?void 0:c.effect)==null?void 0:l.payload)||{},n=(Array.isArray(t.tool_calls)?t.tool_calls:[]).map(d=>{var h,m;return{name:String((d==null?void 0:d.name)||((h=d==null?void 0:d.function)==null?void 0:h.name)||"?"),arguments:e1((d==null?void 0:d.arguments)??((m=d==null?void 0:d.function)==null?void 0:m.arguments)),call_id:String((d==null?void 0:d.call_id)||(d==null?void 0:d.id)||"")}}),r=QN(e.record).map(d=>({name:String((d==null?void 0:d.name)||"?"),success:typeof(d==null?void 0:d.success)=="boolean"?d.success:null,output:(d==null?void 0:d.output)==null?"":Bd(d.output),error:(d==null?void 0:d.error)==null?"":Bd(d.error),call_id:String((d==null?void 0:d.call_id)||""),raw:d}));return{calls:n,results:r}}function NO(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 Am(e){var r,i,o;const t=(r=e==null?void 0:e.result)==null?void 0:r.wait,n=typeof(t==null?void 0:t.wait_key)=="string"&&t.wait_key.startsWith("subworkflow:")?t.wait_key.slice(12):"";return String(((i=t==null?void 0:t.details)==null?void 0:i.sub_run_id)||((o=e==null?void 0:e.result)==null?void 0:o.sub_run_id)||n||"").trim()}function n1(e){var n,r,i,o,c,l,d,h,m,_,g;const t=e.record||{};switch(e.kind){case"llm_call":{const y=Cm(e);return y.tokens_in!==null||y.tokens_out!==null?`${(y.tokens_in??0).toLocaleString("en-US")} in · ${(y.tokens_out??0).toLocaleString("en-US")} out`:""}case"tool":{const y=Em(e).calls;if(!y.length)return"";const x=`${y[0].name}(${NO(y[0].arguments)})`;return y.length>1?`${x} +${y.length-1} more`:x}case"event":return e.event_name;case"subflow":{const y=Am(t);return[String(((r=(n=t==null?void 0:t.effect)==null?void 0:n.payload)==null?void 0:r.workflow_id)||""),y].filter(Boolean).join(" · ")}case"wait":case"resume":return String(((o=(i=t==null?void 0:t.result)==null?void 0:i.wait)==null?void 0:o.reason)||((l=(c=t==null?void 0:t.effect)==null?void 0:c.payload)==null?void 0:l.reason)||"");case"ask":return String(((h=(d=t==null?void 0:t.effect)==null?void 0:d.payload)==null?void 0:h.prompt)||"");case"answer":return String(((_=(m=t==null?void 0:t.effect)==null?void 0:m.payload)==null?void 0:_.message)||((g=t==null?void 0:t.result)==null?void 0:g.message)||"");default:return e.effect_type}}function s1(e){return e.kind==="llm_call"?Cm(e).model:""}function $O(e,t){var r,i;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,n1(e),s1(e)];try{n.push(JSON.stringify(((i=(r=e.started)==null?void 0:r.effect)==null?void 0:i.payload)??null)),n.push(JSON.stringify(e.record??null))}catch{}return n.join(`
91
+ `).toLowerCase()}function CO(e){var r,i;const t=Array.from(new Set((e||[]).map(o=>{var c;return String(o.run_id||((c=o.record)==null?void 0:c.run_id)||"").trim()}).filter(Boolean))),n={llm_calls:0,tokens:0,tool_calls:0,tool_failures:0,failed_steps:0};for(const o of t)for(const c of Pg(e,o))if((c.failed||String(c.status||"")==="failed")&&(n.failed_steps+=1),c.kind==="llm_call"){n.llm_calls+=1;const l=((i=(r=c.record)==null?void 0:r.result)==null?void 0:i.usage)||{};n.tokens+=Number(l.total_tokens??Number(l.prompt_tokens??l.input_tokens??0)+Number(l.completion_tokens??l.output_tokens??0))||0}else if(c.kind==="tool"){const l=Em(c);n.tool_calls+=Math.max(l.calls.length,l.results.length),n.tool_failures+=l.results.filter(d=>d.success===!1).length}return n}function EO(e){const t=[];return e.llm_calls&&t.push(`${e.llm_calls} LLM call${e.llm_calls===1?"":"s"}`),e.tokens&&t.push(`${e.tokens.toLocaleString("en-US")} tokens`),e.tool_calls&&t.push(`${e.tool_calls} tool call${e.tool_calls===1?"":"s"}${e.tool_failures?`, ${e.tool_failures} failed`:""}`),e.failed_steps&&t.push(`${e.failed_steps} failed step${e.failed_steps===1?"":"s"}`),t.join(" · ")}function an(){return new Date().toISOString()}function AO(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Br(e,t){try{const n=JSON.stringify(e);return typeof n!="string"?String(e):n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}catch{const n=String(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}}function tn(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,o=String(e||"").replace(/\r\n/g,`
92
+ `).replace(/\r/g,`
93
+ `).split(`
94
+ `),c=o.slice(0,Math.max(1,r)).join(`
95
+ `),l=o.length>r,d=c.length>n?`${c.slice(0,Math.max(0,n-1))}…`:c;return l&&d===c?`${c}…`:d}function Ln(e,t){const n=String(e||"");return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function $0(e){const t=String(e||"").trim();return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"untitled"}function Vt(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 TO(e){const t=Date.now()-e,n=Math.floor(t/1e3),r=Math.floor(n/60),i=Math.floor(r/60),o=Math.floor(i/24);return n<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:o<=3?`${o}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function cu(e){const t=Vt(e);return t===null?"—":TO(t)}function sm(e){if(!Number.isFinite(e))return"";const t=Math.floor(e/1e3);if(t<=0)return"now";const n=Math.floor(t/60),r=Math.floor(n/60),i=Math.floor(r/24),o=t%60,c=n%60,l=r%24;return i>0?`${i}d ${l}h`:r>0?`${r}h ${c}m`:n>0?`${n}m ${o}s`:`${t}s`}function bu(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3),n=t%60,r=Math.floor(t/60),i=r%60,o=Math.floor(r/60),c=o%24,l=Math.floor(o/24);return l>0?`${l}d ${c}h`:o>0?`${o}h ${i}m`:r>0?`${r}m ${n}s`:`${Math.max(0,t)}s`}function Jd(e){const t=Vt(e);return t===null?"—":new Date(t).toLocaleString()}function Vn(...e){for(const t of e){const n=String(t??"").trim();if(n)return n}return""}function MO(...e){for(const t of e){const n=Number(t);if(Number.isFinite(n))return n}return null}function hs(e){const t=String(e||"").trim().toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}function Yd(e){const t=String(e||"").trim().toLowerCase();return t==="running"||t==="waiting"}function Od(e){return String((e==null?void 0:e.started_at)||(e==null?void 0:e.created_at)||"").trim()}function RO(e){const t=String((e==null?void 0:e.status)||"").trim();return hs(t)?String((e==null?void 0:e.finished_at)||(e==null?void 0:e.updated_at)||"").trim():""}function Tm(e,t=Date.now()){const n=Vt(Od(e));if(n===null)return-1;const r=Vt(RO(e));return Math.max(0,(r!==null?r:t)-n)}function yu(e,t=Date.now()){return bu(Tm(e,t))}function LO(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 tg(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 rm(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 Sa(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"||n==="listening"?"info":"muted"}const IO={all:"All",llm:"LLM calls",tools:"Tools",failed:"Failed"};function wo(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function xa(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 Uy(e){return`${e.toLocaleString("en-US")} chars`}function px(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(xa,{title:"Raw JSON",copy:wo(t),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(hr,{value:t,collapseAfterDepth:2,showCopy:!1})})})}function OO(e){const t=Cm(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(xa,{title:"System",meta:Uy(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(xa,{title:"Messages",meta:`${t.messages.length}${t.messages_source==="sent"?" · as sent":""}`,copy:wo(t.messages),on_copy:e.on_copy,children:s.jsx("ol",{className:"rs_messages",children:t.messages.map((r,i)=>{var o;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,(o=r.tool_calls)==null?void 0:o.map((c,l)=>s.jsx("pre",{className:"rs_text mono",children:`${c.name}(${wo(c.arguments)})`},l))]},i)})})}):null,t.tools.length?s.jsx(xa,{title:"Tools offered",meta:String(t.tools.length),copy:wo(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(xa,{title:"Response",meta:t.tool_calls.length?`${t.tool_calls.length} tool call${t.tool_calls.length===1?"":"s"}`:t.response?Uy(t.response.length):"empty",copy:t.response||wo(t.tool_calls),open:!0,on_copy:e.on_copy,children:[t.response?s.jsx("div",{className:"rs_markdown",children:s.jsx(Ni,{text:t.response})}):null,t.tool_calls.map((r,i)=>s.jsx("pre",{className:"rs_text mono",children:`${r.name}(${wo(r.arguments)})`},i)),!t.response&&!t.tool_calls.length?s.jsx("p",{className:"rs_muted",children:"No text and no tool call."}):null]}),t.reasoning?s.jsx(xa,{title:"Reasoning",meta:Uy(t.reasoning.length),copy:t.reasoning,on_copy:e.on_copy,children:s.jsx("pre",{className:"rs_text",children:t.reasoning})}):null,s.jsx(px,{step:e.step,on_copy:e.on_copy})]})}function PO(e){const t=Em(e.step);return s.jsxs(s.Fragment,{children:[s.jsx(xa,{title:"Calls",meta:String(t.calls.length),copy:wo(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}(${wo(n.arguments)})`},r))}),s.jsxs(xa,{title:"Results",meta:String(t.results.length),copy:wo(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(NN,{sandbox:Xw(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(px,{step:e.step,on_copy:e.on_copy})]})}function DO(e){var i,o,c;const t=e.step.record||{},n=((o=(i=e.step.started)==null?void 0:i.effect)==null?void 0:o.payload)??((c=t==null?void 0:t.effect)==null?void 0:c.payload),r=e.step.kind==="subflow"?Am(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 l;return(l=e.on_open_run)==null?void 0:l.call(e,r)},children:"Open"})]}):null,t.error?s.jsx("pre",{className:"rs_text rs_error",children:typeof t.error=="string"?t.error:wo(t.error)}):null,n!=null?s.jsx(xa,{title:"Payload",copy:wo(n),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(hr,{value:n,collapseAfterDepth:2,showCopy:!1})})}):null,t.result!==void 0&&t.result!==null?s.jsx(xa,{title:"Result",copy:wo(t.result),on_copy:e.on_copy,children:s.jsx("div",{className:"rs_json mono",children:s.jsx(hr,{value:t.result,collapseAfterDepth:2,showCopy:!1})})}):null,s.jsx(px,{step:e.step,on_copy:e.on_copy})]})}function FO(e){const t=e.step,n=n1(t),r=s1(t),i=t.failed&&t.status!=="failed"?"failed":t.status;return s.jsxs("article",{className:`rs_card ${t.failed?"rs_failed":""}`,"data-kind":t.kind,"data-step-id":t.step_id||void 0,children:[s.jsxs("button",{type:"button",className:"rs_card_head","aria-expanded":e.open,onClick:e.on_toggle,children:[s.jsx("span",{className:"rs_chevron","aria-hidden":"true",children:e.open?"▾":"▸"}),s.jsx("span",{className:"rs_kind",children:lO[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 ${Sa(i)}`,children:i||"—"}),s.jsx("span",{className:"rs_dur",children:t.duration_ms!==null?bu(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(OO,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(PO,{step:t,on_copy:e.on_copy}):s.jsx(DO,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function zO(e){const{state:t}=e,n=p.useMemo(()=>Pg(e.items,e.run_id),[e.items,e.run_id]),[r,i]=p.useState({}),o=x=>e.node_label(x.run_id,x.node_id),c=p.useMemo(()=>new Map,[n]),d=bO(n,t,x=>{let k=c.get(x.id);return k===void 0&&(k=$O(x,o(x)),c.set(x.id,k)),k}),h=n.some(x=>x.kind==="llm_call"),m=n.reduce((x,k)=>k.kind==="llm_call"?x+1:x,0),_=n.length-d.length,g=x=>e.on_state({...t,...x}),y=x=>s.jsx(FO,{step:x,node_label:o(x),open:r[x.id]===!0,on_toggle:()=>i(k=>({...k,[x.id]:!k[x.id]})),on_copy:e.on_copy,on_open_run:e.on_open_run},x.id);return s.jsxs("div",{className:"rs_view",children:[s.jsxs("div",{className:"rs_count",children:[s.jsxs("span",{children:[d.length," of ",n.length," steps",h?` · ${m} cycle${m===1?"":"s"}`:"",_&&t.only==="all"&&!t.all_steps&&!t.q?` · ${_} housekeeping hidden`:""]}),e.run_options.length>1?s.jsx("select",{className:"seg_select mono",value:e.run_id,onChange:x=>e.on_select_run(String(x.target.value||"")),"aria-label":"Run",children:e.run_options.map(x=>s.jsxs("option",{value:x,children:[Ln(x,14),e.run_llm_counts[x]?` · ${e.run_llm_counts[x]} LLM`:""]},x))}):null]}),s.jsxs("div",{className:"rs_toolbar",children:[s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Layout",children:["cycles","steps"].map(x=>s.jsx("button",{type:"button",role:"radio","aria-checked":t.view===x,className:`seg_btn ${t.view===x?"active":""}`,onClick:()=>g({view:x}),children:x==="cycles"?"Cycles":"Steps"},x))}),s.jsx("div",{className:"seg_toggle",role:"radiogroup","aria-label":"Show",children:["all","llm","tools","failed"].map(x=>s.jsx("button",{type:"button",role:"radio","data-filter":x,"aria-checked":t.only===x,className:`seg_btn ${t.only===x?"active":""}`,onClick:()=>g({only:x}),children:IO[x]},x))}),s.jsx("input",{className:"rs_search",type:"search",value:t.q,onChange:x=>g({q:x.target.value}),placeholder:"Search steps","aria-label":"Search steps",autoComplete:"off",spellCheck:!1}),t.only==="all"?s.jsx(Fi,{label:"All steps",action:"show-all-steps",hint:"Also list status events, waits, resumes and memory bookkeeping.",checked:t.all_steps,onChange:x=>g({all_steps:x})}):null]}),n.length?null:s.jsx("p",{className:"rs_muted",children:"No steps recorded for this run yet."}),n.length&&!d.length?s.jsx("p",{className:"rs_muted",children:"No step matches."}):null,t.view==="cycles"&&h?vO(d).map(x=>s.jsxs("section",{className:"rs_cycle","data-cycle":x.cycle,children:[s.jsx("h3",{className:"rs_cycle_head",children:x.cycle===0?"Before the first call":`Cycle ${x.cycle}`}),x.steps.map(y)]},x.cycle)):d.map(y)]})}function BO(e){const[t,n]=p.useState(!1),r=e.answer.length>C0,i=t||!r?e.answer:`${e.answer.slice(0,C0).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 ${Sa(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(Ni,{text:i}),r?s.jsx("button",{type:"button",className:"rs_link","aria-expanded":t,onClick:()=>n(o=>!o),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 C0=600;let Rp={connections:null,mailboxes:null};const UO=new Set;function WO(e){if(!(e.connections===Rp.connections&&e.mailboxes===Rp.mailboxes)){Rp={connections:e.connections,mailboxes:e.mailboxes};for(const t of UO)t()}}function qO(e,t,n=Rp){return!e||typeof e!="object"?"":km(e,n.connections,n.mailboxes,t)}const E0="—";function bd(e){return typeof e=="string"&&e?e:void 0}function VO(e){return e.endsWith("+00:00")||e.endsWith("Z")}function Wy(e){if(!e||typeof e!="object")return e;const t=e,n={...e},r=bd(t.next_run_at)??bd(t.next_fire_at);let i=bd(t.next_run_local),o=bd(t.time_zone)??"";return!i&&!o&&r&&VO(r)&&(i=r,o="UTC"),r?n.next_run_at=r:delete n.next_run_at,i?n.next_run_local=i:delete n.next_run_local,n.time_zone=o,n.schedule_rule_text=bd(t.schedule_rule_text)??E0,n.schedule_text=bd(t.schedule_text)??E0,n}function HO(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(Wy)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:Wy(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:Wy(n.summary)}:n}}}const GO="@default:",Ud="abstractcode.agent.v1";function A0(e,t){var n;return e?e.kind==="default"?e.interface===Ud?"@default":"":((n=t.find(r=>r.bundleId===e.bundle_id&&r.flowId===e.flow_id))==null?void 0:n.value)??"":""}function KO(e,t){return e==="@default"?{kind:"default",interface:Ud}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function JO(e){return e?e.kind==="default"?`${GO}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function YO(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 XO(e){const t={};for(const[n,r]of Object.entries(e||{}))if(typeof r=="string"){const i=r.trim();i&&(t[n]=i)}else r!==void 0&&(t[n]=r);return t}const ZO={once:"Run once: start this flow now, a single run you can watch in Observe.",automate:"Automate: the flow runs by itself — with its own trigger, on a schedule, when something arrives (mail, a feed, a webhook), or by hand; manage it on the Automations page."};function QO(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 e3="#launch/automate";function t3(e){const t=ZN(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 iv={when:"every",email_account:"default",connection_id:"",calendar:YS,email:AS,notify_email:!1,email_recipients:Kh,amount:"24",unit:"h",once_at:"",context:"independent",growing_max_tokens:String(tm),tool_approval:"auto",title:"",start_at:"",count:"",until:""},T0={independent:"Each run starts fresh in its own conversation. 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."},r1=["use_context"],n3="This choice also tells the flow whether to read the earlier runs.",i1=["event"];function s3(e,t,n){if(!e||typeof e!="object")return null;const r=String(e.bundle_id||"").trim();if(r&&r!==String(t||"").trim())return null;const i=e.automation_defaults&&typeof e.automation_defaults=="object"?e.automation_defaults[String(n||"").trim()]:null;if(!i||typeof i!="object")return null;const o=i.trigger;return!o||typeof o!="object"||typeof o.source_id!="string"||typeof o.source_version!="number"?null:i}function o1(e){const t={...e.trigger.config||{}};return e.trigger.connection_id&&!t.connection_id&&(t.connection_id=e.trigger.connection_id),{source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:t}}function r3(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function i3(e,t,n){var l,d,h;const r=((l=n.context)==null?void 0:l.mode)==="growing"?"growing":"independent",i=(h=(d=n.context)==null?void 0:d.growing)==null?void 0:h.max_tokens,o={...e,when:"defaults",context:r,...typeof i=="number"&&i>0?{growing_max_tokens:String(i)}:{},...!e.title.trim()&&typeof n.title=="string"&&n.title.trim()?{title:n.title.trim()}:{}},c={...n.input_data||{}};for(const[m,_]of Object.entries(t||{}))r3(_)&&(c[m]=_);return{form:o,input_data:c}}function o3(e,t){return e.interfaces.length?null:e.automationTrigger?[km(e.automationTrigger,t.connections,t.mailboxes),e.bundleVersion?`@${e.bundleVersion}`:""].filter(Boolean).join(" · "):e.triggerable?["Runs by itself",e.bundleVersion?`@${e.bundleVersion}`:""].filter(Boolean).join(" · "):null}function a1(e){return[...e||[]].filter(t=>t.configured!==!1&&t.can_read!==!1).sort((t,n)=>Number(n.primary)-Number(t.primary))}function a3(e){const t=e.last_error&&typeof e.last_error=="object"?e.last_error:null;if(t){const n=i=>typeof t[i]=="string"?String(t[i]).trim():"";return`not working: ${n("cause")||n("message")||n("code")||"it failed"}${n("fix")?` ${n("fix")}`:""}`.trim()}return e.paused===!0||e.status==="paused"?"paused":""}function l3(e,t){const n=[];for(const r of a1(e))n.push({value:`mail:${r.account_id}`,label:`Mail arrives in ${Eg(r.account_id,e)}`,group:"mail",problem:""});for(const r of t||[]){if(r.status&&r.status!=="active"&&r.status!=="paused")continue;const i=kS(r.label||"a connection",r.source_id),o=a3(r);n.push({value:`conn:${r.connection_id}`,label:`${i.replace(/^When /,"")}${o?` — ${o.startsWith("not working")?"not working":o}`:""}`,group:bm(r.source_id),problem:o})}return n}function Xc(e){return e.when==="email"?`mail:${e.email_account||"default"}`:e.when==="connection"&&e.connection_id?`conn:${e.connection_id}`:""}function M0(e){return e.startsWith("mail:")?{when:"email",email_account:e.slice(5)||"default"}:e.startsWith("conn:")?{when:"connection",connection_id:e.slice(5)}:{}}function gx(e,t,n=!1){const r=e.when==="every",i=e.when==="daily"||e.when==="weekly"||e.when==="monthly";return{prompt:t,when:e.when==="once"?{kind:"once",at:e.once_at}:i?ax(e.when,e.calendar):{kind:"every",amount:Number(e.amount),unit:e.unit},...n&&e.when==="email"?{trigger:"email",email:e.email}:{},...n&&e.notify_email?{notifyEmail:!0}:{},...n&&e.email_recipients.mode==="list"?{emailRecipients:e.email_recipients}:{},context:e.context,growingMaxTokens:Number(e.growing_max_tokens),toolApproval:e.tool_approval,title:e.title,...r&&e.start_at?{startAt:e.start_at}:{},...(r||i)&&e.count.trim()?{count:Number(e.count)}:{},...(r||i)&&e.until?{until:e.until}:{}}}function c3(e,t){if(e.when==="defaults")return t&&t.trigger.source_id==="schedule"?o1(t):null;if(e.when==="email"||e.when==="connection"||e.when==="manual")return null;const n=gx(e,"preview");return hT(n.when)?GS(n).trigger:null}function u3(e,t){if(t.input_data===null)return{ok:!1,errors:["The inputs are not valid JSON."]};const n=String(e.email_account||"default").trim()||"default",r=t.mailboxes?a1(t.mailboxes).some(g=>g.account_id===n||n==="default"&&g.primary):n==="default"&&t.email_usable===!0;if(e.when==="email"&&!r)return{ok:!1,errors:[$n.not_set_up]};if(e.when==="defaults"&&!t.defaults)return{ok:!1,errors:["This flow has no trigger of its own: choose Other trigger…."]};let i=null;if(e.when==="connection"&&(i=(t.connections||[]).find(g=>g.connection_id===e.connection_id)??null,!i))return{ok:!1,errors:["Choose what to listen to under When something arrives."]};const o=XO(t.input_data),c=typeof o.prompt=="string"?o.prompt:"";delete o.prompt;for(const g of r1)delete o[g];for(const g of i1)delete o[g];delete o.workspace_root;let l;try{l=YO(t.choice,t.bundle_ref_for,o)}catch(g){return{ok:!1,errors:[String((g==null?void 0:g.message)||g)]}}const d=e.when==="defaults"||e.when==="connection"||e.when==="manual",h=gx(d?{...e,when:"every",amount:"24",unit:"h",start_at:"",count:"",until:""}:e,c,t.email_usable===!0||e.when==="email"&&r),m=KS(h,{target:l,requestId:t.request_id});if(!m.ok)return m;const _=m.body;return e.when==="defaults"&&t.defaults?_.trigger=o1(t.defaults):e.when==="connection"&&i?_.trigger={source_id:i.source_id,source_version:i.source_version,config:{connection_id:i.connection_id}}:e.when==="manual"?_.trigger={source_id:"manual",source_version:1,config:{}}:e.when==="email"&&n!=="default"&&(_.trigger={..._.trigger,config:{..._.trigger.config,account:n}}),{ok:!0,body:_}}function d3(e,t=!1){if(e.when==="email"){if(!t)return"";const n=KS(gx(e,"preview",!0),{target:{flow_id:"@default",interface:Ud},requestId:"preview"});return n.ok?`Runs ${MS(n.body.trigger.config)}.`:""}return""}class f3{constructor(t){jn(this,"key","");jn(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 h3(e,t,n){const r=u3(e,{...t,request_id:""});if(!r.ok)return r;const{request_id:i,...o}=r.body,c=n.id_for(JSON.stringify(o));return{ok:!0,body:{...r.body,request_id:c}}}function pa(e){return typeof e=="string"?e:e??null}function op(e){var t,n,r,i,o,c;return{run_id:String((e==null?void 0:e.run_id)||"").trim(),workflow_id:pa(e==null?void 0:e.workflow_id),status:typeof(e==null?void 0:e.status)=="string"?String(e.status):"",created_at:pa(e==null?void 0:e.created_at),updated_at:pa(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:pa(e==null?void 0:e.parent_run_id),session_id:pa(e==null?void 0:e.session_id),actor_id:pa(e==null?void 0:e.actor_id),session_kind:pa(e==null?void 0:e.session_kind),automation_id:pa(e==null?void 0:e.automation_id),role:pa(e==null?void 0:e.role),occurrence_index:typeof(e==null?void 0:e.occurrence_index)=="number"?Number(e.occurrence_index):null,is_scheduled:typeof(e==null?void 0:e.is_scheduled)=="boolean"?!!e.is_scheduled:(e==null?void 0:e.is_scheduled)??null,paused:typeof(e==null?void 0:e.paused)=="boolean"?!!e.paused:(e==null?void 0:e.paused)??null,pause_reason:pa(e==null?void 0:e.pause_reason),is_draft:(e==null?void 0:e.is_draft)===!0,waiting_reason:typeof((t=e==null?void 0:e.waiting)==null?void 0:t.reason)=="string"?String(e.waiting.reason):((n=e==null?void 0:e.waiting)==null?void 0:n.reason)??null,schedule_interval:typeof((r=e==null?void 0:e.schedule)==null?void 0:r.interval)=="string"?String(e.schedule.interval).trim():((i=e==null?void 0:e.schedule)==null?void 0:i.interval)??null,schedule_target_workflow_id:typeof((o=e==null?void 0:e.schedule)==null?void 0:o.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 m3(e,t){const n=new Set(e.map(i=>String((i==null?void 0:i.run_id)||""))),r=[...e];for(const i of t){const o=String((i==null?void 0:i.run_id)||"");!o||n.has(o)||(n.add(o),r.push(i))}return r}function Dg(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 l1(e){const t=Dg(e);return t==="occurrence"?typeof e.occurrence_index=="number"?`run #${e.occurrence_index}`:"automation run":t==="legacy"?"legacy schedule":t||""}function _3(e){var n,r,i;const t=(i=(r=(n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)==null?void 0:r.common)==null?void 0:i.automations;return t&&typeof t=="object"&&t.available===!0?{available:!0,reason:""}:t&&typeof t=="object"&&t.available===!1?{available:!1,reason:"This gateway has the Automations API turned off."}:{available:!1,reason:"This gateway does not advertise the Automations API (capabilities.contracts.common.automations). Update AbstractGateway to use automations; legacy schedules stay manageable from their run view."}}function el(e){return e.legacy===!0||e.capabilities.includes("legacy")}function c1(e,t=Date.now(),n){const r=el(e),i=e.last_occurrence,o=i&&i.attempts>1?` after ${i.attempts} attempts`:"",c=e.attention.unread||e.attention.pending_waits>0,l=!r&&uc(e.trigger)&&e.status==="active"&&!e.next_run_at,d=l&&i?Qh(i.fired_at,{timeZone:e.time_zone,nowMs:t,style:"day"}):"";return{id:e.automation_id,title:e.title,cadence:nx(e.trigger,e,n??null),next_run:l?"runs when something new arrives":OS(e,t),listening:l,current:IS(e),state:e.status,last:i?i.excerpt:"",last_status:i?`${d?`last: ${d} · `:""}#${i.index} ${i.status}${o}`:"no runs yet",attention:c?PS(e):null,legacy:r}}function u1(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 p3(e,t){const n=em(e,[],t),r=u1(e),i=t?{enabled:!1,reason:"Working…"}:el(e)?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:e.capabilities.includes("discuss")?r===null?{enabled:!1,reason:e.last_occurrence?"Available once the first run finishes.":"No occurrence to discuss yet."}:{enabled:!0,reason:`Discuss run #${r} in a new chat (a fork of this automation).`}:{enabled:!1,reason:"Not permitted for this automation."};return{active:n.active,pause:n.pause,resume:n.resume,run_now:n.run_now,edit:n.revise,archive:n.archive,discuss:i}}function g3(e,t){const n=o=>({enabled:!1,reason:o});if(t)return{legacy_pause:n("Working…"),legacy_resume:n("Working…"),legacy_run_now:n("Working…"),open_run:{enabled:!0},recreate:n("Working…")};const r=e.status==="paused",i=e.status==="active"||e.status==="paused";return{legacy_pause:r?n("Already suspended."):i?{enabled:!0}:n("The schedule has ended."),legacy_resume:r?{enabled:!0}:n(i?"Already running on schedule.":"The schedule has ended."),legacy_run_now:e.status==="active"?{enabled:!0}:n(r?"The schedule is off: switch Active on first.":"The schedule has ended."),open_run:{enabled:!0},recreate:{enabled:!0}}}function y3(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 w3=/^([1-9][0-9]*)([smhd])$/;function v3(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 x3(e,t){const n=e!=null&&e.schedule&&typeof e.schedule=="object"?e.schedule:null;if(!n)throw new Error("This run carries no legacy schedule metadata; nothing to recreate.");const r=String(n.target_bundle_ref||"").trim(),i=String(n.target_host_bundle_id||n.target_bundle_id||(r.includes("@")?r.slice(0,r.lastIndexOf("@")):"")||(t==null?void 0:t.bundle_id)||"").trim(),o=String(n.target_flow_id||(t==null?void 0:t.flow_id)||"").trim();if(!i||!o)throw new Error("The legacy schedule does not name its target workflow.");const c=[],l={...iv},d=typeof n.interval=="string"?n.interval.trim():"";if(!d)l.when="once",c.push("The legacy schedule ran once; pick the date and time to run.");else{const g=w3.exec(d);let y=g?Number(g[1]):0,x=g?g[2]:"";x==="s"&&y%60===0&&(y=y/60,x="m"),x==="m"||x==="h"||x==="d"?(l.amount=String(y),l.unit=x):c.push(`The legacy interval "${d}" is not a whole number of minutes, hours or days; choose an interval.`)}typeof n.repeat_count=="number"&&n.repeat_count>=1&&(l.count=String(n.repeat_count));const h=v3(n.repeat_until);h&&(l.until=h),l.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:{},_={};for(const[g,y]of Object.entries(m))g==="workflow_selection"||g.startsWith("_")||(_[g]=y);return{choice:{kind:"bundle",bundle_id:i,flow_id:o},input_data:_,form:l,notes:c}}const b3={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,trigger_connections:null,mailboxes:null};function k3(e,t,n){var i;const r=(i=e.get_run_input_data)==null?void 0:i.bind(e);return{...r?{run_input_data:async o=>{const c=await r(o),l=c&&typeof c=="object"?c.input_data:null;return l&&typeof l=="object"&&!Array.isArray(l)?l:null}}:{},answer_wait:async(o,c,l)=>{await e.submit_command({command_id:t(),run_id:o,type:"resume",payload:{wait_key:c,payload:l},client_id:"web_pwa"})},legacy_command:async(o,c,l)=>{await e.submit_command({command_id:t(),run_id:o,type:c,payload:l,client_id:"web_pwa"})},now_iso:n}}function j3(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 qy(e){return e.show_archived||e.status_filter==="archived"?e.items:e.items.filter(t=>t.status!=="archived")}function R0(e){return e.items.filter(t=>t.status==="archived").length}function yx(e,t){return`A conversation about run #${e} started. It works in its own folder; it can read the automation's files but not change them (shell commands are not sandboxed), and nothing is written back into the automation.`}const S3=3e4,ap=50;function Pi(e){return ix(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Vy(e,t){const n=new Map;for(const r of e)n.set(r.run_id,r);for(const r of t)n.set(r.run_id,r);return Array.from(n.values()).sort((r,i)=>i.index-r.index)}class N3{constructor(t,n,r=[1500,4e3]){jn(this,"state",{...b3});jn(this,"listeners",new Set);jn(this,"list_seq",0);jn(this,"detail_seq",0);jn(this,"sources_loaded",!1);jn(this,"client");jn(this,"preview_schedule",t=>this.client.previewSchedule(t));jn(this,"events_inflight",new Set);jn(this,"definitions",new Map);this.host=n,this.followups_ms=r,this.client=HO(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}set(t){this.state={...this.state,...t};for(const n of this.listeners)n()}async list_all(){const t=[];let n;for(let r=0;r<200;r+=1){const i=await this.client.listAutomations({...this.state.status_filter?{status:this.state.status_filter}:{},...n?{cursor:n}:{},limit:ap});if(t.push(...i.items),!i.next_cursor)return t;n=i.next_cursor}throw new Error("GET /api/gateway/automations kept returning next_cursor after 200 pages.")}async load_trigger_vocab(){const[t,n]=await Promise.all([this.client.listTriggerConnections?this.client.listTriggerConnections().then(o=>Array.isArray(o==null?void 0:o.connections)?o.connections:null,()=>null):Promise.resolve(null),this.client.listMailboxes?this.client.listMailboxes().then(o=>Array.isArray(o==null?void 0:o.items)?o.items:null,()=>null):Promise.resolve(null)]),r=t??this.state.trigger_connections,i=n??this.state.mailboxes;WO({connections:r,mailboxes:i}),this.set({trigger_connections:r,mailboxes:i})}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 Tg(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(),this.load_trigger_vocab(),t!==this.list_seq)return;const r=this.state.detail,i=r?n.find(o=>o.automation_id===r.automation_id):void 0;this.set({items:n,loaded:!0,loading:!1,list_error:null,refreshed_at:Date.now(),...r&&i?{detail:{...r,summary:i}}:{}}),r&&await this.reload_occurrences(r.automation_id)}catch(n){if(t!==this.list_seq)return;this.set({loading:!1,loaded:!0,list_error:Pi(n)})}}async set_status_filter(t){this.set({status_filter:t}),await this.refresh()}async load_trigger_sources(){if(this.sources_loaded)return;const t=await this.client.listTriggerSources();this.sources_loaded=!0,this.set({trigger_sources:t.items})}async select(t){var i;const n=String(t||"").trim(),r=++this.detail_seq;if(!n){this.set({selected_id:"",detail:null});return}this.set({selected_id:n,notice:"",...((i=this.state.detail)==null?void 0:i.automation_id)!==n?{detail:null}:{}});try{const o=this.state.items.find(d=>d.automation_id===n);if(o&&el(o)){this.set({detail:{automation_id:n,summary:o,definition:null,occurrences:[],next_cursor:null,error:null,occurrence_events:{}}});return}const[c,l]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:ap})]);if(r!==this.detail_seq)return;this.set({detail:{automation_id:n,summary:o??c.summary,definition:c.definition,occurrences:Vy([],l.items),next_cursor:l.next_cursor,error:null,occurrence_events:{}}}),this.load_occurrence_events(n),await this.load_trigger_sources()}catch(o){if(r!==this.detail_seq)return;this.set({error:Pi(o)})}}async reload_occurrences(t){const n=this.state.detail;if(!n||n.automation_id!==t||el(n.summary))return;const[r,i]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:ap})]),o=this.state.detail;if(!o||o.automation_id!==t)return;const c=this.state.items.find(l=>l.automation_id===t);this.set({detail:{...o,summary:c??r.summary,definition:r.definition,occurrences:Vy(o.occurrences,i.items),next_cursor:o.occurrences.length>i.items.length?o.next_cursor:i.next_cursor}}),this.load_occurrence_events(t)}async load_occurrence_events(t){const n=this.state.detail,r=this.host.run_input_data;if(!r||!n||n.automation_id!==t||el(n.summary)||!uc(n.summary.trigger))return;const i=n.occurrences.map(l=>l.run_id).filter(l=>l&&!(l in n.occurrence_events)&&!this.events_inflight.has(l));if(!i.length)return;for(const l of i)this.events_inflight.add(l);const o={};try{await Promise.all(i.map(async l=>{try{const d=await r(l);o[l]=d&&typeof d=="object"&&"event"in d?d.event:null}catch{o[l]=null}}))}finally{for(const l of i)this.events_inflight.delete(l)}const c=this.state.detail;!c||c.automation_id!==t||this.set({detail:{...c,occurrence_events:{...c.occurrence_events,...o}}})}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:ap}),r=this.state.detail;if(!r||r.automation_id!==t.automation_id)return;this.set({detail:{...r,occurrences:Vy(r.occurrences,n.items),next_cursor:n.next_cursor}}),this.load_occurrence_events(t.automation_id)}catch(n){this.set({error:Pi(n)})}}async after_change(t){await this.refresh();for(const n of this.followups_ms)setTimeout(()=>void this.refresh(),n)}async command(t,n,r,i){this.set({busy:!0});try{const o=await this.client.sendAutomationCommand(t,{type:n,...r?{payload:r}:{},...i?{command_id:i}:{}});return await this.after_change(t),o}catch(o){throw Pi(o)}finally{this.set({busy:!1})}}async revise(t,n,r,i){this.set({busy:!0});try{const o=await this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...i?{command_id:i}:{}});return await this.after_change(t),o}catch(o){throw Pi(o)}finally{this.set({busy:!1})}}definition(t){if(el(t))return Promise.resolve(null);const n=t.automation_id,r=this.state.detail;if(r&&r.automation_id===n&&r.definition&&r.definition.revision===t.revision)return Promise.resolve(r.definition);const i=this.definitions.get(n);if(i&&i.revision===t.revision)return i.answer;const o=this.client.getAutomation(n).then(c=>c.definition??null);return o.catch(()=>this.definitions.delete(n)),this.definitions.set(n,{revision:t.revision,answer:o}),o}async discuss(t,n,r,i){this.set({busy:!0});try{const o=await this.client.discuss(t,{occurrence_index:n,prompt:r,...i?{request_id:i}:{}});return this.set({notice:yx(n,o)}),o}catch(o){throw Pi(o)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Pi(r)}}async answer_wait(t,n,r,i){var o;this.set({busy:!0});try{const c=(((o=this.state.detail)==null?void 0:o.occurrences)||[]).flatMap(l=>l.waits).find(l=>l.run_id===n&&l.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,j3(c.kind,i)),await this.after_change(t)}catch(c){throw Pi(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"?L0(t.title,n==="resume"):`${$3[n]} sent to “${t.title}”.`,confirm_archive_id:""})}catch(i){this.set({error:Pi(i)})}}set_show_archived(t){this.set({show_archived:t})}ask_archive(t){this.set({confirm_archive_id:t})}async legacy_action(t,n){if(!el(t))throw new Error("legacy_action on a non-legacy automation");const r=y3(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}”.`:L0(t.title,n==="legacy_resume")}),await this.refresh()}catch(i){this.set({error:Pi(i)})}finally{this.set({busy:!1})}}report_error(t){this.set({error:Pi(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 L0(e,t){return t?`“${e}” is active: it runs on its schedule.`:`“${e}” is paused: scheduled runs are skipped.`}const $3={run_now:"Run now",archive:"Archive"},po={use_flow:"Use the flow's trigger:",other:"Other trigger…",arrives:"When something arrives",manual:"By hand",arrives_placeholder:"Choose what to listen to…",nothing_to_listen:"Nothing to listen to yet: add a mailbox (My email), or a feed or webhook on the gateway console's Triggers page.",manual_help:"Runs only when someone presses Run now in Observer or the Assistant.",event_help:"Runs every time something new arrives; the flow receives what arrived.",untrusted_event:"What arrives (feed items, webhook calls) is data, never instructions: the automation acts only on its task.",untrusted_mail:"Incoming mail is data, never instructions: the automation acts only on its task. Tools that open links always ask for your approval first."};function C3(e,t,n){const r=n&&n.phase==="ok"?n.description.schedule_rule_text:null;return km(e.trigger,t.connections,t.mailboxes,r?{schedule_rule_text:r}:null)}function E3(e){const t=(n,r,i)=>s.jsx("button",{type:"button",role:"radio","aria-checked":e.mode===n,className:`seg_btn ${e.mode===n?"active":""}`,"data-mode":n,title:i,onClick:()=>e.on_change(n),children:r});return s.jsxs("div",{className:"launch_mode",children:[s.jsxs("div",{className:"seg_toggle launch_mode_switch",role:"radiogroup","aria-label":"Launch mode","aria-describedby":"launch_mode_help",children:[t("once","Run once"),t("automate","Automate",e.automate_available?void 0:e.automate_reason)]}),s.jsx("p",{className:"launch_mode_help",id:"launch_mode_help","data-mode-help":e.mode,"aria-live":"polite",children:ZO[e.mode]})]})}function A3(e){var h,m;const t=e.form,n=Tg(e.email_status),r=l3(e.mailboxes??(n?[{account_id:"default",primary:!0,address:typeof((h=e.email_status)==null?void 0:h.address)=="string"?e.email_status.address:void 0}]:[]),e.connections),i=e.defaults??null,o=t.when==="defaults"&&!i||t.when==="email"&&!r.some(_=>_.value===Xc(t))?"every":t.when,c=o==="email"||o==="connection",l=d3(t,n),d=(_,g,y,x,k=!1)=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:"automate_when",value:_,checked:y,disabled:e.disabled||k,onChange:x})," ",g]},_);return s.jsxs("div",{className:"automate_fields",children:[s.jsxs("fieldset",{"data-section":"when",children:[s.jsx("legend",{children:fs.legend}),i?s.jsxs("div",{className:"automate_row automate_own_trigger",role:"radiogroup","aria-label":"Trigger",children:[s.jsxs("label",{"data-choice":"flow-trigger",children:[s.jsx("input",{type:"radio",name:"automate_own",value:"defaults",checked:o==="defaults",disabled:e.disabled,onChange:()=>e.on_change({when:"defaults"})})," ",po.use_flow," ",s.jsx("strong",{"data-field":"flow-trigger",children:C3(i,{connections:e.connections,mailboxes:e.mailboxes},e.served)})]}),s.jsxs("label",{"data-choice":"other-trigger",children:[s.jsx("input",{type:"radio",name:"automate_own",value:"other",checked:o!=="defaults",disabled:e.disabled,onChange:()=>e.on_change({when:"every"})})," ",po.other]})]}):null,o==="defaults"&&i?i.trigger.source_id==="schedule"?s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Vw,{state:e.served,onOpenPreferences:e.on_open_preferences,showZone:!0})}):s.jsx("p",{className:"help_text muted","data-help":"flow-trigger",children:uc(i.trigger)?po.event_help:i.trigger.source_id==="manual"?po.manual_help:""}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"automate_row",role:"radiogroup","aria-label":"Schedule kind",children:[d("every",fs.kind_every,o==="every",()=>e.on_change({when:"every"})),["daily","weekly","monthly"].map(_=>d(_,fs[`kind_${_}`],o===_,()=>e.on_change({when:_}))),d("once",fs.kind_once,o==="once",()=>e.on_change({when:"once"})),d("arrives",po.arrives,c,()=>e.on_change(r.length?M0(r.some(_=>_.value===Xc(t))?Xc(t):r[0].value):{when:"connection",connection_id:""})),d("manual",po.manual,o==="manual",()=>e.on_change({when:"manual"}))]}),c?r.length?s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{className:"sr-only",children:"What to listen to"}),s.jsxs("select",{"data-field":"arrival","aria-label":"What to listen to",value:Xc(t),disabled:e.disabled,onChange:_=>e.on_change(M0(_.target.value)),children:[Xc(t)?null:s.jsx("option",{value:"",children:po.arrives_placeholder}),r.map(_=>s.jsx("option",{value:_.value,"data-group":_.group,children:_.label},_.value))]})]}):s.jsxs("div",{className:"help_text",role:"note","data-note":"nothing-to-listen",children:[po.nothing_to_listen,e.on_open_my_email?s.jsxs(s.Fragment,{children:[" ",s.jsx("button",{type:"button",className:"btn btn_sm","data-action":"open-my-email",onClick:e.on_open_my_email,children:"Open My email"})]}):null]}):null,c&&((m=r.find(_=>_.value===Xc(t)))!=null&&m.problem)?s.jsx("div",{className:"warn_callout",role:"note","data-note":"arrival-problem",children:`This one is ${r.find(_=>_.value===Xc(t)).problem}. It runs again once it reads; fix it on the gateway console's Triggers page.`}):null,o==="email"?s.jsx(GT,{value:t.email,onChange:_=>e.on_change({email:_}),disabled:e.disabled,idBase:"automate"}):o==="daily"||o==="weekly"||o==="monthly"?s.jsx(XS,{value:ax(o,t.calendar),onChange:_=>e.on_change({calendar:lx(t.calendar,_)}),idBase:"automate",disabled:e.disabled}):o==="every"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"automate_row",role:"group","aria-label":"Presets",children:cT.map(_=>_.when.kind==="every"?s.jsx("button",{type:"button",className:"btn btn_sm","data-preset":_.label,"aria-pressed":Number(t.amount)===_.when.amount&&t.unit===_.when.unit,disabled:e.disabled,onClick:()=>{_.when.kind==="every"&&e.on_change({amount:String(_.when.amount),unit:_.when.unit})},children:_.label},_.label):null)}),s.jsxs("div",{className:"automate_row",children:[s.jsx("span",{children:fs.every_label}),s.jsx("input",{type:"number",min:1,step:1,value:t.amount,disabled:e.disabled,"aria-label":"Interval amount",onChange:_=>e.on_change({amount:_.target.value})}),s.jsxs("select",{value:t.unit,disabled:e.disabled,"aria-label":"Interval unit",onChange:_=>e.on_change({unit:_.target.value}),children:[s.jsx("option",{value:"m",children:"minutes"}),s.jsx("option",{value:"h",children:"hours"}),s.jsx("option",{value:"d",children:"days"})]})]})]}):o==="once"?s.jsxs("label",{className:"automate_row",children:[s.jsx("span",{children:fs.once_label}),s.jsx("input",{type:"datetime-local",value:t.once_at,disabled:e.disabled,onChange:_=>e.on_change({once_at:_.target.value})})]}):null,o==="email"?l?s.jsx("div",{className:"automate_preview","aria-live":"polite","data-preview":"true",children:l}):null:o==="connection"?s.jsx("p",{className:"help_text muted","data-help":"arrives",children:po.event_help}):o==="manual"?s.jsx("p",{className:"help_text muted","data-help":"manual",children:po.manual_help}):s.jsx("div",{className:"automate_preview automate_preview--served",children:s.jsx(Vw,{state:e.served,onOpenPreferences:e.on_open_preferences,showZone:o!=="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) — ",T0.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"})," — ",T0.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:_=>e.on_change({growing_max_tokens:_.target.value})})]}):null,s.jsx("p",{className:"help_text muted","data-context-owns":"use_context",children:n3})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(QS,{availableTools:e.available_tools,value:e.tools??null,onChange:e.on_tools_change,disabled:e.disabled}):null,o==="email"||o==="defaults"&&i&&i.trigger.source_id.startsWith("email")?s.jsx("p",{className:"help_text muted","data-email-rule":"untrusted",children:po.untrusted_mail}):o==="connection"||o==="defaults"&&i&&uc(i.trigger)?s.jsx("p",{className:"help_text muted","data-event-rule":"untrusted",children:po.untrusted_event}):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"})})," ",mT,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(oN,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(KT,{notifyEmail:n&&t.notify_email,onNotifyEmailChange:_=>e.on_change({notify_email:_}),recipients:n?t.email_recipients:Kh,onRecipientsChange:_=>e.on_change({email_recipients:_}),disabled:e.disabled||!n,idBase:"automate"})]})]})}function I0(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toISOString().slice(0,16)}function O0(e){if(!e)return"";const t=new Date(`${e.length===16?`${e}:00`:e}Z`);if(Number.isNaN(t.getTime()))return e;const n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function T3(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"}),s.jsx("input",{type:"datetime-local","aria-describedby":"automate_limits_help",value:O0(t.start_at),disabled:e.disabled,onChange:n=>e.on_change({start_at:I0(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 on"}),s.jsx("input",{type:"datetime-local","aria-describedby":"automate_limits_help",value:O0(t.until),disabled:e.disabled,onChange:n=>e.on_change({until:I0(n.target.value)})})]})]}):null]}),t.when==="every"||t.when==="daily"||t.when==="weekly"||t.when==="monthly"?s.jsx("p",{className:"help_text muted",id:"automate_limits_help","data-help":"limits",children:"All optional. Leave the first run empty to start now; times are in this browser's clock."}):null]})})}function M3(e,t){const n=String(t||"").trim();return n||`Loading ${String(e||"").trim()||"data"}…`}function ol(e){const t=M3(e.what,e.label),n=e.size==="block"?"block":"inline";return s.jsxs("div",{className:`af_loading af_loading_${n}${e.className?` ${e.className}`:""}`,role:"status","aria-live":"polite","aria-busy":"true",children:[s.jsx("span",{className:"af_loading_spin","aria-hidden":"true",children:s.jsx(qe,{name:"loader",size:n==="block"?20:16})}),s.jsx("span",{className:"af_loading_text",children:t})]})}const R3={console:"Console",tray:"Tray",watch:"Watch",phone:"Phone",email:"Email",assistant:"Assistant",code:"Code"};function L3(e){switch(e){case"empty title":return"Nothing to notify: the title was empty.";case"no notify":return"Nothing to notify: the run did not reach a Notify me step.";case"still running":return"Still running: nothing has been sent yet.";case"not recorded yet":return"Finished; the automation has not recorded what it sends yet.";default:return e?`Nothing was sent (${e}).`:"Nothing was sent."}}function I3(e){var n;const t=(n=e.trigger)==null?void 0:n.arrived;return t?t.line?`${t.count} ${t.noun}: ${t.line}`:`${t.count} ${t.noun}`:null}function O3(e){return e.title?`“${e.title}”`:e.from==="wait"?e.kind==="question"?"A question for you":"An approval for you":e.from==="email_when_done"?e.kind==="failure"?"It failed":"It finished":"Untitled"}function P3(e){return e.from==="wait"?e.open?"waiting for your answer":"answered":e.from==="email_when_done"?"Email me when done":e.from==="notify_me"?"Notify me":e.from==="failure"?"The run failed":e.from==="publish"?"Publish to channel, with Alert on":"On Flow End’s notify (older flows)"}function D3(e){const t=R3[e.channel]||e.channel,n=e.device_name?`${t} (${e.device_name})`:t,r=e.state==="failed";if(e.channel==="console")return`${n} · listed · ${r?"not listed":"sent"}`;const i=e.via==="push"?"push notification":e.via==="outbox"?"email":"shown by the app";return`${n} · ${i} · ${r?`not delivered${e.reason?`: ${e.reason}`:""}`:"sent"}`}const F3=3e3,z3=5;function B3(e,t){return t>z3?!1:e.quiet_reason==="not recorded yet"||e.quiet_reason==="still running"?!0:!!e.attention&&e.deliveries.length===0}function P0(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function U3(e){const t=e.state;return s.jsxs("section",{className:"after_run","data-section":"after-the-run","aria-label":"After the run",children:[s.jsx("div",{className:"after_run_title",children:"After the run"}),t.status==="loading"?s.jsx(ol,{what:"after the run",label:"Reading what happened after the run…"}):t.status==="failed"?s.jsxs("div",{className:"after_run_error",role:"alert",children:[s.jsxs("span",{children:["Could not read what happened after the run: ",t.error]}),t.on_retry?s.jsx("button",{type:"button",className:"btn btn_sm",onClick:t.on_retry,children:"Retry"}):null]}):s.jsx(W3,{after:t.after})]})}function W3(e){const t=e.after,n=I3(t),r=t.alerts&&t.alerts.length?t.alerts:t.attention?[t.attention]:[];return s.jsxs("dl",{className:"after_run_facts",children:[t.trigger&&n?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"What arrived"}),s.jsx("dd",{"data-field":"arrived",children:n})]}):null,t.run.note?s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Note"}),s.jsx("dd",{"data-field":"note",children:t.run.note})]}):null,s.jsx("dt",{children:"Notified"}),s.jsx("dd",{"data-field":"notified",children:r.length?s.jsx("ul",{className:"after_run_alerts",children:r.map(i=>{const o=t.deliveries.filter(c=>!c.record_key||c.record_key===i.record_key);return s.jsxs("li",{children:[s.jsx("span",{className:"after_run_alert_title",children:O3(i)}),s.jsxs("span",{className:"muted",children:[" ","· ",P3(i),i.raised_at?` · ${P0(i.raised_at)}`:""]}),o.length?s.jsx("ul",{className:"after_run_deliveries",children:o.map((c,l)=>s.jsxs("li",{"data-state":c.state,children:[D3(c),c.time?s.jsxs("span",{className:"muted",children:[" · ",P0(c.time)]}):null]},`${c.channel}:${c.device||""}:${l}`))}):s.jsx("div",{className:"muted",children:"No delivery recorded yet."})]},i.record_key)})}):s.jsx("span",{"data-field":"quiet",children:L3(t.quiet_reason)})})]})}const q3=[1e3,3e3];async function V3(e,t=q3){let n=null;for(let r=0;r<=t.length;r++)try{return await e()}catch(i){n=i,r<t.length&&await new Promise(o=>setTimeout(o,t[r]))}throw n}function H3(e){const{run_id:t,read:n}=e,[r,i]=p.useState({status:"loading"}),[o,c]=p.useState(0),l=p.useRef(null),d=p.useCallback(()=>{i({status:"loading"}),c(h=>h+1)},[]);return p.useEffect(()=>{let h=!0,m=0;const _=async()=>{m+=1;try{const g=await V3(()=>n(t));if(!h)return;i({status:"ready",after:g}),B3(g,m)&&(l.current=setTimeout(_,F3))}catch(g){if(!h)return;i(y=>y.status==="ready"?y:{status:"failed",error:g instanceof Error?g.message:String(g),on_retry:d})}};return _(),()=>{h=!1,l.current&&clearTimeout(l.current)}},[t,n,o,d]),s.jsx(U3,{state:r})}function Zs(){return nl()}const d1=Sg("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",f1="Copy failed — select and copy";function h1(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function G3(e){var i;const t=globalThis.document;if(!t||!t.body||typeof t.execCommand!="function")return!1;const n=t.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0";const r=t.activeElement;t.body.appendChild(n);try{return n.select(),n.setSelectionRange(0,e.length),t.execCommand("copy")===!0}catch{return!1}finally{t.body.removeChild(n);try{(i=r==null?void 0:r.focus)==null||i.call(r)}catch{}}}async function Mm(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 G3(t)}const K3=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 J3(e){const t=e.length,n=new Uint8Array(t+9+63>>6<<6);n.set(e),n[t]=128;const r=new DataView(n.buffer);r.setUint32(n.length-8,Math.floor(t/536870912),!1),r.setUint32(n.length-4,t<<3>>>0,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),c=(l,d)=>l>>>d|l<<32-d;for(let l=0;l<n.length;l+=64){for(let v=0;v<16;v++)o[v]=r.getUint32(l+v*4,!1);for(let v=16;v<64;v++){const N=c(o[v-15],7)^c(o[v-15],18)^o[v-15]>>>3,$=c(o[v-2],17)^c(o[v-2],19)^o[v-2]>>>10;o[v]=o[v-16]+N+o[v-7]+$>>>0}let[d,h,m,_,g,y,x,k]=[i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7]];for(let v=0;v<64;v++){const N=c(g,6)^c(g,11)^c(g,25),$=g&y^~g&x,C=k+N+$+K3[v]+o[v]>>>0,S=c(d,2)^c(d,13)^c(d,22),D=d&h^d&m^h&m,O=S+D>>>0;k=x,x=y,y=g,g=_+C>>>0,_=m,m=h,h=d,d=C+O>>>0}i[0]=i[0]+d>>>0,i[1]=i[1]+h>>>0,i[2]=i[2]+m>>>0,i[3]=i[3]+_>>>0,i[4]=i[4]+g>>>0,i[5]=i[5]+y>>>0,i[6]=i[6]+x>>>0,i[7]=i[7]+k>>>0}return Array.from(i,l=>l.toString(16).padStart(8,"0")).join("")}async function Y3(e){var r;const t=new TextEncoder().encode(String(e??"")),n=(r=globalThis.crypto)==null?void 0:r.subtle;if(n&&typeof n.digest=="function"){const i=await n.digest("SHA-256",t);return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("")}return J3(t)}const X3=/^[a-zA-Z0-9_-]+$/;function D0(e){return X3.test(String(e||"").trim())}async function Z3(e){const t=String(e||"");return Y3(t)}async function Q3(e){const t=String(e||"").trim();if(!t)throw new Error("session_id is required");if(D0(t)){const r=`session_memory_${t}`;if(D0(r))return r}return`session_memory_sha_${(await Z3(t)).slice(0,32)}`}const m1="abstractobserver_voice";function eP(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(m1),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const ov=new Set;function tP(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(m1,JSON.stringify(e||{}))}catch{}for(const n of ov)n(e||{})}function _1(){const[e,t]=p.useState(()=>eP());return p.useEffect(()=>(ov.add(t),()=>{ov.delete(t)}),[]),[e,tP]}function p1(e,t){const[n,r]=p.useState({value:null,failed:!1});return p.useEffect(()=>{if(!t||!e){r({value:null,failed:!1});return}let i=!0;return e.voice_defaults().then(o=>i&&r({value:o||{},failed:!1})).catch(()=>i&&r({value:null,failed:!0})),()=>{i=!1}},[e,t]),n}function nP(e){if(e)return{design:t=>e.voice_design(t),clone:(t,n)=>e.voice_clone(t,n)}}function sP(e){const t=e.gateway;return s.jsx(mR,{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,createVoice:nP(t),unavailableReason:e.connected&&t?null:"Connect to a gateway to configure voice."})}const rP=18e4;function iP(e,t,n,r=()=>{}){return async function*(i,o){r(),yield*K2({path:e.gateway_url(wt(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:o,body:{text:i,request_id:Zs(),...aR(n())}})}}function oP(e,t,n,r,i=()=>{},o=rP){return async(c,l)=>{i();const d=String(l||c.type||"").toLowerCase(),h=d.includes("mp4")?"m4a":d.includes("ogg")?"ogg":d.includes("wav")?"wav":"webm",m=new File([c],`recording.${h}`,{type:d||"audio/webm"}),_=await e.attachments_upload(t,m,{filename:m.name,content_type:m.type});i();let g;const y=await Promise.race([e.audio_transcribe(n,{audio_artifact:_,request_id:Zs(),...lR(r())}),new Promise((x,k)=>{g=setTimeout(()=>k(new Error(`the gateway did not answer within ${Math.round(o/1e3)} s`)),o)})]).finally(()=>clearTimeout(g));return i(),{text:String(y.text||""),provider:y.provider,model:y.model}}}function g1(e){const{gateway:t,prefs:n}=e,r=String(e.session_id||"").trim(),[i,o]=p.useState("");p.useEffect(()=>{let y=!0;if(!r){o("");return}return Q3(r).then(x=>y&&o(x)).catch(()=>y&&o("")),()=>{y=!1}},[r]);const c=`${r}|${i}`,l=p.useRef(c);l.current=c;const d=p.useRef(n);d.current=n;const h=p.useRef(e);h.current=e;const m=()=>{if(l.current!==c)throw new Error("Voice session changed.")},_=!!(t&&i&&r),g=nA({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:_?iP(t,i,()=>d.current,m):void 0,transcribe:_?oP(t,r,i,()=>d.current,m):void 0,on_transcript:y=>{l.current===c&&h.current.on_transcript(y)},on_error:y=>{l.current===c&&h.current.on_error(y)}});return p.useEffect(()=>{var y;return g.stop_tts(),(y=g.cancel_voice_ptt_recording)==null||y.call(g),()=>{var x;g.stop_tts(),(x=g.cancel_voice_ptt_recording)==null||x.call(g)}},[c,g.stop_tts,g.cancel_voice_ptt_recording]),{...g,run_id:i}}function y1(e,t,n){const r=p.useRef(null);p.useEffect(()=>{const i=(n==null?void 0:n.key)||"";if(r.current===null){r.current=i;return}!i||i===r.current||(r.current=i,t&&e.tts_supported&&(n!=null&&n.text.trim())&&e.toggle_tts(i,n.text))},[n==null?void 0:n.key,n==null?void 0:n.text,t,e.tts_supported,e.toggle_tts])}function aP(e){const[t,n]=p.useState(()=>Date.now());return p.useEffect(()=>{if(!e)return;n(Date.now());const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[e]),t}const lP=350;function w1(e){const{voice:t}=e,n=p.useRef(!1),r=p.useRef(!1),i=p.useRef(0),o=()=>{if(r.current){r.current=!1,t.stop_voice_ptt_recording();return}n.current=!0,i.current=Date.now(),t.start_voice_ptt_recording().then(()=>{!n.current&&!r.current&&t.stop_voice_ptt_recording()})},c=()=>{if(n.current){if(n.current=!1,Date.now()-i.current<lP){r.current=!0;return}t.stop_voice_ptt_recording()}};p.useEffect(()=>{const y=()=>{n.current=!1,r.current=!1,t.stop_voice_ptt_recording()};return window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c),window.addEventListener("blur",y),()=>{window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),window.removeEventListener("blur",y)}},[t.stop_voice_ptt_recording]),p.useEffect(()=>{t.voice_ptt_recording||(r.current=!1)},[t.voice_ptt_recording]);const l=t.voice_ptt_since||0,d=aP(!!l),h=q2(e.prefs,e.defaults),m=t.voice_ptt_recording?`Recording… ${l?aS(l,d):""}`.trim():t.voice_ptt_busy?V2(l||d,d,h):"",g=!h1()?d1: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:g||"Hold to dictate, or tap to start and tap again to stop (Space or Enter on keyboard)",disabled:!!g||t.voice_ptt_busy,onPointerDown:y=>{y.button===0&&o()},onPointerUp:c,onPointerCancel:c,onKeyDown:y=>{[" ","Enter"].includes(y.key)&&!y.repeat&&(y.preventDefault(),o())},onKeyUp:y=>{[" ","Enter"].includes(y.key)&&(y.preventDefault(),c())},children:s.jsx(qe,{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(qe,{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 cP(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(qe,{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 uP="abstractobserver";function dP(e){return{replayView:rI({fetch:(t,n)=>e.fetch_gateway(wt(t),n)}),getRun:t=>e.get_run(t),getHistory:t=>e.get_run_history_bundle(t,{include_subruns:!0,include_session:!0,ledger_mode:"full"}),getLedger:(t,n,r)=>e.get_ledger(t,{after:n,limit:200,signal:r}),streamLedger:(t,n,r,i,o)=>e.stream_ledger(t,{after:n,on_step:r,signal:i,on_open:o}),submitCommand:t=>e.submit_command(t)}}function fP(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 hP=new Set(["completed","failed","cancelled"]);function mP(e){var J;const{gateway:t,discussion:n}=e,r=p.useMemo(()=>dP(t),[t]),[i,o]=p.useState(((J=n.session)==null?void 0:J.run_id)||""),[c,l]=p.useState(""),[d,h]=p.useState(!1),[m,_]=p.useState(""),{controller:g,snapshot:y}=II({transport:r,runId:i,enabled:e.connected,clientId:uP}),x=n.session,k=!!i&&!hP.has(y.status)&&y.status!=="idle",v=CI(y),[N]=_1(),$=p1(e.connected?t:null,e.connected),[C,S]=p.useState(""),D=g1({gateway:e.connected?t:null,session_id:(x==null?void 0:x.session_id)||e.voice_session_id||"",prefs:N,on_error:S,on_transcript:G=>l(V=>V.trim()?`${V.trimEnd()}
96
+ ${G}`:G)}),O=p.useMemo(()=>{for(let G=y.messages.length-1;G>=0;G-=1){const V=y.messages[G];if(V.role==="assistant")return V.live?null:{key:String(V.id||""),text:String(V.content||"")}}return null},[y.messages]);y1(D,N.read_aloud===!0,O);const A=G=>D.tts_playback.key&&D.tts_playback.key===String(G.id||"")?D.tts_playback.status:"idle",P=async G=>{var R;const V=G.trim();if(V){h(!0);try{if(x){const M=String(((R=y.run)==null?void 0:R.workflow_id)||""),I=fP(M),L=await t.start_run(I.flow_id,{prompt:V},{bundle_id:I.bundle_id,session_id:x.session_id});o(L)}else{const M=await e.on_fork(n.automation_id,n.occurrence_index,V);o(M.run_id)}l("")}finally{h(!1)}}},W=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(qe,{name:"chevronRight",size:13,className:"flip_x"})," ",n.automation_title]}),s.jsxs("span",{className:"discussion_title",children:[s.jsx(qe,{name:"chat",size:15})," Discussion — fork at #",n.occurrence_index]}),s.jsx("span",{className:"pane_spacer"}),x?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:`btn btn_sm${m==="own"?" active":""}`,"data-action":"discussion-files",onClick:()=>_(m==="own"?"":"own"),title:x.workspace_root,children:[s.jsx(qe,{name:"folder",size:14})," Its files"]}),s.jsxs("button",{type:"button",className:`btn btn_sm${m==="mounted"?" active":""}`,"data-action":"automation-files",onClick:()=>_(m==="mounted"?"":"mounted"),title:x.mounted_workspace,children:[s.jsx(qe,{name:"folder",size:14})," Automation files"]})]}):null]});return s.jsxs("section",{className:"pane auto_detail auto_discussion","data-discussion-session":(x==null?void 0:x.session_id)||void 0,children:[m&&x?s.jsx(FN,{fetchGateway:t.fetch_gateway,runId:m==="own"?x.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:()=>_(""),refreshKey:y.status}):null,s.jsx(NI,{header:W,messages:y.messages,draft:c,onDraftChange:l,onSend:P,busy:k||d,busyLabel:d?x?"Starting…":"Forking the automation…":v?"Waiting for you":"Working…",onCancel:k?()=>g.cancel():void 0,stopState:y.stop??null,disabled:!e.connected,interaction:BI(v,g,{records:y.records,currentRun:y.run}),placeholder:x?"Ask a follow-up…":`Ask about run #${n.occurrence_index}…`,emptyState:s.jsxs("div",{className:"help_text muted discussion_intro",children:["A new conversation from run #",n.occurrence_index," with the automation's history (runs 1–",n.occurrence_index,"). It works in its own folder; it can read the automation's files but not change them (by the file tools; shell commands are not sandboxed), and nothing is written back into the automation."]}),composerExtras:s.jsx(w1,{voice:D,defaults:$.value,prefs:N,blocked:e.connected?null:"Connect to the gateway first.",error:C}),messageProps:D.tts_supported?{onSpeakToggle:G=>{S(""),D.toggle_tts(String(G.id||""),String(G.content||""))},getSpeakState:A}:void 0,footer:s.jsxs(s.Fragment,{children:[y.error?s.jsx("div",{className:"observe_context_card error",role:"alert",children:y.error}):null,y.source?s.jsx("div",{className:"help_text muted discussion_source","data-source":y.source,title:y.sourceReason||void 0,children:$I(y)}):null]})})]})}const _P=qn.title;function F0(e){return`${_P}: ${e}`}const pP=["workspace_access_mode","workspace_allowed_paths"];function gP(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function yP(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 gP(t)?t:null}function v1(e,t){const n={...e||{}};for(const r of pP)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 wP(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:v1(n.input_data,t)}}}const vP=3e4,av=new WeakMap;function xP(e,t,n=Date.now()){let r=av.get(e);r||av.set(e,r=new Map);const i=JSON.stringify(t),o=r.get(i);if(o&&n-o.at<vP)return o.answer;const c=nm(e)(t).then(l=>l.summary);return c.catch(()=>r==null?void 0:r.delete(i)),r.set(i,{at:n,answer:c}),c}function bP(e){av.delete(e)}function kP(e){const[t,n]=p.useState(null),r=JSON.stringify(e.value);return p.useEffect(()=>{if(!e.connected||!e.request){n(null);return}let i=!0;return xP(e.request,e.value).then(o=>i&&n(F0(o))).catch(o=>i&&n(F0(Ig(o)))),()=>{i=!1}},[e.request,e.connected,r,e.refresh_key]),t?s.jsx("span",{className:"auto_workspaces_line","data-field":"workspaces",title:t,children:t}):null}function jP(e){const{connected:t,request:n,value:r}=e,[i,o]=p.useState(null),[c,l]=p.useState(null),d=JSON.stringify(r);p.useEffect(()=>{if(!t){o(null),l(null);return}let g=!0;return l(null),nm(n)(r).then(y=>g&&o(y)).catch(y=>g&&l(`Could not read your workspaces: ${Ig(y)}`)),()=>{g=!1}},[t,d,n]);const h=e.on_change,m=p.useCallback(async g=>{const y=await nm(n)(g);await h(g),o(y),bP(n)},[n,h]),_=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(dN,{level:"run",idPrefix:e.id_prefix,value:r,effective:i,onChange:m,loadError:t?c:_,unavailableReason:_,footer:e.footer})}class SP{constructor(){jn(this,"made",new Map);jn(this,"current",new Map)}record(t,n,r){if(this.current.set(t,r),n===null)return;let i=this.made.get(t);i||this.made.set(t,i=new Set),i.add(n+1)}note(t,n){if(n===null)return;let r=this.made.get(t);r||this.made.set(t,r=new Set),r.add(n+1)}expected(t,n){if(n===null)return null;const r=this.made.get(t);let i=n;for(;r&&r.has(i+1);)i+=1;return i}changes(t,n){if(!this.current.has(t)||!n.target)return n;const r=this.current.get(t)??null;return{...n,target:{...n.target,input_data:v1(n.target.input_data,r)}}}}async function NP(e,t,n,r,i){const o=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,wP(n.definition,r),o,i),t.record(n.automation_id,o,r)}function x1(e){return`abstractobserver_list_open_${e}`}function b1(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function $P(e,t=b1()){try{return(t==null?void 0:t.getItem(x1(e)))!=="0"}catch{return!0}}function CP(e,t,n=b1()){try{n==null||n.setItem(x1(e),t?"1":"0")}catch{}}function ng(e){const[t,n]=p.useState(()=>$P(e)),r=p.useCallback(()=>{n(i=>{const o=!i;return CP(e,o),o})},[e]);return[t,r]}function sg(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(qe,{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 EP=5e3,AP=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],TP={pause:wa.pause,resume:wa.resume,run_now:wa.run_now,edit:wa.revise,archive:`${wa.archive}…`,discuss:wa.discuss},MP={pause:Go.pause,resume:Go.resume,run_now:Go.run_now,edit:Go.revise,archive:Go.archive,discuss:Go.discuss},RP={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},LP={legacy_pause:Go.pause,legacy_resume:Go.resume,legacy_run_now:Go.run_now,open_run:"list",recreate:"refresh"};function IP(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(aN,{status:e.status})})}function lp(e){return s.jsxs("span",{className:`auto_fact${e.className?` ${e.className}`:""}`,"data-field":e.field,title:e.label,children:[s.jsx(qe,{name:e.icon,size:12}),s.jsx("span",{children:e.children})]})}const OP={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},PP="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function z0(e){const t=e.busy||e.ctl.enabled?null:e.ctl.reason||"Not available now.";return s.jsx(Fi,{variant:"sm",className:"auto_switch",action:"active",id:`auto-active-${e.summary.automation_id}`,label:wa.active,checked:e.summary.status==="active",unavailableReason:t,busy:e.busy,hint:e.hint,onChange:e.onChange})}function DP(e){const t=e.summary,n=c1(t,Date.now(),{connections:e.state.trigger_connections,mailboxes:e.state.mailboxes}),r=e.state.selected_id===t.automation_id,i=e.state.busy,o=(d,h,m,_,g,y,x,k)=>s.jsxs("button",{type:"button",className:`btn btn_sm auto_action${x?" auto_action_icon":""}${g?` ${g}`:""}`,"data-action":d,disabled:!m.enabled,title:[x?h:null,m.enabled?null:m.reason,k].filter(Boolean).join(`
97
+ `)||void 0,"aria-label":x?h:void 0,"aria-description":k,onClick:_,children:[y?s.jsx(qe,{name:y,size:13}):null,x?null:s.jsx("span",{children:h})]},d);let c;if(n.legacy){const d=g3(t,i),h=t.status==="paused"?"legacy_resume":"legacy_pause",m=["legacy_run_now","open_run","recreate"];c=[s.jsx(z0,{summary:t,busy:i,ctl:d[h],hint:PP,onChange:()=>e.h.on_legacy_action(t,h)},"active"),...m.map(_=>o(_,OP[_],d[_],()=>e.h.on_legacy_action(t,_),void 0,LP[_]))]}else{const d=p3(t,i),h=t.status==="active"?"pause":"resume",m=["run_now","edit","discuss","archive"];c=[s.jsx(z0,{summary:t,busy:i,ctl:d.active,hint:Jp("active",t),onChange:()=>e.h.on_row_action(t,h)},"active"),...m.map(_=>o(_,TP[_],d[_],()=>e.h.on_row_action(t,_),_==="archive"?"danger auto_action_end":void 0,MP[_],_==="archive",Jp(RP[_],t)))]}const l=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(IP,{status:n.state}),n.attention?s.jsxs("span",{className:"chip warn auto_row_attention","data-field":"attention",children:[s.jsx(qe,{name:"warning",size:12})," ",n.attention]}):null]}),s.jsxs("span",{className:"auto_row_facts",children:[s.jsx(lp,{icon:"refresh",field:"cadence",label:"When it runs",children:n.cadence}),n.current?s.jsx(lp,{icon:"loader",field:"current",label:"Running now",className:"auto_row_current",children:n.current}):null,s.jsx(lp,{icon:"clock",field:"next",label:n.listening?"When it runs":"Next run",children:n.listening?n.next_run:`next: ${n.next_run}`}),s.jsx(lp,{icon:"info",field:"last-status",label:"Last run",children:n.last_status})]}),n.last?s.jsx("span",{className:"auto_row_excerpt","data-field":"excerpt",children:XN(n.last)}):null]}),s.jsx("div",{className:"auto_row_actions",role:"toolbar","aria-label":`Controls for ${n.title}`,children:c}),l?s.jsxs("div",{className:"auto_row_confirm",role:"group","aria-label":"Confirm archive",children:[s.jsxs("span",{children:["Archive “",n.title,"”? Its history stays readable; it will not run again."]}),s.jsxs("button",{type:"button",className:"btn btn_sm danger auto_action","data-action":"archive-confirm",disabled:i,onClick:()=>e.h.on_confirm_archive(t),children:[s.jsx(qe,{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(qe,{name:"x",size:13}),s.jsx("span",{children:"Keep it"})]})]}):null]})}function FP(e){const t=e.state,n=e.list?e.list.open:!0,r=t.error??t.list_error,i=r?Gp(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(sg,{open:n,on_toggle:e.list.on_toggle,controls:"auto_list_body",title:"Automations",count:qy(t).length}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Automations"}),s.jsx("span",{className:"pane_count",children:qy(t).length})]}),s.jsx("span",{className:"pane_spacer"}),s.jsx("select",{className:"seg_select",value:t.status_filter,onChange:o=>e.h.on_status_filter(o.target.value),"aria-label":"Filter by status",children:AP.map(([o,c])=>s.jsx("option",{value:o,children:c},o||"all"))}),s.jsx("button",{type:"button",className:"btn btn_sm auto_icon_btn","data-action":"refresh",onClick:e.h.on_refresh,disabled:t.loading||!e.available.available,title:"Refresh","aria-label":"Refresh",children:s.jsx(qe,{name:t.loading?"loader":"refresh",size:14})}),s.jsxs("a",{className:`btn btn_sm auto_new${e.available.available?"":" disabled"}`,"data-action":"new",href:e3,"aria-disabled":!e.available.available,title:"New automation: run a flow by itself","aria-label":"New automation",onClick:o=>{o.preventDefault(),e.available.available&&e.h.on_new()},children:[s.jsx(qe,{name:"plus",size:14}),s.jsx("span",{className:"auto_new_label",children:"New automation"})]})]}),s.jsxs("div",{className:"pane_body scroll",id:"auto_list_body",hidden:!n,children:[e.available.available?null:s.jsx("div",{className:"warn_callout",role:"note","data-unavailable":"true",children:e.available.reason}),i?s.jsxs("div",{className:"observe_context_card error auto_list_error",role:"alert","data-code":r==null?void 0:r.code,children:[s.jsx(qe,{name:"error",size:14}),s.jsxs("span",{className:"auto_list_msg",children:[s.jsx("strong",{children:i.title})," ",s.jsx("span",{children:i.detail})]}),t.error&&e.h.on_dismiss_error?s.jsx("button",{type:"button",className:"auto_dismiss","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:e.h.on_dismiss_error,children:s.jsx(qe,{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(qe,{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(qe,{name:"x",size:12})}):null]}):null}),e.available.available&&!t.loaded&&t.loading?s.jsx(ol,{what:"automations"}):null,e.available.available&&t.loaded&&!t.items.length?s.jsx("div",{className:"help_text muted","data-empty":"automations",children:"No automations yet. Make one in Flow, or press New automation."}):null,R0(t)>0&&t.status_filter!=="archived"?s.jsx("div",{className:"auto_show_archived",children:s.jsx(Fi,{variant:"sm",action:"show-archived",label:`Archived (${R0(t)})`,hint:"List archived automations too. Their history stays readable; they do not run.",checked:t.show_archived,onChange:o=>e.h.on_show_archived(o)})}):null,s.jsx("ul",{className:"auto_rows",children:qy(t).map(o=>s.jsx(DP,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function zP(e,t,n,r){const i=e.state,o=i.detail;if(!o||el(o.summary))return null;const c=o.automation_id;return{summary:o.summary,...o.definition?{definition:o.definition}:{},occurrences:o.occurrences,triggerSources:i.trigger_sources,triggerConnections:i.trigger_connections,mailboxes:i.mailboxes,occurrenceEvents:o.occurrence_events,busy:i.busy,...o.error?{error:o.error}:{},onRevise:async(l,d,h)=>{if(!r)return e.revise(c,l,d,h==null?void 0:h.command_id);const m=r.expected(c,d),_=await e.revise(c,r.changes(c,l),m,h==null?void 0:h.command_id);return r.note(c,m),_},onCommand:(l,d,h)=>e.command(c,l,d,h==null?void 0:h.command_id),onDiscuss:async(l,d,h)=>{const m=await e.discuss(c,l,d,h==null?void 0:h.request_id);return t.on_open_session(m,yx(l),l),m},onSeen:l=>e.seen(c,l),onLoadMore:()=>void e.load_more(),onOpenRun:l=>t.on_open_run(l),...t.on_open_workspace?{onOpenWorkspace:t.on_open_workspace}:{},...t.fetch_gateway?{fetchGateway:t.fetch_gateway}:{},onAnswerWait:(l,d,h)=>e.answer_wait(c,l,d,h),...n?{editOpen:n.open,onEditOpenChange:n.on_change}:{},emailStatus:i.email_status,previewSchedule:e.preview_schedule,...t.on_open_my_email?{onOpenMyEmail:()=>{var l;return(l=t.on_open_my_email)==null?void 0:l.call(t)}}:{}}}function BP(e,t){var d;const n=String(e||"").trim();if(!n||!(t!=null&&t.length))return;const r=t.find(h=>h.value===n);if(r!=null&&r.name)return r.name;const i=n.indexOf("@"),o=n.lastIndexOf(":");if(i<=0||o<=i)return;const c=n.slice(0,i),l=n.slice(o+1);return((d=t.find(h=>h.bundleId===c&&h.flowId===l))==null?void 0:d.name)||void 0}function UP(e){const{fetchGateway:t,messageProps:n,readRunAfter:r,...i}=e,o=i.onOpenResource??(t?l=>TL(t,l.url,{name:l.name}):void 0),c=l=>l.kind==="answer"&&r?s.jsxs(s.Fragment,{children:[b0(l,n),s.jsx(H3,{run_id:l.runId,read:r})]}):b0(l,n);return s.jsx(mM,{...i,onOpenResource:o,renderText:XN,renderTurn:c})}function WP(e){var l,d,h,m,_;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(ol,{what:"automation",size:"block"})});if(!t)return s.jsx("section",{className:"pane auto_detail auto_detail_empty",children:s.jsx("div",{className:"help_text muted",children:"Select an automation to read its runs, change it, or talk about a result."})});if(el(t.summary)){const g=c1(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:g.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 (",g.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=zP(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),i=e.ctl,o=t.definition,c=yP(o);return s.jsxs("section",{className:"pane auto_detail",children:[e.browser??null,n&&o?s.jsx("div",{className:"auto_workspaces","data-section":"workspaces","data-editing":(l=e.edit)!=null&&l.open?"true":void 0,children:(d=e.edit)!=null&&d.open?s.jsxs("details",{className:"auto_workspaces_details","data-field":"workspaces-details",children:[s.jsx("summary",{children:"Workspaces"}),s.jsx(jP,{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:i.state.busy,on_change:g=>NP(i,n.revisions,{automation_id:t.automation_id,summary:t.summary,definition:o},g,nl())})]}):s.jsxs("details",{className:"auto_workspaces_details","data-field":"workspaces-details",children:[s.jsx("summary",{children:"Workspaces"}),s.jsx(kP,{request:n.request,connected:n.connected,value:c,refresh_key:t.summary.revision??""})]})}):null,r?s.jsx(UP,{...r,readRunAfter:e.host.read_run_after,workflowName:BP(o==null?void 0:o.target.workflow_id,(_=(m=(h=e.workflowPickerOptions)==null?void 0:h.workflows)==null?void 0:m.data)==null?void 0:_.entries),workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools}):null]})}function qP(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=u1(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function VP(e){const t=e.ctl,n=p.useRef(null);n.current||(n.current=new SP);const r=e.workspace_request?{request:e.workspace_request,connected:e.active,definition:S=>t.definition(S)}:void 0,[i,o]=ng("automations"),[c,l]=p.useState(null),d=S=>l(D=>({...S,opened:((D==null?void 0:D.opened)||0)+1})),[h,m]=p.useState(""),[_,g]=p.useState("");p.useSyncExternalStore(S=>t.subscribe(S),()=>t.state,()=>t.state);const[y,x]=p.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");p.useEffect(()=>{const S=()=>x(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",S),()=>document.removeEventListener("visibilitychange",S)},[]),p.useEffect(()=>{if(!e.active||!y||!e.available.available)return;t.refresh();const S=window.setInterval(()=>void t.refresh(),S3);return()=>window.clearInterval(S)},[t,e.active,y,e.available.available]);const k=t.state.detail,v=t.state.notice;p.useEffect(()=>{if(!v)return;const S=window.setTimeout(()=>t.dismiss_notice(),EP);return()=>window.clearTimeout(S)},[t,v]);const N=Ae.useCallback(S=>e.gateway.get_run_after(S),[e.gateway]),$={...e.host,on_open_workspace:S=>m(D=>D===S?"":S),fetch_gateway:e.gateway.fetch_gateway,read_run_after:N,on_open_session:(S,D,O)=>{e.host.on_open_session(S,D,O),k&&d({automation_id:k.automation_id,automation_title:k.summary.title,occurrence_index:O,session:S})}},C={...e.h,on_select:S=>{l(null),m(""),S!==_&&g(""),e.h.on_select(S)},on_dismiss_notice:()=>t.dismiss_notice(),on_dismiss_error:()=>t.dismiss_error(),on_row_action:(S,D)=>{const O=qP(S,D);O.kind==="forward"?e.h.on_row_action(S,D):O.kind==="edit"?(l(null),m(""),g(S.automation_id),e.h.on_select(S.automation_id)):O.kind==="discuss"&&(e.h.on_select(S.automation_id),d({automation_id:S.automation_id,automation_title:S.title,occurrence_index:O.index}))}};return s.jsxs("div",{className:`page auto_page${i?"":" list_collapsed"}`,children:[s.jsx(FP,{state:t.state,available:e.available,h:C,list:{open:i,on_toggle:o},ws:r}),c?s.jsx(mP,{gateway:e.gateway,discussion:c,connected:e.active,voice_session_id:e.voice_session_id||"",on_fork:async(S,D,O)=>{const A=await t.discuss(S,D,O);return e.host.on_open_session(A,yx(D),D),l(P=>P&&{...P,session:A}),A},on_close:()=>l(null)},c.opened):s.jsx(WP,{workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,ctl:t,host:$,h:C,edit:{open:!!k&&_===k.automation_id,on_change:S=>g(S&&k?k.automation_id:"")},workspaces:e.workspace_request?{request:e.workspace_request,connected:e.active,revisions:n.current}:void 0,browser:h?s.jsx(FN,{fetchGateway:e.gateway.fetch_gateway,runId:h,title:h===(k==null?void 0:k.automation_id)?"Automation files":"Run files",onClose:()=>m("")}):void 0})]})}function HP(e){return s.jsx(Fi,{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 GP(e){return s.jsx("div",{className:`settings_choice ${e.checked?"on":""}`,children:s.jsx(Fi,{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 KP="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function JP(e){return s.jsx(Fi,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:KP,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function YP(e){return s.jsx(Fi,{variant:"sm",action:"mindmap-live",label:"Live",hint:"Refresh the map as new memory arrives.",checked:e.checked,onChange:e.onChange})}function XP(e){return s.jsx(Fi,{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 B0={framework:null,gateway:null,gatewayNote:"checking…"};function ZP(){const e="0.10.2".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 QP(){return S2("abstractobserver",ZP())}async function e4(e){let t;try{t=await e.gateway_about()}catch(n){return Gh(null,n instanceof Error?n.message||n.name:String(n))}return Gh(t)}class rg{constructor(t){this._maxSize=rg._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=rg._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 t4(e){try{return new URL(String(e)),!0}catch{return!1}}function n4({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return t4(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function s4({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function r4({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function i4(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(o=>Number(o&&o.utilization_gpu_pct)).filter(o=>Number.isFinite(o));return r.length?r.reduce((o,c)=>o+c,0)/r.length:null}return null}async function o4({baseUrl:e,endpoint:t,token:n,getToken:r,signal:i,fetchImpl:o}={}){const c=n4({baseUrl:e,endpoint:t}),l=await s4({token:n,getToken:r}),d=o||globalThis.fetch;if(typeof d!="function")return{ok:!1,status:0,error:"fetch_unavailable",payload:null};let h;try{h=await d(c,{method:"GET",headers:{Accept:"application/json",...r4({token:l})},signal:i})}catch(_){return{ok:!1,status:0,error:"network_error",detail:_ instanceof Error?_.message:String(_),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 Sh=Object.freeze({tickMs:1500,historySize:20,endpoint:"api/gateway/host/metrics/gpu",baseUrl:"",mode:"full"});function a4(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function U0(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function W0(e,t){const n=Number(e);return Number.isFinite(n)?Math.floor(n):t}function Hy(e,t=1){const n=U0(Number(e)/100,0,1),r=Math.round(140-140*n),i=U0(Number(t),0,1);return i>=1?`hsl(${r} 85% 55%)`:`hsl(${r} 85% 55% / ${i})`}function q0(e){const t={...Sh,...e||{}};return t.tickMs=Math.max(250,W0(t.tickMs,Sh.tickMs)),t.historySize=Math.max(1,Math.min(200,W0(t.historySize,Sh.historySize))),t.endpoint=String(t.endpoint||Sh.endpoint),t.baseUrl=String(t.baseUrl||""),t.mode=String(t.mode||Sh.mode).trim().toLowerCase(),t.mode!=="icon"&&(t.mode="full"),t}function l4(){return`
98
+ :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}
99
+ .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)}
100
+ .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))}
101
+ .wrap.icon .top{display:none}
102
+ .wrap.icon .bars{height:var(--monitor-gpu-bars-height,18px)}
103
+ .top{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
104
+ .label{font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.9}
105
+ .value{font-variant-numeric:tabular-nums;font-size:var(--monitor-gpu-font-size,var(--font-size-sm,12px));opacity:.95}
106
+ .bars{display:flex;align-items:flex-end;gap:2px;height:var(--monitor-gpu-bars-height,34px);overflow:hidden}
107
+ .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}
108
+ .bar.missing{background:var(--monitor-gpu-bar-missing,#62708a);opacity:.35}
109
+ .bar.error{background:var(--monitor-gpu-bar-error,#ff6b6b);opacity:.7}
110
+ .muted{opacity:.6}
111
+ `}class c4{constructor(t,n={}){if(!t||typeof t!="object")throw new TypeError("target element is required");this._target=t,this._opts=q0(n),this._buffer=new rg(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=l4();const r=document.createElement("div");r.className=this._opts.mode==="icon"?"wrap icon":"wrap";const i=document.createElement("div");i.className="top";const o=document.createElement("div");o.className="label",o.textContent="GPU";const c=document.createElement("div");c.className="value muted",c.textContent="—",i.appendChild(o),i.appendChild(c);const l=document.createElement("div");l.className="bars",r.appendChild(i),r.appendChild(l),t.appendChild(n),t.appendChild(r),this._els={wrap:r,value:c,bars:l},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=q0({...this._opts,...t||{}}),r=n.historySize!==this._opts.historySize,i=n.tickMs!==this._opts.tickMs,o=n.mode!==this._opts.mode;this._opts=n,o&&this._mounted&&this._els&&this._els.wrap&&(this._els.wrap.className=n.mode==="icon"?"wrap icon":"wrap"),r&&(this._buffer.setMaxSize(n.historySize),this._mounted&&this._rebuildBars()),i&&this._running?(this.stop(),this.start()):this._mounted&&this._render()}push(t){this._buffer.push(t),this._render()}_rebuildBars(){if(!this._els)return;const{bars:t}=this._els;t.textContent="";for(let n=0;n<this._opts.historySize;n+=1){const r=document.createElement("div");r.className="bar missing",r.style.height="2px",t.appendChild(r)}}_render({error:t=!1}={}){if(!this._els)return;const{wrap:n,value:r,bars:i}=this._els,o=this._buffer.values(),c=this._buffer.last(),l=Number.isFinite(c)?Math.max(0,Math.min(100,c)):null;l==null?(r.textContent=t?"N/A":"—",r.classList.add("muted")):(r.textContent=`${l.toFixed(0)}%`,r.classList.remove("muted")),n&&(n.title=l==null?"GPU —":`GPU ${l.toFixed(0)}%`,l==null?(n.style.removeProperty("--monitor-gpu-accent"),n.style.removeProperty("--monitor-gpu-accent-glow")):(n.style.setProperty("--monitor-gpu-accent",Hy(l,.95)),n.style.setProperty("--monitor-gpu-accent-glow",Hy(l,.35))));const d=Array.from(i.children),h=Math.max(0,d.length-o.length),m=Math.max(2,i&&typeof i.clientHeight=="number"&&i.clientHeight>0?i.clientHeight:34);for(let _=0;_<d.length;_+=1){const g=d[_],y=_-h,x=y>=0?o[y]:null,k=Number.isFinite(x)?x:null,v=k==null?0:a4(k/100),N=Math.max(2,Math.min(m,Math.round(v*m)));g.style.height=`${N}px`,g.style.background=k==null?"":Hy(k),g.className="bar",k==null&&g.classList.add("missing"),t&&g.classList.add("error")}}async _tick(){const t=String(this._token||"").trim(),n=this._getToken,r=!!t||typeof n=="function";this._abort&&this._abort.abort(),this._abort=new AbortController;const i=await o4({baseUrl:this._opts.baseUrl,endpoint:this._opts.endpoint,token:t,getToken:n,signal:this._abort.signal}),o=i&&i.payload,c=o&&typeof o=="object"?o.supported!==!1:!0,l=i4(o);if(!i.ok){if(this._buffer.push(null),this._render({error:!0}),i.status===401||i.status===403){const d=String(this._token||"").trim(),h=typeof this._getToken=="function";if(!r&&(!!d||h))return;this._stoppedForAuth=!0,this.stop()}else i.status===429&&(this.stop(),this._resumeTimer=setTimeout(()=>{this._resumeTimer=null,this._mounted&&this.start()},3e4));return}if(!c||l==null){this._buffer.push(null),this._render();return}this._buffer.push(l),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 u4(e="monitor-gpu"){if(typeof globalThis>"u"||typeof globalThis.customElements>"u"||globalThis.customElements.get(e))return;const t=globalThis.HTMLElement||class{};class n extends t{static get observedAttributes(){return["tick-ms","history-size","endpoint","base-url","mode"]}constructor(){super(),this._shadow=this.attachShadow?this.attachShadow({mode:"open"}):null;const i=this._shadow||this;this._controller=new c4(i,{}),this._upgradeProperty("token"),this._upgradeProperty("getToken"),this._upgradeProperty("mode")}_upgradeProperty(i){if(!Object.prototype.hasOwnProperty.call(this,i))return;const o=this[i];try{delete this[i]}catch{}this[i]=o}connectedCallback(){this._controller.setOptions(this._readAttrs());const i=()=>{this.isConnected&&this._controller.start()};typeof queueMicrotask=="function"?queueMicrotask(i):Promise.resolve().then(i)}disconnectedCallback(){this._controller.destroy()}attributeChangedCallback(){this._controller.setOptions(this._readAttrs())}_readAttrs(){const i=this.getAttribute("tick-ms"),o=this.getAttribute("history-size"),c=this.getAttribute("endpoint"),l=this.getAttribute("base-url"),d=this.getAttribute("mode");return{...i!=null?{tickMs:i}:{},...o!=null?{historySize:o}:{},...c!=null?{endpoint:c}:{},...l!=null?{baseUrl:l}:{},...d!=null?{mode:d}:{}}}set token(i){this._controller.token=i}get token(){return this._controller.token}set getToken(i){this._controller.getToken=i}get getToken(){return this._controller.getToken}set tickMs(i){this._controller.setOptions({tickMs:i})}get tickMs(){return this._controller.options.tickMs}set historySize(i){this._controller.setOptions({historySize:i})}get historySize(){return this._controller.options.historySize}set endpoint(i){this._controller.setOptions({endpoint:i})}get endpoint(){return this._controller.options.endpoint}set baseUrl(i){this._controller.setOptions({baseUrl:i})}get baseUrl(){return this._controller.options.baseUrl}set mode(i){this._controller.setOptions({mode:i})}get mode(){return this._controller.options.mode}}globalThis.customElements.define(e,n)}function Xd(e){return String(e||"").trim().toLowerCase()}function Fg(e){return`${(e==null?void 0:e.filename)||""} ${(e==null?void 0:e.source_path)||""}`.trim().toLowerCase()}function Jh(e,t){return t.some(n=>e.endsWith(n))}function d4(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 f4(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 h4(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 k1(e,t){var c,l,d,h,m;const n=Xd(e==null?void 0:e.content_type),r=Fg(e),i=[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,(l=e==null?void 0:e.tags)==null?void 0:l.render_kind,(d=e==null?void 0:e.tags)==null?void 0:d.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(_=>String(_||"").trim().toLowerCase()).filter(Boolean).join(" ");if(/(^|[^a-z0-9])(code|source_code|script|program|executable)([^a-z0-9]|$)/i.test(i)||n.includes("javascript")||n.includes("typescript")||n.includes("x-python")||n.includes("x-shellscript")||n.includes("x-rust")||n.includes("x-go")||n.includes("x-java")||n.includes("x-csrc")||n.includes("x-c++src")||Jh(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 o=String(t||"").replace(/\r\n/g,`
112
+ `).replace(/\r/g,`
113
+ `).split(`
114
+ `);return j1(o)}function m4(e){const n=String(e||"").replace(/\r\n/g,`
115
+ `).replace(/\r/g,`
116
+ `).split(`
117
+ `),r=n.findIndex(c=>/^Markdown Content:\s*$/i.test(c.trim()));if(r===-1)return null;const i=[];for(const c of n.slice(0,r)){const l=c.match(/^\s*([A-Za-z][A-Za-z0-9 /_-]{1,40}):\s*(.+?)\s*$/);l&&i.push({label:l[1].trim(),value:l[2].trim()})}const o=n.slice(r+1).join(`
118
+ `).trim();return!i.length&&!o?null:{metadata:i,body:o}}function _4(e){const t=e.map(n=>n.trim()).filter(Boolean).slice(0,8);if(t.length<2)return!1;for(const n of[","," ",";"]){const r=t.map(i=>i.split(n).length);if(r[0]>=3&&r.every(i=>Math.abs(i-r[0])<=1))return!0}return!1}function p4(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:j1(e)}function j1(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 g4(e){const t=String(e||"");if(!t.trim())return!1;const n=t.match(/\\[A-Za-z]{2,}\b/g)||[];if(n.length>=1&&/\\(?:setcctype|sectctype|documentclass|begin|end|maketitle|geq|leq|cite|ref|label)\b/.test(t)||n.length>=4)return!0;const i=t.replace(/\r\n/g,`
119
+ `).replace(/\r/g,`
120
+ `).split(`
121
+ `).map(d=>d.trim()).filter(Boolean).slice(0,80);if(i.length<12)return!1;const o=i.filter(d=>d.length<=28).length,c=i.filter(d=>/^[,.;:()†]+$/.test(d)).length;return i.filter(d=>/^(abstract\.?|introduction|references|appendix|figure\s+\d+|table\s+\d+)\b/i.test(d)).length>=2&&(o/i.length>=.45||c>=2)}function y4(e,t){var h;const n=String(t||""),r=d4(e);if(/(^|[^a-z0-9])(markdown|mdown)([^a-z0-9]|$)/i.test(r))return!0;if(!n.trim())return!1;if(/(^|\n)\s*Markdown Content:\s*(\n|$)/i.test(n)||n.includes("```")||/(^|\n)\s*#{1,6}\s+\S/.test(n)||/(^|\n)[ \t]*[-*][ \t]+\S/.test(n)||/(^|\n)[ \t]*\d+[\.)][ \t]+\S/.test(n)||/\*\*[^*\n][\s\S]*?\*\*/.test(n)||/\[[^\]\n]+\]\([^)]+\)/.test(n)||/(^|\n)\s*\|.+\|\s*(\n|$)/.test(n)&&/(^|\n)\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*(\n|$)/.test(n))return!0;const i=n.replace(/\r\n/g,`
122
+ `).replace(/\r/g,`
123
+ `).split(`
124
+ `),o=i.map(m=>m.trim()).filter(Boolean);if(o.length<2||g4(n)||_4(i)||p4(i))return!1;const c=((h=n.match(/[A-Za-z][A-Za-z'-]+/g))==null?void 0:h.length)||0,l=i.filter(m=>!m.trim()).length,d=o.filter(m=>/[A-Za-z]{3,}/.test(m)&&m.length>=12).length;return c>=24&&d>=2&&(l>=1||o[0].length<=140)}function Yh(e){const t=Xd(e==null?void 0:e.modality),n=Xd(e==null?void 0:e.content_type),r=Fg(e),i=f4(e);return t==="image"||n.startsWith("image/")||Jh(r,[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".tif",".tiff",".heic"])?"image":t==="audio"||t==="voice"||t==="music"||t==="sound"||n.startsWith("audio/")||/(tts|stt|voice|music|sound|speech|audio)/i.test(i)||Jh(r,[".wav",".mp3",".m4a",".aac",".flac",".ogg",".opus",".aiff",".mid",".midi"])?"audio":t==="video"||n.startsWith("video/")||Jh(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")||k1(e,"")?"text":"binary"}function ig(e,t){const n=Xd(e==null?void 0:e.content_type),r=Fg(e),i=String(t||"").trim();return n.includes("html")||r.endsWith(".html")||r.endsWith(".htm")||h4(t)?"html":k1(e,t)?"code":n.includes("markdown")||r.endsWith(".md")||r.endsWith(".markdown")?"markdown":n.includes("json")||r.endsWith(".json")||r.endsWith(".jsonl")||(i.startsWith("{")||i.startsWith("["))&&Og(i)!==null?"json":y4(e,t)?"markdown":"text"}function wx(e,t=""){const n=Yh(e);if(n==="image"||n==="video")return n;if(n==="audio"){const r=(e==null?void 0:e.tags)||{},i=[e==null?void 0:e.semantic_kind,e==null?void 0:e.modality,e==null?void 0:e.task,r.semantic_kind,r.modality,r.kind,r.task,r.source,e==null?void 0:e.filename,e==null?void 0:e.source_path].map(o=>String(o||"").trim().toLowerCase()).filter(Boolean).join(" ");return/(^|[^a-z0-9])(voice|tts|speech)([^a-z0-9]|$)/i.test(i)?"voice":/(^|[^a-z0-9])(music|song|instrumental|t2m)([^a-z0-9]|$)/i.test(i)?"music":/(^|[^a-z0-9])(sound|sfx|recording)([^a-z0-9]|$)/i.test(i)?"sound":"audio"}if(n==="binary"){const r=Xd(e==null?void 0:e.modality),i=Xd(e==null?void 0:e.content_type),o=Fg(e);return r==="document"||i.includes("pdf")||Jh(o,[".pdf",".doc",".docx",".ppt",".pptx",".xls",".xlsx"])?"document":"other"}return ig(e,t)}function Gy(e){var h,m;const t=String(e||"").replace(/\r\n/g,`
125
+ `).replace(/\r/g,`
126
+ `).trim();if(!t)return"";const n=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),r=t.match(/<!--[\s\S]*?-->|<!doctype\b[^>]*>|<!\[CDATA\[[\s\S]*?\]\]>|<\/?[A-Za-z][^>]*>|[^<]+/gi)||[t],i=[];let o=0,c="";const l=_=>" ".repeat(Math.max(0,_)),d=(_,g)=>{const y=_.match(/^(<\/?|<!)([^\s/>]+)([\s\S]*?)(\/?>)$/);if(!y||_.length<=120||_.startsWith("</")||_.startsWith("<!"))return[`${l(g)}${_.trim()}`];const x=(y[3]||"").trim();if(!x)return[`${l(g)}${_.trim()}`];const k=x.match(/[^\s="'<>`]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>`]+))?/g)||[x];return[`${l(g)}${y[1]}${y[2]}`,...k.map(v=>`${l(g+1)}${v.trim()}`),`${l(g)}${y[4]}`]};for(const _ of r){const g=String(_||"");if(!g.trim())continue;const y=g.trim().toLowerCase();if(y.startsWith("</")){const k=((h=y.match(/^<\/\s*([a-z0-9:-]+)/))==null?void 0:h[1])||"";c&&k===c&&(c=""),o=Math.max(0,o-1),i.push(`${l(o)}${g.trim()}`);continue}if(g.trimStart().startsWith("<")){i.push(...d(g,o));const k=((m=y.match(/^<\s*([a-z0-9:-]+)/))==null?void 0:m[1])||"";/\/>\s*$/.test(g)||y.startsWith("<!")||n.has(k)||(o+=1,(k==="script"||k==="style")&&(c=k));continue}if(c){const k=g.trim();k&&i.push(...k.split(`
127
+ `).map(v=>`${l(o)}${v.trimEnd()}`));continue}const x=g.replace(/\s+/g," ").trim();x&&i.push(`${l(o)}${x}`)}return i.join(`
128
+ `)}const w4=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function vx(e){const t=typeof e=="string"?e:String(e??""),n=w4.exec(t);if(!n)return{text:t.trim(),metadata:null,stripped:!1};let r=null;try{const i=JSON.parse(String(n[1]||"").trim());i&&typeof i=="object"&&!Array.isArray(i)&&(r=i)}catch{r=null}return{text:t.slice(n[0].length).trim(),metadata:r,stripped:!0}}function S1(...e){const t={};for(const n of e)if(!(!n||typeof n!="object"||Array.isArray(n)))for(const[r,i]of Object.entries(n))i==null||String(i).trim()===""||(t[r]=i);return Object.keys(t).length?t:null}function lv(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(Array.isArray(e))return e.map(t=>lv(t)).filter(Boolean).join(`
129
+ `).trim();if(typeof e=="object"){const t=e.text??e.content??e.message??e.value;if(t!==e){const n=lv(t);if(n)return n}}return""}function N1(e){const t=vx(lv(e));return{text:t.text,runtime_metadata:t.metadata}}function v4(e){var r,i;if(!e)return{text:"",runtime_metadata:null};const t=typeof e.prompt=="string"?String(e.prompt).trim():"";if(t){const o=vx(t);return{text:o.text,runtime_metadata:o.metadata}}const n=[(r=e.context)==null?void 0:r.messages,e.messages,e.conversation,e.history].filter(Array.isArray);for(const o of n)for(let c=o.length-1;c>=0;c-=1){const l=o[c],d=String((l==null?void 0:l.role)||(l==null?void 0:l.speaker)||"").trim().toLowerCase();if(d&&d!=="user"&&d!=="human")continue;const h=N1((l==null?void 0:l.content)??(l==null?void 0:l.text)??l);if(h.text)return{text:h.text,runtime_metadata:S1(h.runtime_metadata,l!=null&&l.runtime_metadata&&typeof l.runtime_metadata=="object"?l.runtime_metadata:null,(i=l==null?void 0:l.metadata)!=null&&i.runtime_metadata&&typeof l.metadata.runtime_metadata=="object"?l.metadata.runtime_metadata:null)}}return{text:"",runtime_metadata:null}}function x4(e,t=6){var o,c;if(!e)return[];const r=[(o=e.context)==null?void 0:o.messages,e.messages,e.conversation,e.history].filter(Array.isArray).find(l=>l.length)||[],i=[];for(const l of r){const d=String((l==null?void 0:l.role)||(l==null?void 0:l.speaker)||(l==null?void 0:l.author)||"").trim().toLowerCase()||"message",h=N1((l==null?void 0:l.content)??(l==null?void 0:l.text)??(l==null?void 0:l.message)??l),m=h.text;if(!m)continue;const _=String((l==null?void 0:l.ts)||(l==null?void 0:l.timestamp)||(l==null?void 0:l.created_at)||(l==null?void 0:l.time)||"").trim(),g=S1(h.runtime_metadata,l!=null&&l.runtime_metadata&&typeof l.runtime_metadata=="object"?l.runtime_metadata:null,(c=l==null?void 0:l.metadata)!=null&&c.runtime_metadata&&typeof l.metadata.runtime_metadata=="object"?l.metadata.runtime_metadata:null);i.push({role:d,text:m,ts:_,runtime_metadata:g})}return i.slice(Math.max(0,i.length-Math.max(1,t)))}function $1(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function b4(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 C1="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function E1(e){const t=String((e==null?void 0:e.name)||"").trim().toLowerCase(),n=e!=null&&e.arguments&&typeof e.arguments=="object"?e.arguments:{},r=String((n==null?void 0:n.command)||(n==null?void 0:n.cmd)||(n==null?void 0:n.shell)||"").trim().toLowerCase(),i=[];return(t.includes("execute_command")||t.includes("terminal")||r)&&i.push("Shell"),/[;&|]?\s*(rm|rmdir|mv|chmod|chown|sudo)\b/.test(r)&&i.push("Destructive risk"),/(^|\s)(curl|wget|scp|ssh|nc|ncat|ftp)\b/.test(r)&&i.push("Network"),/(^|\s)(cat|sed|rg|grep|ls|find|pwd)\b/.test(r)&&!/[>|]\s*\S/.test(r)&&i.push("Read path"),/[>|]\s*\S|(^|\s)(tee|touch|mkdir|cp)\b/.test(r)&&i.push("Filesystem write"),i.length||i.push("Tool call"),Array.from(new Set(i)).slice(0,4)}function xx(e,t){const n=String((e==null?void 0:e.reason)||"").trim().toLowerCase(),r=b4(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 A1(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 T1(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=vx(n),i=v4(t);return r.text&&!$1(r.text)?{text:r.text,runtime_metadata:r.metadata}:i.text?i:{text:r.text||n,runtime_metadata:r.metadata}}function k4(e,t){return T1(e,t).text}function j4(e,t){return e||String(t||"").trim()||{}}function Ko(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 wu(e){const t=String(e.status||"unknown").trim()||"unknown";return s.jsx("span",{className:`run_status_pill ${Sa(t)}`,children:t})}function S4(e){var o;const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(hs(t))return"";const n=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null,r=String((n==null?void 0:n.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase(),i=Array.isArray((o=n==null?void 0:n.details)==null?void 0:o.tool_calls)?n.details.tool_calls:[];return i.length?xx(n,i):r==="user"?"Waiting for your answer":r==="event"?"Waiting for a response event":r==="subworkflow"?"Waiting for subworkflow":r==="until"?"Scheduled wait":r?`Waiting: ${r}`:t==="waiting"?"Waiting, reason unknown":""}function im(e){const t=e==null?void 0:e.error;return t?typeof t=="string"?tn(t,{max_chars:220,max_lines:2}):tn(Br(t,400),{max_chars:220,max_lines:2}):""}function N4(e){const t=S4(e);if(t)return t;const n=im(e);if(n)return n;const r=String((e==null?void 0:e.current_node)||"").trim();if(r)return`Current node: ${r}`;const i=String((e==null?void 0:e.status)||"").trim().toLowerCase();return i==="running"?"Running":hs(i)?"Terminal":"No current activity reported"}function M1(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 V0(e){const t=M1(e),n=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},r=e!=null&&e.tags&&typeof e.tags=="object"?e.tags:{},i=Vn(e==null?void 0:e.modality,t==null?void 0:t.modality,n==null?void 0:n.modality,r.modality).toLowerCase();if(i)return i;const o=Vn(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 o.startsWith("image/")?"image":o.startsWith("audio/")?"audio":o.startsWith("video/")?"video":o.includes("pdf")?"document":o.startsWith("text/")||o.includes("json")||o.includes("markdown")||o.includes("csv")?"text":"artifact"}function $4(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 C4(e,t){if(!e||typeof e!="object")return null;const n=$4(e),r=M1(e),i=e!=null&&e.metadata&&typeof e.metadata=="object"?e.metadata:e!=null&&e.meta&&typeof e.meta=="object"?e.meta:{},o=n!=null&&n.descriptor&&typeof n.descriptor=="object"?n.descriptor:e!=null&&e.descriptor&&typeof e.descriptor=="object"?e.descriptor:{},c=Vn(n.artifact_id,e.artifact_id,e.$artifact,e.id,r.artifact_id,r.$artifact,r.id,i.artifact_id,i.$artifact);if(!c)return null;const l={...r.tags&&typeof r.tags=="object"?r.tags:{},...i.tags&&typeof i.tags=="object"?i.tags:{},...n.tags&&typeof n.tags=="object"?n.tags:{},...e.tags&&typeof e.tags=="object"?e.tags:{}},d={};for(const[S,D]of Object.entries(l)){const O=String(S||"").trim();O&&(d[O]=String(D??""))}const h=Vn(n.filename,e.filename,r.filename,i.filename,d.filename,d.name,e.name,r.name),m=Vn(n.source_path,e.source_path,r.source_path,i.source_path,e.path,r.path,d.path,d.source_path,d.file_path),_=Vn(n.content_type,e.content_type,e.mime_type,e.mime,r.content_type,r.mime_type,r.mime,i.content_type,d.content_type),g=Vn(n.render_kind,o.render_kind,e.render_kind,d.render_kind),y=Vn(n.semantic_kind,o.semantic_kind,e.semantic_kind,d.semantic_kind,d.artifact_type),x=n.access&&typeof n.access=="object"?n.access:e.access&&typeof e.access=="object"?e.access:{},k=n.producer&&typeof n.producer=="object"?n.producer:e.producer&&typeof e.producer=="object"?e.producer:o.producer&&typeof o.producer=="object"?o.producer:{},v=n.provenance&&typeof n.provenance=="object"?n.provenance:e.provenance&&typeof e.provenance=="object"?e.provenance:o.provenance&&typeof o.provenance=="object"?o.provenance:{},N=n.generation&&typeof n.generation=="object"?n.generation:e.generation&&typeof e.generation=="object"?e.generation:o.generation&&typeof o.generation=="object"?o.generation:{},$=n.media&&typeof n.media=="object"?n.media:e.media&&typeof e.media=="object"?e.media:o.media&&typeof o.media=="object"?o.media:{},C=n.links&&typeof n.links=="object"?n.links:e.links&&typeof e.links=="object"?e.links:o.links&&typeof o.links=="object"?o.links:{};return{artifact_id:c,run_id:Vn(n.run_id,e.run_id,r.run_id,i.run_id,d.run_id,v.run_id),content_type:_,modality:Vn(n.modality,e.modality,o.modality,d.modality)||V0({...e,ref:r,metadata:i,tags:d}),semantic_kind:y||V0({...e,ref:r,metadata:i,tags:d}),render_kind:g||wx({content_type:_,filename:h,source_path:m,modality:Vn(n.modality,e.modality,d.modality),tags:d}),task:Vn(n.task,o.task,e.task,d.task,d.provider_task),classification_source:Vn(n.classification_source,o.classification_source,e.classification_source),session_id:Vn(n.session_id,o.session_id,e.session_id,d.session_id),workflow_id:Vn(n.workflow_id,o.workflow_id,e.workflow_id,d.workflow_id,d.workflow),node_id:Vn(n.node_id,o.node_id,e.node_id,d.node_id,d.node),step_id:Vn(n.step_id,o.step_id,e.step_id,d.step_id),effect_id:Vn(n.effect_id,o.effect_id,e.effect_id,d.effect_id,d.effect_idempotency_key),turn_id:Vn(n.turn_id,o.turn_id,e.turn_id,d.turn_id,d.turn),ledger_cursor:Vn(n.ledger_cursor,o.ledger_cursor,e.ledger_cursor,d.ledger_cursor,d.step_cursor),parent_run_id:Vn(n.parent_run_id,o.parent_run_id,e.parent_run_id,d.parent_run_id),actor_id:Vn(n.actor_id,o.actor_id,e.actor_id,d.actor_id),title:Vn(n.title,e.title,d.title,d.label,d.name),created_at:Vn(n.created_at,e.created_at,r.created_at,i.created_at,d.created_at),size_bytes:MO(n.size_bytes,e.size_bytes,r.size_bytes,i.size_bytes,d.size_bytes),filename:h,source_path:m,sha256:Vn(n.sha256,e.sha256,r.sha256,i.sha256,d.sha256),tags:d,producer:k,provenance:v,generation:N,media:$,source_refs:Array.isArray(n.source_refs)?n.source_refs:Array.isArray(e.source_refs)?e.source_refs:[],access:x,links:C,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(Vn(n.classification_source,o.classification_source,e.classification_source))),descriptor:o,source:t,raw:e}}function og(e){return e.filename||e.title||(e.source_path?e.source_path.split("/").filter(Boolean).slice(-1)[0]:"")||Ln(e.artifact_id,16)}function E4(e,t){if(t==="type")return qd(e);if(t==="run")return e.run_id||"(no run)";if(t==="turn")return cv(e);if(t==="node")return Wd(e)||"(node unknown)";if(t==="workflow")return bx(e)||"(workflow unknown)";if(t==="location"){const i=(e.source_path||e.filename||"").split("/").filter(Boolean);return i.length>1?i.slice(0,-1).join("/"):"(root)"}if(t==="source")return om(e)||e.source||"artifact";const n=Vt(e.created_at);return n===null?"(unknown time)":new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function bx(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 Wd(e){const t=(e==null?void 0:e.tags)||{},n=String((e==null?void 0:e.node_id)||t.node_id||t.node||(e==null?void 0:e.step_id)||t.step_id||"").trim();if(n)return n;const i=String((e==null?void 0:e.source_path)||t.path||"").trim().match(/(?:^|[._:/-])(node-[A-Za-z0-9_-]+)/);return i!=null&&i[1]?String(i[1]):""}function cv(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=Wd(e),i=Vt(e==null?void 0:e.created_at),o=i===null?"unknown time":new Date(i).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),c=e!=null&&e.run_id?Ln(String(e.run_id),10):"unknown run";return r?`${c} · ${r} · ${o}`:`${c} · ${o}`}function H0(e){if(!e)return"provenance unavailable";const t=[],n=bx(e),r=Wd(e),i=om(e),o=R1(e);return n&&t.push(n),r&&t.push(r),i&&t.push(i),o&&t.push(o),t.length?t.join(" · "):"provenance unavailable"}function ru(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"—";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;const i=r===0?0:n>=10?1:2;return`${n.toFixed(i)} ${t[r]}`}function qd(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,o=>o.toUpperCase())}function A4(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function T4(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 M4(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 G0(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 R4(e){const t=Jd(e.created_at),n=cu(e.created_at);return t==="—"?"Created —":`${t}${n&&n!=="—"?` (${n})`:""}`}function K0(e){var i;const t=e.tags||{},n=String(((i=e.access)==null?void 0:i.last_accessed_at)||t.last_accessed_at||t.accessed_at||t.updated_at||e.created_at||"").trim(),r=Jd(n);return r==="—"?"—":r}function J0(e){const t=e.tags||{},n=String(e.title||t.title||t.name||t.label||e.filename||"").trim();if(n)return n;const r=String(e.source_path||t.path||"").trim();if(r)return r.split("/").filter(Boolean).slice(-1)[0]||r;const i=om(e),o=qd(e);return i?`${o} ${i}`:`${o} artifact`}function om(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 R1(e){var r,i,o,c,l,d,h,m;if(!e)return"";const t=Vn((r=e.producer)==null?void 0:r.provider,(i=e.producer)==null?void 0:i.provider_id,(o=e.provenance)==null?void 0:o.provider,(c=e.generation)==null?void 0:c.provider),n=Vn((l=e.producer)==null?void 0:l.model,(d=e.producer)==null?void 0:d.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 L4(e){var t,n,r,i;return e?Vn((t=e.generation)==null?void 0:t.prompt,(n=e.generation)==null?void 0:n.input,(r=e.generation)==null?void 0:r.text,(i=e.provenance)==null?void 0:i.prompt):""}function Y0(e){if(!e)return"";const t=e.media||{},n=Number(t.duration_s??t.duration_seconds??t.duration),r=Number(t.width??t.image_width??t.video_width),i=Number(t.height??t.image_height??t.video_height),o=Number(t.sample_rate??t.sample_rate_hz),c=Number(t.channels);if(Number.isFinite(n)&&n>0){const d=[`${n>=60?`${Math.floor(n/60)}m ${Math.round(n%60)}s`:`${n.toFixed(n>=10?1:2)}s`}`];return Number.isFinite(o)&&o>0&&d.push(`${Math.round(o/1e3)} kHz`),Number.isFinite(c)&&c>0&&d.push(`${c} ch`),d.join(" · ")}if(Number.isFinite(r)&&Number.isFinite(i)&&r>0&&i>0)return`${Math.round(r)} x ${Math.round(i)}`;const l=Number(t.page_count??t.pages);return Number.isFinite(l)&&l>0?`${Math.round(l)} pages`:""}function X0(e){return e.source_path||e.filename||""}function ag(e,t,n){const r=e.run_id&&t[e.run_id]||null;if(!r)return e;const i=Ko(r,n),o={...e.tags||{}};return i&&!o.workflow&&(o.workflow=i),i&&!o.workflow_id&&(o.workflow_id=i),{...e,workflow_id:e.workflow_id||i,tags:o}}function uv(e,t,n,r=""){const i=ag(e,t,n),o=wx(i,r);return{json:"JSON",html:"HTML",markdown:"Markdown",code:"Code",voice:"Voice",music:"Music",sound:"Sound",audio:"Unclassified audio",image:"Image",video:"Video",document:"Document",text:"Text",other:"Other"}[o]||qd(i)}function Za(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 cp(e){var o,c,l;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(((o=n==null?void 0:n.payload)==null?void 0:o.name)||((c=n==null?void 0:n.payload)==null?void 0:c.event_name)||"").trim();if(!r)return null;const i=(l=n==null?void 0:n.payload)==null?void 0:l.payload;return{name:r,payload:i}}function af(e){const t=e,n=t==null?void 0:t.details;if(!n||typeof n!="object")return[];if(Array.isArray(n))return n.filter(i=>i&&typeof i=="object"&&typeof i.name=="string");const r=n==null?void 0:n.tool_calls;return Array.isArray(r)?r:[]}function I4(e){var i,o;const t=String((e==null?void 0:e.status)||"").trim(),n=String(((i=e==null?void 0:e.effect)==null?void 0:i.type)||"").trim(),r=(o=e==null?void 0:e.effect)!=null&&o.payload&&typeof e.effect.payload=="object"?String(e.effect.payload.name||"").trim():"";return n==="emit_event"&&r?r:n||t||"record"}function L1(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=I4(e),i=Za(e);if(i){const o=String(i.reason||"").trim();if(String(i.prompt||"").trim())return`${t||"node"} is waiting for a response`;if(o)return`${t||"node"} is waiting (${o})`}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 kd(e){if(typeof e=="string")return{text:e,duration:-1};if(e&&typeof e=="object"){const t=typeof e.text=="string"?String(e.text):typeof e.value=="string"?String(e.value):typeof e.message=="string"?String(e.message):Br(e,320),n=typeof e.duration=="number"?Number(e.duration):-1;return{text:t,duration:n}}return{text:Br(e,320),duration:-1}}function I1(e){var c,l,d,h,m,_,g,y,x;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=k=>typeof k=="string"?k.trim():k==null?"":typeof k=="number"||typeof k=="boolean"?String(k):"",i=k=>{if(!k||typeof k!="object")return"";const v=k,N=[v.response,v.answer,v.message,v.text,v.content];for(const $ of N){const C=r($);if(C)return C}return""};if(t==="answer_user"){const k=r(n==null?void 0:n.message)||r((l=n==null?void 0:n.output)==null?void 0:l.message)||r((d=n==null?void 0:n.output)==null?void 0:d.response)||r((m=(h=e==null?void 0:e.effect)==null?void 0:h.payload)==null?void 0:m.message)||r((g=(_=e==null?void 0:e.effect)==null?void 0:_.payload)==null?void 0:g.text)||r((x=(y=e==null?void 0:e.effect)==null?void 0:y.payload)==null?void 0:x.content);if(k)return k}if(t==="llm_call"){const k=i(n)||r(n==null?void 0:n.output)||i(n==null?void 0:n.output)||r(n==null?void 0:n.response);if(k)return k}return r(n==null?void 0:n.output)||i(n==null?void 0:n.output)||i(n)||r(n==null?void 0:n.response)}function Lp(e){var i;const t=String((e==null?void 0:e.node_id)||""),n=String((e==null?void 0:e.status)||""),r=String(((i=e==null?void 0:e.effect)==null?void 0:i.type)||"");return`${t||"(node?)"} • ${n||"(status?)"} • ${r||"(effect?)"}`}function O4(e){return!!(e&&String(e.status||"")==="waiting")}function P4(e){var n,r;const t=[];for(const i of e||[]){const o=i.record;if(String(((n=o==null?void 0:o.effect)==null?void 0:n.type)||"").trim()!=="llm_call")continue;const l=(r=o==null?void 0:o.effect)!=null&&r.payload&&typeof o.effect.payload=="object"?o.effect.payload:{},d=o!=null&&o.result&&typeof o.result=="object"?o.result:{},h=(d==null?void 0:d.usage)||(d==null?void 0:d.token_usage)||{},m=typeof l.prompt=="string"?l.prompt:Array.isArray(l.messages)?Br(l.messages,1800):"",_=typeof d.content=="string"?d.content:typeof d.response=="string"?d.response:typeof o.result=="string"?String(o.result):"",g=Vt(o.started_at),y=Vt(o.ended_at),x=Number(h.prompt_tokens??h.input_tokens??0)||0,k=Number(h.completion_tokens??h.output_tokens??0)||0;t.push({id:`${String(i.run_id||o.run_id||"")}:${i.cursor}`,cursor:Number(i.cursor||0),ts:String(o.ended_at||o.started_at||""),run_id:String(i.run_id||o.run_id||"").trim(),node_id:String(o.node_id||"").trim(),provider:String(l.provider||d.provider||d.runtime_provider||"").trim(),model:String(l.model||d.model||d.runtime_model||"").trim(),prompt_preview:tn(m,{max_chars:1200,max_lines:10}),response_preview:tn(_,{max_chars:1200,max_lines:10}),missing_response:!String(_||"").trim(),tokens:{prompt:x,completion:k,total:Number(h.total_tokens??x+k)||0},duration_ms:g!==null&&y!==null?Math.max(0,y-g):typeof d.gen_time=="number"?Number(d.gen_time)*1e3:null,status:String(o.status||"").trim(),error:o.error?Br(o.error,500):"",raw:o})}return t.sort((i,o)=>(Vt(o.ts)??0)-(Vt(i.ts)??0))}function Z0(e){const t=e.size||18,n=Yh(e.artifact),r=wx(e.artifact,""),i=`artifact_glyph ${r==="code"?"code":n}`,o={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round"};return n==="image"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 15l3-3 3 3 2-2 4 4"}),s.jsx("circle",{cx:"8",cy:"9",r:"1.4"})]})}):n==="audio"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 12h2"}),s.jsx("path",{d:"M8 8v8"}),s.jsx("path",{d:"M12 5v14"}),s.jsx("path",{d:"M16 8v8"}),s.jsx("path",{d:"M20 12h-2"})]})}):n==="video"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M9 9l6 3-6 3V9z",fill:"currentColor",stroke:"none"})]})}):r==="code"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M8 8l-4 4 4 4"}),s.jsx("path",{d:"M16 8l4 4-4 4"}),s.jsx("path",{d:"M14 4l-4 16"})]})}):n==="text"?s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M10 13h7"}),s.jsx("path",{d:"M10 17h5"})]})}):s.jsx("span",{className:i,children:s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l5 5v13H7z"}),s.jsx("path",{d:"M14 3v6h6"}),s.jsx("path",{d:"M9 14h8"})]})})}const D4=2,F4=Number.MAX_SAFE_INTEGER;function z4(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 B4(e){const t=String(e||"");if(typeof DOMParser>"u")return[{kind:"text",text:Gy(t)||t}];try{const n=new DOMParser().parseFromString(t,"text/html"),r=[];n.doctype&&r.push({kind:"doctype",name:n.doctype.name||"html"});const i=o=>{if(o.nodeType===Node.TEXT_NODE){const c=String(o.textContent||"").trim();return c?{kind:"text",text:c}:null}if(o.nodeType===Node.COMMENT_NODE)return{kind:"comment",text:String(o.textContent||"")};if(o.nodeType===Node.ELEMENT_NODE){const c=o,l=Array.from(c.attributes||[]).map(h=>({name:h.name,value:h.value})),d=Array.from(c.childNodes||[]).map(i).filter(Boolean);return{kind:"element",tag:c.tagName.toLowerCase(),attrs:l,children:d}}return null};if(n.documentElement){const o=i(n.documentElement);o&&r.push(o)}return r.length?r:[{kind:"text",text:Gy(t)||t}]}catch{return[{kind:"text",text:Gy(t)||t}]}}function Ky(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(Ae.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 O1(e){const t=e.node,n=e.depth*14,r=e.depth<e.collapseAfterDepth,[i,o]=p.useState(r);if(p.useEffect(()=>{o(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(Ky,{tag:t.tag,attrs:t.attrs,selfClosing:!0})});const c=t.children.find(l=>l.kind==="text");return s.jsxs("details",{className:"html-tree__details",open:i,onToggle:l=>o(l.currentTarget.open),children:[s.jsxs("summary",{className:"html-tree__summary",style:{paddingLeft:n},children:[s.jsx("span",{className:"html-tree__caret","aria-hidden":"true",children:i?"▾":"▸"}),s.jsx(Ky,{tag:t.tag,attrs:t.attrs}),!i&&c?s.jsxs("span",{className:"html-tree__summary_text",children:[" ",z4(c.text)]}):null]}),i?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((l,d)=>s.jsx(O1,{node:l,depth:e.depth+1,collapseAfterDepth:e.collapseAfterDepth,expansionMode:e.expansionMode,expansionVersion:e.expansionVersion},`${e.depth}:${t.kind}:${t.tag}:${d}`)),s.jsx("div",{className:"html-tree__line",style:{paddingLeft:n},children:s.jsx(Ky,{tag:t.tag,attrs:[],closing:!0})})]}):null]})}function U4(e){const t=p.useMemo(()=>B4(e.text),[e.text]),[n,r]=p.useState({mode:"folded",version:0}),i=n.mode==="unfolded"?F4:D4;p.useEffect(()=>{r(c=>({mode:"folded",version:c.version+1}))},[e.text]);const o=()=>{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:o,"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,l)=>s.jsx(O1,{node:c,depth:0,collapseAfterDepth:i,expansionMode:n.mode,expansionVersion:n.version},`root:${l}`))})]})}function W4(e){var r;const t=m4(e.text);if(!t)return s.jsx("div",{className:`${e.className} structured markdown_preview`,children:s.jsx(Ni,{text:e.text})});const n=((r=t.metadata.find(i=>i.label.toLowerCase()==="title"))==null?void 0:r.value)||"";return s.jsxs("div",{className:`${e.className} structured markdown_preview artifact_markdown_report`,children:[n?s.jsx("h1",{className:"artifact_markdown_title",children:n}):null,t.metadata.length?s.jsx("dl",{className:"artifact_markdown_meta",children:t.metadata.map(i=>{const o=/^https?:\/\//i.test(i.value);return s.jsxs("div",{children:[s.jsx("dt",{children:i.label}),s.jsx("dd",{children:o?s.jsx("a",{href:i.value,target:"_blank",rel:"noreferrer",children:i.value}):i.value})]},`${i.label}:${i.value}`)})}):null,s.jsx(Ni,{text:t.body||e.text})]})}function P1(e){const t=String(e.text||""),n=ig(e.artifact,t);if(n==="json"){const r=Og(t);if(r!==null)return s.jsx("div",{className:`${e.className} structured`,children:s.jsx(hr,{value:r,collapseAfterDepth:4,showCopy:!1})})}return n==="markdown"?s.jsx(W4,{text:t,className:e.className}):n==="html"?s.jsx(U4,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function q4(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:og(n)}):t.kind==="audio"&&t.url?s.jsx(Rg,{className:"runtime_inline_preview audio",src:t.url,name:og(n)}):t.kind==="video"&&t.url?s.jsx("video",{className:"runtime_inline_preview media",src:t.url,controls:!0}):s.jsx(P1,{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 kx(e){const t=e==null?void 0:e.waiting;return t&&typeof t=="object"?t:null}function D1(e){const t=kx(e);return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function Q0(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 V4(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 jx(e){const t=String((e==null?void 0:e.status)||"").trim().toLowerCase();if(hs(t)||t!=="waiting")return"none";const n=kx(e),r=D1(e);return af(n).length?"tool_approval":r==="until"||String((e==null?void 0:e.role)||"").trim()==="controller"?"scheduled":r==="subworkflow"?"subworkflow":r==="event"?Q0(n)?"user_response":"external_event":r==="user"||Q0(n)?"user_response":"unknown_wait"}function H4(e){const t=kx(e),n=af(t),r=jx(e);return r==="tool_approval"?`Tool approval: ${V4(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 G4(e){const t=jx(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.":hs(n)?"Open the ledger and artifacts for the final outcome.":"Open the run to inspect current activity."}function ek(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 K4(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label??"",i=String(e.status||"unknown").trim().toLowerCase()||"unknown",o=jx(e),c=hs(i),l=Tm(e,n),d=Vt(e.updated_at||e.created_at)??0,h=i==="running"&&l>=14400*1e3,m=H4(e)||ek(e)||(e.current_node?`Current node: ${e.current_node}`:i==="running"?"Running":c?"Terminal":"No current activity reported");let _="all";o==="tool_approval"?_="tool_approval":o==="user_response"?_="user_wait":o==="scheduled"?_="scheduled":o==="subworkflow"||o==="external_event"?_="subflows":i==="failed"?_="failed":i==="running"?_="running":c&&(_="finished");const g=o==="tool_approval"?0:o==="user_response"?1:o==="unknown_wait"?2:i==="failed"?3:h?4:i==="running"?5:o!=="none"?6:c?8:7,y=o==="tool_approval"||o==="user_response",x=o==="tool_approval"?"Open approval":o==="user_response"?"Open wait":"Open Observe",k=[e.run_id,e.workflow_id,r,e.session_id,e.parent_run_id,e.status,e.current_node,D1(e),m,ek(e)].join(" ").toLowerCase();return{run:e,run_id:String(e.run_id||"").trim(),status:i,wait_kind:o,queue:_,attention_rank:g,reason:m,expected_action:G4(e),action_label:x,search_text:k,is_terminal:c,needs_user_action:y,is_stale:h,duration_ms:l,updated_ms:d}}function J4(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(i=>K4(i,{now_ms:n,workflow_label:r[String(i.workflow_id||"")]||String(i.workflow_id||"")}))}function Y4(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 X4(e,t){const n=t.queue,i=(t.query??"").trim().toLowerCase();return e.filter(o=>{if(n==="attention"){if(!(o.needs_user_action||o.status==="failed"||o.is_stale||o.wait_kind==="unknown_wait"))return!1}else if(n!=="all"&&o.queue!==n)return!1;return!i||o.search_text.includes(i)})}function Z4(e,t){const n=[...e];return n.sort((r,i)=>{if(t==="recent")return i.updated_ms-r.updated_ms;if(t==="oldest")return r.updated_ms-i.updated_ms;if(t==="duration")return i.duration_ms-r.duration_ms;if(t==="tokens")return(Number(i.run.tokens_total||0)||0)-(Number(r.run.tokens_total||0)||0);if(t==="workflow")return String(r.run.workflow_id||"").localeCompare(String(i.run.workflow_id||""));const o=r.attention_rank-i.attention_rank;return o!==0?o:i.updated_ms-r.updated_ms}),n}function Q4(e){const[t,n]=p.useState("attention"),[r,i]=ng("system_queues"),[o,c]=ng("system_runs"),[l,d]=p.useState(""),[h,m]=p.useState("attention"),[_,g]=p.useState(""),y=p.useMemo(()=>{const L={};for(const K of e.artifacts){const H=String(K.run_id||"").trim();H&&(L[H]=(L[H]||0)+1)}return L},[e.artifacts]),x=p.useMemo(()=>J4(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),k=p.useMemo(()=>Y4(x),[x]),v=p.useMemo(()=>{const L=X4(x,{queue:t,query:l});return Z4(L,h)},[x,t,l,h]),N=v.find(L=>String(L.run_id||"")===_)||v.find(L=>String(L.run_id||"")===e.selected_run_id)||v[0]||null,$=(N==null?void 0:N.run)||null,C=String(($==null?void 0:$.run_id)||"").trim(),S=String(($==null?void 0:$.session_id)||"").trim(),D=p.useMemo(()=>S?new Set(e.runs.filter(L=>String(L.session_id||"").trim()===S).map(L=>String(L.run_id||"").trim()).filter(Boolean)):new Set,[e.runs,S]),O=S?D.size:0,A=p.useMemo(()=>S?e.artifacts.filter(L=>String(L.session_id||"").trim()===S||D.has(String(L.run_id||"").trim())).length:0,[e.artifacts,S,D]),P=$!=null&&$.waiting&&typeof $.waiting=="object"?$.waiting:null,W=P?af(P):[],J=(N==null?void 0:N.reason)||(P?xx(P,W):""),G=(N==null?void 0:N.expected_action)||(P?A1(P,W):""),V=P?k4(P,null):"",R=C&&y[C]||0,M=hs($==null?void 0:$.status),I=[{key:"attention",label:"Needs attention",count:k.attention},{key:"user_wait",label:"Needs my response",count:k.user_wait},{key:"tool_approval",label:"Tool approvals",count:k.tool_approval},{key:"running",label:"Running",count:k.running},{key:"failed",label:"Failed",count:k.failed},{key:"scheduled",label:"Scheduled",count:k.scheduled},{key:"subflows",label:"Subflows / external events",count:k.subflows},{key:"finished",label:"Finished",count:k.finished},{key:"all",label:"All loaded",count:k.all}];return s.jsxs("div",{className:`runtime_ops_layout${r?"":" queues_collapsed"}${o?"":" 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(sg,{open:r,on_toggle:i,controls:"runtime_ops_queues",title:"Queues"}),s.jsx("div",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.gateway_connected?e.on_refresh_runs:e.on_reconnect,children:[s.jsx(qe,{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:[I.map(L=>s.jsxs("button",{className:`runtime_ops_filter ${t===L.key?"selected":""}`,"aria-pressed":t===L.key,onClick:()=>n(L.key),children:[s.jsx("span",{children:L.label}),s.jsx("strong",{children:L.count.toLocaleString()})]},L.key)),s.jsx("div",{className:"runtime_ops_hint",children:"Counts are for the loaded runtime page. Refine search or refresh when supervising large runtimes."})]})]}),s.jsxs("section",{className:`pane runtime_ops_table_panel${o?"":" list_collapsed"}`,children:[s.jsxs("div",{className:"pane_header runtime_ops_list_header",children:[s.jsx(sg,{open:o,on_toggle:c,controls:"runtime_ops_runs",title:"Runs",count:v.length.toLocaleString()}),s.jsx("div",{className:"pane_spacer"}),s.jsx("input",{value:l,onChange:L=>d(L.target.value),placeholder:"Search workflow, run, node, status, error"}),s.jsxs("select",{className:"seg_select",value:h,onChange:L=>m(L.target.value),children:[s.jsx("option",{value:"attention",children:"Attention order"}),s.jsx("option",{value:"recent",children:"Latest event"}),s.jsx("option",{value:"oldest",children:"Oldest event"}),s.jsx("option",{value:"duration",children:"Longest duration"}),s.jsx("option",{value:"tokens",children:"Most tokens"}),s.jsx("option",{value:"workflow",children:"Workflow"})]})]}),s.jsxs("div",{className:"pane_body scroll runtime_ops_rows",id:"runtime_ops_runs",hidden:!o,children:[!v.length&&e.loading&&!e.runs.length?s.jsx(ol,{what:"activity"}):null,!v.length&&!(e.loading&&!e.runs.length)?s.jsx("div",{className:"runtime_ops_empty",children:e.gateway_connected?"No runs match this queue.":"Gateway offline. Runtime activity cannot be loaded until the connection is restored."}):null,v.map(L=>{const K=L.run,H=String(K.run_id||"").trim(),z=y[H]||0;return s.jsxs("div",{className:`raised runtime_ops_row ${H===C?"selected":""}`,"aria-current":H===C?"true":void 0,tabIndex:0,onClick:()=>{g(H),e.on_select_run(H)},onKeyDown:ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),g(H),e.on_select_run(H))},children:[s.jsxs("div",{className:"runtime_ops_row_top",children:[s.jsx("strong",{className:"runtime_ops_row_name",children:Ko(K,e.workflow_label_by_id)}),L.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(wu,{status:K.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Ln(H,18)}),s.jsx("span",{children:cu(K.updated_at||K.created_at)}),s.jsx("span",{children:yu(K)}),s.jsx("span",{className:"runtime_ops_row_reason",title:L.reason,children:L.reason})]}),s.jsxs("div",{className:"runtime_ops_row_foot",children:[s.jsxs("span",{className:"runtime_ops_row_facts",children:[s.jsxs("span",{children:[Number(K.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(K.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(K.tokens_total||0).toLocaleString()," tok"]}),s.jsxs("span",{children:[z.toLocaleString()," artifacts"]})]}),s.jsxs("div",{className:"runtime_ops_actions",children:[L.needs_user_action?s.jsx("button",{className:"btn primary",onClick:ee=>{ee.stopPropagation(),e.on_open_run(H)},children:L.action_label}):s.jsx("button",{className:"btn",onClick:ee=>{ee.stopPropagation(),e.on_open_run(H)},children:"Open"}),s.jsx("button",{className:"btn",onClick:ee=>{ee.stopPropagation(),e.on_open_ledger(H)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:ee=>{ee.stopPropagation(),e.on_select_run(H),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:ee=>{ee.stopPropagation(),e.on_filter_artifacts(H)},children:"Artifacts"})]})]})]},H)})]})]}),s.jsxs("aside",{className:"pane runtime_ops_inspector",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Run inspector"}),$?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"pane_spacer"}),s.jsx(wu,{status:$.status})]}):null]}),s.jsx("div",{className:"pane_body scroll runtime_ops_inspector_body",children:$?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_ops_inspector_head",children:[s.jsx("h3",{children:Ko($,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Ln(C,28)})]}),s.jsxs("div",{className:"runtime_ops_decision",children:[s.jsx("strong",{children:(N==null?void 0:N.reason)||N4($)}),s.jsx("span",{children:(N==null?void 0:N.expected_action)||(String($.status||"").toLowerCase()==="waiting"?"This run is paused until the pending wait is resolved or the run is cancelled.":M?"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:Jd(Od($))})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:yu($)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last event"}),s.jsx("strong",{children:Jd($.updated_at||$.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:$.session_id?Ln(String($.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:$.current_node||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Visible artifacts"}),s.jsx("strong",{children:R.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:Number($.llm_calls||0).toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Tokens"}),s.jsx("strong",{children:Number($.tokens_total||0).toLocaleString()})]})]}),S?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:Ln(S,30)})]}),s.jsxs("div",{className:"runtime_ops_session_facts",children:[s.jsxs("span",{children:[O.toLocaleString()," loaded run",O===1?"":"s"]}),s.jsxs("span",{children:[A.toLocaleString()," visible artifact",A===1?"":"s"]})]}),s.jsxs("div",{className:"runtime_detail_actions compact",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_filter_session_artifacts(S),children:"Open session artifacts"}),s.jsx("button",{className:"btn",onClick:()=>void il(S),children:"Copy session id"})]})]}):null,P?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:J})]}),s.jsx("p",{children:G}),V?s.jsxs("div",{className:"runtime_ops_wait_request",children:[s.jsx("span",{children:"Request"}),s.jsx(Ni,{text:V})]}):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."}),W.length?s.jsx("div",{className:"runtime_ops_wait_tools",children:W.map((L,K)=>s.jsxs(Ae.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((L==null?void 0:L.name)||"tool")}),E1(L).map(H=>s.jsxs("span",{className:"chip muted",title:C1,children:[H,"~"]},`${K}:${H}`))]},`${String((L==null?void 0:L.name)||"tool")}:${K}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(hr,{value:P,collapseAfterDepth:3,showCopy:!0})]})]}):null,im($)?s.jsx("div",{className:"warn_callout",children:im($)}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_open_run(C),children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(C),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>e.on_filter_artifacts(C),children:"Open artifacts"}),s.jsx("button",{className:"btn",onClick:e.on_open_logs,children:"Open logs"}),s.jsx("button",{className:"btn",onClick:()=>void il(C),children:"Copy run id"})]})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run to inspect why it is active or blocked."})})]})]})}function eD(e){const t=e.selected_artifact,n=["voice","music","sound","recording","audio","image","video","markdown","html","json","document","code","text","other"],r=[{value:"all",label:"Any time"},{value:"hour",label:"Last hour"},{value:"today",label:"Today"},{value:"week",label:"7 days"},{value:"month",label:"30 days"}],i=p.useMemo(()=>new Set(e.type_filters),[e.type_filters]),o=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(),l=Math.max(1,Number(e.artifact_page_size||500)),d=Math.max(1,Math.ceil(o/l)),h=Math.min(Math.max(0,Number(e.artifact_page||0)),d-1),m=o?h*l+1:0,_=Math.min(o,h*l+e.artifacts.length),g=p.useMemo(()=>{const R={},M=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,I=(M==null?void 0:M.semantic_kind)||{},L=(M==null?void 0:M.render_kind)||{};for(const K of n)R[K]=Number(I[K]||L[K]||0);return R.audio=Number(I.audio||0),R.other=Number(I.other||0)+Number(I.artifact||0)+Number(I.binary||0)+Number(I["(none)"]||0),R},[e.artifact_facets,e.artifact_type_facets]),y=R=>{const M=new Set(i);M.has(R)?M.delete(R):M.add(R),e.on_type_filters_change(Array.from(M.values()))},x=p.useMemo(()=>{const R={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const M of e.runs){const I=String(M.status||"").trim().toLowerCase();I==="waiting"?R.waiting.push(M):I==="running"?R.running.push(M):I==="failed"?R.failed.push(M):I==="cancelled"?R.cancelled.push(M):I==="completed"?R.completed.push(M):R.other.push(M)}return R},[e.runs]),k=t!=null&&t.run_id&&e.run_by_id[t.run_id]||null,v=e.artifact_run_filter?Ko(e.run_by_id[e.artifact_run_filter],e.workflow_label_by_id):"",N=p.useMemo(()=>{var I;const R=new Set,M=((I=e.artifact_facets)==null?void 0:I.run_id)||{};for(const L of Object.keys(M))L&&L!=="(none)"&&R.add(L);for(const L of e.artifacts)L.run_id&&R.add(L.run_id);for(const L of e.active_runs)L.run_id&&R.add(String(L.run_id));return Array.from(R).map(L=>e.run_by_id[L]||{run_id:L,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((L,K)=>{const H=Yd(L.status)?0:1,z=Yd(K.status)?0:1;if(H!==z)return H-z;const ee=Vt(L.updated_at||L.created_at)??0;return(Vt(K.updated_at||K.created_at)??0)-ee}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),$=R=>{e.on_artifact_run_filter_change(R),e.on_session_filter_change(""),e.on_scope_change(R?"run":"all")},C=R=>e.gateway_connected?Math.max(0,Number(R||0)).toLocaleString():"—",S=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,D=p.useMemo(()=>{const R=e.runtime_log_query.trim().toLowerCase(),M=e.runtime_ledger_log_items||[];return R?M.filter(I=>{var H,z;const L=I.record||{};return[I.cursor,L.run_id,L.node_id,L.status,(H=L.effect)==null?void 0:H.type,L.started_at,L.ended_at,Br(((z=L.effect)==null?void 0:z.payload)??{},900),Br(L.result??{},900)].join(" ").toLowerCase().includes(R)}):M},[e.runtime_ledger_log_items,e.runtime_log_query]),O=p.useMemo(()=>{const R=e.runtime_log_query.trim().toLowerCase(),M=P4(e.runtime_ledger_log_items);return R?M.filter(I=>[I.provider,I.model,I.run_id,I.node_id,I.status,I.error,I.prompt_preview,I.response_preview,I.tokens.prompt,I.tokens.completion,I.tokens.total].join(" ").toLowerCase().includes(R)):M},[e.runtime_ledger_log_items,e.runtime_log_query]),A=O.reduce((R,M)=>R+(Number(M.tokens.total)||0),0),P=O.filter(R=>R.missing_response||R.error).length,W=p.useMemo(()=>{const R=e.runtime_log_query.trim().toLowerCase(),M=String(e.audit_log_text||"").replace(/\r\n/g,`
130
+ `).replace(/\r/g,`
131
+ `).split(`
132
+ `).filter(Boolean);return R?M.filter(I=>I.toLowerCase().includes(R)):M},[e.audit_log_text,e.runtime_log_query]),J=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",G=e.runtime_log_source==="run_ledger"?"Selected Run Ledger":e.runtime_log_source==="provider_calls"?"Provider Calls":"Gateway HTTP Audit",V=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:Ln(e.artifact_run_filter,18)})]}):null,e.session_id?s.jsxs("span",{className:"chip muted",children:["session ",s.jsx("span",{className:"mono",children:Ln(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:C(x.waiting.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Running"}),s.jsx("strong",{children:C(x.running.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsx("span",{children:"Failed"}),s.jsx("strong",{children:C(x.failed.length)})]}),s.jsxs("div",{className:"metric_tile",children:[s.jsxs("span",{children:["Artifacts",c?" (filtered)":""]}),s.jsx("strong",{children:C(o)})]})]})]}),s.jsx("nav",{className:"runtime_mode_tabs",role:"tablist","aria-label":"System sections",children:["activity","artifacts","memory","logs"].map(R=>s.jsxs("button",{role:"tab","aria-selected":e.tab===R,className:`runtime_mode_tab ${e.tab===R?"active":""}`,onClick:()=>e.on_tab_change(R),children:[s.jsx(qe,{name:R==="activity"?"history":R==="artifacts"?"download":R==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:R==="activity"?"Activity":R==="artifacts"?"Artifacts":R==="memory"?"Memory":"Logs"})]},R))}),e.gateway_connected?null:s.jsxs("div",{className:"runtime_offline_banner",role:"status",children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Gateway offline"}),s.jsx("span",{children:"Activity, artifacts, memory, and logs are unavailable until the gateway reconnects."})]}),s.jsxs("div",{children:[s.jsx("button",{className:"btn primary",onClick:e.on_reconnect,children:"Reconnect"}),s.jsx("button",{className:"btn",onClick:e.on_open_settings,children:"Settings"})]})]}),e.error?s.jsx("div",{className:"warn_callout",children:e.error}):null,e.tab==="activity"?s.jsx(Q4,{gateway_connected:e.gateway_connected,loading:e.runs_loading,runs:e.runs,artifacts:e.artifacts,selected_run_id:e.selected_run_id,workflow_label_by_id:e.workflow_label_by_id,on_select_run:e.on_select_run,on_open_run:e.on_open_run,on_open_ledger:e.on_open_ledger,on_refresh_runs:e.on_refresh_runs,on_reconnect:e.on_reconnect,on_open_logs:()=>e.on_tab_change("logs"),on_filter_artifacts:R=>{$(R),e.on_select_run(R),e.on_tab_change("artifacts")},on_filter_session_artifacts:R=>{R&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(R),e.on_scope_change("session"),e.on_tab_change("artifacts"))}}):null,e.tab==="memory"?e.memory_panel?s.jsx("div",{className:"runtime_memory_panel",children:e.memory_panel}):s.jsx("div",{className:"empty_state_inline",children:"The memory explorer needs a gateway connection — sign in to browse knowledge-graph assertions."}):null,e.tab==="artifacts"?s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"pane runtime_artifact_toolbar","aria-label":"Find artifacts",children:[s.jsxs("div",{className:"runtime_artifact_toolbar_top",children:[s.jsxs("label",{className:"artifact_filter_field artifact_filter_search",children:[s.jsx("span",{children:"Search"}),s.jsx("input",{value:e.query,onChange:R=>e.on_query_change(R.target.value),placeholder:"title, path, hash, run, workflow, tag"})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Scope"}),s.jsxs("select",{className:"seg_select",value:e.scope,onChange:R=>{const M=R.target.value;M!=="run"&&e.on_artifact_run_filter_change(""),M==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(M)},children:[s.jsx("option",{value:"all",children:"All runtime"}),s.jsx("option",{value:"session",children:"This session"}),s.jsx("option",{value:"run",children:"Selected run"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Group"}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:R=>e.on_group_by_change(R.target.value),children:[s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"time",children:"Date"}),s.jsx("option",{value:"turn",children:"Turn"}),s.jsx("option",{value:"node",children:"Node"}),s.jsx("option",{value:"workflow",children:"Workflow"}),s.jsx("option",{value:"run",children:"Run"}),s.jsx("option",{value:"location",children:"Location"}),s.jsx("option",{value:"source",children:"Source"})]})]}),s.jsxs("label",{className:"artifact_filter_field",children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{className:"seg_select",value:e.sort_by,onChange:R=>e.on_sort_by_change(R.target.value),children:[s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"oldest",children:"Oldest"}),s.jsx("option",{value:"last_access",children:"Last accessed"}),s.jsx("option",{value:"turn",children:"Turn order"}),s.jsx("option",{value:"type",children:"Type"}),s.jsx("option",{value:"size_desc",children:"Largest"}),s.jsx("option",{value:"size_asc",children:"Smallest"})]})]}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh_artifacts,disabled:!e.gateway_connected||e.loading,children:[s.jsx(qe,{name:"refresh",size:14}),e.loading?"Loading…":"Refresh"]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsxs("div",{className:"artifact_filter_label",children:["Type ",s.jsx("span",{className:"muted",children:"OR"})]}),s.jsxs("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact type filters combine with OR",children:[n.map(R=>{const M=i.has(R),I=g[R]||0,L=A4(R);return s.jsxs("button",{type:"button","aria-pressed":M,"aria-label":`${L} artifact type filter. Type filters combine with OR.`,title:`${L}: ${M?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${M?"active":""}`,onClick:()=>y(R),children:[s.jsx("span",{children:L}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?I.toLocaleString():"—"})]},R)}),e.type_filters.length?s.jsx("button",{type:"button",className:"artifact_filter_chip clear",onClick:()=>e.on_type_filters_change([]),children:"Clear types"}):null]})]}),s.jsxs("div",{className:"artifact_filter_section",children:[s.jsx("div",{className:"artifact_filter_label",children:"Date"}),s.jsx("div",{className:"artifact_filter_chips",role:"group","aria-label":"Artifact date filters",children:r.map(R=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===R.value,className:`artifact_filter_chip ${e.date_filter===R.value?"active":""}`,onClick:()=>e.on_date_filter_change(R.value),children:R.label},R.value))})]})]}),s.jsx("div",{className:"artifact_scope_banner",children:e.artifact_run_filter?s.jsxs(s.Fragment,{children:["Showing artifacts for ",s.jsx("strong",{children:v||Ln(e.artifact_run_filter,18)}),".",s.jsx("button",{className:"btn",onClick:()=>$(""),children:"Show all"})]}):s.jsxs(s.Fragment,{children:["Showing artifacts across the selected runtime scope. Select a run to filter the inventory. ",e.artifact_total_bytes?s.jsxs("span",{className:"mono muted",children:["Total size ",ru(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:()=>$(""),children:[s.jsx("strong",{children:"All artifacts"}),s.jsx("span",{children:e.gateway_connected?`${o.toLocaleString()} match${o===1?"":"es"}`:"counts unavailable"})]}),N.map(R=>{const M=String(R.run_id||"").trim(),I=M===e.artifact_run_filter||M===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${I?"selected":""}`,onClick:()=>$(M),title:M,children:[s.jsx("strong",{children:Ko(R,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Ln(M,15)}),s.jsx("span",{children:yu(R)})]},M)})]})]}),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:o?`${m.toLocaleString()}-${_.toLocaleString()} of ${o.toLocaleString()}`:"0 items"}),s.jsx("div",{className:"pane_spacer"}),d>1?s.jsxs("div",{className:"artifact_pagination","aria-label":"Artifact pages",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(0),disabled: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()," / ",d.toLocaleString()]}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(h+1),disabled:h>=d-1,children:"Next"}),s.jsx("button",{className:"btn",onClick:()=>e.on_artifact_page_change(d-1),disabled:h>=d-1,children:"Last"})]}):null]}),s.jsxs("div",{className:"pane_body scroll artifact_browser_body",children:[!e.artifact_groups.length&&e.loading?s.jsx(ol,{what:"artifacts",size:"block"}):null,!e.artifact_groups.length&&!e.loading?s.jsx("div",{className:"empty_state_inline",children:e.gateway_connected?"No artifacts match the current filters.":"Gateway offline. Artifact inventory cannot be loaded until the connection is restored."}):null,s.jsx("div",{className:"artifact_group_list",children:e.artifact_groups.map(R=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:R.key}),s.jsx("span",{className:"artifact_group_count",children:R.items.length})]}),R.items.map(M=>{var z;const I=M.run_id&&e.run_by_id[M.run_id]||null,L=I?Ko(I,e.workflow_label_by_id):bx(M),K=Y0(M),H=Number(((z=M.access)==null?void 0:z.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===M.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(M.artifact_id),M.run_id&&e.on_select_run(M.run_id)},title:M.artifact_id,children:[s.jsx(Z0,{artifact:M,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:J0(ag(M,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:qd(M)}),M.render_kind&&M.render_kind!==M.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:M.render_kind}):null,M.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"})," ",R4(M)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",ru(M.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",K0(M)]}),H?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",H.toLocaleString()]}):null,K?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",K]}):null,M.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",M.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[L?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",L]}):null,M.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Ln(M.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",cv(M)]}),Wd(M)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Wd(M)]}):null,om(M)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",om(M)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Ln(M.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",H0(M)]})]}),X0(M)?s.jsx("div",{className:"artifact_row_path mono",children:X0(M)}):null]})]},M.artifact_id)})]},R.key))})]})]}),s.jsx("aside",{className:"runtime_detail",children:s.jsxs("section",{className:"overview_panel runtime_artifact_detail",children:[s.jsxs("div",{className:"overview_panel_header",children:[s.jsx("h3",{children:"Artifact Detail"}),t?s.jsx("span",{className:"chip mono muted",children:e.embedded_preview.render_kind?uv(t,e.run_by_id,e.workflow_label_by_id,e.embedded_preview.text):uv(t,e.run_by_id,e.workflow_label_by_id)}):null]}),t?s.jsxs(s.Fragment,{children:[(()=>{var z,ee,B,te,se,de,be;const R=L4(t),M=R1(t),I=Y0(t),L=Number(((z=t.access)==null?void 0:z.access_count)||0)||0,K=Vn((ee=t.links)==null?void 0:ee.provider_trace,(B=t.links)==null?void 0:B.provider_trace_url,(te=t.links)==null?void 0:te.provider_trace_id),H=Vn((se=t.links)==null?void 0:se.audit,(de=t.links)==null?void 0:de.audit_tail,(be=t.links)==null?void 0:be.audit_url);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"artifact_detail_header",children:[s.jsx(Z0,{artifact:t,size:22}),s.jsxs("div",{children:[s.jsx("div",{className:"artifact_detail_title",children:J0(ag(t,e.run_by_id,e.workflow_label_by_id))}),s.jsxs("div",{className:"artifact_detail_subtitle",children:[qd(t)," • ",t.render_kind||e.embedded_preview.render_kind||t.modality||"artifact"," • ",t.content_type||"unknown MIME"," • ",ru(t.size_bytes),t.legacy_inferred?" • legacy inferred":""]})]})]}),s.jsx(q4,{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:qd(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:Jd(t.created_at)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Size"}),s.jsx("strong",{children:ru(t.size_bytes)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Last seen"}),s.jsx("strong",{children:K0(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Accesses"}),s.jsx("strong",{children:L?L.toLocaleString():"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:t.run_id?Ln(t.run_id,24):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:k?Ko(k,e.workflow_label_by_id):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Turn"}),s.jsx("strong",{children:cv(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:Wd(t)||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider/model"}),s.jsx("strong",{children:M||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:I||"—"})]}),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:H0(t)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Artifact id"}),s.jsx("strong",{className:"mono",children:Ln(t.artifact_id,30)})]}),t.sha256?s.jsxs("div",{children:[s.jsx("span",{children:"sha256"}),s.jsx("strong",{className:"mono",children:Ln(t.sha256,30)})]}):null]}),R?s.jsxs("div",{className:"artifact_provenance_panel",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:R})]}):s.jsxs("div",{className:"artifact_provenance_panel muted",children:[s.jsx("div",{className:"artifact_filter_label",children:"Generation prompt / input"}),s.jsx("div",{className:"artifact_prompt_text",children:"Generation prompt not recorded by the runtime artifact descriptor."})]}),Object.keys(t.generation||{}).length||Object.keys(t.producer||{}).length?s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Generation and producer metadata"}),s.jsx(hr,{value:{generation:t.generation,producer:t.producer,source_refs:t.source_refs},collapseAfterDepth:3,showCopy:!0})]}):null,t.source_path?s.jsx("div",{className:"artifact_detail_path mono",children:t.source_path}):null,s.jsxs("div",{className:"runtime_detail_actions",children:[s.jsx("button",{className:"btn primary",onClick:()=>e.on_preview_artifact(t),disabled:!t.run_id,children:e.embedded_preview.render_kind==="html"?"Open as web page":"Open full preview"}),s.jsx("button",{className:"btn",onClick:()=>e.on_download_artifact(t),disabled:!t.run_id,children:"Download"}),s.jsx("button",{className:"btn",onClick:()=>$(t.run_id),disabled:!t.run_id,children:"Show run artifacts"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(t.run_id),disabled:!t.run_id,children:"Open in Observe"}),s.jsx("button",{className:"btn",onClick:()=>e.on_open_ledger(t.run_id),disabled:!t.run_id,children:"Open run ledger"}),s.jsx("button",{className:"btn",onClick:()=>{K&&window.open(K,"_blank","noopener,noreferrer")},disabled:!K,children:"Open provider trace"}),s.jsx("button",{className:"btn",onClick:()=>{H?window.open(H,"_blank","noopener,noreferrer"):e.on_tab_change("logs")},disabled:!H&&!t.audit_available,children:"Open audit trail"}),s.jsx("button",{className:"btn",onClick:()=>void il(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(hr,{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:G}),s.jsx("div",{className:"mono muted",children:V})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[J&&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:()=>{J?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:J?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(qe,{name:"refresh",size:14}),J?e.runtime_ledger_log_loading?"Loading…":"Refresh":e.audit_log_loading?"Loading…":"Refresh"]})]})]}),s.jsxs("div",{className:"runtime_log_toolbar",children:[s.jsxs("div",{className:"seg_toggle mono",children:[s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="run_ledger"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("run_ledger"),children:"Run ledger"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="provider_calls"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("provider_calls"),children:"Provider calls"}),s.jsx("button",{className:`seg_btn ${e.runtime_log_source==="gateway_audit"?"active":""}`,onClick:()=>e.on_runtime_log_source_change("gateway_audit"),children:"Gateway audit"})]}),s.jsx("input",{className:"mono",value:e.runtime_log_query,onChange:R=>e.on_runtime_log_query_change(R.target.value),placeholder:"Search node, status, effect, payload, error"})]}),e.runtime_log_source==="run_ledger"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:S?Ko(S,e.workflow_label_by_id):e.selected_run_id?Ln(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Ln(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:S!=null&&S.session_id?Ln(String(S.session_id),28):e.session_id?Ln(e.session_id,28):"—"})]}),s.jsxs("div",{className:"runtime_log_context_actions",children:[s.jsx("button",{className:"btn",onClick:()=>e.on_open_run(e.selected_run_id),disabled:!e.selected_run_id,children:"Open Observe"}),s.jsx("button",{className:"btn",onClick:()=>$(e.selected_run_id),disabled:!e.selected_run_id,children:"Run artifacts"})]})]}),e.runtime_ledger_log_error?s.jsx("div",{className:"warn_callout",children:e.runtime_ledger_log_error}):null,e.selected_run_id?null:s.jsx("div",{className:"empty_state_inline",children:"Select a run in Activity or Artifact Explorer to inspect its runtime ledger."}),e.selected_run_id&&!D.length&&e.runtime_ledger_log_loading?s.jsx(ol,{what:"ledger"}):null,e.selected_run_id&&!D.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:D.map(R=>{var se,de;const M=R.record||{},I=String(((se=M==null?void 0:M.effect)==null?void 0:se.type)||"").trim(),L=String((M==null?void 0:M.status)||"").trim(),K=String((M==null?void 0:M.node_id)||"").trim(),H=Vn(M==null?void 0:M.ended_at,M==null?void 0:M.started_at,M==null?void 0:M.ts),z=Za(M),ee=L1(M),B=I?tn(Br(((de=M==null?void 0:M.effect)==null?void 0:de.payload)??{},1200),{max_chars:1200,max_lines:6}):"",te=I1(M)||(z?`Waiting for ${String(z.reason||"input")}`:"")||((M==null?void 0:M.result)!==void 0?Br(M.result,700):"");return s.jsxs("article",{className:`runtime_log_event ${Sa(L)}`,children:[s.jsxs("div",{className:"runtime_log_event_header",children:[s.jsxs("span",{className:"mono",children:["#",R.cursor]}),s.jsx(wu,{status:L||"record"}),I?s.jsx("span",{className:"chip mono muted",children:I}):null,K?s.jsx("strong",{className:"mono",children:K}):null,H?s.jsx("span",{className:"mono muted",children:Jd(H)}):null]}),s.jsxs("div",{className:"runtime_log_event_body",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Request / activity"}),s.jsx("p",{children:[ee||Lp(M),B&&B!=="{}"?B:""].filter(Boolean).join(`
133
+ `)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:tn(te||"—",{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(hr,{value:M,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${R.cursor}`)})})]}):e.runtime_log_source==="provider_calls"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"runtime_log_context",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Selected run"}),s.jsx("strong",{children:S?Ko(S,e.workflow_label_by_id):e.selected_run_id?Ln(e.selected_run_id,24):"No run selected"}),e.selected_run_id?s.jsx("em",{className:"mono",children:Ln(e.selected_run_id,34)}):null]}),s.jsxs("div",{children:[s.jsx("span",{children:"Provider calls"}),s.jsx("strong",{children:O.length.toLocaleString()}),s.jsx("em",{className:"mono",children:A?`${A.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:P.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&&!O.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:O.map(R=>s.jsxs("article",{className:`provider_activity ${R.error||R.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[R.provider||"provider unknown",R.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[R.node_id?s.jsx("span",{className:"mono",children:R.node_id}):null,R.run_id?s.jsx("span",{className:"mono",children:Ln(R.run_id,16)}):null,s.jsx("span",{children:bu(R.duration_ms)}),R.status?s.jsx(wu,{status:R.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[R.tokens.total?R.tokens.total.toLocaleString():"—"," tokens"]})]}),s.jsxs("div",{className:"provider_preview_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Prompt / messages"}),s.jsx("p",{children:R.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:R.response_preview||R.error||"No response captured"})]})]}),s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"mono muted",children:"Raw provider ledger record"}),s.jsx(hr,{value:R.raw,collapseAfterDepth:3,showCopy:!0})]})]},R.id))})]}):s.jsxs(s.Fragment,{children:[e.audit_log_error?s.jsx("div",{className:"warn_callout",children:e.audit_log_error}):null,s.jsx("pre",{className:"mono audit_log_tail",children:W.length?W.join(`
134
+ `):"(audit tail not loaded or no lines match search)"})]})]}):null]})}function tD(e){const[t,n]=p.useState(""),r=Array.isArray(e.wait.choices)?e.wait.choices:[],i=e.wait.allow_free_text!==!1,o=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:l=>n(l.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),r.map((l,d)=>s.jsx("option",{value:String(l),children:String(l)},d))]})]}):null,i?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:l=>n(l.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:o||!t.trim(),onClick:()=>e.on_submit(t.trim()),children:"Submit response"})})]})}function tk(e,t,n){if(Dg(e)==="automation"){const r=String(e.automation_id||e.run_id||"").trim();return n[r]||"Automation"}return Ko(e,t)}function nk(e){const t=Dg(e.run);return t?s.jsx("span",{className:"chip scheduled run_tree_tag","data-tag":t,children:l1(e.run)}):null}function nD(e){const t=e.selected_run_id.trim(),n=e.list?e.list.open:!0,r=e.root_run_id.trim()||t,i=e.sections.reduce((o,c)=>o+c.rows.reduce((l,d)=>{const h=[d.run,...d.children];return l+h.filter(m=>Yd(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(sg,{open:n,on_toggle:e.list.on_toggle,controls:"run_nav_controls run_nav_tree",title:"Runs",count:`${e.total_runs.toLocaleString()} runs • ${i.toLocaleString()} active`}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pane_title",children:"Runs"}),s.jsxs("span",{className:"pane_count",children:[e.total_runs.toLocaleString()," runs • ",i.toLocaleString()," active"]})]}),s.jsx("span",{className:"pane_spacer"}),s.jsxs("button",{className:"btn btn_icon",onClick:e.on_refresh,disabled:e.loading,title:"Refresh workflow runs",children:[s.jsx(qe,{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:o=>e.on_search(o.target.value),placeholder:"Search runs, sessions, workflows"}),s.jsxs("div",{className:"run_nav_filter_row",children:[s.jsx("div",{className:"seg_toggle run_nav_segments",children:["active","waiting","terminal","failed","all"].map(o=>s.jsx("button",{className:`seg_btn ${e.filter===o?"active":""}`,onClick:()=>e.on_filter(o),children:o},o))}),s.jsxs("select",{className:"seg_select",value:e.group_by,onChange:o=>e.on_group_by(o.target.value),title:"Group workflow runs",children:[s.jsx("option",{value:"status",children:"Group by status"}),s.jsx("option",{value:"workflow",children:"Group by workflow"}),s.jsx("option",{value:"session",children:"Group by session"})]})]})]}),s.jsxs("div",{className:"run_tree",id:"run_nav_tree",hidden:!n,children:[e.sections.length?null:e.connected&&e.loading?s.jsx(ol,{what:"runs"}):e.connected?s.jsx("div",{className:"run_tree_empty",children:"No runs match the current filters."}):s.jsxs("div",{className:"run_tree_empty",children:["Gateway offline — runs are unavailable."," ",s.jsx("button",{className:"btn btn_sm",onClick:e.on_sign_in,children:"Sign in"})]}),e.sections.map(o=>s.jsxs("section",{className:"run_tree_section",children:[s.jsxs("div",{className:"run_tree_section_header",children:[s.jsx("span",{children:o.label}),s.jsx("span",{className:"mono",children:o.rows.length})]}),o.rows.map(c=>{const l=c.run,d=String(l.run_id||"").trim(),h=d===t;return s.jsxs("div",{className:"run_tree_group",children:[s.jsxs("button",{className:`run_tree_item ${h?"selected":""} ${d===r?"root_context":""}`,onClick:()=>e.on_select(d,d),title:d,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:tk(l,e.workflow_label_by_id,e.automation_titles)}),s.jsx(nk,{run:l}),l.status?s.jsx(wu,{status:rm(l)}):null]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Ln(d,13)}),s.jsx("span",{children:Od(l)?cu(Od(l)):"no start"}),s.jsx("span",{children:yu(l)})]})]}),c.children.length?s.jsx("div",{className:"run_tree_children",children:c.children.map(m=>{const _=String(m.run_id||"").trim();return s.jsxs("button",{className:`run_tree_item run_tree_child ${_===t?"selected":""}`,onClick:()=>e.on_select(_,d),title:_,children:[s.jsxs("div",{className:"run_tree_item_top",children:[s.jsx("span",{className:"run_tree_label",children:tk(m,e.workflow_label_by_id,e.automation_titles)}),s.jsx(nk,{run:m}),s.jsx(wu,{status:rm(m)})]}),s.jsxs("div",{className:"run_tree_meta",children:[s.jsx("span",{className:"mono",children:Ln(_,13)}),s.jsx("span",{children:Od(m)?cu(Od(m)):"child"}),s.jsx("span",{children:yu(m)})]})]},_)})}):null]},d)})]},o.key))]})]})}class sD{constructor(){jn(this,"_buffer","");jn(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
135
+ `);if(r===-1)return;const i=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const o=i.endsWith("\r")?i.slice(0,-1):i;if(o.startsWith(":"))continue;if(o===""){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(`
136
+ `)};n(h)}this._current={data_lines:[]};continue}const c=o.indexOf(":"),l=c===-1?o:o.slice(0,c),d=c===-1?"":o.slice(c+1).trimStart();if(l==="id"){this._current.id=d;continue}if(l==="event"){this._current.event=d;continue}if(l==="data"){this._current.data_lines.push(d);continue}}}}const Xt=Xv;function Xs(e,t=3e4){const n=AbortSignal.timeout(t),r=AbortSignal.any,i=e?typeof r=="function"?r([e,n]):e:n;return F1.set(i,t),i}const F1=new WeakMap;class rD extends Error{constructor(n){super(n);jn(this,"name","GatewayTimeout")}}class iD extends Error{constructor(n){super(n);jn(this,"name","Superseded")}}async function ln(e,t){try{return await globalThis.fetch(e,t)}catch(n){throw z1(n,e,t)}}async function Jy(e,t,n){try{return await e.json()}catch(r){throw z1(r,t,n)}}function z1(e,t,n){{const r=String((e==null?void 0:e.name)||"");if(r!=="AbortError"&&r!=="TimeoutError")return e;const i=n==null?void 0:n.signal,o=i==null?void 0:i.reason,c=r==="TimeoutError"||String((o==null?void 0:o.name)||"")==="TimeoutError";let l=String(t);try{const d=new URL(t,typeof location<"u"?location.href:"http://localhost/");l=`${String((n==null?void 0:n.method)||"GET").toUpperCase()} ${d.pathname}${d.search?"?"+d.searchParams.toString().slice(0,60):""}`}catch{}if(c){const d=i&&F1.get(i)||3e4;return new rD(`${l}: no answer within ${Math.round(d/1e3)} s — the gateway is busy`)}return new iD(`${l}: superseded`)}}function dv(){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 Zt(e){const t=(e||"").trim(),n={};return t&&(n.Authorization=`Bearer ${t}`),{...n,...dv()}}async function bs(e){try{const t=await e.text();return t!=null&&t.trim()?t.trim():`${e.status}`}catch{return`${e.status}`}}class fv extends Error{constructor(n,r){super(r);jn(this,"status");this.name="GatewayRequestError",this.status=n}}async function Zc(e,t){let n="";try{n=(await e.text()).trim()}catch{n=""}let r=n;try{const i=JSON.parse(n),o=i&&typeof i=="object"?i.detail:void 0;typeof o=="string"&&o.trim()?r=o.trim():o&&typeof o=="object"&&typeof o.message=="string"&&o.message.trim()&&(r=o.message.trim())}catch{}return new fv(e.status,`${t} (HTTP ${e.status}): ${r||e.statusText||"no reason given"}`)}async function Yy(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 Xy{constructor(t){jn(this,"_cfg");jn(this,"fetch_gateway",(t,n)=>fetch(Xt(this._cfg.base_url,t),{...n,headers:{...n==null?void 0:n.headers,...Zt(this._cfg.auth_token)}}));this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,r){const i=String((r==null?void 0:r.bundle_id)||"").trim(),o=(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(),l=String((r==null?void 0:r.interface)||"").trim();if(c==="@default"&&(!l||i))throw new Error("start_run: flow_id '@default' needs `interface` and no bundle_id");const d={input_data:n||{}};i&&(d.bundle_id=i),c&&(d.flow_id=c),c==="@default"&&(d.interface=l),o&&(d.session_id=o),r!=null&&r.workspace&&(d.workspace=r.workspace);const h=await ln(Xt(this._cfg.base_url,wt("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(d)});if(!h.ok)throw new Error(await Yy(h)||`start_run failed: ${h.status}`);const m=await h.json(),_=m==null?void 0:m.run_id;if(typeof _!="string"||!_)throw new Error("start_run: missing run_id");return _}async list_mcp_servers(){for(const t of[wt("mcp/servers"),wt("mcp"),wt("discovery/mcp")])try{const n=await ln(Xt(this._cfg.base_url,t),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(n.status===404||!n.ok)continue;const r=await n.json(),i=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.servers)?r.servers:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!i)continue;return i.map(o=>({name:String((o==null?void 0:o.name)||(o==null?void 0:o.id)||"").trim(),url:typeof(o==null?void 0:o.url)=="string"?o.url:void 0,description:typeof(o==null?void 0:o.description)=="string"?o.description:void 0,auth_required:typeof(o==null?void 0:o.auth_required)=="boolean"?o.auth_required:void 0})).filter(o=>o.name)}catch{return null}return null}async list_skills(){for(const t of[wt("skills"),wt("skills/registry")])try{const n=await ln(Xt(this._cfg.base_url,t),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(n.status===404||!n.ok)continue;const r=await n.json(),i=Array.isArray(r)?r:Array.isArray(r==null?void 0:r.skills)?r.skills:Array.isArray(r==null?void 0:r.items)?r.items:null;if(!i)continue;return i.map(o=>({name:String((o==null?void 0:o.name)||(o==null?void 0:o.id)||"").trim(),description:typeof(o==null?void 0:o.description)=="string"?o.description:void 0,version:typeof(o==null?void 0:o.version)=="string"?o.version:void 0,trust_level:typeof(o==null?void 0:o.trust_level)=="string"?o.trust_level:void 0,blocked:typeof(o==null?void 0:o.blocked)=="boolean"?o.blocked:void 0,requires_review:typeof(o==null?void 0:o.requires_review)=="boolean"?o.requires_review:void 0,tree_hash:typeof(o==null?void 0:o.tree_hash)=="string"?o.tree_hash:void 0,reasons:Array.isArray(o==null?void 0:o.reasons)?o.reasons.map(c=>String(c||"")).filter(Boolean):void 0})).filter(o=>o.name)}catch{return null}return null}async get_run(t){const n=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!n.ok)throw new Error(`get_run failed: ${await bs(n)}`);return await n.json()}async find_run(t){const n=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}`)),{headers:{...Zt(this._cfg.auth_token)}});if(n.status===404||n.status===403)return null;if(!n.ok)throw await Zc(n,"Opening the run failed");return await n.json()}async get_run_history_bundle(t,n){const r=String(t||"").trim();if(!r)throw new Error("get_run_history_bundle: run_id is required");const i=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&i.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&i.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&i.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&i.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&i.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const o=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/history_bundle?${i.toString()}`)),c=await ln(o,{headers:{...Zt(this._cfg.auth_token)}});if(!c.ok)throw new Error(`get_run_history_bundle failed: ${await bs(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(),i=String((t==null?void 0:t.workflow_id)||"").trim(),o=String((t==null?void 0:t.session_id)||"").trim(),c=(t==null?void 0:t.root_only)===!0,l=new URLSearchParams;l.set("limit",String(n)),r&&l.set("status",r),i&&l.set("workflow_id",i),o&&l.set("session_id",o),c&&l.set("root_only","true"),(t==null?void 0:t.archived_only)===!0&&l.set("archived_only","true"),typeof(t==null?void 0:t.include_ledger_len)=="boolean"&&l.set("include_ledger_len",String(t.include_ledger_len)),typeof(t==null?void 0:t.include_metrics)=="boolean"&&l.set("include_metrics",String(t.include_metrics)),typeof(t==null?void 0:t.include_drafts)=="boolean"&&l.set("include_drafts",String(t.include_drafts));const d=Xt(this._cfg.base_url,wt(`runs?${l.toString()}`)),h=await ln(d,{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!h.ok)throw new Error(`list_runs failed: ${await bs(h)}`);return await Jy(h,d,{signal:Xs()})}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=Xt(this._cfg.base_url,wt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),i=await ln(r,{headers:{...Zt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`audit_log_tail failed: ${await bs(i)}`);return await i.json()}async gateway_about(){const t=await ln(Xt(this._cfg.base_url,wt("about")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs(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 ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/input_data`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_input_data failed: ${await bs(r)}`);return await r.json()}async get_run_after(t){const n=String(t||"").trim();if(!n)throw new Error("get_run_after: run_id is required");const r=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(n)}/after`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_run_after failed: ${await bs(r)}`);return await r.json()}async list_run_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_run_artifacts: run_id is required");const i=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,o=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,c=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await ln(c,{headers:{...Zt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`list_run_artifacts failed: ${await bs(l)}`);return await l.json()}async list_session_artifacts(t,n){const r=String(t||"").trim();if(!r)throw new Error("list_session_artifacts: session_id is required");const i=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,o=typeof(n==null?void 0:n.offset)=="number"?Math.max(0,Math.floor(n.offset)):0,c=Xt(this._cfg.base_url,wt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await ln(c,{headers:{...Zt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`list_session_artifacts failed: ${await bs(l)}`);return await l.json()}async search_artifacts(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");const r=String((t==null?void 0:t.session_id)||"").trim(),i=String((t==null?void 0:t.run_id)||"").trim(),o=String((t==null?void 0:t.modality)||"").trim(),c=String((t==null?void 0:t.artifact_kind)||"").trim(),l=String((t==null?void 0:t.semantic_kind)||"").trim(),d=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(),_=String((t==null?void 0:t.content_type)||"").trim(),g=String((t==null?void 0:t.query)||"").trim(),y=String((t==null?void 0:t.tags)||"").trim(),x=String((t==null?void 0:t.cursor)||"").trim(),k=String((t==null?void 0:t.order_by)||"").trim(),v=String((t==null?void 0:t.order)||"").trim(),N=String((t==null?void 0:t.created_after)||"").trim(),$=String((t==null?void 0:t.created_before)||"").trim(),C=typeof(t==null?void 0:t.limit)=="number"?t.limit:500,S=typeof(t==null?void 0:t.offset)=="number"?Math.max(0,Math.floor(t.offset)):0;r&&n.set("session_id",r),i&&n.set("run_id",i),o&&n.set("modality",o),c&&n.set("artifact_kind",c),l&&n.set("semantic_kind",l),d&&n.set("render_kind",d),h&&n.set("workflow_id",h),m&&n.set("node_id",m),_&&n.set("content_type",_),g&&n.set("query",g),y&&n.set("tags",y),x&&n.set("cursor",x),k&&n.set("order_by",k),v&&n.set("order",v),N&&n.set("created_after",N),$&&n.set("created_before",$),t!=null&&t.include_stats&&n.set("include_stats","true"),n.set("limit",String(C)),n.set("offset",String(S));const D=await ln(Xt(this._cfg.base_url,wt(`artifacts/search?${n.toString()}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!D.ok)throw new Error(`search_artifacts failed: ${await bs(D)}`);return await D.json()}async artifact_stats(t){const n=new URLSearchParams;n.set("scope",String((t==null?void 0:t.scope)||"all").trim()||"all");for(const i of["session_id","run_id","modality","semantic_kind","render_kind","workflow_id","node_id","content_type","query","tags","created_after","created_before"]){const o=String((t==null?void 0:t[i])||"").trim();o&&n.set(i,o)}const r=await ln(Xt(this._cfg.base_url,wt(`artifacts/stats?${n.toString()}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`artifact_stats failed: ${await bs(r)}`);return await r.json()}async download_run_artifact_content(t,n,r){const i=String(t||"").trim(),o=String(n||"").trim();if(!i)throw new Error("download_run_artifact_content: run_id is required");if(!o)throw new Error("download_run_artifact_content: artifact_id is required");const c=String((r==null?void 0:r.access)||"").trim(),l=c?`?access=${encodeURIComponent(c)}`:"",d=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(i)}/artifacts/${encodeURIComponent(o)}/content${l}`)),h=await ln(d,{headers:{...Zt(this._cfg.auth_token)}});if(!h.ok)throw new Error(`download_run_artifact_content failed: ${await bs(h)}`);return await h.blob()}async list_entities(){const t=await ln(Xt(this._cfg.base_url,wt("entities")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`list_entities failed: ${await bs(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 ln(Xt(this._cfg.base_url,wt("entities/spec/phases")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`get_entity_phases_spec failed: ${await bs(t)}`);return await t.json()}async get_entity_cognition(t){const n=await ln(Xt(this._cfg.base_url,wt(`entities/${encodeURIComponent(t)}/cognition`)),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!n.ok)throw new Error(`get_entity_cognition failed: ${await bs(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 ln(Xt(this._cfg.base_url,wt(`entities/${encodeURIComponent(n)}/card`)),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!r.ok)throw new Error(`get_entity_card failed: ${await bs(r)}`);return await r.json()}async read_entity_diary_entry(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r||!i)throw new Error("read_entity_diary_entry: name and entry_id are required");const o=Xt(this._cfg.base_url,wt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(i)}?reason=${encodeURIComponent("observer board hint chip")}`)),c=await ln(o,{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!c.ok)throw new Error(`read_entity_diary_entry failed: ${await bs(c)}`);return await c.json()}async get_ledger(t,n){const r=Number((n==null?void 0:n.after)||0),i=Number((n==null?void 0:n.limit)||0),o=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(i))}`)),c=await ln(o,{headers:{...Zt(this._cfg.auth_token)},signal:Xs(n==null?void 0:n.signal)});if(!c.ok)throw new Error(`get_ledger failed: ${c.status}`);const l=await Jy(c,o,{signal:Xs()}),d=Array.isArray(l==null?void 0:l.items)?l.items:[],h=typeof(l==null?void 0:l.next_after)=="number"?l.next_after:r;return{items:d,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),i=await ln(Xt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify({runs:n,limit:r}),signal:Xs()});if(!i.ok)throw new Error(`get_ledger_batch failed: ${i.status}`);const o=await Jy(i,Xt(this._cfg.base_url,wt("runs/ledger/batch")),{method:"POST",signal:Xs()}),l=(o&&typeof o=="object"?o:{}).runs;return{runs:l&&typeof l=="object"?l:{}}}async generate_run_summary(t,n){const r=String(t||"").trim();if(!r)throw new Error("generate_run_summary: run_id is required");const i={include_subruns:(n==null?void 0:n.include_subruns)!==!1},o=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";o&&(i.provider=o);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(i.model=c);const l=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/summary`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!l.ok)throw await Zc(l,"The gateway could not summarize this run");return await l.json()}async run_chat(t,n){const r=String(t||"").trim();if(!r)throw new Error("run_chat: run_id is required");const i={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[],persist:!!(n!=null&&n.persist)},o=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";o&&(i.provider=o);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(i.model=c);const l=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!l.ok)throw await Zc(l,"The gateway could not answer");return await l.json()}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const i=n==null?void 0:n.audio_artifact;if(!i||typeof i!="object")throw new Error("audio_transcribe: audio_artifact is required");if(!String(i.$artifact||"").trim())throw new Error("audio_transcribe: audio_artifact.$artifact is required");const c={audio_artifact:i};for(const m of["language","provider","model","request_id"]){const _=String((n==null?void 0:n[m])||"").trim();_&&(c[m]=_)}const l=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(c)});if(!l.ok)throw await Zc(l,"The gateway refused the transcription");const d=await l.json(),h=String((d==null?void 0:d.text)||"");return{ok:!!(d!=null&&d.ok),run_id:String((d==null?void 0:d.run_id)||""),request_id:String((d==null?void 0:d.request_id)||""),text:h,transcript_artifact:d==null?void 0:d.transcript_artifact,provider:d!=null&&d.provider?String(d.provider):null,model:d!=null&&d.model?String(d.model):null,duration_ms:Number.isFinite(Number(d==null?void 0:d.duration_ms))?Number(d.duration_ms):null}}async voice_defaults(){const t=await ln(Xt(this._cfg.base_url,wt("voice/defaults")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw await Zc(t,"The gateway could not list its voice defaults");return await t.json()}async voice_catalog(t,n){const r=new URLSearchParams({compact:"true"});t&&r.set("provider",t),n&&r.set("model",n);const i=await ln(Xt(this._cfg.base_url,wt(`voice/voices?${r.toString()}`)),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!i.ok)throw await Zc(i,"The gateway could not list its voices");return await i.json()}async voice_design(t){const n={description:t.description};t.name&&(n.name=t.name),t.language&&(n.language=t.language);const r=await ln(Xt(this._cfg.base_url,wt("voice/design")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(n)});if(!r.ok)throw new fv(r.status,await Yy(r)||`The gateway could not create the voice (HTTP ${r.status}).`);return await r.json()}async voice_clone(t,n){const r=new FormData;r.set("file",t,t.name||"recording.wav"),n.name&&r.set("name",n.name),n.language&&r.set("language",n.language),n.reference_text&&r.set("reference_text",n.reference_text);const i=await ln(Xt(this._cfg.base_url,wt("voice/clones")),{method:"POST",headers:{...Zt(this._cfg.auth_token)},body:r});if(!i.ok)throw new fv(i.status,await Yy(i)||`The gateway could not clone the voice (HTTP ${i.status}).`);return await i.json()}gateway_url(t){return Xt(this._cfg.base_url,t)}auth_headers(){return Zt(this._cfg.auth_token)}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const i=String((n==null?void 0:n.text)||"").trim();if(!i)throw new Error("voice_tts: text is required");const o={text:i},c=String((n==null?void 0:n.voice)||"").trim();c&&(o.voice=c);const l=String((n==null?void 0:n.format)||"").trim();l&&(o.format=l);const d=String((n==null?void 0:n.request_id)||"").trim();d&&(o.request_id=d);const h=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!h.ok)throw new Error(`voice_tts failed: ${await bs(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 i={include_subruns:(n==null?void 0:n.include_subruns)!==!1,messages:Array.isArray(n==null?void 0:n.messages)?n.messages:[]},o=typeof(n==null?void 0:n.provider)=="string"?String(n.provider).trim():"";o&&(i.provider=o);const c=typeof(n==null?void 0:n.model)=="string"?String(n.model).trim():"";c&&(i.model=c);const l=typeof(n==null?void 0:n.title)=="string"?String(n.title).trim():"";l&&(i.title=l);const d=await ln(Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(r)}/chat_threads`)),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(i)});if(!d.ok)throw new Error(`save_chat_thread failed: ${await bs(d)}`);return await d.json()}async list_bundles(){const t=await ln(Xt(this._cfg.base_url,wt("bundles")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`list_bundles failed: ${t.status}`);return await t.json()}async list_apps(){return await this.get_gateway_json("apps")}async get_gateway_json(t,n){const r=await ln(Xt(this._cfg.base_url,wt(t)),{headers:{...Zt(this._cfg.auth_token)},signal:n??Xs()});if(!r.ok)throw new Error(await bs(r));return await r.json()}async reload_bundles(){const t=await ln(Xt(this._cfg.base_url,wt("bundles/reload")),{method:"POST",headers:{...Zt(this._cfg.auth_token)}});if(!t.ok)throw new Error(`reload_bundles failed: ${t.status}`);return await t.json()}async upload_bundle(t,n){const r=(n==null?void 0:n.overwrite)===!0,i=(n==null?void 0:n.reload)!==!1,o=new FormData;o.set("overwrite",r?"true":"false"),o.set("reload",i?"true":"false"),o.set("file",t,t.name||"upload.flow");const c=await ln(Xt(this._cfg.base_url,wt("bundles/upload")),{method:"POST",headers:{...Zt(this._cfg.auth_token)},body:o});if(!c.ok)throw new Error(`upload_bundle failed: ${await bs(c)}`);return await c.json()}async attachments_upload(t,n,r){const i=String(t||"").trim();if(!i)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const o=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(),l=new FormData;l.append("session_id",i),l.append("file",n,o),l.append("filename",o),c&&l.append("content_type",c);const d=await ln(Xt(this._cfg.base_url,wt("attachments/upload")),{method:"POST",headers:{...Zt(this._cfg.auth_token)},body:l});if(!d.ok)throw new Error(`attachments_upload failed: ${await bs(d)}`);const h=await d.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 i=new URLSearchParams,o=String((n==null?void 0:n.bundle_version)||"").trim();o&&i.set("bundle_version",o),i.set("reload",(n==null?void 0:n.reload)===!1?"false":"true");const c=Xt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}?${i.toString()}`)),l=await ln(c,{method:"DELETE",headers:{...Zt(this._cfg.auth_token)}});if(!l.ok)throw new Error(`remove_bundle failed: ${await bs(l)}`);return await l.json()}async discovery_tools(){const t=await ln(Xt(this._cfg.base_url,wt("discovery/tools")),{headers:{...Zt(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=Xt(this._cfg.base_url,wt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),i=await ln(r,{headers:{...Zt(this._cfg.auth_token)}});if(!i.ok)throw new Error(`discovery_providers failed: ${i.status}`);return await i.json()}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await ln(Xt(this._cfg.base_url,wt(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...Zt(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 ln(Xt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(n)}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!r.ok)throw new Error(`get_bundle failed: ${r.status}`);return await r.json()}async get_bundle_flow(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r)throw new Error("get_bundle_flow: bundle_id is required");if(!i)throw new Error("get_bundle_flow: flow_id is required");const o=await ln(Xt(this._cfg.base_url,wt(`bundles/${encodeURIComponent(r)}/flows/${encodeURIComponent(i)}`)),{headers:{...Zt(this._cfg.auth_token)}});if(!o.ok)throw new Error(`get_bundle_flow failed: ${o.status}`);return await o.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 ln(Xt(this._cfg.base_url,wt(`workflows/${encodeURIComponent(n)}/flow`)),{headers:{...Zt(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 ln(Xt(this._cfg.base_url,wt("discovery/capabilities")),{headers:{...Zt(this._cfg.auth_token)},signal:Xs()});if(!t.ok)throw new Error(`discovery_capabilities failed: ${await bs(t)}`);return await t.json()}automations_client(){const t=this._cfg.auth_token;return kA({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Zt(t)})}async submit_command(t){const n=await ln(Xt(this._cfg.base_url,wt("commands")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(t)});if(!n.ok)throw new Error(`submit_command failed: ${n.status}`);return await n.json()}async kg_query(t){const n=String((t==null?void 0:t.scope)||"session").trim().toLowerCase(),r=String((t==null?void 0:t.order)||"desc").trim().toLowerCase(),i=typeof(t==null?void 0:t.limit)=="number"&&Number.isFinite(t.limit)?Number(t.limit):500,o={scope:n,order:r,limit:i},c=String((t==null?void 0:t.run_id)||"").trim();c&&(o.run_id=c);const l=String((t==null?void 0:t.session_id)||"").trim();l&&(o.session_id=l);const d=String((t==null?void 0:t.owner_id)||"").trim();d&&(o.owner_id=d),t!=null&&t.all_owners&&(o.all_owners=!0);const h=String((t==null?void 0:t.subject)||"").trim();h&&(o.subject=h);const m=String((t==null?void 0:t.predicate)||"").trim();m&&(o.predicate=m);const _=String((t==null?void 0:t.object)||"").trim();_&&(o.object=_);const g=String((t==null?void 0:t.since)||"").trim();g&&(o.since=g);const y=String((t==null?void 0:t.until)||"").trim();y&&(o.until=y);const x=String((t==null?void 0:t.active_at)||"").trim();x&&(o.active_at=x);const k=String((t==null?void 0:t.query_text)||"").trim();k&&(o.query_text=k),typeof(t==null?void 0:t.min_score)=="number"&&Number.isFinite(t.min_score)&&(o.min_score=Number(t.min_score));const v=await ln(Xt(this._cfg.base_url,wt("kg/query")),{method:"POST",headers:{"Content-Type":"application/json",...Zt(this._cfg.auth_token)},body:JSON.stringify(o)});if(!v.ok)throw new Error(`kg_query failed: ${await bs(v)}`);return await v.json()}async stream_ledger(t,n){var _;const r=Number((n==null?void 0:n.after)||0),i=n.on_step,o=n.signal,c=Xt(this._cfg.base_url,wt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),l=await ln(c,{headers:{Accept:"text/event-stream",...Zt(this._cfg.auth_token)},signal:o});if(!l.ok)throw await Zc(l,"The ledger stream was refused");if(!l.body)throw new Error("stream_ledger: response body is missing");(_=n.on_open)==null||_.call(n);const d=l.body.getReader(),h=new TextDecoder("utf-8"),m=new sD;for(;;){const{value:g,done:y}=await d.read();if(y)return;const x=h.decode(g,{stream:!0});m.push(x,k=>{if(!(k.event!=="step"||!k.data))try{const v=JSON.parse(k.data);v&&typeof v.cursor=="number"&&v.record&&i(v)}catch{}})}}}function oD(e,t=()=>({})){return async(n,r)=>{var l;const i=await e(n,{method:r.method,headers:{Accept:"application/json",...r.body!==void 0?{"Content-Type":"application/json"}:{},...t()},...r.body!==void 0?{body:JSON.stringify(r.body)}:{}}),o=await i.text();let c=null;try{c=o?JSON.parse(o):null}catch{c=null}if(!i.ok)throw new Error(typeof(c==null?void 0:c.detail)=="string"?c.detail:typeof((l=c==null?void 0:c.detail)==null?void 0:l.message)=="string"?c.detail.message:o||`Gateway request failed (${i.status})`);return c}}function aD({connected:e,request:t,value:n,onChange:r,disabled:i}){const[o,c]=p.useState(null),[l,d]=p.useState(null),h=JSON.stringify(n);p.useEffect(()=>{if(!e){c(null),d(null);return}let g=!0;return d(null),nm(t)(n).then(y=>g&&c(y)).catch(y=>g&&d(`Could not read your workspaces: ${Ig(y)}`)),()=>{g=!1}},[e,h,t]);const m=p.useCallback(async g=>{const y=await nm(t)(g);c(y),r(g)},[t,r]),_=e?i?"The run is starting.":null:"Connect to your gateway to choose workspaces.";return s.jsx(dN,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:o,onChange:m,loadError:e?l:_,unavailableReason:_})}function lD(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class cD{constructor(t){jn(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)||Zs()),i=t!=null&&t.arguments&&typeof t.arguments=="object"?t.arguments:{};if(!n)return{call_id:r,name:"",success:!1,output:null,error:"Missing tool name"};const o={jsonrpc:"2.0",id:Zs(),method:"tools/call",params:{name:n,arguments:i}},c=await fetch(this._cfg.url,{method:"POST",headers:{"Content-Type":"application/json",...lD(this._cfg.auth_token)},body:JSON.stringify(o)});if(!c.ok)return{call_id:r,name:n,success:!1,output:null,error:`Worker HTTP ${c.status}`};const l=await c.json().catch(()=>null),d=l==null?void 0:l.result,h=!!(d!=null&&d.isError),_=(Array.isArray(d==null?void 0:d.content)?d.content:[]).find(y=>y&&y.type==="text"&&typeof y.text=="string"),g=(_==null?void 0:_.text)??"";return h?{call_id:r,name:n,success:!1,output:null,error:g||"Tool failed"}:{call_id:r,name:n,success:!0,output:g,error:null}}}class sk{constructor(t,n){jn(this,"pending",[]);jn(this,"scheduled",!1);jn(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 rk(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 uD(e,t){const n=Vt(e.updated_at||e.created_at)??0;return(Vt(t.updated_at||t.created_at)??0)-n}function dD(e,t){const n=t.query.trim().toLowerCase(),r=[...e],i={};for(const g of r){const y=String(g.run_id||"").trim();y&&(i[y]=g)}for(const g of e){const y=rk(g);if(String(g.role||"")==="occurrence"&&y&&!i[y]){const x={run_id:y,workflow_id:null,status:"",role:"controller",session_kind:"automation",automation_id:y,updated_at:g.updated_at??null,created_at:g.created_at??null};i[y]=x,r.push(x)}}const o={},c={};for(const g of r){const y=String(g.run_id||"").trim();if(!y)continue;const x=rk(g,t.parent_hint?t.parent_hint(y):"");c[y]=x,x&&(o[x]||(o[x]=[])).push(g)}const l=g=>{const y=String(g.status||"").trim().toLowerCase();return t.filter==="all"?!0:t.filter==="active"?Yd(y):t.filter==="waiting"?y==="waiting":t.filter==="terminal"?hs(y):t.filter==="failed"?y==="failed":!0},d=g=>{if(!n)return!0;const y=String(g.workflow_id||g.schedule_target_workflow_id||"").trim(),x=y?t.workflow_label_by_id[y]||y:"";return[g.run_id,y,x,g.session_id,g.status,g.session_kind,g.automation_id].join(" ").toLowerCase().includes(n)},h=[];for(const g of r){const y=String(g.run_id||"").trim();if(!y)continue;const x=c[y];(!x||!i[x])&&h.push(y)}const m={},_=g=>{if(t.group_by==="workflow"){const x=String(g.schedule_target_workflow_id||g.workflow_id||"").trim()||"(unknown workflow)";return{key:x,label:t.workflow_label_by_id[x]||x}}if(t.group_by==="session"){const x=String(g.session_id||"").trim()||"(no session)";return{key:x,label:x}}const y=String(g.status||"").trim().toLowerCase()||"unknown";return Yd(y)?{key:"active",label:"Active"}:y==="failed"?{key:"failed",label:"Failed"}:hs(y)?{key:"finished",label:"Finished"}:{key:y,label:y}};for(const g of h){const y=i[g];if(!y)continue;const x=[...o[g]||[]].sort(uD),k=x.some(N=>l(N)&&d(N));if(!(l(y)&&d(y))&&!k)continue;const v=_(y);m[v.key]||(m[v.key]={key:v.key,label:v.label,rows:[]}),m[v.key].rows.push({run:y,children:x})}return Object.values(m).sort((g,y)=>{const x={active:0,waiting:1,failed:2,finished:3},k=x[g.key]??10,v=x[y.key]??10;return k!==v?k-v:g.label.localeCompare(y.label)})}const ik=60;function Zd(e){try{const t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function Zy(e,t,n){return`${e.toLocaleString("en-US")} ${e===1?t:n}`}function lg(e){if(e===void 0)return"undefined";if(typeof e=="string")return e.length<=ik&&!e.includes(`
137
+ `)?JSON.stringify(e):`text (${Zy(e.length,"char","chars")})`;if(e===null||typeof e!="object")return Zd(e);const t=Zd(e);return t.length<=ik?t:Array.isArray(e)?`list (${Zy(e.length,"item","items")})`:`object (${Zy(Object.keys(e).length,"key","keys")})`}function fD(e){return e===void 0?!1:e&&typeof e=="object"&&!Array.isArray(e)?Object.values(e).some(t=>lg(t)!==Zd(t)):lg(e)!==Zd(e)}function hD(e){if(e===void 0)return"";if(e&&typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e);return t.length?`{${t.map(n=>`${n}: ${lg(e[n])}`).join(", ")}}`:"{}"}return lg(e)}function Pd(e){return Vt(e)}function mD(e){return e==null||e===""?"":typeof e=="string"?e:Zd(e)}function ok(e){return e.length?e[e.length-1]:null}function ak(e,t){var r,i;const n=String(e.status||"").trim().toLowerCase();if(n==="started"||n==="running")return"running";if(n==="waiting"){const o=(i=(r=e.record)==null?void 0:r.result)==null?void 0:i.wait;if(String((o==null?void 0:o.reason)||"")==="subworkflow"){const c=Am(e.record);if(c&&t(c)==="running")return"running"}return"waiting"}return n==="failed"?"failed":n==="completed"||e.ended_at?"done":"running"}function _D(e,t){return e.t===null||t.t===null?e.t===null&&(t.t!==null||e.seq<t.seq):e.t<t.t||e.t===t.t&&e.seq<t.seq}function lk(e){const t=new Map;for(const i of[...e].sort((o,c)=>o.seq-c.seq)){const o=t.get(i.rid)||[];o.push(i),t.set(i.rid,o)}const n=Array.from(t.values()),r=[];for(;n.some(i=>i.length);){let i=null;for(const o of n)if(o.length){if(!i){i=o;continue}_D(o[0],i[0])&&(i=o)}r.push(i.shift())}return r}function pD(e){return Pd(e.ended_at)??Pd(e.started_at)}function gD(e,t,n){var k,v,N,$,C,S,D,O,A,P;const r=String(t||"").trim();if(!r)return{};const i=[],o=new Set;for(const W of e||[]){const J=String((W==null?void 0:W.run_id)||((k=W==null?void 0:W.record)==null?void 0:k.run_id)||"").trim();J&&!o.has(J)&&(o.add(J),i.push(J))}i.sort((W,J)=>W===r?-1:J===r?1:0);const c=new Map;for(const W of i)c.set(W,Pg(e,W));const l=(W,J)=>{const G=String(n(W,J)||"").trim();return!G||W!==r&&G===J?"":G},d=new Map,h=(W,J=0)=>{if(d.has(W))return d.get(W)??null;d.set(W,null);const G=J<6?ok(c.get(W)||[]):null,V=G?ak(G,R=>h(R,J+1)):null;return d.set(W,V),V},m=new Map,_=(W,J)=>{let G=m.get(W);return G||(G={facts:{node_id:J,graph_id:W,run_ids:[],status:"done",visits:0,first_ms:null,last_ms:null,duration_ms:0,last_effect:"",last_status:"",llm:null,tools:[],waits:[],subruns:[],last_result_summary:"",last_result:void 0,last_error:"",context:null,records:[]},steps:[],records:[]},m.set(W,G)),G};let g=0;for(const W of i)for(const J of c.get(W)||[]){const G=String(J.node_id||"").trim();if(!G)continue;const V=l(W,G);if(!V)continue;const R=_(V,G);R.steps.push({step:J,rid:W,t:pD(J),seq:g++}),R.facts.run_ids.includes(W)||R.facts.run_ids.push(W)}const y=(e||[]).filter(W=>W&&W.record).map((W,J)=>({x:W,i:J})).sort((W,J)=>{const G=i.indexOf(String(W.x.run_id||W.x.record.run_id||"").trim()),V=i.indexOf(String(J.x.run_id||J.x.record.run_id||"").trim());return G!==V?G-V:(W.x.cursor||0)-(J.x.cursor||0)||W.i-J.i});g=0;for(const{x:W}of y){const J=String(W.run_id||W.record.run_id||"").trim(),G=String(W.record.node_id||"").trim();if(!J||!G)continue;const V=l(J,G),R=V?m.get(V):void 0;R&&R.records.push({rec:W.record,rid:J,t:Pd(W.record.ended_at)??Pd(W.record.started_at),seq:g++})}const x={};for(const[W,J]of m){const G=J.facts,V=lk(J.steps).map(se=>se.step),R=ok(V);G.visits=V.length,G.status=ak(R,se=>h(se)),G.last_effect=R.effect_type,G.last_status=R.status;let M=0,I=0,L=0,K=!1,H=0,z=null;const ee=new Map;for(const se of V){const de=Pd(se.started_at),be=Pd(se.ended_at)??de;if(de!==null&&(G.first_ms=G.first_ms===null?de:Math.min(G.first_ms,de)),be!==null&&(G.last_ms=G.last_ms===null?be:Math.max(G.last_ms,be)),typeof se.duration_ms=="number"&&(G.duration_ms+=se.duration_ms),se.kind==="llm_call"){H+=1,z=se;const Ne=((N=(v=se.record)==null?void 0:v.result)==null?void 0:N.usage)||((C=($=se.record)==null?void 0:$.result)==null?void 0:C.token_usage)||null;if(Ne&&typeof Ne=="object"){const ae=Number(Ne.prompt_tokens??Ne.input_tokens),je=Number(Ne.completion_tokens??Ne.output_tokens),Te=Number(Ne.total_tokens);(Number.isFinite(ae)||Number.isFinite(je)||Number.isFinite(Te))&&(K=!0,M+=Number.isFinite(ae)?ae:0,I+=Number.isFinite(je)?je:0,L+=Number.isFinite(Te)?Te:(Number.isFinite(ae)?ae:0)+(Number.isFinite(je)?je:0))}}else if(se.kind==="tool"){const Ne=Em(se),ae=Ne.calls.length?Ne.calls.map(je=>je.name):Ne.results.map(je=>je.name);for(const je of ae){const Te=ee.get(je)||{name:je,calls:0,failed:0};Te.calls+=1,ee.set(je,Te)}for(const je of Ne.results){if(je.success!==!1)continue;const Te=ee.get(je.name)||{name:je.name,calls:0,failed:0};Te.failed+=1,ee.set(je.name,Te)}}const Me=mD((S=se.record)==null?void 0:S.error);Me&&(G.last_error=Me),se.record&&Object.prototype.hasOwnProperty.call(se.record,"result")&&se.record.result!==void 0&&se.record.result!==null&&(G.last_result=se.record.result)}if(G.last_result_summary=hD(G.last_result),G.tools=Array.from(ee.values()),H&&z){const se=Cm(z);if(G.llm={calls:H,model:se.model,provider:se.provider},K&&(G.llm.tokens={in:M,out:I,total:L}),se.messages.length||se.system){const de=se.system?[{role:"system",content:se.system},...se.messages]:[...se.messages];G.context={provider:se.provider,model:se.model,messages_source:se.messages_source,messages:de}}}G.records=lk(J.records).map(se=>se.rec);const B=G.status==="waiting"||G.status==="running"&&String(R.status)==="waiting"?String(((A=(O=(D=R.record)==null?void 0:D.result)==null?void 0:O.wait)==null?void 0:A.wait_key)||""):"",te=new Set;for(const se of G.records){const de=(P=se==null?void 0:se.result)==null?void 0:P.wait;if(String(se.status||"")==="waiting"&&de&&typeof de=="object"){const Me=String(de.wait_key||""),Ne=`${String(de.reason||"")}|${Me}`;if(!te.has(Ne)){te.add(Ne);const ae={reason:String(de.reason||""),wait_key:Me,open:!1};typeof de.prompt=="string"&&de.prompt&&(ae.prompt=de.prompt),G.waits.push(ae)}}const be=Am(se);be&&!G.subruns.includes(be)&&G.subruns.push(be)}if(B)for(const se of G.waits)se.open=se.wait_key===B;x[W]=G}return x}function yD(e){const t={};for(const[n,r]of Object.entries(e||{}))t[n]=r.status;return t}function wD(e){const{records:t,context:n,...r}=e;return JSON.stringify(r,null,2)}function vD(e){return e.records.map(t=>Zd(t)).join(`
138
+ `)}function xD(e){return e.context?JSON.stringify(e.context,null,2):""}function Qy(e){return typeof e=="number"&&Number.isFinite(e)?new Date(e).toISOString():null}function bD(e){const t=new Map(e.nodes.map(r=>[r.id,r])),n=e.current_id?t.get(e.current_id):void 0;return{run_id:e.run_id,status:e.status,state:e.state,finished:e.finished,as_of:Qy(e.now_ms)||"",current_node:n?{id:n.id,label:n.label,type:n.type,status:e.status_of(n.id)}:null,nodes:e.nodes.map(r=>{const i=e.facts[r.id];return{id:r.id,label:r.label,type:r.type,status:e.status_of(r.id),visits:i?i.visits:0,first_at:i?Qy(i.first_ms):null,last_at:i?Qy(i.last_ms):null,duration_ms:i?i.duration_ms:0,llm:i?i.llm:null,tools:i?i.tools:[],waits:i?i.waits:[],subruns:i?i.subruns:[],last_result_summary:i?i.last_result_summary:"",last_error:i?i.last_error:""}}),edges:e.edges.map(r=>({source:r.source,target:r.target}))}}const kD={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"},jD=[{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 SD(){const[e,t]=p.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:[jD.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:kD[n.type]},children:n.shape}),s.jsx("span",{className:"pin-legend-label mono",children:n.label}),s.jsx("span",{className:"pin-legend-desc mono",children:n.description})]},n.type)),s.jsxs("div",{className:"pin-legend-rules mono",children:[s.jsx("strong",{children:"Connection Rules:"}),s.jsxs("ul",{children:[s.jsx("li",{children:"Execution connects to Execution only"}),s.jsx("li",{children:'"Any" type accepts all data types'}),s.jsx("li",{children:"Same types always compatible"}),s.jsx("li",{children:"Array and Object are interchangeable"}),s.jsx("li",{children:'"Tools" is compatible with Array (specialized string[])'})]})]})]})]})}const hv={execution:"#FFFFFF",string:"#FF00FF",number:"#00FF00",boolean:"#FF0000",object:"#00FFFF",json_schema:"#00FFFF",artifact:"#5EEAD4",artifact_image:"#19D3B8",artifact_audio:"#22D3EE",artifact_text:"#D946EF",artifact_video:"#A855F7",artifacts:"#2DD4BF",artifacts_image:"#0F766E",artifacts_audio:"#0891B2",artifacts_text:"#C026D3",artifacts_video:"#7C3AED",workspace_file:"#84CC16",workspace_folder:"#65A30D",memory:"#00C49A",assertion:"#00B8D4",assertions:"#00B8D4",array:"#FF8800",tools:"#FF8800",provider:"#00D2FF",model:"#9D4EDD",provider_text:"#00D2FF",model_text:"#9D4EDD",provider_image:"#19D3B8",model_image:"#9D4EDD",provider_video:"#A855F7",model_video:"#9D4EDD",provider_voice:"#22D3EE",model_voice:"#9D4EDD",provider_music:"#F59E0B",model_music:"#9D4EDD",agent:"#4488FF",email:"#FBBF24",emails:"#D97706",any:"#888888"};function ND(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(hv,e)}function $D(e){return ND(e)?hv[e]:hv.any}function CD(e){switch(e){case"execution":return"triangle";case"boolean":return"diamond";case"array":case"tools":case"assertions":return"square";case"agent":return"hexagon";default:return"circle"}}const ED=280,AD=6,TD=360,MD=1500;function B1(e,t=ED,n=AD){const r=String(e??"");let i=r.length,o=-1;for(let c=0;c<n&&(o=r.indexOf(`
139
+ `,o+1),o!==-1);c+=1)c===n-1&&(i=Math.min(i,o));return i=Math.min(i,t),i>=r.length?{shown:r,clamped:!1}:{shown:`${r.slice(0,i).trimEnd()}…`,clamped:!0}}function al(e){if(e===void 0)return"";if(typeof e=="string")return e;if(e===null||typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function RD(e){return e===null||["string","number","boolean"].includes(typeof e)}function ck(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function LD(e){if(Array.isArray(e)){const t=e.length,n=`array · ${t} item${t===1?"":"s"}`;if(!t)return{head:n,items:[],item_word:"items"};if(e.every(RD))return{head:n,items:e.map(o=>String(o)),item_word:"items"};const r=new Map;for(const o of e)r.set(ck(o),(r.get(ck(o))||0)+1);const i=[...r.entries()].map(([o,c])=>`${c} ${o}${c===1||o==="null"?"":"s"}`);return{head:`${n} (${i.join(", ")})`,items:[],item_word:"items"}}if(e&&typeof e=="object"){const t=e,n=Object.keys(t);return n.length===1&&typeof t.$artifact=="string"?{head:`artifact ${String(t.$artifact)}`,items:[],item_word:"keys"}:{head:`object · ${n.length} key${n.length===1?"":"s"}`,items:n,item_word:"keys"}}return{head:al(e),items:[],item_word:"items"}}function ID(e,t=TD){let n=0;for(let r=0;r<e.length;r+=1)if(n+=e[r].length+(r?2:0),n>t)return r;return e.length}function zg(e){const[t,n]=p.useState("");p.useEffect(()=>{if(!t)return;const i=window.setTimeout(()=>n(""),MD);return()=>window.clearTimeout(i)},[t]);const r=`Copy ${e.label}`;return s.jsx("button",{type:"button",className:`ap_copy_btn${t?` is_${t}`:""}${e.className?` ${e.className}`:""}`,title:r,"aria-label":r,onClick:async i=>{if(i.stopPropagation(),e.on_copy){e.on_copy(e.text),n("copied");return}n(await Mm(e.text)?"copied":"failed")},children:t==="copied"?"copied":t==="failed"?"copy failed":"⧉"})}function U1(e){const t=e.size??12,n=t/2,r=e.filled?"currentColor":"none",i=CD(e.type);let o;if(i==="triangle")o=s.jsx("polygon",{points:`0,0 ${t},${n} 0,${t}`,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="diamond")o=s.jsx("polygon",{points:`${n},0 ${t},${n} ${n},${t} 0,${n}`,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="square")o=s.jsx("rect",{x:"1",y:"1",width:t-2,height:t-2,fill:r,stroke:"currentColor",strokeWidth:"1.5"});else if(i==="hexagon"){const c=[[n,0],[t,t*.25],[t,t*.75],[n,t],[0,t*.75],[0,t*.25]].map(([l,d])=>`${l},${d}`).join(" ");o=s.jsx("polygon",{points:c,fill:r,stroke:"currentColor",strokeWidth:"1.5"})}else o=s.jsx("circle",{cx:n,cy:n,r:n-1,fill:r,stroke:"currentColor",strokeWidth:"1.5"});return s.jsx("svg",{className:"ap_pin_glyph","data-pin-shape":i,width:t,height:t,viewBox:`0 0 ${t} ${t}`,style:{color:$D(e.type)},"aria-hidden":"true",children:o})}function OD(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=B1(e.text);return e.text?s.jsxs("span",{className:"ap_pin_string",children:[s.jsx("span",{className:"ap_pin_text",children:t||!i?e.text:r}),i?s.jsx("button",{type:"button",className:"ap_link_btn","aria-expanded":t,onClick:()=>n(o=>!o),children:t?"show less":`show all (${e.text.length.toLocaleString("en-US")} chars)`}):null]}):s.jsx("span",{className:"ap_pin_muted",children:"empty text"})}function PD(e){const[t,n]=p.useState(!1),r=ID(e.items),o=r<e.items.length&&!t?e.items.slice(0,r):e.items;return s.jsxs("span",{className:"ap_json_items",children:[s.jsx("span",{className:"ap_json_list",children:o.join(", ")}),r<e.items.length?s.jsx("button",{type:"button",className:"ap_link_btn","aria-expanded":t,onClick:()=>n(c=>!c),children:t?"show less":`show all ${e.items.length.toLocaleString("en-US")} ${e.word}`}):null]})}function DD(e){const[t,n]=p.useState(!1),r=LD(e.value);return s.jsxs("div",{className:"ap_json",children:[s.jsxs("div",{className:"ap_json_head",children:[s.jsxs("span",{className:"ap_json_shape mono",children:[r.head,r.items.length?":":""]}),r.items.length?s.jsx(PD,{items:r.items,word:r.item_word}):null]}),s.jsxs("details",{className:"ap_json_details",open:t,onToggle:i=>n(i.currentTarget.open),children:[s.jsx("summary",{className:"mono",children:"full JSON"}),t?s.jsx("pre",{className:"ap_json_body mono",children:al(e.value)}):null]})]})}function am(e){const t=e.value;return t===void 0?s.jsx("span",{className:"ap_pin_muted",children:"—"}):t===null?s.jsx("code",{className:"ap_pin_scalar ap_pin_muted",children:"null"}):typeof t=="string"?s.jsx(OD,{text:t}):typeof t=="number"||typeof t=="boolean"||typeof t=="bigint"?s.jsx("code",{className:"ap_pin_scalar",children:String(t)}):typeof t=="object"?s.jsx(DD,{value:t}):s.jsx("code",{className:"ap_pin_scalar",children:String(t)})}function FD(e){return e.state==="value"?al(e.value):e.state==="not_provided"&&e.flow_default?al(e.flow_default.value):null}function zD(e){const{pin:t}=e;if(t.state==="value")return s.jsx(am,{value:t.value});if(t.state==="not_provided")return s.jsxs("div",{className:"ap_pin_muted ap_pin_unsent",children:[s.jsx("span",{children:"not provided"}),t.flow_default?s.jsxs("div",{className:"ap_pin_default",children:[s.jsx("span",{className:"ap_pin_default_label",children:"flow default"})," ",s.jsx(am,{value:t.flow_default.value})]}):null,t.required&&!t.flow_default?s.jsx("span",{className:"ap_pin_required",children:" · required"}):null]});const n=t.state==="unknown"?"not loaded":e.side==="out"?e.outputs_final?"not in the run's output":"no output until the run ends":"no value";return s.jsx("span",{className:"ap_pin_muted",title:n,children:"—"})}function BD(e){const{pin:t}=e,n=t.typed?t.type:"untyped",r=FD(t);return s.jsxs("li",{className:`ap_pin ap_pin_${t.state} ap_copyable`,"data-pin-id":t.id,"data-pin-state":t.state,children:[s.jsxs("span",{className:"ap_pin_head",title:t.description||void 0,children:[s.jsx(U1,{type:t.type,filled:t.state==="value"}),s.jsx("span",{className:"ap_pin_name",children:t.label}),s.jsx("span",{className:"ap_pin_type mono",children:n}),r!==null?s.jsx(zg,{text:r,label:t.state==="value"?t.label:`${t.label} flow default`,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(zD,{pin:t,side:e.side,outputs_final:e.outputs_final})})]})}function uk(e){const t=e.also||[],n=e.outputs_final===!0;return s.jsxs("div",{className:"ap_pins","aria-label":e.label,children:[e.pins.length?s.jsx("ul",{className:"ap_pin_list",children:e.pins.map(r=>s.jsx(BD,{pin:r,side:e.side,outputs_final:n,on_copy:e.on_copy},r.id))}):s.jsx("p",{className:"ap_pin_muted ap_pins_empty",children:e.empty_text||"no pins"}),t.length?s.jsxs("div",{className:"ap_pins_also",children:[s.jsx("div",{className:"ap_pins_also_label",children:e.also_label||"also on the wire"}),s.jsx("ul",{className:"ap_pin_list",children:t.map(([r,i])=>s.jsxs("li",{className:"ap_pin ap_pin_also ap_copyable","data-pin-id":r,"data-pin-state":"also",children:[s.jsxs("span",{className:"ap_pin_head",children:[s.jsx(U1,{type:"any",filled:!0}),s.jsx("span",{className:"ap_pin_name",children:r}),s.jsx("span",{className:"ap_pin_type mono",children:"not a pin"}),i!==void 0?s.jsx(zg,{text:al(i),label:r,on_copy:e.on_copy}):null]}),s.jsx("div",{className:"ap_pin_value",children:s.jsx(am,{value:i})})]},r))})]}):null]})}const mv=5*6e4;function UD(e){const t=new Map,n=new Map;for(const r of e||[]){const i=String((r==null?void 0:r.run_id)||"").trim();i&&t.set(i,r)}for(const r of t.values()){const i=String((r==null?void 0:r.parent_run_id)||"").trim();if(!i)continue;const o=n.get(i)||[];o.push(r),n.set(i,o)}return{by_id:t,children_of:n}}function Sx(e,t){const{by_id:n,children_of:r}=UD(e);return{by_id:n,children_of:r,now_ms:Date.now(),...t||{}}}function W1(e,t){var i;const n=(i=t.details)==null?void 0:i.get(String((e==null?void 0:e.run_id)||"")),r=(n==null?void 0:n.waiting)??(e==null?void 0:e.waiting);return r&&typeof r=="object"?r:null}function WD(e,t){return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function qD(e,t,n){var o,c;const r=(o=t.details)==null?void 0:o.get(String((e==null?void 0:e.run_id)||""));return(e==null?void 0:e.paused)===!0||(r==null?void 0:r.paused)===!0||String((n==null?void 0:n.wait_key)||"").startsWith("pause:")?!0:String(((c=n==null?void 0:n.details)==null?void 0:c.kind)||"").trim().toLowerCase()==="pause"}function dk(e){return e?String(e.prompt||"").trim()?!0:Array.isArray(e.choices)&&e.choices.length>0:!1}function _v(e){return Vt((e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||"")}function er(e){const t=Math.max(0,Math.floor(e/1e3)),n=Math.floor(t/60),r=Math.floor(n/60),i=Math.floor(r/24);return i>0?`${i}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}function VD(e,t){return e===null?"":er(t-e)}function fk(e,t){if(e===null)return"";const n=new Date(e).toISOString().slice(11,16),r=e-t;return r>0?`${n} UTC (in ${sm(r)})`:`${n} UTC (due)`}function Dd(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const HD=6e4;function GD(e,t){var c;const n=W1(e,t),r=String(((c=n==null?void 0:n.details)==null?void 0:c.sub_run_id)||"").trim();if(r&&t.by_id.has(r))return t.by_id.get(r)||null;const o=(t.children_of.get(String((e==null?void 0:e.run_id)||""))||[]).filter(l=>!hs(String((l==null?void 0:l.status)||"")));return o.length?(o.sort((l,d)=>(_v(d)??0)-(_v(l)??0)),o[0]):null}function Bg(e){const t=String(e||"").trim();if(!t)return"";const n=t.match(/^visual_react_agent_(.+)$/);if(n){const l=n[1],d=l.match(/^(.+?)_(\d+)_(\d+)_(\d+)_(.+)$/);if(d){const h=d[1];let m=d[5];return m.startsWith(`${h}_`)?m=m.slice(h.length+1):m=m.replace(/^[^_]+_/,""),m||l}return l}const r=t.indexOf("@"),i=t.indexOf(":",r<0?0:r),o=r>=0?t.slice(0,r):i>=0?t.slice(0,i):t,c=i>=0?t.slice(i+1):"";return c&&!/^[0-9a-f]{8,}$/i.test(c)?c:o||si(t)}function KD(e){const t=String(e||"").trim(),n=si(t);return n&&n!==t?`${n} — ${t}`:t}function q1(e,t){var r,i;const n=String((e==null?void 0:e.run_id)||"");return String(((i=(r=t.details)==null?void 0:r.get(n))==null?void 0:i.current_node)||(e==null?void 0:e.current_node)||"").trim()}function si(e){const t=String(e||"").trim();if(!t)return"";const n=t.includes("@")?t.split(":")[0]:t,[r,i]=n.split("@"),o=String(r||"").split(".").pop()||r||"";return i?`${o} ${i}`:o}function Qd(e){const t=String(e||"").trim();return t.length>14?`${t.slice(0,6)}…${t.slice(-6)}`:t}function ef(e,t,n=0){const r=JD(e,t,n);return{...r,brief:r.brief||r.text}}function JD(e,t,n=0){var N,$,C,S,D,O,A,P,W,J,G;const r=t.now_ms,i=typeof t.stall_after_ms=="number"?t.stall_after_ms:mv,o=String((e==null?void 0:e.run_id)||"").trim(),c=String((e==null?void 0:e.status)||"").trim().toLowerCase(),l=W1(e,t),d=WD(e,l),h=_v(e),m=String((e==null?void 0:e.role)||"").trim(),_={verb:"waiting",lane:"waiting_on",object:"",actor:"unknown",actor_run_id:"",action:"inspect",since_ms:h,stale_ms:null,stalled:!1,open_step:"",unresolved:!1,text:"",brief:""},g=VD(h,r),y=g?` · ${g}`:"";if(hs(c)){const V=rm(e),R=String((e==null?void 0:e.error)||"").trim(),M=(N=t.details)==null?void 0:N.get(o),I=Vt((e==null?void 0:e.created_at)||""),L=Vt((e==null?void 0:e.updated_at)||""),K=I!==null&&L!==null&&L>=I?er(L-I):"";let H=V;V==="failed"?H=R?`failed: ${Dd(R,120)}`:"failed":V==="completed"?H=K?`completed in ${K}`:"completed":V==="stopped"?H="stopped before the turn finished":V==="cancelled"&&(H="cancelled");const z=String((M==null?void 0:M.error)||"").trim();return V==="failed"&&!R&&z&&(H=`failed: ${Dd(z,120)}`),{..._,verb:"done",lane:"done",object:H,actor:"none",action:"open_run",text:H}}if(m==="controller"){const V=($=t.automations)==null?void 0:$.get(String((e==null?void 0:e.automation_id)||o)),R=Vt((l==null?void 0:l.until)||""),M=(V==null?void 0:V.next_fire_ms)??R,I=[];V!=null&&V.current&&!hs(V.current.status)?I.push(`run #${V.current.index} in progress`):d==="subworkflow"&&I.push("a run is in progress"),(V==null?void 0:V.status)==="paused"?I.push("paused: scheduled runs are skipped"):M!==null?I.push(`next run in ${sm(Math.max(0,M-r))}`):(V==null?void 0:V.status)==="completed"||(V==null?void 0:V.status)==="failed"?I.push(`${V.status}: no next run`):V!=null&&V.event_driven?I.push("listening"):((C=V==null?void 0:V.trigger)==null?void 0:C.source_id)==="manual"?I.push("runs when someone presses Run now"):I.push("next run not scheduled"),V!=null&&V.last&&I.push(`last #${V.last.index} ${V.last.status}`),V&&I.push(`${V.occurrence_count} turn${V.occurrence_count===1?"":"s"}`);const L=I.join(" · ");return{..._,verb:"scheduled",lane:"scheduled",object:L,actor:"clock",action:"open_run",text:L}}if((e==null?void 0:e.is_draft)===!0){const V="draft · not started";return{..._,verb:"scheduled",lane:"scheduled",object:V,actor:"none",action:"open_run",text:V}}if(c==="running"){const V=((S=t.pulses)==null?void 0:S.get(o))||null,R=V&&V.ended_ms===null&&V.started_ms!==null?V:null,M=Math.max(h??0,(V==null?void 0:V.ended_ms)??0,(V==null?void 0:V.started_ms)??0)||null,I=M?Math.max(0,r-M):null,L=I!==null&&I>i,K=R?`${R.effect||R.node_id||"step"} open ${er(r-R.started_ms)}`:"",H=String(((O=(D=t.details)==null?void 0:D.get(o))==null?void 0:O.current_node)||(e==null?void 0:e.current_node)||"").trim(),z=["running"];return H&&z.push(`step ${H}`),K?z.push(K):I!==null&&z.push(`last step ${er(I)} ago`),L&&z.push("no progress"),{..._,verb:"running",lane:"working",object:K||H||"",actor:"runtime",action:"open_run",stale_ms:I,stalled:L,open_step:K,text:z.join(" · ")}}if(c!=="waiting"){if((e==null?void 0:e.is_scheduled)===!0){const R=e!=null&&e.schedule_interval?`scheduled · every ${e.schedule_interval}`:"scheduled";return{..._,verb:"scheduled",lane:"scheduled",object:R,actor:"clock",action:"open_run",text:R}}const V=c?`${c}${y}`:"state unknown";return{..._,object:V,text:V,action:"inspect"}}if(qD(e,t,l)){const V=`paused${y} · resume when ready`;return{..._,verb:"paused",lane:"needs_you",object:"paused",actor:"you",action:"resume",text:V}}const x=af(l);if(x.length){const V=x.map(I=>String((I==null?void 0:I.name)||"tool").trim()).filter(Boolean),R=`${V.slice(0,3).join(", ")}${V.length>3?` +${V.length-3}`:""}`,M=`needs your approval: ${R||"tool call"}${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`approval: ${R}`,actor:"you",action:"approve",text:M}}if(d==="user"){if(dk(l)){const M=Dd(String((l==null?void 0:l.prompt)||""),80),I=M?`asks: ${M}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:M||"a question",actor:"you",action:"answer",text:I,brief:`asks a question${y}`}}if(((A=t.details)==null?void 0:A.has(o))===!0){const M=`waits for your answer${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:"your answer",actor:"you",action:"answer",text:M}}const R=`needs you: question, approval or pause${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:"question, approval or pause",actor:"you",action:"open_run",unresolved:!0,text:R}}if(d==="subworkflow"){const V=n<4?GD(e,t):null;if(!V){const L=String(((P=l==null?void 0:l.details)==null?void 0:P.sub_run_id)||"").trim(),K=L?(W=t.fates)==null?void 0:W.get(L):void 0,z=q1(e,t)||K&&Bg(K.workflow_id)||Qd(L);if(K&&K.status==="missing"){const B=`stuck: subrun ${z} no longer exists${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`subrun ${z} (missing)`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:z,status:"missing",ended_ms:null},text:B}}if(K&&hs(K.status)){const B=Vt(K.updated_at),te=B!==null?Math.max(0,t.now_ms-B):null;if(te!==null&&te<=HD){const Me=`its subrun ${z} ${K.status} ${er(te)} ago · resuming${y}`;return{..._,verb:"running",lane:"working",object:`subrun ${z}`,actor:"runtime",action:"open_run",text:Me}}const se=te!==null?` ${er(te)} ago`:"",de=K.status==="cancelled"?"was cancelled":K.status==="failed"?"failed":`ended ${K.status}`,be=`stuck: subrun ${z} ${de}${se}, this run was not resumed${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`subrun ${z} (${K.status})`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:z,status:K.status,ended_ms:te},text:be}}if(L){const B=`waiting for its subrun ${z} to finish${y}`;return{..._,object:`subrun ${z}`,actor:"run",actor_run_id:L,action:"open_subrun",text:B}}const ee=`waiting for a subrun to finish${y}`;return{..._,object:"a subrun",actor:"run",action:"open_run",text:ee}}const R=ef(V,t,n+1),M=si(String(V.workflow_id||""))||Qd(String(V.run_id||""));if(R.verb==="running"){const L=[`running subrun ${M}`];return R.open_step?L.push(R.open_step):R.stale_ms!==null&&L.push(`last step ${er(R.stale_ms)} ago`),R.stalled&&L.push("no progress"),{..._,verb:"running",lane:"working",object:`subrun ${M}`,actor:"run",actor_run_id:String(V.run_id||""),action:"open_subrun",stale_ms:R.stale_ms,stalled:R.stalled,open_step:R.open_step,text:L.join(" · ")}}const I=`waiting for subrun ${M}: ${R.brief||R.text}`;return{..._,verb:"waiting",lane:"waiting_on",object:`subrun ${M}`,actor:"run",actor_run_id:String(V.run_id||""),action:"open_subrun",unresolved:R.unresolved,text:I}}if(d==="until"){const V=Vt((l==null?void 0:l.until)||""),R=V!==null?`sleeps until ${fk(V,r)}`:`sleeps until an unknown time${y}`,M=(e==null?void 0:e.is_scheduled)===!0;return{..._,...M?{verb:"scheduled",lane:"scheduled"}:{},object:"the clock",actor:"clock",action:"open_run",text:R}}if(d==="event"){if(dk(l)){const L=Dd(String((l==null?void 0:l.prompt)||""),80),K=L?`asks: ${L}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:L||"a question",actor:"you",action:"answer",text:K,brief:`asks a question${y}`}}const V=Vt((l==null?void 0:l.until)||""),R=String(((J=l==null?void 0:l.details)==null?void 0:J.event)||((G=l==null?void 0:l.details)==null?void 0:G.name)||"").trim(),M=R?`event ${R}`:"an event",I=V!==null?`waiting for ${M} until ${fk(V,r)}`:`waiting for ${M}${y}`;return{..._,object:M,actor:"external",action:"open_run",text:I}}if(d==="job"){const V=`waiting for a delegated tool job${y}`;return{..._,object:"a delegated tool job",actor:"runtime",action:"open_run",text:V}}const k=String((l==null?void 0:l.wait_key)||"").trim(),v=`waiting, reason unknown${k?` (${k})`:""}${y} · inspect`;return{..._,object:"unknown",actor:"unknown",action:"inspect",text:v}}function V1(e,t,n,r){if(String((e==null?void 0:e.role)||"").trim()==="controller")return(r==null?void 0:r.status)==="paused"?"paused":r!=null&&r.event_driven?"listening":"scheduled";if(t.stuck)return"stuck";const i=rm({status:e==null?void 0:e.status,paused:(e==null?void 0:e.paused)===!0||t.verb==="paused",stop_reason:n??null});return t.verb==="running"&&i==="waiting"?"running":i}const ew={automation:"⟳",agent:"◉",run:"▭"};function H1(e,t){var d;const n=String((e==null?void 0:e.role)||"").trim(),r=String((e==null?void 0:e.session_kind)||"").trim(),i=String((e==null?void 0:e.automation_id)||"").trim(),o=i?(d=t.automations)==null?void 0:d.get(i):void 0,c=si(String((e==null?void 0:e.workflow_id)||""));if(n==="controller"||n==="occurrence"||n==="descendant"||n==="discussion"||r==="automation"){const h=[];return n==="occurrence"&&typeof(e==null?void 0:e.occurrence_index)=="number"?h.push(`run #${e.occurrence_index}`):n==="descendant"&&typeof(e==null?void 0:e.occurrence_index)=="number"?h.push(`run #${e.occurrence_index} · subrun`):n==="discussion"&&h.push("discussion"),c&&n!=="controller"&&!(o!=null&&o.title)&&h.push(c),n==="controller"&&o&&h.push(o.cadence),{kind:"automation",glyph:ew.automation,label:(o==null?void 0:o.title)||"",secondary:h.join(" · "),automation_id:i,id_hint:i}}const l=String((e==null?void 0:e.session_id)||"").trim();if(l){const h=[c,String((e==null?void 0:e.parent_run_id)||"").trim()?"subrun":""].filter(Boolean);return{kind:"agent",glyph:ew.agent,label:"session",secondary:h.join(" · "),automation_id:"",id_hint:l}}return{kind:"run",glyph:ew.run,label:"",secondary:c,automation_id:"",id_hint:""}}function G1(e,t,n){var _,g,y;const r=String((e==null?void 0:e.automation_id)||"").trim(),i=r?(_=t.automations)==null?void 0:_.get(r):void 0;if(i!=null&&i.title)return{text:i.title,source:"automation",untitled:!1};const o=String(((g=e==null?void 0:e.brief)==null?void 0:g.title)||"").trim();if(o)return{text:o,source:"brief",untitled:!1};const c=String(((y=e==null?void 0:e.brief)==null?void 0:y.task_excerpt)||"").trim();if(c)return{text:Dd(c,80),source:"brief",untitled:!1};const l=String((e==null?void 0:e.session_kind)||"").trim(),d=String((e==null?void 0:e.role)||"").trim();return!(!!r||l==="automation"||d==="occurrence"||d==="descendant"||d==="controller")&&(n!=null&&n.excerpt)?{text:Dd(n.excerpt,80),source:"excerpt",untitled:!1}:{text:si(String((e==null?void 0:e.workflow_id)||""))||"(workflow?)",source:"workflow",untitled:!0}}function Nx(e,t=""){var r;if(!e||typeof e!="object")return"";const n=String((e==null?void 0:e.source_id)||"").trim();if(n==="schedule"){if(t)return t;const i=String(((r=e==null?void 0:e.config)==null?void 0:r.every)||"").trim();return i?`every ${i}`:"scheduled"}return n?qO(e):""}function Rm(e){var k,v,N,$,C,S,D,O;const t=e!=null&&e.summary&&typeof e.summary=="object"?e.summary:null,n=e!=null&&e.definition&&typeof e.definition=="object"?e.definition:null,r=String((t==null?void 0:t.automation_id)||(e==null?void 0:e.automation_id)||"").trim();if(!r)return null;const i=(k=n==null?void 0:n.target)!=null&&k.input_data&&typeof n.target.input_data=="object"?n.target.input_data:{},o=t!=null&&t.last_occurrence&&typeof t.last_occurrence=="object"?t.last_occurrence:null,c=t!=null&&t.current_occurrence&&typeof t.current_occurrence=="object"?t.current_occurrence:null,l=Array.isArray(i==null?void 0:i.tools)?i.tools.map(A=>String(A)).filter(Boolean):[],d=Array.isArray((v=n==null?void 0:n.notify)==null?void 0:v.channels)?n.notify.channels.map(A=>String(A)):[],h=Array.isArray(t==null?void 0:t.capabilities)?t.capabilities.map(A=>String(A)):[],m=i!=null&&i._runtime&&typeof i._runtime=="object"?i._runtime:{},_=A=>Array.isArray(A)?A.map(P=>String(P)).filter(Boolean):null,g=t!=null&&t.trigger&&typeof t.trigger=="object"?t.trigger:n!=null&&n.trigger&&typeof n.trigger=="object"?n.trigger:null,y=g?{source_id:String(g.source_id||""),source_version:Number(g.source_version||0),config:g.config&&typeof g.config=="object"?g.config:{}}:null,x=(y==null?void 0:y.source_id)==="schedule"?String((t==null?void 0:t.schedule_rule_text)||"").trim():"";return{automation_id:r,title:String((t==null?void 0:t.title)||(n==null?void 0:n.title)||"").trim(),status:String((t==null?void 0:t.status)||"").trim(),cadence:String((t==null?void 0:t.trigger_text)||"").trim()||Nx(y,x),trigger_text:String((t==null?void 0:t.trigger_text)||"").trim(),trigger:y,event_driven:uc(y),time_zone:String((t==null?void 0:t.time_zone)||"").trim(),next_fire_ms:Vt((t==null?void 0:t.next_run_at)||(t==null?void 0:t.next_fire_at)||""),last:o?{index:Number(o.index||0),status:String(o.status||""),fired_ms:Vt(o.fired_at||""),finished_ms:Vt(o.finished_at||"")}:null,occurrence_count:typeof(t==null?void 0:t.occurrence_count)=="number"?t.occurrence_count:0,current:c?{index:Number(c.index||0),run_id:String(c.run_id||""),status:String(c.status||"")}:null,context_mode:String((t==null?void 0:t.context_mode)||((N=n==null?void 0:n.context)==null?void 0:N.mode)||"").trim(),growing_max_tokens:typeof(t==null?void 0:t.growing_max_tokens)=="number"?t.growing_max_tokens:null,model:String((i==null?void 0:i.model)||"").trim(),provider:String((i==null?void 0:i.provider)||"").trim(),tools:l,max_iterations:typeof(i==null?void 0:i.max_iterations)=="number"?i.max_iterations:null,tool_approval:String((($=n==null?void 0:n.policy)==null?void 0:$.tool_approval)||"").trim(),allowed_tools:_(m.allowed_tools),untrusted_input_tools:_((C=n==null?void 0:n.policy)==null?void 0:C.untrusted_input_tools),email_allowed_recipients:_((S=n==null?void 0:n.policy)==null?void 0:S.email_allowed_recipients),workspace_access_mode:String((i==null?void 0:i.workspace_access_mode)||"").trim(),notify_channels:d,task:String((i==null?void 0:i.prompt)||((D=i==null?void 0:i.context)==null?void 0:D.task)||"").trim(),workspace_root:String((t==null?void 0:t.workspace_root)||(n==null?void 0:n.workspace_root)||"").trim(),can_revise:h.includes("revise"),capabilities:h,legacy:(t==null?void 0:t.legacy)===!0,schedule_rule_text:x,next_run_local:String((t==null?void 0:t.next_run_local)||"").trim(),paused_reason:String((t==null?void 0:t.paused_reason)||"").trim(),context_used_tokens:typeof(t==null?void 0:t.context_used_tokens)=="number"&&Number.isFinite(t.context_used_tokens)&&t.context_used_tokens>=0?t.context_used_tokens:null,last_run_id:String((o==null?void 0:o.run_id)||"").trim(),last_excerpt:String((o==null?void 0:o.excerpt)||"").trim(),last_notification_text:String(((O=t==null?void 0:t.last_notification)==null?void 0:O.text)||"").trim()}}function YD(e,t,n){var i;const r=n!=null&&n.record&&typeof n.record=="object"?n.record:n;return!r||typeof r!="object"?null:{run_id:String(e||"").trim(),ledger_len:Number(t||0),node_id:String(r.node_id||"").trim(),effect:String(((i=r==null?void 0:r.effect)==null?void 0:i.type)||"").trim(),status:String(r.status||"").trim(),started_ms:Vt(r.started_at||""),ended_ms:Vt(r.ended_at||"")}}function Rn(e){return typeof e=="string"?e:e==null?"":String(e)}function hk(e,t){const n=Rn(e).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function K1(e){const t=Rn(e==null?void 0:e.targetHandle),n=Rn(e==null?void 0:e.sourceHandle);return!!(t==="exec-in"||n==="exec-out"||t.includes("exec")||n.includes("exec"))}function J1(e){if(!e||typeof e!="object")return"";const t=e!=null&&e.data&&typeof e.data=="object"?e.data:{};return Rn((t==null?void 0:t.nodeType)||(e==null?void 0:e.type)||"").trim()}function Y1(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=Rn(n).trim();if(!r)return"";if(r.includes(":")){const i=r.split(":",2);if(i.length===2&&i[1])return i[1].trim()}return r}function XD(e){const t=Rn(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(J1(r)==="on_flow_start"){const i=Rn(r==null?void 0:r.id).trim();if(i)return i}return""}function tw(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 Nh(e,t){const n=Rn(e).trim(),r=Rn(t).trim();return r?n?`${n}::${r}`:r:""}function ZD(e){const t=e.root&&typeof e.root=="object"?e.root:{};if(!e.expand_subflows)return t;const n=[],r=[],i=new Set,o=(c,l,d,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:[],_=Array.isArray(c.edges)?c.edges:[];for(const g of m){const y=Rn(g==null?void 0:g.id).trim();if(!y)continue;const x=Nh(l,y);if(!x||i.has(x))continue;const k=tw(g),v={...g,id:x,position:{x:k.x+d.x,y:k.y+d.y}};if(n.push(v),i.add(x),n.length>=e.max_nodes)break}for(const g of _){if(!K1(g))continue;const y=Rn(g==null?void 0:g.source).trim(),x=Rn(g==null?void 0:g.target).trim();if(!y||!x)continue;const k=Nh(l,y),v=Nh(l,x);if(!k||!v)continue;const N=Rn(g==null?void 0:g.id).trim(),$=N?`${k}->${v}::${N}`:`${k}->${v}`;if(r.push({...g,id:$,source:k,target:v}),r.length>=e.max_edges)break}if(!(h>=e.max_depth))for(const g of m){if(n.length>=e.max_nodes||r.length>=e.max_edges)return;if(J1(g)!=="subflow")continue;const y=Y1(g);if(!y)continue;const x=e.flow_by_id[y];if(!x||typeof x!="object")continue;const k=Nh(l,Rn(g==null?void 0:g.id));if(!k)continue;const v=XD(x);if(!v)continue;const $=(Array.isArray(x.nodes)?x.nodes:[]).find(W=>Rn(W==null?void 0:W.id).trim()===v)||null;if(!$)continue;const C=tw(g),S=tw($),A={x:C.x+d.x+240-S.x,y:C.y+d.y+0-S.y},P=Nh(k,v);r.push({id:`${k}=>${P}`,source:k,target:P,sourceHandle:"exec-out",targetHandle:"exec-in"}),o(x,k,A,h+1)}};return o(t,"",{x:0,y:0},0),{...t,id:Rn(t.id),nodes:n,edges:r}}function QD(e){const t=Rn(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 e5(e){const t=e.nodes.filter(o=>e.keep_id(o.id)),n=new Set(t.map(o=>o.id)),r={};for(const o of e.edges)r[o.source]||(r[o.source]=[]),r[o.source].push(o.target);const i=new Map;for(const o of t){const c=new Set,l=(r[o.id]||[]).slice();for(;l.length;){const d=l.pop();if(!d||c.has(d))continue;if(c.add(d),n.has(d)){const m=`${o.id}->${d}`;i.has(m)||i.set(m,{id:m,source:o.id,target:d});continue}const h=r[d]||[];for(const m of h)c.has(m)||l.push(m);if(i.size>=e.max_edges)break}if(i.size>=e.max_edges)break}return{nodes:t,edges:Array.from(i.values())}}function mk(e,t){const i=Math.max(t.w*8,160),o=Math.max(t.h*8,120),c=Math.max(160,Math.min(i,e.w)),l=Math.max(120,Math.min(o,e.h));return{x:e.x,y:e.y,w:c,h:l}}const t5=new Set(["completed","failed","cancelled","stopped"]),X1={running:"here",waiting:"waiting here",failed:"failed here",done:"here",none:"here"},Z1={running:"running",waiting:"waiting",failed:"failed",done:"done",none:"not visited"},Q1={user:"waiting for you",subworkflow:"waiting for its subrun",until:"waiting for the clock",event:"waiting for an event",job:"waiting for a tool job"};function e$(e){const t=(e==null?void 0:e.waits.find(n=>n.open))||null;return t?Q1[t.reason]||`waiting (${t.reason||"reason not recorded"})`:"waiting, reason not recorded"}function Qc(e){return e==="running"?3:e==="waiting"?2:0}function _k(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);return[t.getHours(),t.getMinutes(),t.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}const pk=typeof window>"u"?p.useEffect:p.useLayoutEffect;function n5(e){const t=e.status;if(t==="none")return null;let n;return t==="running"?n=s.jsx("circle",{className:"flow_badge_spin",r:4,fill:"none",strokeDasharray:"18 8"}):t==="waiting"?n=s.jsx("path",{d:"M -2 -3.5 V 3.5 M 2 -3.5 V 3.5"}):t==="failed"?n=s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M 0 -4 V 1"}),s.jsx("circle",{className:"flow_badge_dot",cx:0,cy:3.6,r:.9})]}):n=s.jsx("path",{d:"M -3.5 0.2 L -1 2.8 L 3.6 -2.6"}),s.jsxs(s.Fragment,{children:[s.jsx("circle",{className:"flow_badge_bg",r:8.5}),n]})}function Ip(e){const[t,n]=p.useState("idle"),r=p.useRef(null);return p.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),s.jsx("button",{type:"button",className:e.className||"btn flow_copy_btn",title:e.title,"aria-label":e.title,disabled:e.disabled,"data-copy-state":t,onClick:async i=>{i.stopPropagation();const o=await Mm(e.get_text());n(o?"copied":"failed"),r.current!==null&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>n("idle"),1500)},children:s.jsx("span",{"aria-live":"polite",children:t==="copied"?e.copied??"Copied":t==="failed"?e.failed??f1:e.label})})}function gk(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=B1(e.text);return s.jsxs("span",{className:"flow_facts_text",children:[s.jsx("span",{children:t||!i?e.text:r}),i?s.jsx("button",{type:"button",className:"flow_link_btn","aria-expanded":t,onClick:()=>n(o=>!o),children:t?"show less":`show all (${e.text.length.toLocaleString("en-US")} chars)`}):null]})}function s5(e){const[t,n]=p.useState(!1),r=fD(e.value);return s.jsxs("span",{className:"flow_facts_text",children:[s.jsx("code",{className:"flow_facts_summary",children:e.summary}),r?s.jsx("button",{type:"button",className:"flow_link_btn","aria-expanded":t,onClick:()=>n(i=>!i),children:t?"show less":"show all"}):null,r&&t?s.jsx("pre",{className:"flow_facts_json",children:JSON.stringify(e.value,null,2)}):null]})}function r5(e){const{node:t,facts:n,status:r}=e,i=r==="waiting"?e$(n):Z1[r],o=n?[`${n.visits.toLocaleString("en-US")} visit${n.visits===1?"":"s"}`,n.first_ms!==null?`first ${_k(n.first_ms)}`:"",n.last_ms!==null?`last ${_k(n.last_ms)}`:"",`${bu(n.duration_ms)} in steps`].filter(Boolean):[],c=(n==null?void 0:n.llm)||null;return s.jsxs("div",{className:"flow_facts",children:[s.jsxs("div",{className:"flow_facts_head",children:[s.jsx("span",{className:"flow_facts_title",children:t.label}),s.jsx("span",{className:"flow_facts_type",children:t.type})]}),s.jsxs("div",{className:"flow_facts_status",children:[s.jsx("span",{className:"flow_status_chip","data-run-status":r,children:i}),e.here?s.jsx("span",{className:"flow_facts_here",children:X1[r]}):null]}),n?s.jsxs("dl",{className:"flow_facts_rows",children:[s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Visits"}),s.jsx("dd",{children:o.join(" · ")})]}),c?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"LLM"}),s.jsx("dd",{children:[c.model||"model not recorded",c.provider||"provider not recorded",`${c.calls.toLocaleString("en-US")} call${c.calls===1?"":"s"}`,c.tokens?`${c.tokens.in.toLocaleString("en-US")} in · ${c.tokens.out.toLocaleString("en-US")} out tokens`:""].filter(Boolean).join(" · ")})]}):null,n.tools.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Tools"}),s.jsx("dd",{children:s.jsxs("table",{className:"flow_facts_tools",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:"tool"}),s.jsx("th",{scope:"col",children:"calls"}),s.jsx("th",{scope:"col",children:"failed"})]})}),s.jsx("tbody",{children:n.tools.map(l=>s.jsxs("tr",{"data-failed":l.failed>0?"true":void 0,children:[s.jsx("td",{children:l.name}),s.jsx("td",{children:l.calls}),s.jsx("td",{children:l.failed})]},l.name))})]})})]}):null,n.waits.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Waits"}),s.jsx("dd",{children:s.jsx("ul",{className:"flow_facts_list",children:n.waits.map((l,d)=>s.jsxs("li",{children:[s.jsx("span",{children:Q1[l.reason]||l.reason||"reason not recorded"}),l.open?s.jsx("span",{className:"flow_facts_open",children:" · now"}):null,l.prompt?s.jsxs(s.Fragment,{children:[" · ",s.jsx(gk,{text:l.prompt})]}):null]},`${l.reason}|${l.wait_key}|${d}`))})})]}):null,n.subruns.length?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Subruns"}),s.jsx("dd",{className:"flow_facts_subruns",children:n.subruns.map(l=>s.jsx("button",{type:"button",className:"flow_link_btn mono",title:e.on_open_run?`Open run ${l}`:`${l} (opening runs is not wired here)`,disabled:!e.on_open_run,onClick:()=>{var d;return(d=e.on_open_run)==null?void 0:d.call(e,l)},children:Qd(l)},l))})]}):null,n.last_result_summary?s.jsxs("div",{className:"flow_facts_row",children:[s.jsx("dt",{children:"Result"}),s.jsx("dd",{children:s.jsx(s5,{summary:n.last_result_summary,value:n.last_result})})]}):null,n.last_error?s.jsxs("div",{className:"flow_facts_row flow_facts_error",children:[s.jsx("dt",{children:"Error"}),s.jsx("dd",{children:s.jsx(gk,{text:n.last_error})})]}):null]}):s.jsx("p",{className:"flow_facts_none",children:e.finished?"Not visited in this run.":"Not visited yet."}),s.jsxs("div",{className:"flow_facts_actions",children:[s.jsx(Ip,{label:"Copy facts (JSON)",disabled:!n,get_text:()=>n?wD(n):""}),s.jsx(Ip,{label:"Copy records (JSONL)",disabled:!n||!n.records.length,get_text:()=>n?vD(n):""}),n!=null&&n.context?s.jsx(Ip,{label:"Copy context",get_text:()=>xD(n)}):null]})]})}function i5(e){var yt;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=e.flow,r=Rn(e.active_node_id),i=e.recent_nodes||{},o=e.visited_nodes||{},c=e.highlight_path===!0,l=typeof e.vertical_compact=="number"?Math.max(.4,Math.min(1,e.vertical_compact)):.78,{nodes:d,edges:h,bounds:m}=p.useMemo(()=>{const re=ZD({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),he=Array.isArray(re.nodes)?re.nodes:[],Ee=Array.isArray(re.edges)?re.edges:[];let Ie=[];for(const Be of he){const Qt=Rn(Be==null?void 0:Be.id).trim();if(!Qt)continue;const Ot=Be!=null&&Be.position&&typeof Be.position=="object"?Be.position:{},Fn=typeof Ot.x=="number"?Ot.x:0,hn=typeof Ot.y=="number"?Ot.y:0,Xe=Be!=null&&Be.data&&typeof Be.data=="object"?Be.data:{},sn=Rn((Xe==null?void 0:Xe.label)||(Be==null?void 0:Be.label)||Qt)||Qt,un=Rn((Xe==null?void 0:Xe.nodeType)||(Be==null?void 0:Be.type)||"unknown")||"unknown",Ar=Rn((Xe==null?void 0:Xe.headerColor)||(Be==null?void 0:Be.headerColor)||"")||"",As=Xe!=null&&Xe.eventConfig&&typeof Xe.eventConfig=="object"?Xe.eventConfig:null,ws=As&&typeof As.schedule=="string"?Rn(As.schedule).trim():"",_r=As&&typeof As.recurrent=="boolean"?!!As.recurrent:void 0,ve=un==="subflow"?Y1(Be):"",Ct=ws||_r!==void 0||ve?{schedule:ws||void 0,recurrent:_r,subflow_id:ve||void 0}:void 0;Ie.push({id:Qt,x:Fn,y:hn,label:sn,type:un,color:Ar,meta:Ct})}const We={};for(const Be of Ie)We[Be.id]=Be;let Ue=[];for(const Be of Ee){if(!K1(Be))continue;const Qt=Rn(Be==null?void 0:Be.source).trim(),Ot=Rn(Be==null?void 0:Be.target).trim();!Qt||!Ot||Ue.push({id:Rn((Be==null?void 0:Be.id)||`${Qt}->${Ot}`),source:Qt,target:Ot})}const tt=new Set(Ie.map(Be=>Be.id));if(Ue=Ue.filter(Be=>tt.has(Be.source)&&tt.has(Be.target)),e.simplify===!0){const Qt=e5({nodes:Ie,edges:Ue,keep_id:Ot=>{if(r&&Ot===r)return!0;const Fn=We[Ot];if(!Fn)return!1;const hn=Rn(Fn.type).trim().toLowerCase();return hn==="on_flow_start"||hn==="on_flow_end"||hn==="subflow"?!0:!QD(hn)},max_edges:900});Ie=Qt.nodes,Ue=Qt.edges}if(e.prefer_vertical===!0&&Ie.length>=2){const Be=Ie.map(Xe=>Xe.x),Qt=Ie.map(Xe=>Xe.y),Ot=Math.max(...Be)-Math.min(...Be),Fn=Math.max(...Qt)-Math.min(...Qt);Ot>=Fn&&(Ie=Ie.map(Xe=>({...Xe,x:Xe.y,y:Xe.x})));const hn=Math.min(...Ie.map(Xe=>Xe.y));Ie=Ie.map(Xe=>({...Xe,y:hn+(Xe.y-hn)*l}))}const ut={};for(const Be of Ie)ut[Be.id]=Be;const xt=160,bt=56,Mt=xt/2,zt=bt/2;let lt=0,Yt=0,vn=0,mn=0;Ie.length&&(lt=Math.min(...Ie.map(Be=>Be.x)),Yt=Math.min(...Ie.map(Be=>Be.y)),vn=Math.max(...Ie.map(Be=>Be.x+xt)),mn=Math.max(...Ie.map(Be=>Be.y+bt)));let rn=0;if(Ue.length){const Be=new Set(Ue.map(Qt=>`${Qt.source}->${Qt.target}`));for(const Qt of Ue){if(!Be.has(`${Qt.target}->${Qt.source}`))continue;const Ot=ut[Qt.source],Fn=ut[Qt.target];if(!Ot||!Fn)continue;const hn=Ot.x+Mt,Xe=Ot.y+zt,sn=Fn.x+Mt,un=Fn.y+zt,Ar=Math.max(1,Math.hypot(sn-hn,un-Xe)),As=Math.max(28,Math.min(72,Ar*.14)),ws=Math.min(200,As*3.5);ws>rn&&(rn=ws)}}const Ht=60+rn,is={x:lt-Ht,y:Yt-Ht,w:vn-lt+Ht*2,h:mn-Yt+Ht*2,node_w:xt,node_h:bt};return{nodes:Ie,edges:Ue,bounds:is}},[n,e.flow_by_id,e.expand_subflows,e.simplify,e.prefer_vertical,r,l]),_=p.useRef(null),[g,y]=p.useState(()=>({x:m.x,y:m.y,w:m.w,h:m.h})),x=p.useRef(g);x.current=g,p.useEffect(()=>{y({x:m.x,y:m.y,w:m.w,h:m.h})},[m.x,m.y,m.w,m.h]);const k=p.useRef(new Map),v=p.useRef(null),N=p.useMemo(()=>{const re=new Set;for(const he of h)re.add(`${he.source}->${he.target}`);return re},[h]),[$,C]=p.useState(null),[S,D]=p.useState(null),O=p.useRef({}),A=p.useRef(null),P=p.useRef(null),W=p.useRef(null),J=p.useRef(!1),V=`flow_facts_${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,R=()=>{P.current!==null&&window.clearTimeout(P.current),P.current=null},M=re=>{const he=O.current[re];if(!he||typeof window>"u")return;const Ee=he.getBoundingClientRect(),Ie=window.innerWidth,We=Math.min(400,Ie-16);let Ue=Ee.right+10,tt=Ee.top;Ue+We>Ie-8&&(Ue=Ee.left-10-We),Ue<8&&(Ue=Math.min(Math.max(8,Ee.left),Math.max(8,Ie-We-8)),tt=Ee.bottom+8),D(ut=>ut&&ut.top===tt&&ut.left===Ue&&ut.width===We?ut:{top:tt,left:Ue,width:We})},I=(re,he)=>{R(),M(re),C({id:re,mode:he})},L=re=>{R(),P.current=window.setTimeout(()=>C(he=>he&&he.id===re&&he.mode!=="pinned"?null:he),200)},K=(re,he)=>{if(R(),$&&$.id===re&&$.mode==="pinned"){C(null);return}M(re),C({id:re,mode:"pinned"}),he&&window.setTimeout(()=>{var Ee;return(Ee=A.current)==null?void 0:Ee.focus()},0)};p.useEffect(()=>()=>R(),[]),pk(()=>{$&&M($.id)},[$==null?void 0:$.id,g.x,g.y,g.w,g.h]);const H=()=>{const re=A.current;if(!re)return;const he=re.offsetHeight,Ee=window.innerHeight;D(Ie=>{if(!Ie||Ie.top+he<=Ee-8)return Ie;const We=Math.max(8,Ee-8-he);return We===Ie.top?Ie:{...Ie,top:We}})};pk(()=>{$&&S&&H()},[$==null?void 0:$.id,S==null?void 0:S.top,S==null?void 0:S.left,S==null?void 0:S.width]);const z=!!S;p.useEffect(()=>{const re=A.current;if(!$||!re||typeof ResizeObserver>"u")return;const he=new ResizeObserver(()=>H());return he.observe(re),()=>he.disconnect()},[$==null?void 0:$.id,z]),p.useEffect(()=>{if(!$)return;const re=Ie=>{var We;Ie.key==="Escape"&&(C(null),$.mode!=="hover"&&(J.current=!0,(We=O.current[$.id])==null||We.focus(),J.current=!1))},he=Ie=>{var Ue;const We=Ie.target;We&&((Ue=A.current)!=null&&Ue.contains(We))||We&&typeof We.closest=="function"&&We.closest("[data-flow-node]")||C(null)},Ee=()=>M($.id);return document.addEventListener("keydown",re,!0),document.addEventListener("pointerdown",he,!0),window.addEventListener("resize",Ee),window.addEventListener("scroll",Ee,!0),()=>{document.removeEventListener("keydown",re,!0),document.removeEventListener("pointerdown",he,!0),window.removeEventListener("resize",Ee),window.removeEventListener("scroll",Ee,!0)}},[$==null?void 0:$.id,$==null?void 0:$.mode]);const ee=`${g.x} ${g.y} ${g.w} ${g.h}`,B={};for(const re of d)B[re.id]=re;const te=re=>{let he=Rn(re).trim();if(!he)return"";if(B[he])return he;for(;he.includes("::");)if(he=he.slice(0,Math.max(0,he.lastIndexOf("::"))),B[he])return he;return""},se=te(r),de={};for(const[re,he]of Object.entries(i)){if(typeof he!="number")continue;const Ee=te(re);Ee&&(de[Ee]=Math.max(de[Ee]||0,he))}const be={};if(c)for(const[re,he]of Object.entries(o)){if(typeof he!="number")continue;const Ee=te(re);Ee&&(be[Ee]=typeof be[Ee]=="number"?Math.min(be[Ee],he):he)}const Me=Rn(e.schedule_next_in).trim(),Ne=Rn(e.schedule_interval).trim(),ae=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},je=re=>{try{const he=new Date(re),Ee=String(he.getHours()).padStart(2,"0"),Ie=String(he.getMinutes()).padStart(2,"0");return`${Ee}:${Ie}`}catch{return""}},Te=(re,he)=>{var Ue,tt;const Ee=Rn((Ue=re.meta)==null?void 0:Ue.schedule).trim();if(!(((tt=re.meta)==null?void 0:tt.recurrent)===!0))return he&&Me?`next ${Me}`:Ee&&Ee.length<=12&&!Ee.includes("T")?`in ${Ee}`:"scheduled";const We=Ee||Ne;return We?he&&Me?`${We} • next ${Me}`:`every ${We}`:he&&Me?`next ${Me}`:"scheduled"},Ve=re=>{var xt;const he=Rn((xt=re.meta)==null?void 0:xt.subflow_id).trim(),Ee=he&&e.flow_by_id?e.flow_by_id[he]:null,We=Rn(Ee==null?void 0:Ee.name).trim()||he||re.label||re.id,Ue=typeof ae[re.id]=="number"?Number(ae[re.id]):null,tt=Ue!==null?je(Ue):"",ut=tt?`last ${tt}`:"subflow";return{label:We,sub:ut}},_t=(re,he)=>{let Ee=re.label||re.id,Ie=re.type;if(re.type==="on_schedule")Ie=Te(re,he);else if(re.type==="subflow"){const We=Ve(re);Ee=We.label,Ie=We.sub}return{label:Ee,type:Ie}},Qe=Rn(e.run_status).trim().toLowerCase(),it=e.run_line||null,$t=Rn(e.run_id).trim(),ot=!!(Qe||it||$t),mt=Qe?t5.has(Qe):it?it.verb==="done":!1,et=Qe==="failed"||Qe==="cancelled",Lt=e.node_facts||{},ce=e.node_status||yD(Lt),Se={};for(const[re,he]of Object.entries(ce)){const Ee=te(re);if(!Ee)continue;let Ie=he;mt&&(Ie==="running"||Ie==="waiting")&&(Ie=et?"failed":"done");const We=((yt=Lt[re])==null?void 0:yt.last_ms)??(typeof ae[re]=="number"?ae[re]:0),Ue=Se[Ee];if(!Ue){Se[Ee]={s:Ie,t:We};continue}const tt=Qc(Ie),ut=Qc(Ue.s);(tt!==ut?tt>ut:We!==Ue.t?We>Ue.t:Ie==="failed"&&Ue.s!=="failed")&&(Se[Ee]={s:Ie,t:We})}const He=re=>{var he;return((he=Se[re])==null?void 0:he.s)||"none"};let ne=se;if(!ne&&ot){let re=null;for(const[he,Ee]of Object.entries(Se))(mt?et&&Ee.s==="failed":Qc(Ee.s)>0)&&(!re||Qc(Ee.s)>Qc(re.s)||Qc(Ee.s)===Qc(re.s)&&Ee.t>re.t)&&(re={id:he,...Ee});ne=re?re.id:""}const we=re=>mt&&Qe==="cancelled"&&re==="failed"?"cancelled here":X1[re],fe=new Set;let $e=null,pe=null;for(const[re,he]of Object.entries(Lt)){if(!he||he.visits<=0)continue;const Ee=te(re);Ee&&fe.add(Ee),he.first_ms!==null&&($e=$e===null?he.first_ms:Math.min($e,he.first_ms)),he.last_ms!==null&&(pe=pe===null?he.last_ms:Math.max(pe,he.last_ms))}for(const[re,he]of Object.entries(o)){if(typeof he!="number")continue;const Ee=te(re);Ee&&fe.add(Ee)}if($e===null||pe===null){const re=Object.values(ae).filter(he=>typeof he=="number"&&Number.isFinite(he));re.length>=2&&($e=Math.min(...re),pe=Math.max(...re))}const le=$e!==null&&pe!==null&&pe>=$e?pe-$e:null,ze=re=>re?re==="waiting"?"waiting, reason not loaded":re:"state not loaded",st=(it==null?void 0:it.text)||ze(Qe),pt=Sa(Qe||(it?{running:"running",needs_you:"waiting",paused:"paused",waiting:"waiting",scheduled:"scheduled",done:""}[it.verb]??"":"")),jt=ne?B[ne]:void 0,ct=Rn(e.current_node_label).trim()||(jt?_t(jt,ne===se).label:""),It=!!ct&&(!mt||et),vt=`${fe.size.toLocaleString("en-US")} node${fe.size===1?"":"s"} visited${le!==null?` in ${bu(le)}`:""}`,nn=ot?s.jsxs("div",{className:"flow_banner","data-phase":mt?"finished":"ongoing",children:[s.jsx("span",{className:`chip ${pt}`,children:mt?"finished":"ongoing"}),s.jsx("span",{className:"flow_banner_text",children:st}),It?s.jsxs("span",{className:"flow_banner_at",children:["· at ",s.jsx("strong",{children:ct})]}):null,mt&&n?s.jsxs("span",{className:"flow_banner_meta",children:["· ",vt]}):null]}):s.jsxs("div",{className:"flow_banner","data-phase":"none",children:[s.jsx("span",{className:"chip muted",children:"no run"}),s.jsx("span",{className:"flow_banner_text",children:"the workflow only — open a run to see where it is"})]});if(!n)return ot?s.jsxs("div",{className:"graph_wrap",children:[nn,s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"})]}):s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const wn=(re,he,Ee)=>{const Ie=Ee||x.current,We=_.current;if(!We)return{x:re,y:he};const Ue=We.getBoundingClientRect(),tt=Ue.width>0?(re-Ue.left)/Ue.width:0,ut=Ue.height>0?(he-Ue.top)/Ue.height:0;return{x:Ie.x+tt*Ie.w,y:Ie.y+ut*Ie.h}},On=(re,he,Ee)=>{const Ie=Ee||x.current,We=Math.max(.12,Math.min(8,he)),Ue=Ie.w*We,tt=Ie.h*We,ut=Ie.w>0?(re.x-Ie.x)/Ie.w:.5,xt=Ie.h>0?(re.y-Ie.y)/Ie.h:.5,bt=re.x-ut*Ue,Mt=re.y-xt*tt;y(mk({x:bt,y:Mt,w:Ue,h:tt},m))},Ks=(re,he,Ee)=>{const Ie=Ee||x.current,We=_.current;if(!We)return;const Ue=We.getBoundingClientRect(),tt=.88,ut=Ue.width>0?re/Ue.width*Ie.w*tt:0,xt=Ue.height>0?he/Ue.height*Ie.h*tt:0;y(bt=>mk({x:(Ee||bt).x-ut,y:(Ee||bt).y-xt,w:(Ee||bt).w,h:(Ee||bt).h},m))},rs=(re,he,Ee,Ie)=>{const We=m.node_w,Ue=m.node_h,tt=Math.abs(Ee),ut=Math.abs(Ie);if(tt<1e-6&&ut<1e-6)return{x:re,y:he};const xt=tt>1e-6?We/2/tt:Number.POSITIVE_INFINITY,bt=ut>1e-6?Ue/2/ut:Number.POSITIVE_INFINITY,Mt=Math.min(xt,bt);return{x:re+Ee*Mt,y:he+Ie*Mt}},ge=()=>JSON.stringify(bD({run_id:$t,status:Qe,state:st,finished:mt,now_ms:t,current_id:ne,nodes:d.map(re=>({id:re.id,label:_t(re,!1).label,type:re.type})),edges:h,facts:Lt,status_of:He}),null,2),Le=$?B[$.id]:void 0;return s.jsxs("div",{className:"graph_wrap",children:[nn,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:()=>y({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 re=_.current;if(!re)return;const he=re.getBoundingClientRect(),Ee=wn(he.left+he.width/2,he.top+he.height/2);On(Ee,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const re=_.current;if(!re)return;const he=re.getBoundingClientRect(),Ee=wn(he.left+he.width/2,he.top+he.height/2);On(Ee,1.18)},title:"Zoom out",children:"−"}),s.jsx(Ip,{className:"btn graph_corner_btn flow_copy_state_btn",title:"Copy run state (JSON: where the run is and what each node did)",label:"⧉",copied:"✓",failed:"!",get_text:ge})]}),s.jsx(SD,{})]}),s.jsxs("svg",{ref:_,className:"graph_svg",viewBox:ee,role:"group","aria-label":"Workflow execution graph",onWheel:re=>{re.preventDefault();const he=wn(re.clientX,re.clientY),Ee=typeof re.deltaY=="number"?re.deltaY:0,Ie=typeof re.deltaMode=="number"?Number(re.deltaMode):0,We=Ie===1?Ee*24:Ie===2?Ee*800:Ee,Ue=45e-5*1.15*1.1;let tt=Math.exp(We*Ue);tt=Math.max(.86,Math.min(1.16,tt)),On(he,tt)},onPointerDown:re=>{var Ee,Ie;(Ie=(Ee=re.currentTarget).setPointerCapture)==null||Ie.call(Ee,re.pointerId),k.current.set(re.pointerId,{x:re.clientX,y:re.clientY});const he=Array.from(k.current.values());if(he.length===1)v.current={mode:"pan",start_view:x.current,start_client:{x:re.clientX,y:re.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(he.length>=2){W.current=null;const We=he[0],Ue=he[1],tt=We.x-Ue.x,ut=We.y-Ue.y,xt=Math.max(1,Math.hypot(tt,ut)),bt={x:(We.x+Ue.x)/2,y:(We.y+Ue.y)/2},Mt=x.current;v.current={mode:"pinch",start_view:Mt,start_client:bt,start_dist:xt,anchor_svg:wn(bt.x,bt.y,Mt)}}},onPointerMove:re=>{if(!k.current.has(re.pointerId))return;k.current.set(re.pointerId,{x:re.clientX,y:re.clientY});const he=v.current;if(!he)return;const Ee=Array.from(k.current.values());if(he.mode==="pan"&&Ee.length===1){const Ie=re.clientX-he.start_client.x,We=re.clientY-he.start_client.y;Ks(Ie,We,he.start_view)}else if(he.mode==="pinch"&&Ee.length>=2){const Ie=Ee[0],We=Ee[1],Ue=Ie.x-We.x,tt=Ie.y-We.y,ut=Math.max(1,Math.hypot(Ue,tt)),xt=he.start_dist/ut;On(he.anchor_svg,xt,he.start_view)}},onPointerUp:re=>{k.current.delete(re.pointerId),k.current.size===0&&(v.current=null);const he=W.current;W.current=null,he&&k.current.size===0&&Math.hypot(re.clientX-he.x,re.clientY-he.y)<5&&K(he.id,!1)},onPointerCancel:re=>{k.current.delete(re.pointerId),k.current.size===0&&(v.current=null),W.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(re=>{const he=B[re.source],Ee=B[re.target];if(!he||!Ee)return null;const Ie=he.x+m.node_w/2,We=he.y+m.node_h/2,Ue=Ee.x+m.node_w/2,tt=Ee.y+m.node_h/2,ut=Ue-Ie,xt=tt-We,bt=rs(Ie,We,ut,xt),Mt=rs(Ue,tt,-ut,-xt),zt=re.source!==re.target&&N.has(`${re.target}->${re.source}`),lt=Math.max(1,Math.hypot(ut,xt)),Yt=-xt/lt,vn=ut/lt,mn=String(re.source)<String(re.target)?1:-1,Ht=Math.abs(ut)>=Math.abs(xt)?ut>=0:xt>=0,is=!zt||Ht,Be=Math.max(28,Math.min(72,lt*.14)),Qt=Math.min(200,Be*3.5),Ot=zt&&!is?Qt*mn:0,Fn=(bt.x+Mt.x)/2+Yt*Ot,hn=(bt.y+Mt.y)/2+vn*Ot,Xe=zt&&!is?`M ${bt.x} ${bt.y} Q ${Fn} ${hn} ${Mt.x} ${Mt.y}`:`M ${bt.x} ${bt.y} L ${Mt.x} ${Mt.y}`,sn=c&&be&&be[re.source]!==void 0&&be[re.target]!==void 0;return s.jsx("path",{d:Xe,className:`graph_edge ${sn?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},re.id)}),d.map(re=>{const Ee=(typeof de[re.id]=="number"?de[re.id]:0)>t,Ie=se&&re.id===se,We=c&&be&&be[re.id]!==void 0,Ue=He(re.id),tt=!!ne&&re.id===ne,ut=`graph_node ${Ie?"active":Ee?"recent":""} ${We?"visited":""}${tt?" here":""}`,xt=re.color||"rgba(255,255,255,0.16)",{label:bt,type:Mt}=_t(re,!!Ie),zt=hk(bt,22),lt=hk(Mt,22),Yt=tt?we(Ue):"",vn=Yt?Math.round(Yt.length*6.2+14):0,mn=Ue==="waiting"?e$(Lt[re.id]):Z1[Ue],rn=($==null?void 0:$.id)===re.id;return s.jsxs("g",{ref:Ht=>{O.current[re.id]=Ht},className:ut,transform:`translate(${re.x}, ${re.y})`,"data-flow-node":re.id,"data-run-status":Ue,tabIndex:0,role:"button","aria-label":`${bt} (${Mt}): ${mn}${Yt?`, ${Yt}`:""}`,"aria-haspopup":"dialog","aria-expanded":rn,"aria-describedby":rn?V:void 0,onPointerDown:Ht=>{W.current={id:re.id,x:Ht.clientX,y:Ht.clientY}},onMouseEnter:()=>{($==null?void 0:$.mode)!=="pinned"&&(R(),!rn&&(P.current=window.setTimeout(()=>{v.current||I(re.id,"hover")},150)))},onMouseLeave:()=>{rn&&($==null?void 0:$.mode)==="hover"?L(re.id):($==null?void 0:$.mode)!=="pinned"&&R()},onFocus:()=>{J.current||rn&&($==null?void 0:$.mode)==="pinned"||I(re.id,"focus")},onBlur:Ht=>{var is;rn&&($==null?void 0:$.mode)==="focus"&&!((is=A.current)!=null&&is.contains(Ht.relatedTarget))&&L(re.id)},onKeyDown:Ht=>{Ht.key!=="Enter"&&Ht.key!==" "||(Ht.preventDefault(),K(re.id,!0))},children:[Ue==="running"||Ue==="waiting"||Ue==="failed"||tt?s.jsx("rect",{className:"flow_node_ring",x:-5,y:-5,width:m.node_w+10,height:m.node_h+10,rx:16,ry:16}):null,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:xt}),s.jsx("text",{className:"graph_node_label",x:12,y:28,children:zt}),s.jsx("text",{className:"graph_node_type",x:12,y:46,children:lt}),re.type==="on_schedule"?s.jsx("text",{className:"graph_node_icon",x:m.node_w-18,y:18,children:"⏰"}):null,Ue!=="none"?s.jsx("g",{className:"flow_status_badge",transform:`translate(${m.node_w-12}, 0)`,"aria-hidden":"true",children:s.jsx(n5,{status:Ue})}):null,Yt?s.jsxs("g",{className:"flow_here_chip",transform:`translate(${m.node_w-26-vn}, -9)`,"aria-hidden":"true",children:[s.jsx("rect",{width:vn,height:18,rx:9,ry:9}),s.jsx("text",{x:7,y:12.5,children:Yt})]}):null]},re.id)})]}),$&&Le&&S&&typeof document<"u"?jg.createPortal(s.jsx("div",{ref:A,id:V,className:"flow_facts_pop",role:"dialog","aria-label":`About the node ${_t(Le,Le.id===se).label}`,tabIndex:-1,style:{top:S.top,left:S.left,width:S.width},onMouseEnter:R,onMouseLeave:()=>$.mode==="hover"?L($.id):void 0,onBlur:re=>{$.mode==="focus"&&!re.currentTarget.contains(re.relatedTarget)&&L($.id)},children:s.jsx(r5,{node:{id:Le.id,..._t(Le,Le.id===se)},facts:Lt[Le.id]||null,status:He(Le.id),here:Le.id===ne,finished:mt,on_open_run:e.on_open_run})}),document.body):null]})}function Er(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=Er(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var nw={exports:{}},sw={},rw={exports:{}},iw={};/**
140
+ * @license React
141
+ * use-sync-external-store-shim.production.js
142
+ *
143
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
144
+ *
145
+ * This source code is licensed under the MIT license found in the
146
+ * LICENSE file in the root directory of this source tree.
147
+ */var yk;function o5(){if(yk)return iw;yk=1;var e=vm();function t(_,g){return _===g&&(_!==0||1/_===1/g)||_!==_&&g!==g}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,i=e.useEffect,o=e.useLayoutEffect,c=e.useDebugValue;function l(_,g){var y=g(),x=r({inst:{value:y,getSnapshot:g}}),k=x[0].inst,v=x[1];return o(function(){k.value=y,k.getSnapshot=g,d(k)&&v({inst:k})},[_,y,g]),i(function(){return d(k)&&v({inst:k}),_(function(){d(k)&&v({inst:k})})},[_]),c(y),y}function d(_){var g=_.getSnapshot;_=_.value;try{var y=g();return!n(_,y)}catch{return!0}}function h(_,g){return g()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?h:l;return iw.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:m,iw}var wk;function a5(){return wk||(wk=1,rw.exports=o5()),rw.exports}/**
148
+ * @license React
149
+ * use-sync-external-store-shim/with-selector.production.js
150
+ *
151
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
152
+ *
153
+ * This source code is licensed under the MIT license found in the
154
+ * LICENSE file in the root directory of this source tree.
155
+ */var vk;function l5(){if(vk)return sw;vk=1;var e=vm(),t=a5();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,i=t.useSyncExternalStore,o=e.useRef,c=e.useEffect,l=e.useMemo,d=e.useDebugValue;return sw.useSyncExternalStoreWithSelector=function(h,m,_,g,y){var x=o(null);if(x.current===null){var k={hasValue:!1,value:null};x.current=k}else k=x.current;x=l(function(){function N(O){if(!$){if($=!0,C=O,O=g(O),y!==void 0&&k.hasValue){var A=k.value;if(y(A,O))return S=A}return S=O}if(A=S,r(C,O))return A;var P=g(O);return y!==void 0&&y(A,P)?(C=O,A):(C=O,S=P)}var $=!1,C,S,D=_===void 0?null:_;return[function(){return N(m())},D===null?void 0:function(){return N(D())}]},[m,_,g,y]);var v=i(h,x[0],x[1]);return c(function(){k.hasValue=!0,k.value=v},[v]),d(v),v},sw}var xk;function c5(){return xk||(xk=1,nw.exports=l5()),nw.exports}var u5=c5();const d5=Yv(u5),f5={},bk=e=>{let t;const n=new Set,r=(m,_)=>{const g=typeof m=="function"?m(t):m;if(!Object.is(g,t)){const y=t;t=_??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(x=>x(t,y))}},i=()=>t,d={setState:r,getState:i,getInitialState:()=>h,subscribe:m=>(n.add(m),()=>n.delete(m)),destroy:()=>{(f5?"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,i,d);return d},h5=e=>e?bk(e):bk,{useDebugValue:m5}=Ae,{useSyncExternalStoreWithSelector:_5}=d5,p5=e=>e;function t$(e,t=p5,n){const r=_5(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return m5(r),r}const kk=(e,t)=>{const n=h5(e),r=(i,o=t)=>t$(n,i,o);return Object.assign(r,n),r},g5=(e,t)=>e?kk(e,t):kk;function mr(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,i]of e)if(!Object.is(i,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var y5={value:()=>{}};function Ug(){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 Op(n)}function Op(e){this._=e}function w5(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",i=n.indexOf(".");if(i>=0&&(r=n.slice(i+1),n=n.slice(0,i)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}Op.prototype=Ug.prototype={constructor:Op,on:function(e,t){var n=this._,r=w5(e+"",n),i,o=-1,c=r.length;if(arguments.length<2){for(;++o<c;)if((i=(e=r[o]).type)&&(i=v5(n[i],e.name)))return i;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++o<c;)if(i=(e=r[o]).type)n[i]=jk(n[i],e.name,t);else if(t==null)for(i in n)n[i]=jk(n[i],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Op(e)},call:function(e,t){if((i=arguments.length-2)>0)for(var n=new Array(i),r=0,i,o;r<i;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(o=this._[e],r=0,i=o.length;r<i;++r)o[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],i=0,o=r.length;i<o;++i)r[i].value.apply(t,n)}};function v5(e,t){for(var n=0,r=e.length,i;n<r;++n)if((i=e[n]).name===t)return i.value}function jk(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=y5,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var pv="http://www.w3.org/1999/xhtml";const Sk={svg:"http://www.w3.org/2000/svg",xhtml:pv,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Wg(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Sk.hasOwnProperty(t)?{space:Sk[t],local:e}:e}function x5(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===pv&&t.documentElement.namespaceURI===pv?t.createElement(e):t.createElementNS(n,e)}}function b5(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function n$(e){var t=Wg(e);return(t.local?b5:x5)(t)}function k5(){}function $x(e){return e==null?k5:function(){return this.querySelector(e)}}function j5(e){typeof e!="function"&&(e=$x(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],c=o.length,l=r[i]=new Array(c),d,h,m=0;m<c;++m)(d=o[m])&&(h=e.call(d,d.__data__,m,o))&&("__data__"in d&&(h.__data__=d.__data__),l[m]=h);return new zi(r,this._parents)}function S5(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function N5(){return[]}function s$(e){return e==null?N5:function(){return this.querySelectorAll(e)}}function $5(e){return function(){return S5(e.apply(this,arguments))}}function C5(e){typeof e=="function"?e=$5(e):e=s$(e);for(var t=this._groups,n=t.length,r=[],i=[],o=0;o<n;++o)for(var c=t[o],l=c.length,d,h=0;h<l;++h)(d=c[h])&&(r.push(e.call(d,d.__data__,h,c)),i.push(d));return new zi(r,i)}function r$(e){return function(){return this.matches(e)}}function i$(e){return function(t){return t.matches(e)}}var E5=Array.prototype.find;function A5(e){return function(){return E5.call(this.children,e)}}function T5(){return this.firstElementChild}function M5(e){return this.select(e==null?T5:A5(typeof e=="function"?e:i$(e)))}var R5=Array.prototype.filter;function L5(){return Array.from(this.children)}function I5(e){return function(){return R5.call(this.children,e)}}function O5(e){return this.selectAll(e==null?L5:I5(typeof e=="function"?e:i$(e)))}function P5(e){typeof e!="function"&&(e=r$(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],c=o.length,l=r[i]=[],d,h=0;h<c;++h)(d=o[h])&&e.call(d,d.__data__,h,o)&&l.push(d);return new zi(r,this._parents)}function o$(e){return new Array(e.length)}function D5(){return new zi(this._enter||this._groups.map(o$),this._parents)}function cg(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}cg.prototype={constructor:cg,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 F5(e){return function(){return e}}function z5(e,t,n,r,i,o){for(var c=0,l,d=t.length,h=o.length;c<h;++c)(l=t[c])?(l.__data__=o[c],r[c]=l):n[c]=new cg(e,o[c]);for(;c<d;++c)(l=t[c])&&(i[c]=l)}function B5(e,t,n,r,i,o,c){var l,d,h=new Map,m=t.length,_=o.length,g=new Array(m),y;for(l=0;l<m;++l)(d=t[l])&&(g[l]=y=c.call(d,d.__data__,l,t)+"",h.has(y)?i[l]=d:h.set(y,d));for(l=0;l<_;++l)y=c.call(e,o[l],l,o)+"",(d=h.get(y))?(r[l]=d,d.__data__=o[l],h.delete(y)):n[l]=new cg(e,o[l]);for(l=0;l<m;++l)(d=t[l])&&h.get(g[l])===d&&(i[l]=d)}function U5(e){return e.__data__}function W5(e,t){if(!arguments.length)return Array.from(this,U5);var n=t?B5:z5,r=this._parents,i=this._groups;typeof e!="function"&&(e=F5(e));for(var o=i.length,c=new Array(o),l=new Array(o),d=new Array(o),h=0;h<o;++h){var m=r[h],_=i[h],g=_.length,y=q5(e.call(m,m&&m.__data__,h,r)),x=y.length,k=l[h]=new Array(x),v=c[h]=new Array(x),N=d[h]=new Array(g);n(m,_,k,v,N,y,t);for(var $=0,C=0,S,D;$<x;++$)if(S=k[$]){for($>=C&&(C=$+1);!(D=v[C])&&++C<x;);S._next=D||null}}return c=new zi(c,r),c._enter=l,c._exit=d,c}function q5(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function V5(){return new zi(this._exit||this._groups.map(o$),this._parents)}function H5(e,t,n){var r=this.enter(),i=this,o=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(i=t(i),i&&(i=i.selection())),n==null?o.remove():n(o),r&&i?r.merge(i).order():i}function G5(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,o=r.length,c=Math.min(i,o),l=new Array(i),d=0;d<c;++d)for(var h=n[d],m=r[d],_=h.length,g=l[d]=new Array(_),y,x=0;x<_;++x)(y=h[x]||m[x])&&(g[x]=y);for(;d<i;++d)l[d]=n[d];return new zi(l,this._parents)}function K5(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],i=r.length-1,o=r[i],c;--i>=0;)(c=r[i])&&(o&&c.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(c,o),o=c);return this}function J5(e){e||(e=Y5);function t(_,g){return _&&g?e(_.__data__,g.__data__):!_-!g}for(var n=this._groups,r=n.length,i=new Array(r),o=0;o<r;++o){for(var c=n[o],l=c.length,d=i[o]=new Array(l),h,m=0;m<l;++m)(h=c[m])&&(d[m]=h);d.sort(t)}return new zi(i,this._parents).order()}function Y5(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function X5(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Z5(){return Array.from(this)}function Q5(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length;i<o;++i){var c=r[i];if(c)return c}return null}function eF(){let e=0;for(const t of this)++e;return e}function tF(){return!this.node()}function nF(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i=t[n],o=0,c=i.length,l;o<c;++o)(l=i[o])&&e.call(l,l.__data__,o,i);return this}function sF(e){return function(){this.removeAttribute(e)}}function rF(e){return function(){this.removeAttributeNS(e.space,e.local)}}function iF(e,t){return function(){this.setAttribute(e,t)}}function oF(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function aF(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function lF(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 cF(e,t){var n=Wg(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?rF:sF:typeof t=="function"?n.local?lF:aF:n.local?oF:iF)(n,t))}function a$(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function uF(e){return function(){this.style.removeProperty(e)}}function dF(e,t,n){return function(){this.style.setProperty(e,t,n)}}function fF(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function hF(e,t,n){return arguments.length>1?this.each((t==null?uF:typeof t=="function"?fF:dF)(e,t,n??"")):tf(this.node(),e)}function tf(e,t){return e.style.getPropertyValue(t)||a$(e).getComputedStyle(e,null).getPropertyValue(t)}function mF(e){return function(){delete this[e]}}function _F(e,t){return function(){this[e]=t}}function pF(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function gF(e,t){return arguments.length>1?this.each((t==null?mF:typeof t=="function"?pF:_F)(e,t)):this.node()[e]}function l$(e){return e.trim().split(/^|\s+/)}function Cx(e){return e.classList||new c$(e)}function c$(e){this._node=e,this._names=l$(e.getAttribute("class")||"")}c$.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 u$(e,t){for(var n=Cx(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function d$(e,t){for(var n=Cx(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function yF(e){return function(){u$(this,e)}}function wF(e){return function(){d$(this,e)}}function vF(e,t){return function(){(t.apply(this,arguments)?u$:d$)(this,e)}}function xF(e,t){var n=l$(e+"");if(arguments.length<2){for(var r=Cx(this.node()),i=-1,o=n.length;++i<o;)if(!r.contains(n[i]))return!1;return!0}return this.each((typeof t=="function"?vF:t?yF:wF)(n,t))}function bF(){this.textContent=""}function kF(e){return function(){this.textContent=e}}function jF(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function SF(e){return arguments.length?this.each(e==null?bF:(typeof e=="function"?jF:kF)(e)):this.node().textContent}function NF(){this.innerHTML=""}function $F(e){return function(){this.innerHTML=e}}function CF(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function EF(e){return arguments.length?this.each(e==null?NF:(typeof e=="function"?CF:$F)(e)):this.node().innerHTML}function AF(){this.nextSibling&&this.parentNode.appendChild(this)}function TF(){return this.each(AF)}function MF(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function RF(){return this.each(MF)}function LF(e){var t=typeof e=="function"?e:n$(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function IF(){return null}function OF(e,t){var n=typeof e=="function"?e:n$(e),r=t==null?IF:typeof t=="function"?t:$x(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function PF(){var e=this.parentNode;e&&e.removeChild(this)}function DF(){return this.each(PF)}function FF(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function zF(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function BF(e){return this.select(e?zF:FF)}function UF(e){return arguments.length?this.property("__data__",e):this.node().__data__}function WF(e){return function(t){e.call(this,t,this.__data__)}}function qF(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 VF(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,o;n<i;++n)o=t[n],(!e.type||o.type===e.type)&&o.name===e.name?this.removeEventListener(o.type,o.listener,o.options):t[++r]=o;++r?t.length=r:delete this.__on}}}function HF(e,t,n){return function(){var r=this.__on,i,o=WF(t);if(r){for(var c=0,l=r.length;c<l;++c)if((i=r[c]).type===e.type&&i.name===e.name){this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=o,i.options=n),i.value=t;return}}this.addEventListener(e.type,o,n),i={type:e.type,name:e.name,value:t,listener:o,options:n},r?r.push(i):this.__on=[i]}}function GF(e,t,n){var r=qF(e+""),i,o=r.length,c;if(arguments.length<2){var l=this.node().__on;if(l){for(var d=0,h=l.length,m;d<h;++d)for(i=0,m=l[d];i<o;++i)if((c=r[i]).type===m.type&&c.name===m.name)return m.value}return}for(l=t?HF:VF,i=0;i<o;++i)this.each(l(r[i],t,n));return this}function f$(e,t,n){var r=a$(e),i=r.CustomEvent;typeof i=="function"?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function KF(e,t){return function(){return f$(this,e,t)}}function JF(e,t){return function(){return f$(this,e,t.apply(this,arguments))}}function YF(e,t){return this.each((typeof t=="function"?JF:KF)(e,t))}function*XF(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,o=r.length,c;i<o;++i)(c=r[i])&&(yield c)}var h$=[null];function zi(e,t){this._groups=e,this._parents=t}function Lm(){return new zi([[document.documentElement]],h$)}function ZF(){return this}zi.prototype=Lm.prototype={constructor:zi,select:j5,selectAll:C5,selectChild:M5,selectChildren:O5,filter:P5,data:W5,enter:D5,exit:V5,join:H5,merge:G5,selection:ZF,order:K5,sort:J5,call:X5,nodes:Z5,node:Q5,size:eF,empty:tF,each:nF,attr:cF,style:hF,property:gF,classed:xF,text:SF,html:EF,raise:TF,lower:RF,append:LF,insert:OF,remove:DF,clone:BF,datum:UF,on:GF,dispatch:YF,[Symbol.iterator]:XF};function vo(e){return typeof e=="string"?new zi([[document.querySelector(e)]],[document.documentElement]):new zi([[e]],h$)}function QF(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Ho(e,t){if(e=QF(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}const e6={passive:!1},lm={capture:!0,passive:!1};function ow(e){e.stopImmediatePropagation()}function Vd(e){e.preventDefault(),e.stopImmediatePropagation()}function m$(e){var t=e.document.documentElement,n=vo(e).on("dragstart.drag",Vd,lm);"onselectstart"in t?n.on("selectstart.drag",Vd,lm):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function _$(e,t){var n=e.document.documentElement,r=vo(e).on("dragstart.drag",null);t&&(r.on("click.drag",Vd,lm),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 up=e=>()=>e;function gv(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:o,x:c,y:l,dx:d,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:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:c,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:d,enumerable:!0,configurable:!0},dy:{value:h,enumerable:!0,configurable:!0},_:{value:m}})}gv.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function t6(e){return!e.ctrlKey&&!e.button}function n6(){return this.parentNode}function s6(e,t){return t??{x:e.x,y:e.y}}function r6(){return navigator.maxTouchPoints||"ontouchstart"in this}function i6(){var e=t6,t=n6,n=s6,r=r6,i={},o=Ug("start","drag","end"),c=0,l,d,h,m,_=0;function g(S){S.on("mousedown.drag",y).filter(r).on("touchstart.drag",v).on("touchmove.drag",N,e6).on("touchend.drag touchcancel.drag",$).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function y(S,D){if(!(m||!e.call(this,S,D))){var O=C(this,t.call(this,S,D),S,D,"mouse");O&&(vo(S.view).on("mousemove.drag",x,lm).on("mouseup.drag",k,lm),m$(S.view),ow(S),h=!1,l=S.clientX,d=S.clientY,O("start",S))}}function x(S){if(Vd(S),!h){var D=S.clientX-l,O=S.clientY-d;h=D*D+O*O>_}i.mouse("drag",S)}function k(S){vo(S.view).on("mousemove.drag mouseup.drag",null),_$(S.view,h),Vd(S),i.mouse("end",S)}function v(S,D){if(e.call(this,S,D)){var O=S.changedTouches,A=t.call(this,S,D),P=O.length,W,J;for(W=0;W<P;++W)(J=C(this,A,S,D,O[W].identifier,O[W]))&&(ow(S),J("start",S,O[W]))}}function N(S){var D=S.changedTouches,O=D.length,A,P;for(A=0;A<O;++A)(P=i[D[A].identifier])&&(Vd(S),P("drag",S,D[A]))}function $(S){var D=S.changedTouches,O=D.length,A,P;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),A=0;A<O;++A)(P=i[D[A].identifier])&&(ow(S),P("end",S,D[A]))}function C(S,D,O,A,P,W){var J=o.copy(),G=Ho(W||O,D),V,R,M;if((M=n.call(S,new gv("beforestart",{sourceEvent:O,target:g,identifier:P,active:c,x:G[0],y:G[1],dx:0,dy:0,dispatch:J}),A))!=null)return V=M.x-G[0]||0,R=M.y-G[1]||0,function I(L,K,H){var z=G,ee;switch(L){case"start":i[P]=I,ee=c++;break;case"end":delete i[P],--c;case"drag":G=Ho(H||K,D),ee=c;break}J.call(L,S,new gv(L,{sourceEvent:K,subject:M,target:g,identifier:P,active:ee,x:G[0]+V,y:G[1]+R,dx:G[0]-z[0],dy:G[1]-z[1],dispatch:J}),A)}}return g.filter=function(S){return arguments.length?(e=typeof S=="function"?S:up(!!S),g):e},g.container=function(S){return arguments.length?(t=typeof S=="function"?S:up(S),g):t},g.subject=function(S){return arguments.length?(n=typeof S=="function"?S:up(S),g):n},g.touchable=function(S){return arguments.length?(r=typeof S=="function"?S:up(!!S),g):r},g.on=function(){var S=o.on.apply(o,arguments);return S===o?g:S},g.clickDistance=function(S){return arguments.length?(_=(S=+S)*S,g):Math.sqrt(_)},g}function Ex(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function p$(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Im(){}var cm=.7,ug=1/cm,Hd="\\s*([+-]?\\d+)\\s*",um="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ja="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",o6=/^#([0-9a-f]{3,8})$/,a6=new RegExp(`^rgb\\(${Hd},${Hd},${Hd}\\)$`),l6=new RegExp(`^rgb\\(${ja},${ja},${ja}\\)$`),c6=new RegExp(`^rgba\\(${Hd},${Hd},${Hd},${um}\\)$`),u6=new RegExp(`^rgba\\(${ja},${ja},${ja},${um}\\)$`),d6=new RegExp(`^hsl\\(${um},${ja},${ja}\\)$`),f6=new RegExp(`^hsla\\(${um},${ja},${ja},${um}\\)$`),Nk={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};Ex(Im,dm,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:$k,formatHex:$k,formatHex8:h6,formatHsl:m6,formatRgb:Ck,toString:Ck});function $k(){return this.rgb().formatHex()}function h6(){return this.rgb().formatHex8()}function m6(){return g$(this).formatHsl()}function Ck(){return this.rgb().formatRgb()}function dm(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=o6.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Ek(t):n===3?new Si(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?dp(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?dp(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=a6.exec(e))?new Si(t[1],t[2],t[3],1):(t=l6.exec(e))?new Si(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=c6.exec(e))?dp(t[1],t[2],t[3],t[4]):(t=u6.exec(e))?dp(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=d6.exec(e))?Mk(t[1],t[2]/100,t[3]/100,1):(t=f6.exec(e))?Mk(t[1],t[2]/100,t[3]/100,t[4]):Nk.hasOwnProperty(e)?Ek(Nk[e]):e==="transparent"?new Si(NaN,NaN,NaN,0):null}function Ek(e){return new Si(e>>16&255,e>>8&255,e&255,1)}function dp(e,t,n,r){return r<=0&&(e=t=n=NaN),new Si(e,t,n,r)}function _6(e){return e instanceof Im||(e=dm(e)),e?(e=e.rgb(),new Si(e.r,e.g,e.b,e.opacity)):new Si}function yv(e,t,n,r){return arguments.length===1?_6(e):new Si(e,t,n,r??1)}function Si(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Ex(Si,yv,p$(Im,{brighter(e){return e=e==null?ug:Math.pow(ug,e),new Si(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?cm:Math.pow(cm,e),new Si(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Si(uu(this.r),uu(this.g),uu(this.b),dg(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:Ak,formatHex:Ak,formatHex8:p6,formatRgb:Tk,toString:Tk}));function Ak(){return`#${iu(this.r)}${iu(this.g)}${iu(this.b)}`}function p6(){return`#${iu(this.r)}${iu(this.g)}${iu(this.b)}${iu((isNaN(this.opacity)?1:this.opacity)*255)}`}function Tk(){const e=dg(this.opacity);return`${e===1?"rgb(":"rgba("}${uu(this.r)}, ${uu(this.g)}, ${uu(this.b)}${e===1?")":`, ${e})`}`}function dg(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function uu(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function iu(e){return e=uu(e),(e<16?"0":"")+e.toString(16)}function Mk(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Jo(e,t,n,r)}function g$(e){if(e instanceof Jo)return new Jo(e.h,e.s,e.l,e.opacity);if(e instanceof Im||(e=dm(e)),!e)return new Jo;if(e instanceof Jo)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),o=Math.max(t,n,r),c=NaN,l=o-i,d=(o+i)/2;return l?(t===o?c=(n-r)/l+(n<r)*6:n===o?c=(r-t)/l+2:c=(t-n)/l+4,l/=d<.5?o+i:2-o-i,c*=60):l=d>0&&d<1?0:c,new Jo(c,l,d,e.opacity)}function g6(e,t,n,r){return arguments.length===1?g$(e):new Jo(e,t,n,r??1)}function Jo(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Ex(Jo,g6,p$(Im,{brighter(e){return e=e==null?ug:Math.pow(ug,e),new Jo(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?cm:Math.pow(cm,e),new Jo(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new Si(aw(e>=240?e-240:e+120,i,r),aw(e,i,r),aw(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new Jo(Rk(this.h),fp(this.s),fp(this.l),dg(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=dg(this.opacity);return`${e===1?"hsl(":"hsla("}${Rk(this.h)}, ${fp(this.s)*100}%, ${fp(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Rk(e){return e=(e||0)%360,e<0?e+360:e}function fp(e){return Math.max(0,Math.min(1,e||0))}function aw(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 y$=e=>()=>e;function y6(e,t){return function(n){return e+n*t}}function w6(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 v6(e){return(e=+e)==1?w$:function(t,n){return n-t?w6(t,n,e):y$(isNaN(t)?n:t)}}function w$(e,t){var n=t-e;return n?y6(e,n):y$(isNaN(e)?t:e)}const Lk=(function e(t){var n=v6(t);function r(i,o){var c=n((i=yv(i)).r,(o=yv(o)).r),l=n(i.g,o.g),d=n(i.b,o.b),h=w$(i.opacity,o.opacity);return function(m){return i.r=c(m),i.g=l(m),i.b=d(m),i.opacity=h(m),i+""}}return r.gamma=e,r})(1);function Ql(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var wv=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,lw=new RegExp(wv.source,"g");function x6(e){return function(){return e}}function b6(e){return function(t){return e(t)+""}}function k6(e,t){var n=wv.lastIndex=lw.lastIndex=0,r,i,o,c=-1,l=[],d=[];for(e=e+"",t=t+"";(r=wv.exec(e))&&(i=lw.exec(t));)(o=i.index)>n&&(o=t.slice(n,o),l[c]?l[c]+=o:l[++c]=o),(r=r[0])===(i=i[0])?l[c]?l[c]+=i:l[++c]=i:(l[++c]=null,d.push({i:c,x:Ql(r,i)})),n=lw.lastIndex;return n<t.length&&(o=t.slice(n),l[c]?l[c]+=o:l[++c]=o),l.length<2?d[0]?b6(d[0].x):x6(t):(t=d.length,function(h){for(var m=0,_;m<t;++m)l[(_=d[m]).i]=_.x(h);return l.join("")})}var Ik=180/Math.PI,vv={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function v$(e,t,n,r,i,o){var c,l,d;return(c=Math.sqrt(e*e+t*t))&&(e/=c,t/=c),(d=e*n+t*r)&&(n-=e*d,r-=t*d),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,d/=l),e*r<t*n&&(e=-e,t=-t,d=-d,c=-c),{translateX:i,translateY:o,rotate:Math.atan2(t,e)*Ik,skewX:Math.atan(d)*Ik,scaleX:c,scaleY:l}}var hp;function j6(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?vv:v$(t.a,t.b,t.c,t.d,t.e,t.f)}function S6(e){return e==null||(hp||(hp=document.createElementNS("http://www.w3.org/2000/svg","g")),hp.setAttribute("transform",e),!(e=hp.transform.baseVal.consolidate()))?vv:(e=e.matrix,v$(e.a,e.b,e.c,e.d,e.e,e.f))}function x$(e,t,n,r){function i(h){return h.length?h.pop()+" ":""}function o(h,m,_,g,y,x){if(h!==_||m!==g){var k=y.push("translate(",null,t,null,n);x.push({i:k-4,x:Ql(h,_)},{i:k-2,x:Ql(m,g)})}else(_||g)&&y.push("translate("+_+t+g+n)}function c(h,m,_,g){h!==m?(h-m>180?m+=360:m-h>180&&(h+=360),g.push({i:_.push(i(_)+"rotate(",null,r)-2,x:Ql(h,m)})):m&&_.push(i(_)+"rotate("+m+r)}function l(h,m,_,g){h!==m?g.push({i:_.push(i(_)+"skewX(",null,r)-2,x:Ql(h,m)}):m&&_.push(i(_)+"skewX("+m+r)}function d(h,m,_,g,y,x){if(h!==_||m!==g){var k=y.push(i(y)+"scale(",null,",",null,")");x.push({i:k-4,x:Ql(h,_)},{i:k-2,x:Ql(m,g)})}else(_!==1||g!==1)&&y.push(i(y)+"scale("+_+","+g+")")}return function(h,m){var _=[],g=[];return h=e(h),m=e(m),o(h.translateX,h.translateY,m.translateX,m.translateY,_,g),c(h.rotate,m.rotate,_,g),l(h.skewX,m.skewX,_,g),d(h.scaleX,h.scaleY,m.scaleX,m.scaleY,_,g),h=m=null,function(y){for(var x=-1,k=g.length,v;++x<k;)_[(v=g[x]).i]=v.x(y);return _.join("")}}}var N6=x$(j6,"px, ","px)","deg)"),$6=x$(S6,", ",")",")"),C6=1e-12;function Ok(e){return((e=Math.exp(e))+1/e)/2}function E6(e){return((e=Math.exp(e))-1/e)/2}function A6(e){return((e=Math.exp(2*e))-1)/(e+1)}const T6=(function e(t,n,r){function i(o,c){var l=o[0],d=o[1],h=o[2],m=c[0],_=c[1],g=c[2],y=m-l,x=_-d,k=y*y+x*x,v,N;if(k<C6)N=Math.log(g/h)/t,v=function(A){return[l+A*y,d+A*x,h*Math.exp(t*A*N)]};else{var $=Math.sqrt(k),C=(g*g-h*h+r*k)/(2*h*n*$),S=(g*g-h*h-r*k)/(2*g*n*$),D=Math.log(Math.sqrt(C*C+1)-C),O=Math.log(Math.sqrt(S*S+1)-S);N=(O-D)/t,v=function(A){var P=A*N,W=Ok(D),J=h/(n*$)*(W*A6(t*P+D)-E6(D));return[l+J*y,d+J*x,h*W/Ok(t*P+D)]}}return v.duration=N*1e3*t/Math.SQRT2,v}return i.rho=function(o){var c=Math.max(.001,+o),l=c*c,d=l*l;return e(c,l,d)},i})(Math.SQRT2,2,4);var nf=0,Vh=0,$h=0,b$=1e3,fg,Hh,hg=0,vu=0,qg=0,fm=typeof performance=="object"&&performance.now?performance:Date,k$=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ax(){return vu||(k$(M6),vu=fm.now()+qg)}function M6(){vu=0}function mg(){this._call=this._time=this._next=null}mg.prototype=j$.prototype={constructor:mg,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Ax():+n)+(t==null?0:+t),!this._next&&Hh!==this&&(Hh?Hh._next=this:fg=this,Hh=this),this._call=e,this._time=n,xv()},stop:function(){this._call&&(this._call=null,this._time=1/0,xv())}};function j$(e,t,n){var r=new mg;return r.restart(e,t,n),r}function R6(){Ax(),++nf;for(var e=fg,t;e;)(t=vu-e._time)>=0&&e._call.call(void 0,t),e=e._next;--nf}function Pk(){vu=(hg=fm.now())+qg,nf=Vh=0;try{R6()}finally{nf=0,I6(),vu=0}}function L6(){var e=fm.now(),t=e-hg;t>b$&&(qg-=t,hg=e)}function I6(){for(var e,t=fg,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:fg=n);Hh=e,xv(r)}function xv(e){if(!nf){Vh&&(Vh=clearTimeout(Vh));var t=e-vu;t>24?(e<1/0&&(Vh=setTimeout(Pk,e-fm.now()-qg)),$h&&($h=clearInterval($h))):($h||(hg=fm.now(),$h=setInterval(L6,b$)),nf=1,k$(Pk))}}function Dk(e,t,n){var r=new mg;return t=t==null?0:+t,r.restart(i=>{r.stop(),e(i+t)},t,n),r}var O6=Ug("start","end","cancel","interrupt"),P6=[],S$=0,Fk=1,bv=2,Pp=3,zk=4,kv=5,Dp=6;function Vg(e,t,n,r,i,o){var c=e.__transition;if(!c)e.__transition={};else if(n in c)return;D6(e,n,{name:t,index:r,group:i,on:O6,tween:P6,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:S$})}function Tx(e,t){var n=Xo(e,t);if(n.state>S$)throw new Error("too late; already scheduled");return n}function Na(e,t){var n=Xo(e,t);if(n.state>Pp)throw new Error("too late; already running");return n}function Xo(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function D6(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=j$(o,0,n.time);function o(h){n.state=Fk,n.timer.restart(c,n.delay,n.time),n.delay<=h&&c(h-n.delay)}function c(h){var m,_,g,y;if(n.state!==Fk)return d();for(m in r)if(y=r[m],y.name===n.name){if(y.state===Pp)return Dk(c);y.state===zk?(y.state=Dp,y.timer.stop(),y.on.call("interrupt",e,e.__data__,y.index,y.group),delete r[m]):+m<t&&(y.state=Dp,y.timer.stop(),y.on.call("cancel",e,e.__data__,y.index,y.group),delete r[m])}if(Dk(function(){n.state===Pp&&(n.state=zk,n.timer.restart(l,n.delay,n.time),l(h))}),n.state=bv,n.on.call("start",e,e.__data__,n.index,n.group),n.state===bv){for(n.state=Pp,i=new Array(g=n.tween.length),m=0,_=-1;m<g;++m)(y=n.tween[m].value.call(e,e.__data__,n.index,n.group))&&(i[++_]=y);i.length=_+1}}function l(h){for(var m=h<n.duration?n.ease.call(null,h/n.duration):(n.timer.restart(d),n.state=kv,1),_=-1,g=i.length;++_<g;)i[_].call(e,m);n.state===kv&&(n.on.call("end",e,e.__data__,n.index,n.group),d())}function d(){n.state=Dp,n.timer.stop(),delete r[t];for(var h in r)return;delete e.__transition}}function Fp(e,t){var n=e.__transition,r,i,o=!0,c;if(n){t=t==null?null:t+"";for(c in n){if((r=n[c]).name!==t){o=!1;continue}i=r.state>bv&&r.state<kv,r.state=Dp,r.timer.stop(),r.on.call(i?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[c]}o&&delete e.__transition}}function F6(e){return this.each(function(){Fp(this,e)})}function z6(e,t){var n,r;return function(){var i=Na(this,e),o=i.tween;if(o!==n){r=n=o;for(var c=0,l=r.length;c<l;++c)if(r[c].name===t){r=r.slice(),r.splice(c,1);break}}i.tween=r}}function B6(e,t,n){var r,i;if(typeof n!="function")throw new Error;return function(){var o=Na(this,e),c=o.tween;if(c!==r){i=(r=c).slice();for(var l={name:t,value:n},d=0,h=i.length;d<h;++d)if(i[d].name===t){i[d]=l;break}d===h&&i.push(l)}o.tween=i}}function U6(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Xo(this.node(),n).tween,i=0,o=r.length,c;i<o;++i)if((c=r[i]).name===e)return c.value;return null}return this.each((t==null?z6:B6)(n,e,t))}function Mx(e,t,n){var r=e._id;return e.each(function(){var i=Na(this,r);(i.value||(i.value={}))[t]=n.apply(this,arguments)}),function(i){return Xo(i,r).value[t]}}function N$(e,t){var n;return(typeof t=="number"?Ql:t instanceof dm?Lk:(n=dm(t))?(t=n,Lk):k6)(e,t)}function W6(e){return function(){this.removeAttribute(e)}}function q6(e){return function(){this.removeAttributeNS(e.space,e.local)}}function V6(e,t,n){var r,i=n+"",o;return function(){var c=this.getAttribute(e);return c===i?null:c===r?o:o=t(r=c,n)}}function H6(e,t,n){var r,i=n+"",o;return function(){var c=this.getAttributeNS(e.space,e.local);return c===i?null:c===r?o:o=t(r=c,n)}}function G6(e,t,n){var r,i,o;return function(){var c,l=n(this),d;return l==null?void this.removeAttribute(e):(c=this.getAttribute(e),d=l+"",c===d?null:c===r&&d===i?o:(i=d,o=t(r=c,l)))}}function K6(e,t,n){var r,i,o;return function(){var c,l=n(this),d;return l==null?void this.removeAttributeNS(e.space,e.local):(c=this.getAttributeNS(e.space,e.local),d=l+"",c===d?null:c===r&&d===i?o:(i=d,o=t(r=c,l)))}}function J6(e,t){var n=Wg(e),r=n==="transform"?$6:N$;return this.attrTween(e,typeof t=="function"?(n.local?K6:G6)(n,r,Mx(this,"attr."+e,t)):t==null?(n.local?q6:W6)(n):(n.local?H6:V6)(n,r,t))}function Y6(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function X6(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Z6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&X6(e,o)),n}return i._value=t,i}function Q6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&Y6(e,o)),n}return i._value=t,i}function e8(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=Wg(e);return this.tween(n,(r.local?Z6:Q6)(r,t))}function t8(e,t){return function(){Tx(this,e).delay=+t.apply(this,arguments)}}function n8(e,t){return t=+t,function(){Tx(this,e).delay=t}}function s8(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?t8:n8)(t,e)):Xo(this.node(),t).delay}function r8(e,t){return function(){Na(this,e).duration=+t.apply(this,arguments)}}function i8(e,t){return t=+t,function(){Na(this,e).duration=t}}function o8(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?r8:i8)(t,e)):Xo(this.node(),t).duration}function a8(e,t){if(typeof t!="function")throw new Error;return function(){Na(this,e).ease=t}}function l8(e){var t=this._id;return arguments.length?this.each(a8(t,e)):Xo(this.node(),t).ease}function c8(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Na(this,e).ease=n}}function u8(e){if(typeof e!="function")throw new Error;return this.each(c8(this._id,e))}function d8(e){typeof e!="function"&&(e=r$(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var o=t[i],c=o.length,l=r[i]=[],d,h=0;h<c;++h)(d=o[h])&&e.call(d,d.__data__,h,o)&&l.push(d);return new ll(r,this._parents,this._name,this._id)}function f8(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,i=n.length,o=Math.min(r,i),c=new Array(r),l=0;l<o;++l)for(var d=t[l],h=n[l],m=d.length,_=c[l]=new Array(m),g,y=0;y<m;++y)(g=d[y]||h[y])&&(_[y]=g);for(;l<r;++l)c[l]=t[l];return new ll(c,this._parents,this._name,this._id)}function h8(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 m8(e,t,n){var r,i,o=h8(t)?Tx:Na;return function(){var c=o(this,e),l=c.on;l!==r&&(i=(r=l).copy()).on(t,n),c.on=i}}function _8(e,t){var n=this._id;return arguments.length<2?Xo(this.node(),n).on.on(e):this.each(m8(n,e,t))}function p8(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function g8(){return this.on("end.remove",p8(this._id))}function y8(e){var t=this._name,n=this._id;typeof e!="function"&&(e=$x(e));for(var r=this._groups,i=r.length,o=new Array(i),c=0;c<i;++c)for(var l=r[c],d=l.length,h=o[c]=new Array(d),m,_,g=0;g<d;++g)(m=l[g])&&(_=e.call(m,m.__data__,g,l))&&("__data__"in m&&(_.__data__=m.__data__),h[g]=_,Vg(h[g],t,n,g,h,Xo(m,n)));return new ll(o,this._parents,t,n)}function w8(e){var t=this._name,n=this._id;typeof e!="function"&&(e=s$(e));for(var r=this._groups,i=r.length,o=[],c=[],l=0;l<i;++l)for(var d=r[l],h=d.length,m,_=0;_<h;++_)if(m=d[_]){for(var g=e.call(m,m.__data__,_,d),y,x=Xo(m,n),k=0,v=g.length;k<v;++k)(y=g[k])&&Vg(y,t,n,k,g,x);o.push(g),c.push(m)}return new ll(o,c,t,n)}var v8=Lm.prototype.constructor;function x8(){return new v8(this._groups,this._parents)}function b8(e,t){var n,r,i;return function(){var o=tf(this,e),c=(this.style.removeProperty(e),tf(this,e));return o===c?null:o===n&&c===r?i:i=t(n=o,r=c)}}function $$(e){return function(){this.style.removeProperty(e)}}function k8(e,t,n){var r,i=n+"",o;return function(){var c=tf(this,e);return c===i?null:c===r?o:o=t(r=c,n)}}function j8(e,t,n){var r,i,o;return function(){var c=tf(this,e),l=n(this),d=l+"";return l==null&&(d=l=(this.style.removeProperty(e),tf(this,e))),c===d?null:c===r&&d===i?o:(i=d,o=t(r=c,l))}}function S8(e,t){var n,r,i,o="style."+t,c="end."+o,l;return function(){var d=Na(this,e),h=d.on,m=d.value[o]==null?l||(l=$$(t)):void 0;(h!==n||i!==m)&&(r=(n=h).copy()).on(c,i=m),d.on=r}}function N8(e,t,n){var r=(e+="")=="transform"?N6:N$;return t==null?this.styleTween(e,b8(e,r)).on("end.style."+e,$$(e)):typeof t=="function"?this.styleTween(e,j8(e,r,Mx(this,"style."+e,t))).each(S8(this._id,e)):this.styleTween(e,k8(e,r,t),n).on("end.style."+e,null)}function $8(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function C8(e,t,n){var r,i;function o(){var c=t.apply(this,arguments);return c!==i&&(r=(i=c)&&$8(e,c,n)),r}return o._value=t,o}function E8(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,C8(e,t,n??""))}function A8(e){return function(){this.textContent=e}}function T8(e){return function(){var t=e(this);this.textContent=t??""}}function M8(e){return this.tween("text",typeof e=="function"?T8(Mx(this,"text",e)):A8(e==null?"":e+""))}function R8(e){return function(t){this.textContent=e.call(this,t)}}function L8(e){var t,n;function r(){var i=e.apply(this,arguments);return i!==n&&(t=(n=i)&&R8(i)),t}return r._value=e,r}function I8(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,L8(e))}function O8(){for(var e=this._name,t=this._id,n=C$(),r=this._groups,i=r.length,o=0;o<i;++o)for(var c=r[o],l=c.length,d,h=0;h<l;++h)if(d=c[h]){var m=Xo(d,t);Vg(d,e,n,h,c,{time:m.time+m.delay+m.duration,delay:0,duration:m.duration,ease:m.ease})}return new ll(r,this._parents,e,n)}function P8(){var e,t,n=this,r=n._id,i=n.size();return new Promise(function(o,c){var l={value:c},d={value:function(){--i===0&&o()}};n.each(function(){var h=Na(this,r),m=h.on;m!==e&&(t=(e=m).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(d)),h.on=t}),i===0&&o()})}var D8=0;function ll(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function C$(){return++D8}var Xa=Lm.prototype;ll.prototype={constructor:ll,select:y8,selectAll:w8,selectChild:Xa.selectChild,selectChildren:Xa.selectChildren,filter:d8,merge:f8,selection:x8,transition:O8,call:Xa.call,nodes:Xa.nodes,node:Xa.node,size:Xa.size,empty:Xa.empty,each:Xa.each,on:_8,attr:J6,attrTween:e8,style:N8,styleTween:E8,text:M8,textTween:I8,remove:g8,tween:U6,delay:s8,duration:o8,ease:l8,easeVarying:u8,end:P8,[Symbol.iterator]:Xa[Symbol.iterator]};function F8(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var z8={time:null,delay:0,duration:250,ease:F8};function B8(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 U8(e){var t,n;e instanceof ll?(t=e._id,e=e._name):(t=C$(),(n=z8).time=Ax(),e=e==null?null:e+"");for(var r=this._groups,i=r.length,o=0;o<i;++o)for(var c=r[o],l=c.length,d,h=0;h<l;++h)(d=c[h])&&Vg(d,e,t,h,c,n||B8(d,t));return new ll(r,this._parents,e,t)}Lm.prototype.interrupt=F6;Lm.prototype.transition=U8;const mp=e=>()=>e;function W8(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function tl(e,t,n){this.k=e,this.x=t,this.y=n}tl.prototype={constructor:tl,scale:function(e){return e===1?this:new tl(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new tl(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 sl=new tl(1,0,0);tl.prototype;function cw(e){e.stopImmediatePropagation()}function Ch(e){e.preventDefault(),e.stopImmediatePropagation()}function q8(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function V8(){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 Bk(){return this.__zoom||sl}function H8(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function G8(){return navigator.maxTouchPoints||"ontouchstart"in this}function K8(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],c=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),c>o?(o+c)/2:Math.min(0,o)||Math.max(0,c))}function E$(){var e=q8,t=V8,n=K8,r=H8,i=G8,o=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],l=250,d=T6,h=Ug("start","zoom","end"),m,_,g,y=500,x=150,k=0,v=10;function N(M){M.property("__zoom",Bk).on("wheel.zoom",P,{passive:!1}).on("mousedown.zoom",W).on("dblclick.zoom",J).filter(i).on("touchstart.zoom",G).on("touchmove.zoom",V).on("touchend.zoom touchcancel.zoom",R).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function(M,I,L,K){var H=M.selection?M.selection():M;H.property("__zoom",Bk),M!==H?D(M,I,L,K):H.interrupt().each(function(){O(this,arguments).event(K).start().zoom(null,typeof I=="function"?I.apply(this,arguments):I).end()})},N.scaleBy=function(M,I,L,K){N.scaleTo(M,function(){var H=this.__zoom.k,z=typeof I=="function"?I.apply(this,arguments):I;return H*z},L,K)},N.scaleTo=function(M,I,L,K){N.transform(M,function(){var H=t.apply(this,arguments),z=this.__zoom,ee=L==null?S(H):typeof L=="function"?L.apply(this,arguments):L,B=z.invert(ee),te=typeof I=="function"?I.apply(this,arguments):I;return n(C($(z,te),ee,B),H,c)},L,K)},N.translateBy=function(M,I,L,K){N.transform(M,function(){return n(this.__zoom.translate(typeof I=="function"?I.apply(this,arguments):I,typeof L=="function"?L.apply(this,arguments):L),t.apply(this,arguments),c)},null,K)},N.translateTo=function(M,I,L,K,H){N.transform(M,function(){var z=t.apply(this,arguments),ee=this.__zoom,B=K==null?S(z):typeof K=="function"?K.apply(this,arguments):K;return n(sl.translate(B[0],B[1]).scale(ee.k).translate(typeof I=="function"?-I.apply(this,arguments):-I,typeof L=="function"?-L.apply(this,arguments):-L),z,c)},K,H)};function $(M,I){return I=Math.max(o[0],Math.min(o[1],I)),I===M.k?M:new tl(I,M.x,M.y)}function C(M,I,L){var K=I[0]-L[0]*M.k,H=I[1]-L[1]*M.k;return K===M.x&&H===M.y?M:new tl(M.k,K,H)}function S(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function D(M,I,L,K){M.on("start.zoom",function(){O(this,arguments).event(K).start()}).on("interrupt.zoom end.zoom",function(){O(this,arguments).event(K).end()}).tween("zoom",function(){var H=this,z=arguments,ee=O(H,z).event(K),B=t.apply(H,z),te=L==null?S(B):typeof L=="function"?L.apply(H,z):L,se=Math.max(B[1][0]-B[0][0],B[1][1]-B[0][1]),de=H.__zoom,be=typeof I=="function"?I.apply(H,z):I,Me=d(de.invert(te).concat(se/de.k),be.invert(te).concat(se/be.k));return function(Ne){if(Ne===1)Ne=be;else{var ae=Me(Ne),je=se/ae[2];Ne=new tl(je,te[0]-ae[0]*je,te[1]-ae[1]*je)}ee.zoom(null,Ne)}})}function O(M,I,L){return!L&&M.__zooming||new A(M,I)}function A(M,I){this.that=M,this.args=I,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,I),this.taps=0}A.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,I){return this.mouse&&M!=="mouse"&&(this.mouse[1]=I.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=I.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=I.invert(this.touch1[0])),this.that.__zoom=I,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var I=vo(this.that).datum();h.call(M,this.that,new W8(M,{sourceEvent:this.sourceEvent,target:N,transform:this.that.__zoom,dispatch:h}),I)}};function P(M,...I){if(!e.apply(this,arguments))return;var L=O(this,I).event(M),K=this.__zoom,H=Math.max(o[0],Math.min(o[1],K.k*Math.pow(2,r.apply(this,arguments)))),z=Ho(M);if(L.wheel)(L.mouse[0][0]!==z[0]||L.mouse[0][1]!==z[1])&&(L.mouse[1]=K.invert(L.mouse[0]=z)),clearTimeout(L.wheel);else{if(K.k===H)return;L.mouse=[z,K.invert(z)],Fp(this),L.start()}Ch(M),L.wheel=setTimeout(ee,x),L.zoom("mouse",n(C($(K,H),L.mouse[0],L.mouse[1]),L.extent,c));function ee(){L.wheel=null,L.end()}}function W(M,...I){if(g||!e.apply(this,arguments))return;var L=M.currentTarget,K=O(this,I,!0).event(M),H=vo(M.view).on("mousemove.zoom",te,!0).on("mouseup.zoom",se,!0),z=Ho(M,L),ee=M.clientX,B=M.clientY;m$(M.view),cw(M),K.mouse=[z,this.__zoom.invert(z)],Fp(this),K.start();function te(de){if(Ch(de),!K.moved){var be=de.clientX-ee,Me=de.clientY-B;K.moved=be*be+Me*Me>k}K.event(de).zoom("mouse",n(C(K.that.__zoom,K.mouse[0]=Ho(de,L),K.mouse[1]),K.extent,c))}function se(de){H.on("mousemove.zoom mouseup.zoom",null),_$(de.view,K.moved),Ch(de),K.event(de).end()}}function J(M,...I){if(e.apply(this,arguments)){var L=this.__zoom,K=Ho(M.changedTouches?M.changedTouches[0]:M,this),H=L.invert(K),z=L.k*(M.shiftKey?.5:2),ee=n(C($(L,z),K,H),t.apply(this,I),c);Ch(M),l>0?vo(this).transition().duration(l).call(D,ee,K,M):vo(this).call(N.transform,ee,K,M)}}function G(M,...I){if(e.apply(this,arguments)){var L=M.touches,K=L.length,H=O(this,I,M.changedTouches.length===K).event(M),z,ee,B,te;for(cw(M),ee=0;ee<K;++ee)B=L[ee],te=Ho(B,this),te=[te,this.__zoom.invert(te),B.identifier],H.touch0?!H.touch1&&H.touch0[2]!==te[2]&&(H.touch1=te,H.taps=0):(H.touch0=te,z=!0,H.taps=1+!!m);m&&(m=clearTimeout(m)),z&&(H.taps<2&&(_=te[0],m=setTimeout(function(){m=null},y)),Fp(this),H.start())}}function V(M,...I){if(this.__zooming){var L=O(this,I).event(M),K=M.changedTouches,H=K.length,z,ee,B,te;for(Ch(M),z=0;z<H;++z)ee=K[z],B=Ho(ee,this),L.touch0&&L.touch0[2]===ee.identifier?L.touch0[0]=B:L.touch1&&L.touch1[2]===ee.identifier&&(L.touch1[0]=B);if(ee=L.that.__zoom,L.touch1){var se=L.touch0[0],de=L.touch0[1],be=L.touch1[0],Me=L.touch1[1],Ne=(Ne=be[0]-se[0])*Ne+(Ne=be[1]-se[1])*Ne,ae=(ae=Me[0]-de[0])*ae+(ae=Me[1]-de[1])*ae;ee=$(ee,Math.sqrt(Ne/ae)),B=[(se[0]+be[0])/2,(se[1]+be[1])/2],te=[(de[0]+Me[0])/2,(de[1]+Me[1])/2]}else if(L.touch0)B=L.touch0[0],te=L.touch0[1];else return;L.zoom("touch",n(C(ee,B,te),L.extent,c))}}function R(M,...I){if(this.__zooming){var L=O(this,I).event(M),K=M.changedTouches,H=K.length,z,ee;for(cw(M),g&&clearTimeout(g),g=setTimeout(function(){g=null},y),z=0;z<H;++z)ee=K[z],L.touch0&&L.touch0[2]===ee.identifier?delete L.touch0:L.touch1&&L.touch1[2]===ee.identifier&&delete L.touch1;if(L.touch1&&!L.touch0&&(L.touch0=L.touch1,delete L.touch1),L.touch0)L.touch0[1]=this.__zoom.invert(L.touch0[0]);else if(L.end(),L.taps===2&&(ee=Ho(ee,this),Math.hypot(_[0]-ee[0],_[1]-ee[1])<v)){var B=vo(this).on("dblclick.zoom");B&&B.apply(this,arguments)}}}return N.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:mp(+M),N):r},N.filter=function(M){return arguments.length?(e=typeof M=="function"?M:mp(!!M),N):e},N.touchable=function(M){return arguments.length?(i=typeof M=="function"?M:mp(!!M),N):i},N.extent=function(M){return arguments.length?(t=typeof M=="function"?M:mp([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),N):t},N.scaleExtent=function(M){return arguments.length?(o[0]=+M[0],o[1]=+M[1],N):[o[0],o[1]]},N.translateExtent=function(M){return arguments.length?(c[0][0]=+M[0][0],c[1][0]=+M[1][0],c[0][1]=+M[0][1],c[1][1]=+M[1][1],N):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},N.constrain=function(M){return arguments.length?(n=M,N):n},N.duration=function(M){return arguments.length?(l=+M,N):l},N.interpolate=function(M){return arguments.length?(d=M,N):d},N.on=function(){var M=h.on.apply(h,arguments);return M===h?N:M},N.clickDistance=function(M){return arguments.length?(k=(M=+M)*M,N):Math.sqrt(k)},N.tapDistance=function(M){return arguments.length?(v=+M,N):v},N}const Hg=p.createContext(null),J8=Hg.Provider,cl={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.`},A$=cl.error001();function ms(e,t){const n=p.useContext(Hg);if(n===null)throw new Error(A$);return t$(n,e,t)}const tr=()=>{const e=p.useContext(Hg);if(e===null)throw new Error(A$);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},Y8=e=>e.userSelectionActive?"none":"all";function hm({position:e,children:t,className:n,style:r,...i}){const o=ms(Y8),c=`${e}`.split("-");return Ae.createElement("div",{className:Er(["react-flow__panel",n,...c]),style:{...r,pointerEvents:o},...i},t)}function X8({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:Ae.createElement(hm,{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"},Ae.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const Z8=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:i=!0,labelBgStyle:o={},labelBgPadding:c=[2,4],labelBgBorderRadius:l=2,children:d,className:h,...m})=>{const _=p.useRef(null),[g,y]=p.useState({x:0,y:0,width:0,height:0}),x=Er(["react-flow__edge-textwrapper",h]);return p.useEffect(()=>{if(_.current){const k=_.current.getBBox();y({x:k.x,y:k.y,width:k.width,height:k.height})}},[n]),typeof n>"u"||!n?null:Ae.createElement("g",{transform:`translate(${e-g.width/2} ${t-g.height/2})`,className:x,visibility:g.width?"visible":"hidden",...m},i&&Ae.createElement("rect",{width:g.width+2*c[0],x:-c[0],y:-c[1],height:g.height+2*c[1],className:"react-flow__edge-textbg",style:o,rx:l,ry:l}),Ae.createElement("text",{className:"react-flow__edge-text",y:g.height/2,dy:"0.3em",ref:_,style:r},n),d)};var Q8=p.memo(Z8);const Rx=e=>({width:e.offsetWidth,height:e.offsetHeight}),sf=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Lx=(e={x:0,y:0},t)=>({x:sf(e.x,t[0][0],t[1][0]),y:sf(e.y,t[0][1],t[1][1])}),Uk=(e,t,n)=>e<t?sf(Math.abs(e-t),1,50)/50:e>n?-sf(Math.abs(e-n),1,50)/50:0,T$=(e,t)=>{const n=Uk(e.x,35,t.width-35)*20,r=Uk(e.y,35,t.height-35)*20;return[n,r]},M$=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},R$=(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)}),mm=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),L$=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Wk=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),ez=(e,t)=>L$(R$(mm(e),mm(t))),jv=(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)},tz=e=>xo(e.width)&&xo(e.height)&&xo(e.x)&&xo(e.y),xo=e=>!isNaN(e)&&isFinite(e),Gs=Symbol.for("internals"),I$=["Enter"," ","Escape"],nz=(e,t)=>{},sz=e=>"nativeEvent"in e;function Sv(e){var i,o;const t=sz(e)?e.nativeEvent:e,n=((o=(i=t.composedPath)==null?void 0:i.call(t))==null?void 0:o[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 O$=e=>"clientX"in e,ac=(e,t)=>{var o,c;const n=O$(e),r=n?e.clientX:(o=e.touches)==null?void 0:o[0].clientX,i=n?e.clientY:(c=e.touches)==null?void 0:c[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:i-((t==null?void 0:t.top)??0)}},_g=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0},Om=({id:e,path:t,labelX:n,labelY:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y=20})=>Ae.createElement(Ae.Fragment,null,Ae.createElement("path",{id:e,style:m,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:_,markerStart:g}),y&&Ae.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:y,className:"react-flow__edge-interaction"}),i&&xo(n)&&xo(r)?Ae.createElement(Q8,{x:n,y:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h}):null);Om.displayName="BaseEdge";function Eh(e,t,n){return n===void 0?n:r=>{const i=t().edges.find(o=>o.id===e);i&&n(r,{...i})}}function P$({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,o=n<e?n+i:n-i,c=Math.abs(r-t)/2,l=r<t?r+c:r-c;return[o,l,i,c]}function D$({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:o,targetControlX:c,targetControlY:l}){const d=e*.125+i*.375+c*.375+n*.125,h=t*.125+o*.375+l*.375+r*.125,m=Math.abs(d-e),_=Math.abs(h-t);return[d,h,m,_]}var xu;(function(e){e.Strict="strict",e.Loose="loose"})(xu||(xu={}));var ou;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(ou||(ou={}));var _m;(function(e){e.Partial="partial",e.Full="full"})(_m||(_m={}));var nc;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(nc||(nc={}));var pm;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(pm||(pm={}));var Ut;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Ut||(Ut={}));function qk({pos:e,x1:t,y1:n,x2:r,y2:i}){return e===Ut.Left||e===Ut.Right?[.5*(t+r),n]:[t,.5*(n+i)]}function F$({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top}){const[c,l]=qk({pos:n,x1:e,y1:t,x2:r,y2:i}),[d,h]=qk({pos:o,x1:r,y1:i,x2:e,y2:t}),[m,_,g,y]=D$({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:c,sourceControlY:l,targetControlX:d,targetControlY:h});return[`M${e},${t} C${c},${l} ${d},${h} ${r},${i}`,m,_,g,y]}const Ix=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Ut.Bottom,targetPosition:o=Ut.Top,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,interactionWidth:k})=>{const[v,N,$]=F$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o});return Ae.createElement(Om,{path:v,labelX:N,labelY:$,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,interactionWidth:k})});Ix.displayName="SimpleBezierEdge";const Vk={[Ut.Left]:{x:-1,y:0},[Ut.Right]:{x:1,y:0},[Ut.Top]:{x:0,y:-1},[Ut.Bottom]:{x:0,y:1}},rz=({source:e,sourcePosition:t=Ut.Bottom,target:n})=>t===Ut.Left||t===Ut.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},Hk=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function iz({source:e,sourcePosition:t=Ut.Bottom,target:n,targetPosition:r=Ut.Top,center:i,offset:o}){const c=Vk[t],l=Vk[r],d={x:e.x+c.x*o,y:e.y+c.y*o},h={x:n.x+l.x*o,y:n.y+l.y*o},m=rz({source:d,sourcePosition:t,target:h}),_=m.x!==0?"x":"y",g=m[_];let y=[],x,k;const v={x:0,y:0},N={x:0,y:0},[$,C,S,D]=P$({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(c[_]*l[_]===-1){x=i.x||$,k=i.y||C;const A=[{x,y:d.y},{x,y:h.y}],P=[{x:d.x,y:k},{x:h.x,y:k}];c[_]===g?y=_==="x"?A:P:y=_==="x"?P:A}else{const A=[{x:d.x,y:h.y}],P=[{x:h.x,y:d.y}];if(_==="x"?y=c.x===g?P:A:y=c.y===g?A:P,t===r){const R=Math.abs(e[_]-n[_]);if(R<=o){const M=Math.min(o-1,o-R);c[_]===g?v[_]=(d[_]>e[_]?-1:1)*M:N[_]=(h[_]>n[_]?-1:1)*M}}if(t!==r){const R=_==="x"?"y":"x",M=c[_]===l[R],I=d[R]>h[R],L=d[R]<h[R];(c[_]===1&&(!M&&I||M&&L)||c[_]!==1&&(!M&&L||M&&I))&&(y=_==="x"?A:P)}const W={x:d.x+v.x,y:d.y+v.y},J={x:h.x+N.x,y:h.y+N.y},G=Math.max(Math.abs(W.x-y[0].x),Math.abs(J.x-y[0].x)),V=Math.max(Math.abs(W.y-y[0].y),Math.abs(J.y-y[0].y));G>=V?(x=(W.x+J.x)/2,k=y[0].y):(x=y[0].x,k=(W.y+J.y)/2)}return[[e,{x:d.x+v.x,y:d.y+v.y},...y,{x:h.x+N.x,y:h.y+N.y},n],x,k,S,D]}function oz(e,t,n,r){const i=Math.min(Hk(e,t)/2,Hk(t,n)/2,r),{x:o,y:c}=t;if(e.x===o&&o===n.x||e.y===c&&c===n.y)return`L${o} ${c}`;if(e.y===c){const h=e.x<n.x?-1:1,m=e.y<n.y?1:-1;return`L ${o+i*h},${c}Q ${o},${c} ${o},${c+i*m}`}const l=e.x<n.x?1:-1,d=e.y<n.y?-1:1;return`L ${o},${c+i*d}Q ${o},${c} ${o+i*l},${c}`}function Nv({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top,borderRadius:c=5,centerX:l,centerY:d,offset:h=20}){const[m,_,g,y,x]=iz({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:o,center:{x:l,y:d},offset:h});return[m.reduce((v,N,$)=>{let C="";return $>0&&$<m.length-1?C=oz(m[$-1],N,m[$+1],c):C=`${$===0?"M":"L"}${N.x} ${N.y}`,v+=C,v},""),_,g,y,x]}const Gg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,sourcePosition:_=Ut.Bottom,targetPosition:g=Ut.Top,markerEnd:y,markerStart:x,pathOptions:k,interactionWidth:v})=>{const[N,$,C]=Nv({sourceX:e,sourceY:t,sourcePosition:_,targetX:n,targetY:r,targetPosition:g,borderRadius:k==null?void 0:k.borderRadius,offset:k==null?void 0:k.offset});return Ae.createElement(Om,{path:N,labelX:$,labelY:C,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:y,markerStart:x,interactionWidth:v})});Gg.displayName="SmoothStepEdge";const Ox=p.memo(e=>{var t;return Ae.createElement(Gg,{...e,pathOptions:p.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});Ox.displayName="StepEdge";function az({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,c,l]=P$({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,o,c,l]}const Px=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y})=>{const[x,k,v]=az({sourceX:e,sourceY:t,targetX:n,targetY:r});return Ae.createElement(Om,{path:x,labelX:k,labelY:v,label:i,labelStyle:o,labelShowBg:c,labelBgStyle:l,labelBgPadding:d,labelBgBorderRadius:h,style:m,markerEnd:_,markerStart:g,interactionWidth:y})});Px.displayName="StraightEdge";function _p(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Gk({pos:e,x1:t,y1:n,x2:r,y2:i,c:o}){switch(e){case Ut.Left:return[t-_p(t-r,o),n];case Ut.Right:return[t+_p(r-t,o),n];case Ut.Top:return[t,n-_p(n-i,o)];case Ut.Bottom:return[t,n+_p(i-n,o)]}}function z$({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:o=Ut.Top,curvature:c=.25}){const[l,d]=Gk({pos:n,x1:e,y1:t,x2:r,y2:i,c}),[h,m]=Gk({pos:o,x1:r,y1:i,x2:e,y2:t,c}),[_,g,y,x]=D$({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:l,sourceControlY:d,targetControlX:h,targetControlY:m});return[`M${e},${t} C${l},${d} ${h},${m} ${r},${i}`,_,g,y,x]}const pg=p.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=Ut.Bottom,targetPosition:o=Ut.Top,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,pathOptions:k,interactionWidth:v})=>{const[N,$,C]=z$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o,curvature:k==null?void 0:k.curvature});return Ae.createElement(Om,{path:N,labelX:$,labelY:C,label:c,labelStyle:l,labelShowBg:d,labelBgStyle:h,labelBgPadding:m,labelBgBorderRadius:_,style:g,markerEnd:y,markerStart:x,interactionWidth:v})});pg.displayName="BezierEdge";const Dx=p.createContext(null),lz=Dx.Provider;Dx.Consumer;const cz=()=>p.useContext(Dx),uz=e=>"id"in e&&"source"in e&&"target"in e,dz=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,$v=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,fz=(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)),hz=(e,t)=>{if(!e.source||!e.target)return t;let n;return uz(e)?n={...e}:n={...e,id:dz(e)},fz(n,t)?t:t.concat(n)},Cv=({x:e,y:t},[n,r,i],o,[c,l])=>{const d={x:(e-n)/i,y:(t-r)/i};return o?{x:c*Math.round(d.x/c),y:l*Math.round(d.y/l)}:d},B$=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r}),du=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],r=(e.height??0)*t[1],i={x:e.position.x-n,y:e.position.y-r};return{...i,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:i}},Kg=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,i)=>{const{x:o,y:c}=du(i,t).positionAbsolute;return R$(r,mm({x:o,y:c,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return L$(n)},U$=(e,t,[n,r,i]=[0,0,1],o=!1,c=!1,l=[0,0])=>{const d={x:(t.x-n)/i,y:(t.y-r)/i,width:t.width/i,height:t.height/i},h=[];return e.forEach(m=>{const{width:_,height:g,selectable:y=!0,hidden:x=!1}=m;if(c&&!y||x)return!1;const{positionAbsolute:k}=du(m,l),v={x:k.x,y:k.y,width:_||0,height:g||0},N=jv(d,v),$=typeof _>"u"||typeof g>"u"||_===null||g===null,C=o&&N>0,S=(_||0)*(g||0);($||C||N>=S||m.dragging)&&h.push(m)}),h},W$=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},q$=(e,t,n,r,i,o=.1)=>{const c=t/(e.width*(1+o)),l=n/(e.height*(1+o)),d=Math.min(c,l),h=sf(d,r,i),m=e.x+e.width/2,_=e.y+e.height/2,g=t/2-m*h,y=n/2-_*h;return{x:g,y,zoom:h}},nu=(e,t=0)=>e.transition().duration(t);function Kk(e,t,n,r){return(t[n]||[]).reduce((i,o)=>{var c,l;return`${e.id}-${o.id}-${n}`!==r&&i.push({id:o.id||null,type:n,nodeId:e.id,x:(((c=e.positionAbsolute)==null?void 0:c.x)??0)+o.x+o.width/2,y:(((l=e.positionAbsolute)==null?void 0:l.y)??0)+o.y+o.height/2}),i},[])}function mz(e,t,n,r,i,o){const{x:c,y:l}=ac(e),h=t.elementsFromPoint(c,l).find(x=>x.classList.contains("react-flow__handle"));if(h){const x=h.getAttribute("data-nodeid");if(x){const k=Fx(void 0,h),v=h.getAttribute("data-handleid"),N=o({nodeId:x,id:v,type:k});if(N){const $=i.find(C=>C.nodeId===x&&C.type===k&&C.id===v);return{handle:{id:v,type:k,nodeId:x,x:($==null?void 0:$.x)||n.x,y:($==null?void 0:$.y)||n.y},validHandleResult:N}}}}let m=[],_=1/0;if(i.forEach(x=>{const k=Math.sqrt((x.x-n.x)**2+(x.y-n.y)**2);if(k<=r){const v=o(x);k<=_&&(k<_?m=[{handle:x,validHandleResult:v}]:k===_&&m.push({handle:x,validHandleResult:v}),_=k)}}),!m.length)return{handle:null,validHandleResult:V$()};if(m.length===1)return m[0];const g=m.some(({validHandleResult:x})=>x.isValid),y=m.some(({handle:x})=>x.type==="target");return m.find(({handle:x,validHandleResult:k})=>y?x.type==="target":g?k.isValid:!0)||m[0]}const _z={source:null,target:null,sourceHandle:null,targetHandle:null},V$=()=>({handleDomNode:null,isValid:!1,connection:_z,endHandle:null});function H$(e,t,n,r,i,o,c){const l=i==="target",d=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={...V$(),handleDomNode:d};if(d){const m=Fx(void 0,d),_=d.getAttribute("data-nodeid"),g=d.getAttribute("data-handleid"),y=d.classList.contains("connectable"),x=d.classList.contains("connectableend"),k={source:l?_:n,sourceHandle:l?g:r,target:l?n:_,targetHandle:l?r:g};h.connection=k,y&&x&&(t===xu.Strict?l&&m==="source"||!l&&m==="target":_!==n||g!==r)&&(h.endHandle={nodeId:_,handleId:g,type:m},h.isValid=o(k))}return h}function pz({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((i,o)=>{if(o[Gs]){const{handleBounds:c}=o[Gs];let l=[],d=[];c&&(l=Kk(o,c,"source",`${t}-${n}-${r}`),d=Kk(o,c,"target",`${t}-${n}-${r}`)),i.push(...l,...d)}return i},[])}function Fx(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function uw(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function gz(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function G$({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:i,getState:o,setState:c,isValidConnection:l,edgeUpdaterType:d,onEdgeUpdateEnd:h}){const m=M$(e.target),{connectionMode:_,domNode:g,autoPanOnConnect:y,connectionRadius:x,onConnectStart:k,panBy:v,getNodes:N,cancelConnection:$}=o();let C=0,S;const{x:D,y:O}=ac(e),A=m==null?void 0:m.elementFromPoint(D,O),P=Fx(d,A),W=g==null?void 0:g.getBoundingClientRect();if(!W||!P)return;let J,G=ac(e,W),V=!1,R=null,M=!1,I=null;const L=pz({nodes:N(),nodeId:n,handleId:t,handleType:P}),K=()=>{if(!y)return;const[ee,B]=T$(G,W);v({x:ee,y:B}),C=requestAnimationFrame(K)};c({connectionPosition:G,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:P,connectionStartHandle:{nodeId:n,handleId:t,type:P},connectionEndHandle:null}),k==null||k(e,{nodeId:n,handleId:t,handleType:P});function H(ee){const{transform:B}=o();G=ac(ee,W);const{handle:te,validHandleResult:se}=mz(ee,m,Cv(G,B,!1,[1,1]),x,L,de=>H$(de,_,n,t,i?"target":"source",l,m));if(S=te,V||(K(),V=!0),I=se.handleDomNode,R=se.connection,M=se.isValid,c({connectionPosition:S&&M?B$({x:S.x,y:S.y},B):G,connectionStatus:gz(!!S,M),connectionEndHandle:se.endHandle}),!S&&!M&&!I)return uw(J);R.source!==R.target&&I&&(uw(J),J=I,I.classList.add("connecting","react-flow__handle-connecting"),I.classList.toggle("valid",M),I.classList.toggle("react-flow__handle-valid",M))}function z(ee){var B,te;(S||I)&&R&&M&&(r==null||r(R)),(te=(B=o()).onConnectEnd)==null||te.call(B,ee),d&&(h==null||h(ee)),uw(J),$(),cancelAnimationFrame(C),V=!1,M=!1,R=null,I=null,m.removeEventListener("mousemove",H),m.removeEventListener("mouseup",z),m.removeEventListener("touchmove",H),m.removeEventListener("touchend",z)}m.addEventListener("mousemove",H),m.addEventListener("mouseup",z),m.addEventListener("touchmove",H),m.addEventListener("touchend",z)}const Jk=()=>!0,yz=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),wz=(e,t,n)=>r=>{const{connectionStartHandle:i,connectionEndHandle:o,connectionClickStartHandle:c}=r;return{connecting:(i==null?void 0:i.nodeId)===e&&(i==null?void 0:i.handleId)===t&&(i==null?void 0:i.type)===n||(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n,clickConnecting:(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.handleId)===t&&(c==null?void 0:c.type)===n}},K$=p.forwardRef(({type:e="source",position:t=Ut.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:o=!0,id:c,onConnect:l,children:d,className:h,onMouseDown:m,onTouchStart:_,...g},y)=>{var W,J;const x=c||null,k=e==="target",v=tr(),N=cz(),{connectOnClick:$,noPanClassName:C}=ms(yz,mr),{connecting:S,clickConnecting:D}=ms(wz(N,x,e),mr);N||(J=(W=v.getState()).onError)==null||J.call(W,"010",cl.error010());const O=G=>{const{defaultEdgeOptions:V,onConnect:R,hasDefaultEdges:M}=v.getState(),I={...V,...G};if(M){const{edges:L,setEdges:K}=v.getState();K(hz(I,L))}R==null||R(I),l==null||l(I)},A=G=>{if(!N)return;const V=O$(G);i&&(V&&G.button===0||!V)&&G$({event:G,handleId:x,nodeId:N,onConnect:O,isTarget:k,getState:v.getState,setState:v.setState,isValidConnection:n||v.getState().isValidConnection||Jk}),V?m==null||m(G):_==null||_(G)},P=G=>{const{onClickConnectStart:V,onClickConnectEnd:R,connectionClickStartHandle:M,connectionMode:I,isValidConnection:L}=v.getState();if(!N||!M&&!i)return;if(!M){V==null||V(G,{nodeId:N,handleId:x,handleType:e}),v.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:x}});return}const K=M$(G.target),H=n||L||Jk,{connection:z,isValid:ee}=H$({nodeId:N,id:x,type:e},I,M.nodeId,M.handleId||null,M.type,H,K);ee&&O(z),R==null||R(G),v.setState({connectionClickStartHandle:null})};return Ae.createElement("div",{"data-handleid":x,"data-nodeid":N,"data-handlepos":t,"data-id":`${N}-${x}-${e}`,className:Er(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",C,h,{source:!k,target:k,connectable:r,connectablestart:i,connectableend:o,connecting:D,connectionindicator:r&&(i&&!S||o&&S)}]),onMouseDown:A,onTouchStart:A,onClick:$?P:void 0,ref:y,...g},d)});K$.displayName="Handle";var gg=p.memo(K$);const J$=({data:e,isConnectable:t,targetPosition:n=Ut.Top,sourcePosition:r=Ut.Bottom})=>Ae.createElement(Ae.Fragment,null,Ae.createElement(gg,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,Ae.createElement(gg,{type:"source",position:r,isConnectable:t}));J$.displayName="DefaultNode";var Ev=p.memo(J$);const Y$=({data:e,isConnectable:t,sourcePosition:n=Ut.Bottom})=>Ae.createElement(Ae.Fragment,null,e==null?void 0:e.label,Ae.createElement(gg,{type:"source",position:n,isConnectable:t}));Y$.displayName="InputNode";var X$=p.memo(Y$);const Z$=({data:e,isConnectable:t,targetPosition:n=Ut.Top})=>Ae.createElement(Ae.Fragment,null,Ae.createElement(gg,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);Z$.displayName="OutputNode";var Q$=p.memo(Z$);const zx=()=>null;zx.displayName="GroupNode";const vz=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),pp=e=>e.id;function xz(e,t){return mr(e.selectedNodes.map(pp),t.selectedNodes.map(pp))&&mr(e.selectedEdges.map(pp),t.selectedEdges.map(pp))}const eC=p.memo(({onSelectionChange:e})=>{const t=tr(),{selectedNodes:n,selectedEdges:r}=ms(vz,xz);return p.useEffect(()=>{const i={nodes:n,edges:r};e==null||e(i),t.getState().onSelectionChange.forEach(o=>o(i))},[n,r,e]),null});eC.displayName="SelectionListener";const bz=e=>!!e.onSelectionChange;function kz({onSelectionChange:e}){const t=ms(bz);return e||t?Ae.createElement(eC,{onSelectionChange:e}):null}const jz=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 jd(e,t){p.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Nn(e,t,n){p.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const Sz=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:i,onConnectStart:o,onConnectEnd:c,onClickConnectStart:l,onClickConnectEnd:d,nodesDraggable:h,nodesConnectable:m,nodesFocusable:_,edgesFocusable:g,edgesUpdatable:y,elevateNodesOnSelect:x,minZoom:k,maxZoom:v,nodeExtent:N,onNodesChange:$,onEdgesChange:C,elementsSelectable:S,connectionMode:D,snapGrid:O,snapToGrid:A,translateExtent:P,connectOnClick:W,defaultEdgeOptions:J,fitView:G,fitViewOptions:V,onNodesDelete:R,onEdgesDelete:M,onNodeDrag:I,onNodeDragStart:L,onNodeDragStop:K,onSelectionDrag:H,onSelectionDragStart:z,onSelectionDragStop:ee,noPanClassName:B,nodeOrigin:te,rfId:se,autoPanOnConnect:de,autoPanOnNodeDrag:be,onError:Me,connectionRadius:Ne,isValidConnection:ae,nodeDragThreshold:je})=>{const{setNodes:Te,setEdges:Ve,setDefaultNodesAndEdges:_t,setMinZoom:Qe,setMaxZoom:it,setTranslateExtent:$t,setNodeExtent:ot,reset:mt}=ms(jz,mr),et=tr();return p.useEffect(()=>{const Lt=r==null?void 0:r.map(ce=>({...ce,...J}));return _t(n,Lt),()=>{mt()}},[]),Nn("defaultEdgeOptions",J,et.setState),Nn("connectionMode",D,et.setState),Nn("onConnect",i,et.setState),Nn("onConnectStart",o,et.setState),Nn("onConnectEnd",c,et.setState),Nn("onClickConnectStart",l,et.setState),Nn("onClickConnectEnd",d,et.setState),Nn("nodesDraggable",h,et.setState),Nn("nodesConnectable",m,et.setState),Nn("nodesFocusable",_,et.setState),Nn("edgesFocusable",g,et.setState),Nn("edgesUpdatable",y,et.setState),Nn("elementsSelectable",S,et.setState),Nn("elevateNodesOnSelect",x,et.setState),Nn("snapToGrid",A,et.setState),Nn("snapGrid",O,et.setState),Nn("onNodesChange",$,et.setState),Nn("onEdgesChange",C,et.setState),Nn("connectOnClick",W,et.setState),Nn("fitViewOnInit",G,et.setState),Nn("fitViewOnInitOptions",V,et.setState),Nn("onNodesDelete",R,et.setState),Nn("onEdgesDelete",M,et.setState),Nn("onNodeDrag",I,et.setState),Nn("onNodeDragStart",L,et.setState),Nn("onNodeDragStop",K,et.setState),Nn("onSelectionDrag",H,et.setState),Nn("onSelectionDragStart",z,et.setState),Nn("onSelectionDragStop",ee,et.setState),Nn("noPanClassName",B,et.setState),Nn("nodeOrigin",te,et.setState),Nn("rfId",se,et.setState),Nn("autoPanOnConnect",de,et.setState),Nn("autoPanOnNodeDrag",be,et.setState),Nn("onError",Me,et.setState),Nn("connectionRadius",Ne,et.setState),Nn("isValidConnection",ae,et.setState),Nn("nodeDragThreshold",je,et.setState),jd(e,Te),jd(t,Ve),jd(k,Qe),jd(v,it),jd(P,$t),jd(N,ot),null},Yk={display:"none"},Nz={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},tC="react-flow__node-desc",nC="react-flow__edge-desc",$z="react-flow__aria-live",Cz=e=>e.ariaLiveMessage;function Ez({rfId:e}){const t=ms(Cz);return Ae.createElement("div",{id:`${$z}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Nz},t)}function Az({rfId:e,disableKeyboardA11y:t}){return Ae.createElement(Ae.Fragment,null,Ae.createElement("div",{id:`${tC}-${e}`,style:Yk},"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."," "),Ae.createElement("div",{id:`${nC}-${e}`,style:Yk},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&Ae.createElement(Ez,{rfId:e}))}var gm=(e=null,t={actInsideInputWithModifier:!0})=>{const[n,r]=p.useState(!1),i=p.useRef(!1),o=p.useRef(new Set([])),[c,l]=p.useMemo(()=>{if(e!==null){const h=(Array.isArray(e)?e:[e]).filter(_=>typeof _=="string").map(_=>_.split("+")),m=h.reduce((_,g)=>_.concat(...g),[]);return[h,m]}return[[],[]]},[e]);return p.useEffect(()=>{const d=typeof document<"u"?document:null,h=(t==null?void 0:t.target)||d;if(e!==null){const m=y=>{if(i.current=y.ctrlKey||y.metaKey||y.shiftKey,(!i.current||i.current&&!t.actInsideInputWithModifier)&&Sv(y))return!1;const k=Zk(y.code,l);o.current.add(y[k]),Xk(c,o.current,!1)&&(y.preventDefault(),r(!0))},_=y=>{if((!i.current||i.current&&!t.actInsideInputWithModifier)&&Sv(y))return!1;const k=Zk(y.code,l);Xk(c,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(y[k]),y.key==="Meta"&&o.current.clear(),i.current=!1},g=()=>{o.current.clear(),r(!1)};return h==null||h.addEventListener("keydown",m),h==null||h.addEventListener("keyup",_),window.addEventListener("blur",g),()=>{h==null||h.removeEventListener("keydown",m),h==null||h.removeEventListener("keyup",_),window.removeEventListener("blur",g)}}},[e,r]),n};function Xk(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(i=>t.has(i)))}function Zk(e,t){return t.includes(e)?"code":"key"}function sC(e,t,n,r){var c,l;if(!e.parentNode)return n;const i=t.get(e.parentNode),o=du(i,r);return sC(i,t,{x:(n.x??0)+o.x,y:(n.y??0)+o.y,z:(((c=i[Gs])==null?void 0:c.z)??0)>(n.z??0)?((l=i[Gs])==null?void 0:l.z)??0:n.z??0},r)}function rC(e,t,n){e.forEach(r=>{var i;if(r.parentNode&&!e.has(r.parentNode))throw new Error(`Parent node ${r.parentNode} not found`);if(r.parentNode||n!=null&&n[r.id]){const{x:o,y:c,z:l}=sC(r,e,{...r.position,z:((i=r[Gs])==null?void 0:i.z)??0},t);r.positionAbsolute={x:o,y:c},r[Gs].z=l,n!=null&&n[r.id]&&(r[Gs].isParent=!0)}})}function dw(e,t,n,r){const i=new Map,o={},c=r?1e3:0;return e.forEach(l=>{var g;const d=(xo(l.zIndex)?l.zIndex:0)+(l.selected?c:0),h=t.get(l.id),m={...l,positionAbsolute:{x:l.position.x,y:l.position.y}};l.parentNode&&(o[l.parentNode]=!0);const _=(h==null?void 0:h.type)&&(h==null?void 0:h.type)!==l.type;Object.defineProperty(m,Gs,{enumerable:!1,value:{handleBounds:_||(g=h==null?void 0:h[Gs])==null?void 0:g.handleBounds,z:d}}),i.set(l.id,m)}),rC(i,n,o),i}function iC(e,t={}){const{getNodes:n,width:r,height:i,minZoom:o,maxZoom:c,d3Zoom:l,d3Selection:d,fitViewOnInitDone:h,fitViewOnInit:m,nodeOrigin:_}=e(),g=t.initial&&!h&&m;if(l&&d&&(g||!t.initial)){const x=n().filter(v=>{var $;const N=t.includeHiddenNodes?v.width&&v.height:!v.hidden;return($=t.nodes)!=null&&$.length?N&&t.nodes.some(C=>C.id===v.id):N}),k=x.every(v=>v.width&&v.height);if(x.length>0&&k){const v=Kg(x,_),{x:N,y:$,zoom:C}=q$(v,r,i,t.minZoom??o,t.maxZoom??c,t.padding??.1),S=sl.translate(N,$).scale(C);return typeof t.duration=="number"&&t.duration>0?l.transform(nu(d,t.duration),S):l.transform(d,S),!0}}return!1}function Tz(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[Gs]:r[Gs],selected:n.selected})}),new Map(t)}function Mz(e,t){return t.map(n=>{const r=e.find(i=>i.id===n.id);return r&&(n.selected=r.selected),n})}function gp({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:i,edges:o,onNodesChange:c,onEdgesChange:l,hasDefaultNodes:d,hasDefaultEdges:h}=n();e!=null&&e.length&&(d&&r({nodeInternals:Tz(e,i)}),c==null||c(e)),t!=null&&t.length&&(h&&r({edges:Mz(t,o)}),l==null||l(t))}const Sd=()=>{},Rz={zoomIn:Sd,zoomOut:Sd,zoomTo:Sd,getZoom:()=>1,setViewport:Sd,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:Sd,fitBounds:Sd,project:e=>e,screenToFlowPosition:e=>e,flowToScreenPosition:e=>e,viewportInitialized:!1},Lz=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),Iz=()=>{const e=tr(),{d3Zoom:t,d3Selection:n}=ms(Lz,mr);return p.useMemo(()=>n&&t?{zoomIn:i=>t.scaleBy(nu(n,i==null?void 0:i.duration),1.2),zoomOut:i=>t.scaleBy(nu(n,i==null?void 0:i.duration),1/1.2),zoomTo:(i,o)=>t.scaleTo(nu(n,o==null?void 0:o.duration),i),getZoom:()=>e.getState().transform[2],setViewport:(i,o)=>{const[c,l,d]=e.getState().transform,h=sl.translate(i.x??c,i.y??l).scale(i.zoom??d);t.transform(nu(n,o==null?void 0:o.duration),h)},getViewport:()=>{const[i,o,c]=e.getState().transform;return{x:i,y:o,zoom:c}},fitView:i=>iC(e.getState,i),setCenter:(i,o,c)=>{const{width:l,height:d,maxZoom:h}=e.getState(),m=typeof(c==null?void 0:c.zoom)<"u"?c.zoom:h,_=l/2-i*m,g=d/2-o*m,y=sl.translate(_,g).scale(m);t.transform(nu(n,c==null?void 0:c.duration),y)},fitBounds:(i,o)=>{const{width:c,height:l,minZoom:d,maxZoom:h}=e.getState(),{x:m,y:_,zoom:g}=q$(i,c,l,d,h,(o==null?void 0:o.padding)??.1),y=sl.translate(m,_).scale(g);t.transform(nu(n,o==null?void 0:o.duration),y)},project:i=>{const{transform:o,snapToGrid:c,snapGrid:l}=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"),Cv(i,o,c,l)},screenToFlowPosition:i=>{const{transform:o,snapToGrid:c,snapGrid:l,domNode:d}=e.getState();if(!d)return i;const{x:h,y:m}=d.getBoundingClientRect(),_={x:i.x-h,y:i.y-m};return Cv(_,o,c,l)},flowToScreenPosition:i=>{const{transform:o,domNode:c}=e.getState();if(!c)return i;const{x:l,y:d}=c.getBoundingClientRect(),h=B$(i,o);return{x:h.x+l,y:h.y+d}},viewportInitialized:!0}:Rz,[t,n])};function Bx(){const e=Iz(),t=tr(),n=p.useCallback(()=>t.getState().getNodes().map(k=>({...k})),[]),r=p.useCallback(k=>t.getState().nodeInternals.get(k),[]),i=p.useCallback(()=>{const{edges:k=[]}=t.getState();return k.map(v=>({...v}))},[]),o=p.useCallback(k=>{const{edges:v=[]}=t.getState();return v.find(N=>N.id===k)},[]),c=p.useCallback(k=>{const{getNodes:v,setNodes:N,hasDefaultNodes:$,onNodesChange:C}=t.getState(),S=v(),D=typeof k=="function"?k(S):k;if($)N(D);else if(C){const O=D.length===0?S.map(A=>({type:"remove",id:A.id})):D.map(A=>({item:A,type:"reset"}));C(O)}},[]),l=p.useCallback(k=>{const{edges:v=[],setEdges:N,hasDefaultEdges:$,onEdgesChange:C}=t.getState(),S=typeof k=="function"?k(v):k;if($)N(S);else if(C){const D=S.length===0?v.map(O=>({type:"remove",id:O.id})):S.map(O=>({item:O,type:"reset"}));C(D)}},[]),d=p.useCallback(k=>{const v=Array.isArray(k)?k:[k],{getNodes:N,setNodes:$,hasDefaultNodes:C,onNodesChange:S}=t.getState();if(C){const O=[...N(),...v];$(O)}else if(S){const D=v.map(O=>({item:O,type:"add"}));S(D)}},[]),h=p.useCallback(k=>{const v=Array.isArray(k)?k:[k],{edges:N=[],setEdges:$,hasDefaultEdges:C,onEdgesChange:S}=t.getState();if(C)$([...N,...v]);else if(S){const D=v.map(O=>({item:O,type:"add"}));S(D)}},[]),m=p.useCallback(()=>{const{getNodes:k,edges:v=[],transform:N}=t.getState(),[$,C,S]=N;return{nodes:k().map(D=>({...D})),edges:v.map(D=>({...D})),viewport:{x:$,y:C,zoom:S}}},[]),_=p.useCallback(({nodes:k,edges:v})=>{const{nodeInternals:N,getNodes:$,edges:C,hasDefaultNodes:S,hasDefaultEdges:D,onNodesDelete:O,onEdgesDelete:A,onNodesChange:P,onEdgesChange:W}=t.getState(),J=(k||[]).map(I=>I.id),G=(v||[]).map(I=>I.id),V=$().reduce((I,L)=>{const K=!J.includes(L.id)&&L.parentNode&&I.find(z=>z.id===L.parentNode);return(typeof L.deletable=="boolean"?L.deletable:!0)&&(J.includes(L.id)||K)&&I.push(L),I},[]),R=C.filter(I=>typeof I.deletable=="boolean"?I.deletable:!0),M=R.filter(I=>G.includes(I.id));if(V||M){const I=W$(V,R),L=[...M,...I],K=L.reduce((H,z)=>(H.includes(z.id)||H.push(z.id),H),[]);if((D||S)&&(D&&t.setState({edges:C.filter(H=>!K.includes(H.id))}),S&&(V.forEach(H=>{N.delete(H.id)}),t.setState({nodeInternals:new Map(N)}))),K.length>0&&(A==null||A(L),W&&W(K.map(H=>({id:H,type:"remove"})))),V.length>0&&(O==null||O(V),P)){const H=V.map(z=>({id:z.id,type:"remove"}));P(H)}}},[]),g=p.useCallback(k=>{const v=tz(k),N=v?null:t.getState().nodeInternals.get(k.id);return!v&&!N?[null,null,v]:[v?k:Wk(N),N,v]},[]),y=p.useCallback((k,v=!0,N)=>{const[$,C,S]=g(k);return $?(N||t.getState().getNodes()).filter(D=>{if(!S&&(D.id===C.id||!D.positionAbsolute))return!1;const O=Wk(D),A=jv(O,$);return v&&A>0||A>=$.width*$.height}):[]},[]),x=p.useCallback((k,v,N=!0)=>{const[$]=g(k);if(!$)return!1;const C=jv($,v);return N&&C>0||C>=$.width*$.height},[]);return p.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:i,getEdge:o,setNodes:c,setEdges:l,addNodes:d,addEdges:h,toObject:m,deleteElements:_,getIntersectingNodes:y,isNodeIntersecting:x}),[e,n,r,i,o,c,l,d,h,m,_,y,x])}const Oz={actInsideInputWithModifier:!1};var Pz=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=tr(),{deleteElements:r}=Bx(),i=gm(e,Oz),o=gm(t);p.useEffect(()=>{if(i){const{edges:c,getNodes:l}=n.getState(),d=l().filter(m=>m.selected),h=c.filter(m=>m.selected);r({nodes:d,edges:h}),n.setState({nodesSelectionActive:!1})}},[i]),p.useEffect(()=>{n.setState({multiSelectionActive:o})},[o])};function Dz(e){const t=tr();p.useEffect(()=>{let n;const r=()=>{var o,c;if(!e.current)return;const i=Rx(e.current);(i.height===0||i.width===0)&&((c=(o=t.getState()).onError)==null||c.call(o,"004",cl.error004())),t.setState({width:i.width||500,height:i.height||500})};return r(),window.addEventListener("resize",r),e.current&&(n=new ResizeObserver(()=>r()),n.observe(e.current)),()=>{window.removeEventListener("resize",r),n&&e.current&&n.unobserve(e.current)}},[])}const Ux={position:"absolute",width:"100%",height:"100%",top:0,left:0},Fz=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,yp=e=>({x:e.x,y:e.y,zoom:e.k}),Nd=(e,t)=>e.target.closest(`.${t}`),Qk=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),ej=e=>{const t=e.ctrlKey&&_g()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t},zz=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),Bz=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:i=!0,zoomOnPinch:o=!0,panOnScroll:c=!1,panOnScrollSpeed:l=.5,panOnScrollMode:d=ou.Free,zoomOnDoubleClick:h=!0,elementsSelectable:m,panOnDrag:_=!0,defaultViewport:g,translateExtent:y,minZoom:x,maxZoom:k,zoomActivationKeyCode:v,preventScrolling:N=!0,children:$,noWheelClassName:C,noPanClassName:S})=>{const D=p.useRef(),O=tr(),A=p.useRef(!1),P=p.useRef(!1),W=p.useRef(null),J=p.useRef({x:0,y:0,zoom:0}),{d3Zoom:G,d3Selection:V,d3ZoomHandler:R,userSelectionActive:M}=ms(zz,mr),I=gm(v),L=p.useRef(0),K=p.useRef(!1),H=p.useRef();return Dz(W),p.useEffect(()=>{if(W.current){const z=W.current.getBoundingClientRect(),ee=E$().scaleExtent([x,k]).translateExtent(y),B=vo(W.current).call(ee),te=sl.translate(g.x,g.y).scale(sf(g.zoom,x,k)),se=[[0,0],[z.width,z.height]],de=ee.constrain()(te,se,y);ee.transform(B,de),ee.wheelDelta(ej),O.setState({d3Zoom:ee,d3Selection:B,d3ZoomHandler:B.on("wheel.zoom"),transform:[de.x,de.y,de.k],domNode:W.current.closest(".react-flow")})}},[]),p.useEffect(()=>{V&&G&&(c&&!I&&!M?V.on("wheel.zoom",z=>{if(Nd(z,C))return!1;z.preventDefault(),z.stopImmediatePropagation();const ee=V.property("__zoom").k||1,B=_g();if(z.ctrlKey&&o&&B){const je=Ho(z),Te=ej(z),Ve=ee*Math.pow(2,Te);G.scaleTo(V,Ve,je,z);return}const te=z.deltaMode===1?20:1;let se=d===ou.Vertical?0:z.deltaX*te,de=d===ou.Horizontal?0:z.deltaY*te;!B&&z.shiftKey&&d!==ou.Vertical&&(se=z.deltaY*te,de=0),G.translateBy(V,-(se/ee)*l,-(de/ee)*l,{internal:!0});const be=yp(V.property("__zoom")),{onViewportChangeStart:Me,onViewportChange:Ne,onViewportChangeEnd:ae}=O.getState();clearTimeout(H.current),K.current||(K.current=!0,t==null||t(z,be),Me==null||Me(be)),K.current&&(e==null||e(z,be),Ne==null||Ne(be),H.current=setTimeout(()=>{n==null||n(z,be),ae==null||ae(be),K.current=!1},150))},{passive:!1}):typeof R<"u"&&V.on("wheel.zoom",function(z,ee){if(!N||Nd(z,C))return null;z.preventDefault(),R.call(this,z,ee)},{passive:!1}))},[M,c,d,V,G,R,I,o,N,C,t,e,n]),p.useEffect(()=>{G&&G.on("start",z=>{var te,se;if(!z.sourceEvent||z.sourceEvent.internal)return null;L.current=(te=z.sourceEvent)==null?void 0:te.button;const{onViewportChangeStart:ee}=O.getState(),B=yp(z.transform);A.current=!0,J.current=B,((se=z.sourceEvent)==null?void 0:se.type)==="mousedown"&&O.setState({paneDragging:!0}),ee==null||ee(B),t==null||t(z.sourceEvent,B)})},[G,t]),p.useEffect(()=>{G&&(M&&!A.current?G.on("zoom",null):M||G.on("zoom",z=>{var B;const{onViewportChange:ee}=O.getState();if(O.setState({transform:[z.transform.x,z.transform.y,z.transform.k]}),P.current=!!(r&&Qk(_,L.current??0)),(e||ee)&&!((B=z.sourceEvent)!=null&&B.internal)){const te=yp(z.transform);ee==null||ee(te),e==null||e(z.sourceEvent,te)}}))},[M,G,e,_,r]),p.useEffect(()=>{G&&G.on("end",z=>{if(!z.sourceEvent||z.sourceEvent.internal)return null;const{onViewportChangeEnd:ee}=O.getState();if(A.current=!1,O.setState({paneDragging:!1}),r&&Qk(_,L.current??0)&&!P.current&&r(z.sourceEvent),P.current=!1,(n||ee)&&Fz(J.current,z.transform)){const B=yp(z.transform);J.current=B,clearTimeout(D.current),D.current=setTimeout(()=>{ee==null||ee(B),n==null||n(z.sourceEvent,B)},c?150:0)}})},[G,c,_,n,r]),p.useEffect(()=>{G&&G.filter(z=>{const ee=I||i,B=o&&z.ctrlKey;if((_===!0||Array.isArray(_)&&_.includes(1))&&z.button===1&&z.type==="mousedown"&&(Nd(z,"react-flow__node")||Nd(z,"react-flow__edge")))return!0;if(!_&&!ee&&!c&&!h&&!o||M||!h&&z.type==="dblclick"||Nd(z,C)&&z.type==="wheel"||Nd(z,S)&&(z.type!=="wheel"||c&&z.type==="wheel"&&!I)||!o&&z.ctrlKey&&z.type==="wheel"||!ee&&!c&&!B&&z.type==="wheel"||!_&&(z.type==="mousedown"||z.type==="touchstart")||Array.isArray(_)&&!_.includes(z.button)&&(z.type==="mousedown"||z.type==="touchstart"))return!1;const te=Array.isArray(_)&&_.includes(z.button)||!z.button||z.button<=1;return(!z.ctrlKey||z.type==="wheel")&&te})},[M,G,i,o,c,h,_,m,I]),Ae.createElement("div",{className:"react-flow__renderer",ref:W,style:Ux},$)},Uz=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Wz(){const{userSelectionActive:e,userSelectionRect:t}=ms(Uz,mr);return e&&t?Ae.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 tj(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,i=t.position.y+t.height-n.height;if(r>0||i>0||t.position.x<0||t.position.y<0){if(n.style={...n.style},n.style.width=n.style.width??n.width,n.style.height=n.style.height??n.height,r>0&&(n.style.width+=r),i>0&&(n.style.height+=i),t.position.x<0){const o=Math.abs(t.position.x);n.position.x=n.position.x-o,n.style.width+=o,t.position.x=0}if(t.position.y<0){const o=Math.abs(t.position.y);n.position.y=n.position.y-o,n.style.height+=o,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function qz(e,t){if(e.some(r=>r.type==="reset"))return e.filter(r=>r.type==="reset").map(r=>r.item);const n=e.filter(r=>r.type==="add").map(r=>r.item);return t.reduce((r,i)=>{const o=e.filter(l=>l.id===i.id);if(o.length===0)return r.push(i),r;const c={...i};for(const l of o)if(l)switch(l.type){case"select":{c.selected=l.selected;break}case"position":{typeof l.position<"u"&&(c.position=l.position),typeof l.positionAbsolute<"u"&&(c.positionAbsolute=l.positionAbsolute),typeof l.dragging<"u"&&(c.dragging=l.dragging),c.expandParent&&tj(r,c);break}case"dimensions":{typeof l.dimensions<"u"&&(c.width=l.dimensions.width,c.height=l.dimensions.height),typeof l.updateStyle<"u"&&(c.style={...c.style||{},...l.dimensions}),typeof l.resizing=="boolean"&&(c.resizing=l.resizing),c.expandParent&&tj(r,c);break}case"remove":return r}return r.push(c),r},n)}function Vz(e,t){return qz(e,t)}const ec=(e,t)=>({id:e,type:"select",selected:t});function Fd(e,t){return e.reduce((n,r)=>{const i=t.includes(r.id);return!r.selected&&i?(r.selected=!0,n.push(ec(r.id,!0))):r.selected&&!i&&(r.selected=!1,n.push(ec(r.id,!1))),n},[])}const fw=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},Hz=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),oC=p.memo(({isSelecting:e,selectionMode:t=_m.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:i,onPaneClick:o,onPaneContextMenu:c,onPaneScroll:l,onPaneMouseEnter:d,onPaneMouseMove:h,onPaneMouseLeave:m,children:_})=>{const g=p.useRef(null),y=tr(),x=p.useRef(0),k=p.useRef(0),v=p.useRef(),{userSelectionActive:N,elementsSelectable:$,dragging:C}=ms(Hz,mr),S=()=>{y.setState({userSelectionActive:!1,userSelectionRect:null}),x.current=0,k.current=0},D=R=>{o==null||o(R),y.getState().resetSelectedElements(),y.setState({nodesSelectionActive:!1})},O=R=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){R.preventDefault();return}c==null||c(R)},A=l?R=>l(R):void 0,P=R=>{const{resetSelectedElements:M,domNode:I}=y.getState();if(v.current=I==null?void 0:I.getBoundingClientRect(),!$||!e||R.button!==0||R.target!==g.current||!v.current)return;const{x:L,y:K}=ac(R,v.current);M(),y.setState({userSelectionRect:{width:0,height:0,startX:L,startY:K,x:L,y:K}}),r==null||r(R)},W=R=>{const{userSelectionRect:M,nodeInternals:I,edges:L,transform:K,onNodesChange:H,onEdgesChange:z,nodeOrigin:ee,getNodes:B}=y.getState();if(!e||!v.current||!M)return;y.setState({userSelectionActive:!0,nodesSelectionActive:!1});const te=ac(R,v.current),se=M.startX??0,de=M.startY??0,be={...M,x:te.x<se?te.x:se,y:te.y<de?te.y:de,width:Math.abs(te.x-se),height:Math.abs(te.y-de)},Me=B(),Ne=U$(I,be,K,t===_m.Partial,!0,ee),ae=W$(Ne,L).map(Te=>Te.id),je=Ne.map(Te=>Te.id);if(x.current!==je.length){x.current=je.length;const Te=Fd(Me,je);Te.length&&(H==null||H(Te))}if(k.current!==ae.length){k.current=ae.length;const Te=Fd(L,ae);Te.length&&(z==null||z(Te))}y.setState({userSelectionRect:be})},J=R=>{if(R.button!==0)return;const{userSelectionRect:M}=y.getState();!N&&M&&R.target===g.current&&(D==null||D(R)),y.setState({nodesSelectionActive:x.current>0}),S(),i==null||i(R)},G=R=>{N&&(y.setState({nodesSelectionActive:x.current>0}),i==null||i(R)),S()},V=$&&(e||N);return Ae.createElement("div",{className:Er(["react-flow__pane",{dragging:C,selection:e}]),onClick:V?void 0:fw(D,g),onContextMenu:fw(O,g),onWheel:fw(A,g),onMouseEnter:V?void 0:d,onMouseDown:V?P:void 0,onMouseMove:V?W:h,onMouseUp:V?J:void 0,onMouseLeave:V?G:m,ref:g,style:Ux},_,Ae.createElement(Wz,null))});oC.displayName="Pane";function aC(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:aC(n,t):!1}function nj(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 Gz(e,t,n,r){return Array.from(e.values()).filter(i=>(i.selected||i.id===r)&&(!i.parentNode||!aC(i,e))&&(i.draggable||t&&typeof i.draggable>"u")).map(i=>{var o,c;return{id:i.id,position:i.position||{x:0,y:0},positionAbsolute:i.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((o=i.positionAbsolute)==null?void 0:o.x)??0),y:n.y-(((c=i.positionAbsolute)==null?void 0:c.y)??0)},delta:{x:0,y:0},extent:i.extent,parentNode:i.parentNode,width:i.width,height:i.height,expandParent:i.expandParent}})}function Kz(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function lC(e,t,n,r,i=[0,0],o){const c=Kz(e,e.extent||r);let l=c;if(e.extent==="parent"&&!e.expandParent)if(e.parentNode&&e.width&&e.height){const m=n.get(e.parentNode),{x:_,y:g}=du(m,i).positionAbsolute;l=m&&xo(_)&&xo(g)&&xo(m.width)&&xo(m.height)?[[_+e.width*i[0],g+e.height*i[1]],[_+m.width-e.width+e.width*i[0],g+m.height-e.height+e.height*i[1]]]:l}else o==null||o("005",cl.error005()),l=c;else if(e.extent&&e.parentNode&&e.extent!=="parent"){const m=n.get(e.parentNode),{x:_,y:g}=du(m,i).positionAbsolute;l=[[e.extent[0][0]+_,e.extent[0][1]+g],[e.extent[1][0]+_,e.extent[1][1]+g]]}let d={x:0,y:0};if(e.parentNode){const m=n.get(e.parentNode);d=du(m,i).positionAbsolute}const h=l&&l!=="parent"?Lx(t,l):t;return{position:{x:h.x-d.x,y:h.y-d.y},positionAbsolute:h}}function hw({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(i=>({...n.get(i.id),position:i.position,positionAbsolute:i.positionAbsolute}));return[e?r.find(i=>i.id===e):r[0],r]}const sj=(e,t,n,r)=>{const i=t.querySelectorAll(e);if(!i||!i.length)return null;const o=Array.from(i),c=t.getBoundingClientRect(),l={x:c.width*r[0],y:c.height*r[1]};return o.map(d=>{const h=d.getBoundingClientRect();return{id:d.getAttribute("data-handleid"),position:d.getAttribute("data-handlepos"),x:(h.left-c.left-l.x)/n,y:(h.top-c.top-l.y)/n,...Rx(d)}})};function Ah(e,t,n){return n===void 0?n:r=>{const i=t().nodeInternals.get(e);i&&n(r,{...i})}}function Av({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:o,multiSelectionActive:c,nodeInternals:l,onError:d}=t.getState(),h=l.get(e);if(!h){d==null||d("012",cl.error012(e));return}t.setState({nodesSelectionActive:!1}),h.selected?(n||h.selected&&c)&&(o({nodes:[h],edges:[]}),requestAnimationFrame(()=>{var m;return(m=r==null?void 0:r.current)==null?void 0:m.blur()})):i([e])}function Jz(){const e=tr();return p.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:i,snapToGrid:o}=e.getState(),c=n.touches?n.touches[0].clientX:n.clientX,l=n.touches?n.touches[0].clientY:n.clientY,d={x:(c-r[0])/r[2],y:(l-r[1])/r[2]};return{xSnapped:o?i[0]*Math.round(d.x/i[0]):d.x,ySnapped:o?i[1]*Math.round(d.y/i[1]):d.y,...d}},[])}function mw(e){return(t,n,r)=>e==null?void 0:e(t,r)}function cC({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:o,selectNodesOnDrag:c}){const l=tr(),[d,h]=p.useState(!1),m=p.useRef([]),_=p.useRef({x:null,y:null}),g=p.useRef(0),y=p.useRef(null),x=p.useRef({x:0,y:0}),k=p.useRef(null),v=p.useRef(!1),N=p.useRef(!1),$=Jz();return p.useEffect(()=>{if(e!=null&&e.current){const C=vo(e.current),S=({x:A,y:P})=>{const{nodeInternals:W,onNodeDrag:J,onSelectionDrag:G,updateNodePositions:V,nodeExtent:R,snapGrid:M,snapToGrid:I,nodeOrigin:L,onError:K}=l.getState();_.current={x:A,y:P};let H=!1,z={x:0,y:0,x2:0,y2:0};if(m.current.length>1&&R){const B=Kg(m.current,L);z=mm(B)}if(m.current=m.current.map(B=>{const te={x:A-B.distance.x,y:P-B.distance.y};I&&(te.x=M[0]*Math.round(te.x/M[0]),te.y=M[1]*Math.round(te.y/M[1]));const se=[[R[0][0],R[0][1]],[R[1][0],R[1][1]]];m.current.length>1&&R&&!B.extent&&(se[0][0]=B.positionAbsolute.x-z.x+R[0][0],se[1][0]=B.positionAbsolute.x+(B.width??0)-z.x2+R[1][0],se[0][1]=B.positionAbsolute.y-z.y+R[0][1],se[1][1]=B.positionAbsolute.y+(B.height??0)-z.y2+R[1][1]);const de=lC(B,te,W,se,L,K);return H=H||B.position.x!==de.position.x||B.position.y!==de.position.y,B.position=de.position,B.positionAbsolute=de.positionAbsolute,B}),!H)return;V(m.current,!0,!0),h(!0);const ee=i?J:mw(G);if(ee&&k.current){const[B,te]=hw({nodeId:i,dragItems:m.current,nodeInternals:W});ee(k.current,B,te)}},D=()=>{if(!y.current)return;const[A,P]=T$(x.current,y.current);if(A!==0||P!==0){const{transform:W,panBy:J}=l.getState();_.current.x=(_.current.x??0)-A/W[2],_.current.y=(_.current.y??0)-P/W[2],J({x:A,y:P})&&S(_.current)}g.current=requestAnimationFrame(D)},O=A=>{var L;const{nodeInternals:P,multiSelectionActive:W,nodesDraggable:J,unselectNodesAndEdges:G,onNodeDragStart:V,onSelectionDragStart:R}=l.getState();N.current=!0;const M=i?V:mw(R);(!c||!o)&&!W&&i&&((L=P.get(i))!=null&&L.selected||G()),i&&o&&c&&Av({id:i,store:l,nodeRef:e});const I=$(A);if(_.current=I,m.current=Gz(P,J,I,i),M&&m.current){const[K,H]=hw({nodeId:i,dragItems:m.current,nodeInternals:P});M(A.sourceEvent,K,H)}};if(t)C.on(".drag",null);else{const A=i6().on("start",P=>{const{domNode:W,nodeDragThreshold:J}=l.getState();J===0&&O(P);const G=$(P);_.current=G,y.current=(W==null?void 0:W.getBoundingClientRect())||null,x.current=ac(P.sourceEvent,y.current)}).on("drag",P=>{var V,R;const W=$(P),{autoPanOnNodeDrag:J,nodeDragThreshold:G}=l.getState();if(!v.current&&N.current&&J&&(v.current=!0,D()),!N.current){const M=W.xSnapped-(((V=_==null?void 0:_.current)==null?void 0:V.x)??0),I=W.ySnapped-(((R=_==null?void 0:_.current)==null?void 0:R.y)??0);Math.sqrt(M*M+I*I)>G&&O(P)}(_.current.x!==W.xSnapped||_.current.y!==W.ySnapped)&&m.current&&N.current&&(k.current=P.sourceEvent,x.current=ac(P.sourceEvent,y.current),S(W))}).on("end",P=>{if(N.current&&(h(!1),v.current=!1,N.current=!1,cancelAnimationFrame(g.current),m.current)){const{updateNodePositions:W,nodeInternals:J,onNodeDragStop:G,onSelectionDragStop:V}=l.getState(),R=i?G:mw(V);if(W(m.current,!1,!1),R){const[M,I]=hw({nodeId:i,dragItems:m.current,nodeInternals:J});R(P.sourceEvent,M,I)}}}).filter(P=>{const W=P.target;return!P.button&&(!n||!nj(W,`.${n}`,e))&&(!r||nj(W,r,e))});return C.call(A),()=>{C.on(".drag",null)}}}},[e,t,n,r,o,l,i,c,$]),d}function uC(){const e=tr();return p.useCallback(n=>{const{nodeInternals:r,nodeExtent:i,updateNodePositions:o,getNodes:c,snapToGrid:l,snapGrid:d,onError:h,nodesDraggable:m}=e.getState(),_=c().filter($=>$.selected&&($.draggable||m&&typeof $.draggable>"u")),g=l?d[0]:5,y=l?d[1]:5,x=n.isShiftPressed?4:1,k=n.x*g*x,v=n.y*y*x,N=_.map($=>{if($.positionAbsolute){const C={x:$.positionAbsolute.x+k,y:$.positionAbsolute.y+v};l&&(C.x=d[0]*Math.round(C.x/d[0]),C.y=d[1]*Math.round(C.y/d[1]));const{positionAbsolute:S,position:D}=lC($,C,r,i,void 0,h);$.position=D,$.positionAbsolute=S}return $});o(N,!0,!1)},[])}const Gd={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Th=e=>{const t=({id:n,type:r,data:i,xPos:o,yPos:c,xPosOrigin:l,yPosOrigin:d,selected:h,onClick:m,onMouseEnter:_,onMouseMove:g,onMouseLeave:y,onContextMenu:x,onDoubleClick:k,style:v,className:N,isDraggable:$,isSelectable:C,isConnectable:S,isFocusable:D,selectNodesOnDrag:O,sourcePosition:A,targetPosition:P,hidden:W,resizeObserver:J,dragHandle:G,zIndex:V,isParent:R,noDragClassName:M,noPanClassName:I,initialized:L,disableKeyboardA11y:K,ariaLabel:H,rfId:z,hasHandleBounds:ee})=>{const B=tr(),te=p.useRef(null),se=p.useRef(A),de=p.useRef(P),be=p.useRef(r),Me=C||$||m||_||g||y,Ne=uC(),ae=Ah(n,B.getState,_),je=Ah(n,B.getState,g),Te=Ah(n,B.getState,y),Ve=Ah(n,B.getState,x),_t=Ah(n,B.getState,k),Qe=ot=>{const{nodeDragThreshold:mt}=B.getState();if(C&&(!O||!$||mt>0)&&Av({id:n,store:B,nodeRef:te}),m){const et=B.getState().nodeInternals.get(n);et&&m(ot,{...et})}},it=ot=>{if(!Sv(ot))if(I$.includes(ot.key)&&C){const mt=ot.key==="Escape";Av({id:n,store:B,unselect:mt,nodeRef:te})}else!K&&$&&h&&Object.prototype.hasOwnProperty.call(Gd,ot.key)&&(B.setState({ariaLiveMessage:`Moved selected node ${ot.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~o}, y: ${~~c}`}),Ne({x:Gd[ot.key].x,y:Gd[ot.key].y,isShiftPressed:ot.shiftKey}))};p.useEffect(()=>()=>{te.current&&(J==null||J.unobserve(te.current))},[]),p.useEffect(()=>{if(te.current&&!W){const ot=te.current;(!L||!ee)&&(J==null||J.unobserve(ot),J==null||J.observe(ot))}},[W,L,ee]),p.useEffect(()=>{const ot=be.current!==r,mt=se.current!==A,et=de.current!==P;te.current&&(ot||mt||et)&&(ot&&(be.current=r),mt&&(se.current=A),et&&(de.current=P),B.getState().updateNodeDimensions([{id:n,nodeElement:te.current,forceUpdate:!0}]))},[n,r,A,P]);const $t=cC({nodeRef:te,disabled:W||!$,noDragClassName:M,handleSelector:G,nodeId:n,isSelectable:C,selectNodesOnDrag:O});return W?null:Ae.createElement("div",{className:Er(["react-flow__node",`react-flow__node-${r}`,{[I]:$},N,{selected:h,selectable:C,parent:R,dragging:$t}]),ref:te,style:{zIndex:V,transform:`translate(${l}px,${d}px)`,pointerEvents:Me?"all":"none",visibility:L?"visible":"hidden",...v},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:ae,onMouseMove:je,onMouseLeave:Te,onContextMenu:Ve,onClick:Qe,onDoubleClick:_t,onKeyDown:D?it:void 0,tabIndex:D?0:void 0,role:D?"button":void 0,"aria-describedby":K?void 0:`${tC}-${z}`,"aria-label":H},Ae.createElement(lz,{value:n},Ae.createElement(e,{id:n,data:i,type:r,xPos:o,yPos:c,selected:h,isConnectable:S,sourcePosition:A,targetPosition:P,dragging:$t,dragHandle:G,zIndex:V})))};return t.displayName="NodeWrapper",p.memo(t)};const Yz=e=>{const t=e.getNodes().filter(n=>n.selected);return{...Kg(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function Xz({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=tr(),{width:i,height:o,x:c,y:l,transformString:d,userSelectionActive:h}=ms(Yz,mr),m=uC(),_=p.useRef(null);if(p.useEffect(()=>{var x;n||(x=_.current)==null||x.focus({preventScroll:!0})},[n]),cC({nodeRef:_}),h||!i||!o)return null;const g=e?x=>{const k=r.getState().getNodes().filter(v=>v.selected);e(x,k)}:void 0,y=x=>{Object.prototype.hasOwnProperty.call(Gd,x.key)&&m({x:Gd[x.key].x,y:Gd[x.key].y,isShiftPressed:x.shiftKey})};return Ae.createElement("div",{className:Er(["react-flow__nodesselection","react-flow__container",t]),style:{transform:d}},Ae.createElement("div",{ref:_,className:"react-flow__nodesselection-rect",onContextMenu:g,tabIndex:n?void 0:-1,onKeyDown:n?void 0:y,style:{width:i,height:o,top:l,left:c}}))}var Zz=p.memo(Xz);const Qz=e=>e.nodesSelectionActive,dC=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:c,deleteKeyCode:l,onMove:d,onMoveStart:h,onMoveEnd:m,selectionKeyCode:_,selectionOnDrag:g,selectionMode:y,onSelectionStart:x,onSelectionEnd:k,multiSelectionKeyCode:v,panActivationKeyCode:N,zoomActivationKeyCode:$,elementsSelectable:C,zoomOnScroll:S,zoomOnPinch:D,panOnScroll:O,panOnScrollSpeed:A,panOnScrollMode:P,zoomOnDoubleClick:W,panOnDrag:J,defaultViewport:G,translateExtent:V,minZoom:R,maxZoom:M,preventScrolling:I,onSelectionContextMenu:L,noWheelClassName:K,noPanClassName:H,disableKeyboardA11y:z})=>{const ee=ms(Qz),B=gm(_),te=gm(N),se=te||J,de=te||O,be=B||g&&se!==!0;return Pz({deleteKeyCode:l,multiSelectionKeyCode:v}),Ae.createElement(Bz,{onMove:d,onMoveStart:h,onMoveEnd:m,onPaneContextMenu:o,elementsSelectable:C,zoomOnScroll:S,zoomOnPinch:D,panOnScroll:de,panOnScrollSpeed:A,panOnScrollMode:P,zoomOnDoubleClick:W,panOnDrag:!B&&se,defaultViewport:G,translateExtent:V,minZoom:R,maxZoom:M,zoomActivationKeyCode:$,preventScrolling:I,noWheelClassName:K,noPanClassName:H},Ae.createElement(oC,{onSelectionStart:x,onSelectionEnd:k,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:c,panOnDrag:se,isSelecting:!!be,selectionMode:y},e,ee&&Ae.createElement(Zz,{onSelectionContextMenu:L,noPanClassName:H,disableKeyboardA11y:z})))};dC.displayName="FlowRenderer";var eB=p.memo(dC);function tB(e){return ms(p.useCallback(n=>e?U$(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function nB(e){const t={input:Th(e.input||X$),default:Th(e.default||Ev),output:Th(e.output||Q$),group:Th(e.group||zx)},n={},r=Object.keys(e).filter(i=>!["input","default","output","group"].includes(i)).reduce((i,o)=>(i[o]=Th(e[o]||Ev),i),n);return{...t,...r}}const sB=({x:e,y:t,width:n,height:r,origin:i})=>!n||!r?{x:e,y:t}:i[0]<0||i[1]<0||i[0]>1||i[1]>1?{x:e,y:t}:{x:e-n*i[0],y:t-r*i[1]},rB=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),fC=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,updateNodeDimensions:o,onError:c}=ms(rB,mr),l=tB(e.onlyRenderVisibleElements),d=p.useRef(),h=p.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const m=new ResizeObserver(_=>{const g=_.map(y=>({id:y.target.getAttribute("data-id"),nodeElement:y.target,forceUpdate:!0}));o(g)});return d.current=m,m},[]);return p.useEffect(()=>()=>{var m;(m=d==null?void 0:d.current)==null||m.disconnect()},[]),Ae.createElement("div",{className:"react-flow__nodes",style:Ux},l.map(m=>{var D,O,A;let _=m.type||"default";e.nodeTypes[_]||(c==null||c("003",cl.error003(_)),_="default");const g=e.nodeTypes[_]||e.nodeTypes.default,y=!!(m.draggable||t&&typeof m.draggable>"u"),x=!!(m.selectable||i&&typeof m.selectable>"u"),k=!!(m.connectable||n&&typeof m.connectable>"u"),v=!!(m.focusable||r&&typeof m.focusable>"u"),N=e.nodeExtent?Lx(m.positionAbsolute,e.nodeExtent):m.positionAbsolute,$=(N==null?void 0:N.x)??0,C=(N==null?void 0:N.y)??0,S=sB({x:$,y:C,width:m.width??0,height:m.height??0,origin:e.nodeOrigin});return Ae.createElement(g,{key:m.id,id:m.id,className:m.className,style:m.style,type:_,data:m.data,sourcePosition:m.sourcePosition||Ut.Bottom,targetPosition:m.targetPosition||Ut.Top,hidden:m.hidden,xPos:$,yPos:C,xPosOrigin:S.x,yPosOrigin:S.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:y,isSelectable:x,isConnectable:k,isFocusable:v,resizeObserver:h,dragHandle:m.dragHandle,zIndex:((D=m[Gs])==null?void 0:D.z)??0,isParent:!!((O=m[Gs])!=null&&O.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!m.width&&!!m.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:m.ariaLabel,hasHandleBounds:!!((A=m[Gs])!=null&&A.handleBounds)})}))};fC.displayName="NodeRenderer";var iB=p.memo(fC);const oB=(e,t,n)=>n===Ut.Left?e-t:n===Ut.Right?e+t:e,aB=(e,t,n)=>n===Ut.Top?e-t:n===Ut.Bottom?e+t:e,rj="react-flow__edgeupdater",ij=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:o,onMouseOut:c,type:l})=>Ae.createElement("circle",{onMouseDown:i,onMouseEnter:o,onMouseOut:c,className:Er([rj,`${rj}-${l}`]),cx:oB(t,r,e),cy:aB(n,r,e),r,stroke:"transparent",fill:"transparent"}),lB=()=>!0;var $d=e=>{const t=({id:n,className:r,type:i,data:o,onClick:c,onEdgeDoubleClick:l,selected:d,animated:h,label:m,labelStyle:_,labelShowBg:g,labelBgStyle:y,labelBgPadding:x,labelBgBorderRadius:k,style:v,source:N,target:$,sourceX:C,sourceY:S,targetX:D,targetY:O,sourcePosition:A,targetPosition:P,elementsSelectable:W,hidden:J,sourceHandleId:G,targetHandleId:V,onContextMenu:R,onMouseEnter:M,onMouseMove:I,onMouseLeave:L,edgeUpdaterRadius:K,onEdgeUpdate:H,onEdgeUpdateStart:z,onEdgeUpdateEnd:ee,markerEnd:B,markerStart:te,rfId:se,ariaLabel:de,isFocusable:be,isUpdatable:Me,pathOptions:Ne,interactionWidth:ae})=>{const je=p.useRef(null),[Te,Ve]=p.useState(!1),[_t,Qe]=p.useState(!1),it=tr(),$t=p.useMemo(()=>`url('#${$v(te,se)}')`,[te,se]),ot=p.useMemo(()=>`url('#${$v(B,se)}')`,[B,se]);if(J)return null;const mt=st=>{var vt;const{edges:kt,addSelectedEdges:pt,unselectNodesAndEdges:jt,multiSelectionActive:ct}=it.getState(),It=kt.find(nn=>nn.id===n);It&&(W&&(it.setState({nodesSelectionActive:!1}),It.selected&&ct?(jt({nodes:[],edges:[It]}),(vt=je.current)==null||vt.blur()):pt([n])),c&&c(st,It))},et=Eh(n,it.getState,l),Lt=Eh(n,it.getState,R),ce=Eh(n,it.getState,M),Se=Eh(n,it.getState,I),He=Eh(n,it.getState,L),ne=(st,kt)=>{if(st.button!==0)return;const{edges:pt,isValidConnection:jt}=it.getState(),ct=kt?$:N,It=(kt?V:G)||null,vt=kt?"target":"source",nn=jt||lB,wn=kt,On=pt.find(ge=>ge.id===n);Qe(!0),z==null||z(st,On,vt);const Ks=ge=>{Qe(!1),ee==null||ee(ge,On,vt)};G$({event:st,handleId:It,nodeId:ct,onConnect:ge=>H==null?void 0:H(On,ge),isTarget:wn,getState:it.getState,setState:it.setState,isValidConnection:nn,edgeUpdaterType:vt,onEdgeUpdateEnd:Ks})},we=st=>ne(st,!0),fe=st=>ne(st,!1),$e=()=>Ve(!0),pe=()=>Ve(!1),le=!W&&!c,ze=st=>{var kt;if(I$.includes(st.key)&&W){const{unselectNodesAndEdges:pt,addSelectedEdges:jt,edges:ct}=it.getState();st.key==="Escape"?((kt=je.current)==null||kt.blur(),pt({edges:[ct.find(vt=>vt.id===n)]})):jt([n])}};return Ae.createElement("g",{className:Er(["react-flow__edge",`react-flow__edge-${i}`,r,{selected:d,animated:h,inactive:le,updating:Te}]),onClick:mt,onDoubleClick:et,onContextMenu:Lt,onMouseEnter:ce,onMouseMove:Se,onMouseLeave:He,onKeyDown:be?ze:void 0,tabIndex:be?0:void 0,role:be?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":de===null?void 0:de||`Edge from ${N} to ${$}`,"aria-describedby":be?`${nC}-${se}`:void 0,ref:je},!_t&&Ae.createElement(e,{id:n,source:N,target:$,selected:d,animated:h,label:m,labelStyle:_,labelShowBg:g,labelBgStyle:y,labelBgPadding:x,labelBgBorderRadius:k,data:o,style:v,sourceX:C,sourceY:S,targetX:D,targetY:O,sourcePosition:A,targetPosition:P,sourceHandleId:G,targetHandleId:V,markerStart:$t,markerEnd:ot,pathOptions:Ne,interactionWidth:ae}),Me&&Ae.createElement(Ae.Fragment,null,(Me==="source"||Me===!0)&&Ae.createElement(ij,{position:A,centerX:C,centerY:S,radius:K,onMouseDown:we,onMouseEnter:$e,onMouseOut:pe,type:"source"}),(Me==="target"||Me===!0)&&Ae.createElement(ij,{position:P,centerX:D,centerY:O,radius:K,onMouseDown:fe,onMouseEnter:$e,onMouseOut:pe,type:"target"})))};return t.displayName="EdgeWrapper",p.memo(t)};function cB(e){const t={default:$d(e.default||pg),straight:$d(e.bezier||Px),step:$d(e.step||Ox),smoothstep:$d(e.step||Gg),simplebezier:$d(e.simplebezier||Ix)},n={},r=Object.keys(e).filter(i=>!["default","bezier"].includes(i)).reduce((i,o)=>(i[o]=$d(e[o]||pg),i),n);return{...t,...r}}function oj(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,i=((n==null?void 0:n.y)||0)+t.y,o=(n==null?void 0:n.width)||t.width,c=(n==null?void 0:n.height)||t.height;switch(e){case Ut.Top:return{x:r+o/2,y:i};case Ut.Right:return{x:r+o,y:i+c/2};case Ut.Bottom:return{x:r+o/2,y:i+c};case Ut.Left:return{x:r,y:i+c/2}}}function aj(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const uB=(e,t,n,r,i,o)=>{const c=oj(n,e,t),l=oj(o,r,i);return{sourceX:c.x,sourceY:c.y,targetX:l.x,targetY:l.y}};function dB({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:i,targetHeight:o,width:c,height:l,transform:d}){const h={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+i),y2:Math.max(e.y+r,t.y+o)};h.x===h.x2&&(h.x2+=1),h.y===h.y2&&(h.y2+=1);const m=mm({x:(0-d[0])/d[2],y:(0-d[1])/d[2],width:c/d[2],height:l/d[2]}),_=Math.max(0,Math.min(m.x2,h.x2)-Math.max(m.x,h.x)),g=Math.max(0,Math.min(m.y2,h.y2)-Math.max(m.y,h.y));return Math.ceil(_*g)>0}function lj(e){var r,i,o,c,l;const t=((r=e==null?void 0:e[Gs])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((i=e==null?void 0:e.positionAbsolute)==null?void 0:i.x)<"u"&&typeof((o=e==null?void 0:e.positionAbsolute)==null?void 0:o.y)<"u";return[{x:((c=e==null?void 0:e.positionAbsolute)==null?void 0:c.x)||0,y:((l=e==null?void 0:e.positionAbsolute)==null?void 0:l.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}const fB=[{level:0,isMaxLevel:!0,edges:[]}];function hB(e,t,n=!1){let r=-1;const i=e.reduce((c,l)=>{var m,_;const d=xo(l.zIndex);let h=d?l.zIndex:0;if(n){const g=t.get(l.target),y=t.get(l.source),x=l.selected||(g==null?void 0:g.selected)||(y==null?void 0:y.selected),k=Math.max(((m=y==null?void 0:y[Gs])==null?void 0:m.z)||0,((_=g==null?void 0:g[Gs])==null?void 0:_.z)||0,1e3);h=(d?l.zIndex:0)+(x?k:0)}return c[h]?c[h].push(l):c[h]=[l],r=h>r?h:r,c},{}),o=Object.entries(i).map(([c,l])=>{const d=+c;return{edges:l,level:d,isMaxLevel:d===r}});return o.length===0?fB:o}function mB(e,t,n){const r=ms(p.useCallback(i=>e?i.edges.filter(o=>{const c=t.get(o.source),l=t.get(o.target);return(c==null?void 0:c.width)&&(c==null?void 0:c.height)&&(l==null?void 0:l.width)&&(l==null?void 0:l.height)&&dB({sourcePos:c.positionAbsolute||{x:0,y:0},targetPos:l.positionAbsolute||{x:0,y:0},sourceWidth:c.width,sourceHeight:c.height,targetWidth:l.width,targetHeight:l.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return hB(r,t,n)}const _B=({color:e="none",strokeWidth:t=1})=>Ae.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),pB=({color:e="none",strokeWidth:t=1})=>Ae.createElement("polyline",{style:{stroke:e,fill:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"}),cj={[pm.Arrow]:_B,[pm.ArrowClosed]:pB};function gB(e){const t=tr();return p.useMemo(()=>{var i,o;return Object.prototype.hasOwnProperty.call(cj,e)?cj[e]:((o=(i=t.getState()).onError)==null||o.call(i,"009",cl.error009(e)),null)},[e])}const yB=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:o="strokeWidth",strokeWidth:c,orient:l="auto-start-reverse"})=>{const d=gB(t);return d?Ae.createElement("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:"-10 -10 20 20",markerUnits:o,orient:l,refX:"0",refY:"0"},Ae.createElement(d,{color:n,strokeWidth:c})):null},wB=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((i,o)=>([o.markerStart,o.markerEnd].forEach(c=>{if(c&&typeof c=="object"){const l=$v(c,t);r.includes(l)||(i.push({id:l,color:c.color||e,...c}),r.push(l))}}),i),[]).sort((i,o)=>i.id.localeCompare(o.id))},hC=({defaultColor:e,rfId:t})=>{const n=ms(p.useCallback(wB({defaultColor:e,rfId:t}),[e,t]),(r,i)=>!(r.length!==i.length||r.some((o,c)=>o.id!==i[c].id)));return Ae.createElement("defs",null,n.map(r=>Ae.createElement(yB,{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})))};hC.displayName="MarkerDefinitions";var vB=p.memo(hC);const xB=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}),mC=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:i,noPanClassName:o,onEdgeUpdate:c,onEdgeContextMenu:l,onEdgeMouseEnter:d,onEdgeMouseMove:h,onEdgeMouseLeave:m,onEdgeClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,children:v})=>{const{edgesFocusable:N,edgesUpdatable:$,elementsSelectable:C,width:S,height:D,connectionMode:O,nodeInternals:A,onError:P}=ms(xB,mr),W=mB(t,A,n);return S?Ae.createElement(Ae.Fragment,null,W.map(({level:J,edges:G,isMaxLevel:V})=>Ae.createElement("svg",{key:J,style:{zIndex:J},width:S,height:D,className:"react-flow__edges react-flow__container"},V&&Ae.createElement(vB,{defaultColor:e,rfId:r}),Ae.createElement("g",null,G.map(R=>{const[M,I,L]=lj(A.get(R.source)),[K,H,z]=lj(A.get(R.target));if(!L||!z)return null;let ee=R.type||"default";i[ee]||(P==null||P("011",cl.error011(ee)),ee="default");const B=i[ee]||i.default,te=O===xu.Strict?H.target:(H.target??[]).concat(H.source??[]),se=aj(I.source,R.sourceHandle),de=aj(te,R.targetHandle),be=(se==null?void 0:se.position)||Ut.Bottom,Me=(de==null?void 0:de.position)||Ut.Top,Ne=!!(R.focusable||N&&typeof R.focusable>"u"),ae=typeof c<"u"&&(R.updatable||$&&typeof R.updatable>"u");if(!se||!de)return P==null||P("008",cl.error008(se,R)),null;const{sourceX:je,sourceY:Te,targetX:Ve,targetY:_t}=uB(M,se,be,K,de,Me);return Ae.createElement(B,{key:R.id,id:R.id,className:Er([R.className,o]),type:ee,data:R.data,selected:!!R.selected,animated:!!R.animated,hidden:!!R.hidden,label:R.label,labelStyle:R.labelStyle,labelShowBg:R.labelShowBg,labelBgStyle:R.labelBgStyle,labelBgPadding:R.labelBgPadding,labelBgBorderRadius:R.labelBgBorderRadius,style:R.style,source:R.source,target:R.target,sourceHandleId:R.sourceHandle,targetHandleId:R.targetHandle,markerEnd:R.markerEnd,markerStart:R.markerStart,sourceX:je,sourceY:Te,targetX:Ve,targetY:_t,sourcePosition:be,targetPosition:Me,elementsSelectable:C,onEdgeUpdate:c,onContextMenu:l,onMouseEnter:d,onMouseMove:h,onMouseLeave:m,onClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,rfId:r,ariaLabel:R.ariaLabel,isFocusable:Ne,isUpdatable:ae,pathOptions:"pathOptions"in R?R.pathOptions:void 0,interactionWidth:R.interactionWidth})})))),v):null};mC.displayName="EdgeRenderer";var bB=p.memo(mC);const kB=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function jB({children:e}){const t=ms(kB);return Ae.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function SB(e){const t=Bx(),n=p.useRef(!1);p.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const NB={[Ut.Left]:Ut.Right,[Ut.Right]:Ut.Left,[Ut.Top]:Ut.Bottom,[Ut.Bottom]:Ut.Top},_C=({nodeId:e,handleType:t,style:n,type:r=nc.Bezier,CustomComponent:i,connectionStatus:o})=>{var O,A,P;const{fromNode:c,handleId:l,toX:d,toY:h,connectionMode:m}=ms(p.useCallback(W=>({fromNode:W.nodeInternals.get(e),handleId:W.connectionHandleId,toX:(W.connectionPosition.x-W.transform[0])/W.transform[2],toY:(W.connectionPosition.y-W.transform[1])/W.transform[2],connectionMode:W.connectionMode}),[e]),mr),_=(O=c==null?void 0:c[Gs])==null?void 0:O.handleBounds;let g=_==null?void 0:_[t];if(m===xu.Loose&&(g=g||(_==null?void 0:_[t==="source"?"target":"source"])),!c||!g)return null;const y=l?g.find(W=>W.id===l):g[0],x=y?y.x+y.width/2:(c.width??0)/2,k=y?y.y+y.height/2:c.height??0,v=(((A=c.positionAbsolute)==null?void 0:A.x)??0)+x,N=(((P=c.positionAbsolute)==null?void 0:P.y)??0)+k,$=y==null?void 0:y.position,C=$?NB[$]:null;if(!$||!C)return null;if(i)return Ae.createElement(i,{connectionLineType:r,connectionLineStyle:n,fromNode:c,fromHandle:y,fromX:v,fromY:N,toX:d,toY:h,fromPosition:$,toPosition:C,connectionStatus:o});let S="";const D={sourceX:v,sourceY:N,sourcePosition:$,targetX:d,targetY:h,targetPosition:C};return r===nc.Bezier?[S]=z$(D):r===nc.Step?[S]=Nv({...D,borderRadius:0}):r===nc.SmoothStep?[S]=Nv(D):r===nc.SimpleBezier?[S]=F$(D):S=`M${v},${N} ${d},${h}`,Ae.createElement("path",{d:S,fill:"none",className:"react-flow__connection-path",style:n})};_C.displayName="ConnectionLine";const $B=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function CB({containerStyle:e,style:t,type:n,component:r}){const{nodeId:i,handleType:o,nodesConnectable:c,width:l,height:d,connectionStatus:h}=ms($B,mr);return!(i&&o&&l&&c)?null:Ae.createElement("svg",{style:e,width:l,height:d,className:"react-flow__edges react-flow__connectionline react-flow__container"},Ae.createElement("g",{className:Er(["react-flow__connection",h])},Ae.createElement(_C,{nodeId:i,handleType:o,style:t,type:n,CustomComponent:r,connectionStatus:h})))}function uj(e,t){return p.useRef(null),tr(),p.useMemo(()=>t(e),[e])}const pC=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:i,onInit:o,onNodeClick:c,onEdgeClick:l,onNodeDoubleClick:d,onEdgeDoubleClick:h,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,onSelectionContextMenu:x,onSelectionStart:k,onSelectionEnd:v,connectionLineType:N,connectionLineStyle:$,connectionLineComponent:C,connectionLineContainerStyle:S,selectionKeyCode:D,selectionOnDrag:O,selectionMode:A,multiSelectionKeyCode:P,panActivationKeyCode:W,zoomActivationKeyCode:J,deleteKeyCode:G,onlyRenderVisibleElements:V,elementsSelectable:R,selectNodesOnDrag:M,defaultViewport:I,translateExtent:L,minZoom:K,maxZoom:H,preventScrolling:z,defaultMarkerColor:ee,zoomOnScroll:B,zoomOnPinch:te,panOnScroll:se,panOnScrollSpeed:de,panOnScrollMode:be,zoomOnDoubleClick:Me,panOnDrag:Ne,onPaneClick:ae,onPaneMouseEnter:je,onPaneMouseMove:Te,onPaneMouseLeave:Ve,onPaneScroll:_t,onPaneContextMenu:Qe,onEdgeUpdate:it,onEdgeContextMenu:$t,onEdgeMouseEnter:ot,onEdgeMouseMove:mt,onEdgeMouseLeave:et,edgeUpdaterRadius:Lt,onEdgeUpdateStart:ce,onEdgeUpdateEnd:Se,noDragClassName:He,noWheelClassName:ne,noPanClassName:we,elevateEdgesOnSelect:fe,disableKeyboardA11y:$e,nodeOrigin:pe,nodeExtent:le,rfId:ze})=>{const st=uj(e,nB),kt=uj(t,cB);return SB(o),Ae.createElement(eB,{onPaneClick:ae,onPaneMouseEnter:je,onPaneMouseMove:Te,onPaneMouseLeave:Ve,onPaneContextMenu:Qe,onPaneScroll:_t,deleteKeyCode:G,selectionKeyCode:D,selectionOnDrag:O,selectionMode:A,onSelectionStart:k,onSelectionEnd:v,multiSelectionKeyCode:P,panActivationKeyCode:W,zoomActivationKeyCode:J,elementsSelectable:R,onMove:n,onMoveStart:r,onMoveEnd:i,zoomOnScroll:B,zoomOnPinch:te,zoomOnDoubleClick:Me,panOnScroll:se,panOnScrollSpeed:de,panOnScrollMode:be,panOnDrag:Ne,defaultViewport:I,translateExtent:L,minZoom:K,maxZoom:H,onSelectionContextMenu:x,preventScrolling:z,noDragClassName:He,noWheelClassName:ne,noPanClassName:we,disableKeyboardA11y:$e},Ae.createElement(jB,null,Ae.createElement(bB,{edgeTypes:kt,onEdgeClick:l,onEdgeDoubleClick:h,onEdgeUpdate:it,onlyRenderVisibleElements:V,onEdgeContextMenu:$t,onEdgeMouseEnter:ot,onEdgeMouseMove:mt,onEdgeMouseLeave:et,onEdgeUpdateStart:ce,onEdgeUpdateEnd:Se,edgeUpdaterRadius:Lt,defaultMarkerColor:ee,noPanClassName:we,elevateEdgesOnSelect:!!fe,disableKeyboardA11y:$e,rfId:ze},Ae.createElement(CB,{style:$,type:N,component:C,containerStyle:S})),Ae.createElement("div",{className:"react-flow__edgelabel-renderer"}),Ae.createElement(iB,{nodeTypes:st,onNodeClick:c,onNodeDoubleClick:d,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,selectNodesOnDrag:M,onlyRenderVisibleElements:V,noPanClassName:we,noDragClassName:He,disableKeyboardA11y:$e,nodeOrigin:pe,nodeExtent:le,rfId:ze})))};pC.displayName="GraphView";var EB=p.memo(pC);const Tv=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Kl={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:Tv,nodeExtent:Tv,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:xu.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:nz,isValidConnection:void 0},AB=()=>g5((e,t)=>({...Kl,setNodes:n=>{const{nodeInternals:r,nodeOrigin:i,elevateNodesOnSelect:o}=t();e({nodeInternals:dw(n,r,i,o)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(i=>({...r,...i}))})},setDefaultNodesAndEdges:(n,r)=>{const i=typeof n<"u",o=typeof r<"u",c=i?dw(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:c,edges:o?r:[],hasDefaultNodes:i,hasDefaultEdges:o})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:i,fitViewOnInit:o,fitViewOnInitDone:c,fitViewOnInitOptions:l,domNode:d,nodeOrigin:h}=t(),m=d==null?void 0:d.querySelector(".react-flow__viewport");if(!m)return;const _=window.getComputedStyle(m),{m22:g}=new window.DOMMatrixReadOnly(_.transform),y=n.reduce((k,v)=>{const N=i.get(v.id);if(N){const $=Rx(v.nodeElement);!!($.width&&$.height&&(N.width!==$.width||N.height!==$.height||v.forceUpdate))&&(i.set(N.id,{...N,[Gs]:{...N[Gs],handleBounds:{source:sj(".source",v.nodeElement,g,h),target:sj(".target",v.nodeElement,g,h)}},...$}),k.push({id:N.id,type:"dimensions",dimensions:$}))}return k},[]);rC(i,h);const x=c||o&&!c&&iC(t,{initial:!0,...l});e({nodeInternals:new Map(i),fitViewOnInitDone:x}),(y==null?void 0:y.length)>0&&(r==null||r(y))},updateNodePositions:(n,r=!0,i=!1)=>{const{triggerNodeChanges:o}=t(),c=n.map(l=>{const d={id:l.id,type:"position",dragging:i};return r&&(d.positionAbsolute=l.positionAbsolute,d.position=l.position),d});o(c)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:i,hasDefaultNodes:o,nodeOrigin:c,getNodes:l,elevateNodesOnSelect:d}=t();if(n!=null&&n.length){if(o){const h=Vz(n,l()),m=dw(h,i,c,d);e({nodeInternals:m})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let c,l=null;r?c=n.map(d=>ec(d,!0)):(c=Fd(o(),n),l=Fd(i,[])),gp({changedNodes:c,changedEdges:l,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let c,l=null;r?c=n.map(d=>ec(d,!0)):(c=Fd(i,n),l=Fd(o(),[])),gp({changedNodes:l,changedEdges:c,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:i,getNodes:o}=t(),c=n||o(),l=r||i,d=c.map(m=>(m.selected=!1,ec(m.id,!1))),h=l.map(m=>ec(m.id,!1));gp({changedNodes:d,changedEdges:h,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:i}=t();r==null||r.scaleExtent([n,i]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:i}=t();r==null||r.scaleExtent([i,n]),e({maxZoom:n})},setTranslateExtent:n=>{var r;(r=t().d3Zoom)==null||r.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:r}=t(),o=r().filter(l=>l.selected).map(l=>ec(l.id,!1)),c=n.filter(l=>l.selected).map(l=>ec(l.id,!1));gp({changedNodes:o,changedEdges:c,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(i=>{i.positionAbsolute=Lx(i.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:i,height:o,d3Zoom:c,d3Selection:l,translateExtent:d}=t();if(!c||!l||!n.x&&!n.y)return!1;const h=sl.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),m=[[0,0],[i,o]],_=c==null?void 0:c.constrain()(h,m,d);return c.transform(l,_),r[0]!==_.x||r[1]!==_.y||r[2]!==_.k},cancelConnection:()=>e({connectionNodeId:Kl.connectionNodeId,connectionHandleId:Kl.connectionHandleId,connectionHandleType:Kl.connectionHandleType,connectionStatus:Kl.connectionStatus,connectionStartHandle:Kl.connectionStartHandle,connectionEndHandle:Kl.connectionEndHandle}),reset:()=>e({...Kl})}),Object.is),Wx=({children:e})=>{const t=p.useRef(null);return t.current||(t.current=AB()),Ae.createElement(J8,{value:t.current},e)};Wx.displayName="ReactFlowProvider";const gC=({children:e})=>p.useContext(Hg)?Ae.createElement(Ae.Fragment,null,e):Ae.createElement(Wx,null,e);gC.displayName="ReactFlowWrapper";const TB={input:X$,default:Ev,output:Q$,group:zx},MB={default:pg,straight:Px,step:Ox,smoothstep:Gg,simplebezier:Ix},RB=[0,0],LB=[15,15],IB={x:0,y:0,zoom:1},OB={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},yC=p.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:o=TB,edgeTypes:c=MB,onNodeClick:l,onEdgeClick:d,onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onConnect:y,onConnectStart:x,onConnectEnd:k,onClickConnectStart:v,onClickConnectEnd:N,onNodeMouseEnter:$,onNodeMouseMove:C,onNodeMouseLeave:S,onNodeContextMenu:D,onNodeDoubleClick:O,onNodeDragStart:A,onNodeDrag:P,onNodeDragStop:W,onNodesDelete:J,onEdgesDelete:G,onSelectionChange:V,onSelectionDragStart:R,onSelectionDrag:M,onSelectionDragStop:I,onSelectionContextMenu:L,onSelectionStart:K,onSelectionEnd:H,connectionMode:z=xu.Strict,connectionLineType:ee=nc.Bezier,connectionLineStyle:B,connectionLineComponent:te,connectionLineContainerStyle:se,deleteKeyCode:de="Backspace",selectionKeyCode:be="Shift",selectionOnDrag:Me=!1,selectionMode:Ne=_m.Full,panActivationKeyCode:ae="Space",multiSelectionKeyCode:je=_g()?"Meta":"Control",zoomActivationKeyCode:Te=_g()?"Meta":"Control",snapToGrid:Ve=!1,snapGrid:_t=LB,onlyRenderVisibleElements:Qe=!1,selectNodesOnDrag:it=!0,nodesDraggable:$t,nodesConnectable:ot,nodesFocusable:mt,nodeOrigin:et=RB,edgesFocusable:Lt,edgesUpdatable:ce,elementsSelectable:Se,defaultViewport:He=IB,minZoom:ne=.5,maxZoom:we=2,translateExtent:fe=Tv,preventScrolling:$e=!0,nodeExtent:pe,defaultMarkerColor:le="#b1b1b7",zoomOnScroll:ze=!0,zoomOnPinch:st=!0,panOnScroll:kt=!1,panOnScrollSpeed:pt=.5,panOnScrollMode:jt=ou.Free,zoomOnDoubleClick:ct=!0,panOnDrag:It=!0,onPaneClick:vt,onPaneMouseEnter:nn,onPaneMouseMove:wn,onPaneMouseLeave:On,onPaneScroll:Ks,onPaneContextMenu:rs,children:ge,onEdgeUpdate:Le,onEdgeContextMenu:yt,onEdgeDoubleClick:re,onEdgeMouseEnter:he,onEdgeMouseMove:Ee,onEdgeMouseLeave:Ie,onEdgeUpdateStart:We,onEdgeUpdateEnd:Ue,edgeUpdaterRadius:tt=10,onNodesChange:ut,onEdgesChange:xt,noDragClassName:bt="nodrag",noWheelClassName:Mt="nowheel",noPanClassName:zt="nopan",fitView:lt=!1,fitViewOptions:Yt,connectOnClick:vn=!0,attributionPosition:mn,proOptions:rn,defaultEdgeOptions:Ht,elevateNodesOnSelect:is=!0,elevateEdgesOnSelect:Be=!1,disableKeyboardA11y:Qt=!1,autoPanOnConnect:Ot=!0,autoPanOnNodeDrag:Fn=!0,connectionRadius:hn=20,isValidConnection:Xe,onError:sn,style:un,id:Ar,nodeDragThreshold:As,...ws},_r)=>{const ve=Ar||"1";return Ae.createElement("div",{...ws,style:{...un,...OB},ref:_r,className:Er(["react-flow",i]),"data-testid":"rf__wrapper",id:Ar},Ae.createElement(gC,null,Ae.createElement(EB,{onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onNodeClick:l,onEdgeClick:d,onNodeMouseEnter:$,onNodeMouseMove:C,onNodeMouseLeave:S,onNodeContextMenu:D,onNodeDoubleClick:O,nodeTypes:o,edgeTypes:c,connectionLineType:ee,connectionLineStyle:B,connectionLineComponent:te,connectionLineContainerStyle:se,selectionKeyCode:be,selectionOnDrag:Me,selectionMode:Ne,deleteKeyCode:de,multiSelectionKeyCode:je,panActivationKeyCode:ae,zoomActivationKeyCode:Te,onlyRenderVisibleElements:Qe,selectNodesOnDrag:it,defaultViewport:He,translateExtent:fe,minZoom:ne,maxZoom:we,preventScrolling:$e,zoomOnScroll:ze,zoomOnPinch:st,zoomOnDoubleClick:ct,panOnScroll:kt,panOnScrollSpeed:pt,panOnScrollMode:jt,panOnDrag:It,onPaneClick:vt,onPaneMouseEnter:nn,onPaneMouseMove:wn,onPaneMouseLeave:On,onPaneScroll:Ks,onPaneContextMenu:rs,onSelectionContextMenu:L,onSelectionStart:K,onSelectionEnd:H,onEdgeUpdate:Le,onEdgeContextMenu:yt,onEdgeDoubleClick:re,onEdgeMouseEnter:he,onEdgeMouseMove:Ee,onEdgeMouseLeave:Ie,onEdgeUpdateStart:We,onEdgeUpdateEnd:Ue,edgeUpdaterRadius:tt,defaultMarkerColor:le,noDragClassName:bt,noWheelClassName:Mt,noPanClassName:zt,elevateEdgesOnSelect:Be,rfId:ve,disableKeyboardA11y:Qt,nodeOrigin:et,nodeExtent:pe}),Ae.createElement(Sz,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:y,onConnectStart:x,onConnectEnd:k,onClickConnectStart:v,onClickConnectEnd:N,nodesDraggable:$t,nodesConnectable:ot,nodesFocusable:mt,edgesFocusable:Lt,edgesUpdatable:ce,elementsSelectable:Se,elevateNodesOnSelect:is,minZoom:ne,maxZoom:we,nodeExtent:pe,onNodesChange:ut,onEdgesChange:xt,snapToGrid:Ve,snapGrid:_t,connectionMode:z,translateExtent:fe,connectOnClick:vn,defaultEdgeOptions:Ht,fitView:lt,fitViewOptions:Yt,onNodesDelete:J,onEdgesDelete:G,onNodeDragStart:A,onNodeDrag:P,onNodeDragStop:W,onSelectionDrag:M,onSelectionDragStart:R,onSelectionDragStop:I,noPanClassName:zt,nodeOrigin:et,rfId:ve,autoPanOnConnect:Ot,autoPanOnNodeDrag:Fn,onError:sn,connectionRadius:hn,isValidConnection:Xe,nodeDragThreshold:As}),Ae.createElement(kz,{onSelectionChange:V}),ge,Ae.createElement(X8,{proOptions:rn,position:mn}),Ae.createElement(Az,{rfId:ve,disableKeyboardA11y:Qt})))});yC.displayName="ReactFlow";const wC=({id:e,x:t,y:n,width:r,height:i,style:o,color:c,strokeColor:l,strokeWidth:d,className:h,borderRadius:m,shapeRendering:_,onClick:g,selected:y})=>{const{background:x,backgroundColor:k}=o||{},v=c||x||k;return Ae.createElement("rect",{className:Er(["react-flow__minimap-node",{selected:y},h]),x:t,y:n,rx:m,ry:m,width:r,height:i,fill:v,stroke:l,strokeWidth:d,shapeRendering:_,onClick:g?N=>g(N,e):void 0})};wC.displayName="MiniMapNode";var PB=p.memo(wC);const DB=e=>e.nodeOrigin,FB=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),_w=e=>e instanceof Function?e:()=>e;function zB({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:i=2,nodeComponent:o=PB,onClick:c}){const l=ms(FB,mr),d=ms(DB),h=_w(t),m=_w(e),_=_w(n),g=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return Ae.createElement(Ae.Fragment,null,l.map(y=>{const{x,y:k}=du(y,d).positionAbsolute;return Ae.createElement(o,{key:y.id,x,y:k,width:y.width,height:y.height,style:y.style,selected:y.selected,className:_(y),color:h(y),borderRadius:r,strokeColor:m(y),strokeWidth:i,shapeRendering:g,onClick:c,id:y.id})}))}var BB=p.memo(zB);const UB=200,WB=150,qB=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?ez(Kg(t,e.nodeOrigin),n):n,rfId:e.rfId}},VB="react-flow__minimap-desc";function vC({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:i="",nodeBorderRadius:o=5,nodeStrokeWidth:c=2,nodeComponent:l,maskColor:d="rgb(240, 240, 240, 0.6)",maskStrokeColor:h="none",maskStrokeWidth:m=1,position:_="bottom-right",onClick:g,onNodeClick:y,pannable:x=!1,zoomable:k=!1,ariaLabel:v="React Flow mini map",inversePan:N=!1,zoomStep:$=10,offsetScale:C=5}){const S=tr(),D=p.useRef(null),{boundingRect:O,viewBB:A,rfId:P}=ms(qB,mr),W=(e==null?void 0:e.width)??UB,J=(e==null?void 0:e.height)??WB,G=O.width/W,V=O.height/J,R=Math.max(G,V),M=R*W,I=R*J,L=C*R,K=O.x-(M-O.width)/2-L,H=O.y-(I-O.height)/2-L,z=M+L*2,ee=I+L*2,B=`${VB}-${P}`,te=p.useRef(0);te.current=R,p.useEffect(()=>{if(D.current){const be=vo(D.current),Me=je=>{const{transform:Te,d3Selection:Ve,d3Zoom:_t}=S.getState();if(je.sourceEvent.type!=="wheel"||!Ve||!_t)return;const Qe=-je.sourceEvent.deltaY*(je.sourceEvent.deltaMode===1?.05:je.sourceEvent.deltaMode?1:.002)*$,it=Te[2]*Math.pow(2,Qe);_t.scaleTo(Ve,it)},Ne=je=>{const{transform:Te,d3Selection:Ve,d3Zoom:_t,translateExtent:Qe,width:it,height:$t}=S.getState();if(je.sourceEvent.type!=="mousemove"||!Ve||!_t)return;const ot=te.current*Math.max(1,Te[2])*(N?-1:1),mt={x:Te[0]-je.sourceEvent.movementX*ot,y:Te[1]-je.sourceEvent.movementY*ot},et=[[0,0],[it,$t]],Lt=sl.translate(mt.x,mt.y).scale(Te[2]),ce=_t.constrain()(Lt,et,Qe);_t.transform(Ve,ce)},ae=E$().on("zoom",x?Ne:null).on("zoom.wheel",k?Me:null);return be.call(ae),()=>{be.on("zoom",null)}}},[x,k,N,$]);const se=g?be=>{const Me=Ho(be);g(be,{x:Me[0],y:Me[1]})}:void 0,de=y?(be,Me)=>{const Ne=S.getState().nodeInternals.get(Me);y(be,Ne)}:void 0;return Ae.createElement(hm,{position:_,style:e,className:Er(["react-flow__minimap",t]),"data-testid":"rf__minimap"},Ae.createElement("svg",{width:W,height:J,viewBox:`${K} ${H} ${z} ${ee}`,role:"img","aria-labelledby":B,ref:D,onClick:se},v&&Ae.createElement("title",{id:B},v),Ae.createElement(BB,{onClick:de,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:o,nodeClassName:i,nodeStrokeWidth:c,nodeComponent:l}),Ae.createElement("path",{className:"react-flow__minimap-mask",d:`M${K-L},${H-L}h${z+L*2}v${ee+L*2}h${-z-L*2}z
156
+ M${A.x},${A.y}h${A.width}v${A.height}h${-A.width}z`,fill:d,fillRule:"evenodd",stroke:h,strokeWidth:m,pointerEvents:"none"})))}vC.displayName="MiniMap";var HB=p.memo(vC);function GB(){return Ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},Ae.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function KB(){return Ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},Ae.createElement("path",{d:"M0 0h32v4.2H0z"}))}function JB(){return Ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},Ae.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 YB(){return Ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ae.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 XB(){return Ae.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ae.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 zd=({children:e,className:t,...n})=>Ae.createElement("button",{type:"button",className:Er(["react-flow__controls-button",t]),...n},e);zd.displayName="ControlButton";const ZB=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),xC=({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:i,onZoomIn:o,onZoomOut:c,onFitView:l,onInteractiveChange:d,className:h,children:m,position:_="bottom-left"})=>{const g=tr(),[y,x]=p.useState(!1),{isInteractive:k,minZoomReached:v,maxZoomReached:N}=ms(ZB,mr),{zoomIn:$,zoomOut:C,fitView:S}=Bx();if(p.useEffect(()=>{x(!0)},[]),!y)return null;const D=()=>{$(),o==null||o()},O=()=>{C(),c==null||c()},A=()=>{S(i),l==null||l()},P=()=>{g.setState({nodesDraggable:!k,nodesConnectable:!k,elementsSelectable:!k}),d==null||d(!k)};return Ae.createElement(hm,{className:Er(["react-flow__controls",h]),position:_,style:e,"data-testid":"rf__controls"},t&&Ae.createElement(Ae.Fragment,null,Ae.createElement(zd,{onClick:D,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},Ae.createElement(GB,null)),Ae.createElement(zd,{onClick:O,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:v},Ae.createElement(KB,null))),n&&Ae.createElement(zd,{className:"react-flow__controls-fitview",onClick:A,title:"fit view","aria-label":"fit view"},Ae.createElement(JB,null)),r&&Ae.createElement(zd,{className:"react-flow__controls-interactive",onClick:P,title:"toggle interactivity","aria-label":"toggle interactivity"},k?Ae.createElement(XB,null):Ae.createElement(YB,null)),m)};xC.displayName="Controls";var QB=p.memo(xC),Yo;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Yo||(Yo={}));function e9({color:e,dimensions:t,lineWidth:n}){return Ae.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function t9({color:e,radius:t}){return Ae.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const n9={[Yo.Dots]:"#91919a",[Yo.Lines]:"#eee",[Yo.Cross]:"#e2e2e2"},s9={[Yo.Dots]:1,[Yo.Lines]:1,[Yo.Cross]:6},r9=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function bC({id:e,variant:t=Yo.Dots,gap:n=20,size:r,lineWidth:i=1,offset:o=2,color:c,style:l,className:d}){const h=p.useRef(null),{transform:m,patternId:_}=ms(r9,mr),g=c||n9[t],y=r||s9[t],x=t===Yo.Dots,k=t===Yo.Cross,v=Array.isArray(n)?n:[n,n],N=[v[0]*m[2]||1,v[1]*m[2]||1],$=y*m[2],C=k?[$,$]:N,S=x?[$/o,$/o]:[C[0]/o,C[1]/o];return Ae.createElement("svg",{className:Er(["react-flow__background",d]),style:{...l,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:h,"data-testid":"rf__background"},Ae.createElement("pattern",{id:_+e,x:m[0]%N[0],y:m[1]%N[1],width:N[0],height:N[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${S[0]},-${S[1]})`},x?Ae.createElement(t9,{color:g,radius:$/o}):Ae.createElement(e9,{dimensions:C,color:g,lineWidth:i})),Ae.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${_+e})`}))}bC.displayName="Background";var i9=p.memo(bC);function kC(e,t={}){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!n)return null;const r=typeof n.x=="number"&&Number.isFinite(n.x)?n.x:null,i=typeof n.y=="number"&&Number.isFinite(n.y)?n.y:null,o=typeof n.zoom=="number"&&Number.isFinite(n.zoom)?n.zoom:null;if(r===null||i===null||o===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(i)>c)return null;const l=typeof t.minZoom=="number"&&Number.isFinite(t.minZoom)?t.minZoom:.025,d=typeof t.maxZoom=="number"&&Number.isFinite(t.maxZoom)?t.maxZoom:6,h=Math.min(l,d),m=Math.max(l,d);return{x:r,y:i,zoom:Math.min(m,Math.max(h,o))}}function yg(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 o9(e){const t=String(e||"").trim();if(!t)return"entity";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return"entity";const r=t.slice(0,n).toLowerCase(),i=t.slice(n+1).toLowerCase();if(r==="ex"){const o=i.indexOf("-"),c=o>0?i.slice(0,o):i;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 a9(e){const t=String(e||"").trim();if(!t)return"";const n=t.indexOf(":");if(n<=0||n>=t.length-1)return yg(t);const r=t.slice(0,n).toLowerCase(),i=t.slice(n+1);if(r==="ex"){const o=i.indexOf("-");if(o>0&&o<i.length-1)return i.slice(o+1)}return yg(t)}function Mv(e){const r=Math.max(1,Math.ceil(Math.sqrt(e.length))),i={};for(let o=0;o<e.length;o++){const c=Math.floor(o/r),l=o%r;i[e[o]]={x:l*240,y:c*120}}return i}function Rv(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 jC(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 l9(e,t){const n={},r=e.length;if(!r)return n;const i=Math.max(260,Math.sqrt(r)*150),o=t%360*Math.PI/180;for(let c=0;c<r;c++){const l=o+2*Math.PI*c/r;n[e[c]]={x:i*Math.cos(l),y:i*Math.sin(l)}}return n}function dj(e,t,n){var x;const r={};if(!e.length)return r;const i=new Map;for(const k of e)i.set(k,new Set);for(const k of t){const v=String((k==null?void 0:k.source)||"").trim(),N=String((k==null?void 0:k.target)||"").trim();if(!v||!N||v===N)continue;const $=i.get(v),C=i.get(N);$&&$.add(N),C&&C.add(v)}let o=e[0],c=-1;for(const k of e){const v=((x=i.get(k))==null?void 0:x.size)??0;(v>c||v===c&&k.localeCompare(o)<0)&&(o=k,c=v)}const l=new Map,d=[];for(l.set(o,0),d.push(o);d.length;){const k=d.shift(),v=l.get(k)??0,N=Array.from(i.get(k)??[]);N.sort(($,C)=>$.localeCompare(C));for(const $ of N)l.has($)||(l.set($,v+1),d.push($))}let h=0;for(const k of l.values())h=Math.max(h,k);for(const k of e)l.has(k)||l.set(k,h+1);const m=new Map;for(const k of e){const v=l.get(k)??0,N=m.get(v);N?N.push(k):m.set(v,[k])}const _=Array.from(m.keys()).sort((k,v)=>k-v),g=260,y=n%360*Math.PI/180;for(const k of _){const v=m.get(k)||[];if(v.sort((S,D)=>S.localeCompare(D)),k===0){if(v.length===1)r[v[0]]={x:0,y:0};else for(let D=0;D<v.length;D++){const O=y+2*Math.PI*D/v.length;r[v[D]]={x:80*Math.cos(O),y:80*Math.sin(O)}}continue}const N=g*k,$=v.length;if($===1){r[v[0]]={x:N,y:0};continue}const C=y+k*.35;for(let S=0;S<$;S++){const D=C+2*Math.PI*S/$;r[v[S]]={x:N*Math.cos(D),y:N*Math.sin(D)}}}return r}function Md(e,t={}){const n=t.kind??"grid",r=typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):0,i=e.nodes.map(o=>o.id);if(n==="grid")return Mv(i);if(n==="circle")return l9(i,r);if(n==="radial")return dj(i,e.edges,r);if(n==="force"){const o=dj(i,e.edges,r),c=jC(r||1),l=Math.max(10,Math.min(42,Math.sqrt(i.length)*2.75)),d={};for(const h of i){const m=o[h]||{x:0,y:0};d[h]={x:m.x+(c()-.5)*l,y:m.y+(c()-.5)*l}}return d}return Mv(i)}function c9(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 u9(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),i=c9(e),o=new Set;for(const g of i){const y=String(g.subject||"").trim(),x=String(g.object||"").trim();y&&o.add(y),x&&o.add(x)}const c=Array.from(o);c.sort((g,y)=>g.localeCompare(y));const l=Mv(c),d=c.map(g=>({id:g,type:"default",data:{label:a9(g),kind:o9(g)},position:l[g]||{x:0,y:0}})),h=new Map,m=(g,y)=>{const x=String(g.subject||"").trim(),k=String(g.object||"").trim(),v=String(g.predicate||"").trim();return n?`edge:${x}:${k}`:`edge:${y}:${x}:${v}:${k}`};for(let g=0;g<i.length;g++){const y=i[g],x=m(y,g),k=h.get(x);k?k.push(y):h.set(x,[y])}const _=[];for(const[g,y]of h.entries()){const x=y[0],k=String(x.subject||"").trim(),v=String(x.object||"").trim();if(!k||!v)continue;const N=new Map;for(const A of y){const P=String(A.predicate||"").trim();P&&N.set(P,(N.get(P)||0)+1)}const $=Array.from(N.entries());$.sort((A,P)=>P[1]-A[1]||A[0].localeCompare(P[0]));const S=$.slice(0,r).map(([A,P])=>P>1?`${yg(A)}×${P}`:yg(A)).join(" | "),D=$.length>r?` +${$.length-r}`:"",O=`${S}${D}`.trim();_.push({id:g,source:k,target:v,label:O,animated:!1,data:{assertions:y,predicateSummary:O}})}return{nodes:d,edges:_}}function d9(e,t,n,r={}){const i=r.directed!==!1,o=String(t||"").trim(),c=String(n||"").trim();if(!o||!c)return null;if(o===c)return{nodeIds:[o],edgeIds:[]};const l=new Map,d=(k,v,N)=>{const $=l.get(k);$?$.push({to:v,edgeId:N}):l.set(k,[{to:v,edgeId:N}])};for(const k of e.edges)d(k.source,k.target,k.id),i||d(k.target,k.source,k.id);const h=[o],m=new Map,_=new Map;for(m.set(o,null),_.set(o,null);h.length;){const k=h.shift(),v=l.get(k)||[];for(const N of v)if(!m.has(N.to)){if(m.set(N.to,k),_.set(N.to,N.edgeId),N.to===c){h.length=0;break}h.push(N.to)}}if(!m.has(c))return null;const g=[],y=[];let x=c;for(;x;){g.push(x);const k=_.get(x);k&&y.push(k),x=m.get(x)||null}return g.reverse(),y.reverse(),{nodeIds:g,edgeIds:y}}const fj={seed:1,dt:1,springLength:240,springStrength:.03,repulsionStrength:9e3,centeringStrength:.003,damping:.85,maxSpeed:90,maxRepulsionNodes:320};function wp(e,t={}){const n={...fj,...t,seed:typeof t.seed=="number"&&Number.isFinite(t.seed)?Math.trunc(t.seed):fj.seed},r=e.nodes.map(y=>y.id),i=r.length,o=new Float64Array(2*i),c=new Float64Array(2*i),l=new Float64Array(2*i),d=new Map;for(let y=0;y<i;y++)d.set(r[y],y);const h=t.positions??Md(e,{kind:"force",seed:n.seed}),m=jC(n.seed||1),_=Math.max(8,Math.min(38,Math.sqrt(i)*2.25));for(let y=0;y<i;y++){const x=r[y],k=h[x],v=typeof(k==null?void 0:k.x)=="number"&&Number.isFinite(k.x)?k.x:(m()-.5)*500,N=typeof(k==null?void 0:k.y)=="number"&&Number.isFinite(k.y)?k.y:(m()-.5)*500;o[2*y]=v+(m()-.5)*_,o[2*y+1]=N+(m()-.5)*_,c[2*y]=0,c[2*y+1]=0}const g=[];for(const y of e.edges){const x=d.get(String((y==null?void 0:y.source)||"").trim()),k=d.get(String((y==null?void 0:y.target)||"").trim());typeof x!="number"||typeof k!="number"||x===k||g.push(x,k)}return{nodeIds:r,pos:o,vel:c,acc:l,edges:new Uint32Array(g),options:n,tick:0}}function f9(e,t=1){const n=e.nodeIds.length;if(!n)return;const r=e.options,i=r.dt;for(let o=0;o<Math.max(1,Math.trunc(t));o++){if(e.acc.fill(0),n<=r.maxRepulsionNodes){const y=r.repulsionStrength;for(let x=0;x<n;x++){const k=e.pos[2*x],v=e.pos[2*x+1];for(let N=x+1;N<n;N++){const $=e.pos[2*N]-k,C=e.pos[2*N+1]-v,S=$*$+C*C+1e-6,D=1/Math.sqrt(S),O=y/S,A=O*$*D,P=O*C*D;e.acc[2*x]-=A,e.acc[2*x+1]-=P,e.acc[2*N]+=A,e.acc[2*N+1]+=P}}}const l=r.springLength,d=r.springStrength,h=e.edges;for(let y=0;y<h.length;y+=2){const x=h[y],k=h[y+1],v=e.pos[2*x],N=e.pos[2*x+1],$=e.pos[2*k],C=e.pos[2*k+1],S=$-v,D=C-N,O=S*S+D*D+1e-6,A=Math.sqrt(O),P=d*(A-l),W=P*S/A,J=P*D/A;e.acc[2*x]+=W,e.acc[2*x+1]+=J,e.acc[2*k]-=W,e.acc[2*k+1]-=J}const m=r.centeringStrength;for(let y=0;y<n;y++)e.acc[2*y]+=-m*e.pos[2*y],e.acc[2*y+1]+=-m*e.pos[2*y+1];const _=r.damping,g=r.maxSpeed;for(let y=0;y<n;y++){let x=(e.vel[2*y]+e.acc[2*y]*i)*_,k=(e.vel[2*y+1]+e.acc[2*y+1]*i)*_;const v=Math.sqrt(x*x+k*k);if(v>g){const N=g/v;x*=N,k*=N}e.vel[2*y]=x,e.vel[2*y+1]=k,e.pos[2*y]+=x*i,e.pos[2*y+1]+=k*i}e.tick+=1}}function h9(e){const t=e.nodeIds.length;if(!t)return 0;let n=0;for(let r=0;r<t;r++){const i=e.vel[2*r],o=e.vel[2*r+1];n+=Math.sqrt(i*i+o*o)}return n/t}function m9(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 hj(e,t="session"){const n=String(e??"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function _9(){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 p9(){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 SC(e,t,n,r){const i=typeof e=="number"&&Number.isFinite(e)?e:r;return Math.min(n,Math.max(t,i))}function Mh(e){const t=SC(e,.6,2.4,1),n=240*t,r=9e3*t*t;return{springLength:n,repulsionStrength:r}}const ym="abstractuic_amx_saved_layouts_v1",Lv=.025,Iv=6,NC=1e6;function qx(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function Ov(e,t="grid"){const n=String(e??"").trim().toLowerCase();return n==="grid"||n==="circle"||n==="radial"||n==="force"?n:t}function g9(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 mj(e){const t=qx();if(!t)return null;const n=String(e??"").trim();if(!n)return null;try{const r=t.getItem(ym);if(!r)return null;const i=JSON.parse(r),o=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!o)return null;const c=o[n],l=c&&typeof c=="object"&&!Array.isArray(c)?c:null;if(!l)return null;const d=l.version===1?1:null;if(d===null)return null;const h=Ov(l.kind,"grid"),m=typeof l.seed=="number"&&Number.isFinite(l.seed)?Math.trunc(l.seed):Rv(n),_=l.positions&&typeof l.positions=="object"&&!Array.isArray(l.positions)?l.positions:null,g={};if(_)for(const[k,v]of Object.entries(_)){const N=g9(v);N&&(g[String(k)]=N)}const y=kC(l.viewport,{minZoom:Lv,maxZoom:Iv,maxAbsTranslate:NC})??void 0,x=typeof l.saved_at=="string"&&l.saved_at.trim()?l.saved_at.trim():"";return{version:d,kind:h,seed:m,positions:g,viewport:y,saved_at:x}}catch{return null}}function y9(e,t){const n=qx();if(!n)return;const r=String(e??"").trim();if(r)try{const i=n.getItem(ym),o=i?JSON.parse(i):null,c=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};c[r]=t,n.setItem(ym,JSON.stringify(c))}catch{}}function w9(e){const t=qx();if(!t)return;const n=String(e??"").trim();if(n)try{const r=t.getItem(ym);if(!r)return;const i=JSON.parse(r),o=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:null;if(!o||!(n in o))return;delete o[n],t.setItem(ym,JSON.stringify(o))}catch{}}function v9(e){const t=String(e??"").trim();if(!t)return;const n=Number(t);if(Number.isFinite(n))return n}function pw(e,t){const n=!!(t!=null&&t.allowZero),r=!!(t!=null&&t.allowNegativeOne),i=String(e??"").trim();if(!i)return;const o=Number(i);if(!Number.isFinite(o))return;const c=Math.trunc(o);if(r&&c===-1)return-1;if(!(!n&&c<=0)&&!(n&&c<0))return c}function x9(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.recall_level=="string"?t.recall_level:"",r=t.applied&&typeof t.applied=="object"&&!Array.isArray(t.applied)?t.applied:null,i=[];return n&&i.push(`recall_level=${n}`),r&&(typeof r.limit=="number"&&i.push(`limit=${r.limit}`),typeof r.min_score=="number"&&i.push(`min_score=${r.min_score}`),typeof r.max_input_tokens=="number"&&i.push(`max_input_tokens=${r.max_input_tokens}`)),i.length?i.join(" · "):null}function b9(e){if(!e||typeof e!="object")return null;const t=[],n=typeof e.scope=="string"?e.scope.trim():"",r=typeof e.owner_id=="string"?e.owner_id.trim():"";n&&t.push(`scope=${n}`),r&&t.push(`owner_id=${r}`);const i=typeof e.confidence=="number"&&Number.isFinite(e.confidence)?e.confidence:null;i!==null&&t.push(`confidence=${i.toFixed(3)}`);const o=e.provenance&&typeof e.provenance=="object"&&!Array.isArray(e.provenance)?e.provenance:null;if(o){const h=typeof o.writer_run_id=="string"?o.writer_run_id.trim():"",m=typeof o.writer_workflow_id=="string"?o.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,l=c&&c._retrieval&&typeof c._retrieval=="object"&&!Array.isArray(c._retrieval)?c._retrieval:null,d=l&&typeof l.score=="number"&&Number.isFinite(l.score)?l.score:null;return d!==null&&t.push(`score=${d.toFixed(3)}`),t.length?t.join(" · "):null}function k9(e,t){const n=String(e??""),r=String(t??"").trim();if(!r)return n;const i=n.toLowerCase().indexOf(r.toLowerCase());if(i<0)return n;const o=n.slice(0,i),c=n.slice(i,i+r.length),l=n.slice(i+r.length);return s.jsxs(s.Fragment,{children:[o,s.jsx("span",{className:"amx-hl",children:c}),l]})}function Rh(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 j9(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 Lh(e){const t=j9(e);if(t===null)return"";const n=new Date(t),r=n.getUTCFullYear(),i=String(n.getUTCMonth()+1).padStart(2,"0"),o=String(n.getUTCDate()).padStart(2,"0"),c=String(n.getUTCHours()).padStart(2,"0"),l=String(n.getUTCMinutes()).padStart(2,"0");return`${r}/${i}/${o} ${c}:${l}`}function $C(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 gw(e,t){const n=String(e??"").trim().toLowerCase();return!!(n&&t.has(n))}function S9(e,t={}){const n=Math.max(1,t.maxPredicates??3),r=new Map;for(const d of e){const h=String((d==null?void 0:d.predicate)||"").trim();h&&r.set(h,(r.get(h)||0)+1)}const i=Array.from(r.entries());i.sort((d,h)=>h[1]-d[1]||d[0].localeCompare(h[0]));const c=i.slice(0,n).map(([d,h])=>{const m=$C(d);return h>1?`${m}×${h}`:m}).join(" | "),l=i.length>n?` +${i.length-n}`:"";return`${c}${l}`.trim()}function N9({resetKey:e,queryMode:t,items:n,activeMemoryText:r,packets:i,packetsVersion:o,packedCount:c,dropped:l,estimatedTokens:d,effort:h,warnings:m,onQuery:_,onItemsReplace:g,onOpenSpan:y,onOpenTranscript:x}){var Kn;const k=p.useRef(null),v=p.useMemo(()=>{const Y=n==null?void 0:n[0],me=n==null?void 0:n[n.length-1],Oe=Y?`${Y.subject}|${Y.predicate}|${Y.object}`:"",De=me?`${me.subject}|${me.predicate}|${me.object}`:"";return`${(n==null?void 0:n.length)||0}:${Oe}:${De}`},[n]),N=String(e??v),$=t==="replace"?"replace":"override",[C,S]=p.useState(null),[D,O]=p.useState(null),[A,P]=p.useState(!1),[W,J]=p.useState(""),[G,V]=p.useState(!1),[R,M]=p.useState("");p.useEffect(()=>{S(null),O(null),J(""),P(!1),M(""),V(!1)},[N]);const[I,L]=p.useState(""),[K,H]=p.useState(!0),[z,ee]=p.useState(!1),[B,te]=p.useState(!0),[se]=p.useState(()=>({compact:_9(),show:!1})),de=se.compact,[be,Me]=p.useState(se.show),[Ne,ae]=p.useState(!1),je=N,Te=p.useMemo(()=>Rv(je),[je]),[Ve,_t]=p.useState("grid"),[Qe,it]=p.useState(Te),[$t,ot]=p.useState(!1),[mt,et]=p.useState(1),Lt=p.useRef(null),ce=p.useRef(null),Se=p.useRef(!1),[He,ne]=p.useState(0),we=p.useRef(null),fe=p.useRef(0),$e=p.useRef(0),pe=p.useRef(0),le=p.useRef(0),[ze,st]=p.useState(!1),[kt,pt]=p.useState(""),[jt,ct]=p.useState({}),It=p.useRef({});p.useEffect(()=>{It.current=jt},[jt]);const[vt,nn]=p.useState(""),[wn,On]=p.useState(""),Ks=p.useMemo(()=>{var me;const Y=(me=n==null?void 0:n[0])==null?void 0:me.scope;return hj(Y,"session")},[n]),[rs,ge]=p.useState(Ks),[Le,yt]=p.useState("standard"),[re,he]=p.useState(""),[Ee,Ie]=p.useState(""),[We,Ue]=p.useState(""),[tt,ut]=p.useState(""),[xt,bt]=p.useState(""),[Mt,zt]=p.useState(""),[lt,Yt]=p.useState(""),[vn,mn]=p.useState("qwen/qwen3-next-80b");p.useEffect(()=>{ge(Ks)},[N]);const rn=Array.isArray(n)?n:[],Ht=typeof r=="string"?r:"",is=Array.isArray(i)?i:[],Be=typeof o=="number"?o:void 0,Qt=typeof c=="number"?c:void 0,Ot=typeof l=="number"?l:void 0,Fn=typeof d=="number"?d:void 0,hn=h,Xe=m,sn=$==="override"&&(C!=null&&C.items)&&Array.isArray(C.items)?C.items:rn,un=typeof(C==null?void 0:C.active_memory_text)=="string"&&C.active_memory_text.trim()?C.active_memory_text:Ht,Ar=(C==null?void 0:C.effort)??hn,As=(C==null?void 0:C.warnings)??Xe,ws=p.useMemo(()=>new Set(["rdf:type","schema:name","skos:preflabel","skos:altlabel","dcterms:title","dcterms:identifier"]),[]),_r=p.useMemo(()=>B?sn:(sn||[]).filter(Y=>!gw(Y==null?void 0:Y.predicate,ws)),[sn,B,ws]),ve=p.useMemo(()=>u9(sn,{groupEdges:K}),[sn,K]),Ct=p.useMemo(()=>{if(B)return ve;const Y=[];for(const me of ve.edges){const De=(me&&me.data&&Array.isArray(me.data.assertions)?me.data.assertions:[]).filter(ht=>!gw(ht==null?void 0:ht.predicate,ws));if(!De.length)continue;const Ye=S9(De);Y.push({...me,label:Ye,data:{...me.data,assertions:De,predicateSummary:Ye}})}return{nodes:ve.nodes,edges:Y}},[ve,B,ws]),zn=p.useMemo(()=>Ct.nodes.map(Y=>Y.id),[Ct.nodes]),nr=p.useMemo(()=>{const Y=zn[0]||"",me=zn[zn.length-1]||"";return`${zn.length}:${Y}:${me}`},[zn]),$i=p.useMemo(()=>{var me;const Y=new Map;for(const Oe of Ct.nodes)Y.set(Oe.id,String(((me=Oe.data)==null?void 0:me.label)||Oe.id));return Y},[Ct.nodes]),sr=p.useMemo(()=>{var me;const Y=new Map;for(const Oe of Ct.nodes)Y.set(Oe.id,String(((me=Oe.data)==null?void 0:me.kind)||""));return Y},[Ct.nodes]),bo=I.trim().toLowerCase(),dc=p.useMemo(()=>{var me;if(!bo)return new Set;const Y=new Set;for(const Oe of Ct.nodes){const De=String(Oe.id||"").toLowerCase(),Ye=String(((me=Oe.data)==null?void 0:me.label)||"").toLowerCase();(De.includes(bo)||Ye.includes(bo))&&Y.add(Oe.id)}return Y},[Ct.nodes,bo]),ul=p.useCallback((Y,me)=>{const Oe={};for(const De of zn){const Ye=Y[De]||me[De];Oe[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Oe},[zn]);p.useEffect(()=>{ct(Y=>{const me=Md(Ct,{kind:Ve,seed:Qe}),Oe={};for(const De of zn){const Ye=Y[De]||me[De];Oe[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Oe})},[Ct,Ve,Qe,zn,nr]),p.useEffect(()=>{if(!Se.current)return;const Y=k.current;if(!(!Y||typeof Y.fitView!="function")&&zn.length){Se.current=!1;try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}}},[zn.length,nr,jt]),p.useEffect(()=>{ot(!1),Lt.current=null,ce.current=null,Se.current=!1,fe.current=0,$e.current=0,pe.current=0;const Y=mj(je);if(Y&&Object.keys(Y.positions||{}).length){if(_t(Y.kind),it(Y.seed),st(!0),pt(Y.saved_at||""),Y.viewport){ce.current=Y.viewport;const Ye=k.current;if(Ye&&typeof Ye.setViewport=="function"){try{Ye.setViewport(Y.viewport,{duration:0})}catch{try{Ye.setViewport(Y.viewport)}catch{}}ce.current=null}}else Se.current=!0;const De=Md(Ct,{kind:Y.kind,seed:Y.seed});ct(ul(Y.positions,De));return}st(!1),pt("");const me=Rv(je);it(me);const Oe=Md(Ct,{kind:Ve,seed:me});ct(Oe),Ve==="force"&&Ct.nodes.length>0&&Ct.nodes.length<=320&&(Lt.current=wp(Ct,{seed:me,positions:Oe,...Mh(mt)}),ot(!0))},[je]);const js=p.useMemo(()=>{const Y=String(vt||"").trim(),me=String(wn||"").trim();return!Y||!me?null:d9(Ct,Y,me,{directed:z})},[Ct,vt,wn,z]),pr=!!(js&&String(vt||"").trim()&&String(wn||"").trim()),Rs=p.useMemo(()=>{const Y=String(vt||"").trim(),me=String(wn||"").trim();if(!Y||!me)return null;const Oe=z,De=new Map,Ye=(Dt,Bt)=>{const pn=De.get(Dt);pn?pn.push(Bt):De.set(Dt,[Bt])};for(const Dt of Ct.edges)Ye(Dt.source,Dt.target),Oe||Ye(Dt.target,Dt.source);const ht=new Set,Wt=[];for(ht.add(Y),Wt.push(Y);Wt.length;){const Dt=Wt.shift(),Bt=De.get(Dt)||[];for(const pn of Bt)ht.has(pn)||(ht.add(pn),Wt.push(pn))}return{reachableFromStart:ht.size,endReachable:ht.has(me),nodes:Ct.nodes.length,edges:Ct.edges.length,assertions:_r.length}},[z,Ct.edges,Ct.nodes.length,wn,vt,_r.length]),Bi=p.useMemo(()=>new Set((js==null?void 0:js.nodeIds)||[]),[js]),dl=p.useMemo(()=>new Set((js==null?void 0:js.edgeIds)||[]),[js]),[vs,ri]=p.useState(""),[Ls,ii]=p.useState(""),Ss=!!(String(vs||"").trim()||String(Ls||"").trim()),oi=p.useMemo(()=>{const Y=new Set,me=new Set,Oe=String(vs||"").trim(),De=String(Ls||"").trim();if(Oe){Y.add(Oe);for(const Ye of Ct.edges)(Ye.source===Oe||Ye.target===Oe)&&(me.add(Ye.id),Y.add(Ye.source),Y.add(Ye.target));return{nodes:Y,edges:me}}if(De){const Ye=Ct.edges.find(ht=>ht.id===De);Ye&&(me.add(Ye.id),Y.add(Ye.source),Y.add(Ye.target))}return{nodes:Y,edges:me}},[Ct.edges,Ls,vs]);p.useEffect(()=>{ri(""),ii(""),nn(""),On("")},[N]);const[Ui,In]=p.useState(!1);p.useEffect(()=>{In(!1)},[N]),p.useEffect(()=>{$t||(Lt.current=null)},[$t]),p.useEffect(()=>{if(Ve!=="force")return;const Y=Lt.current;if(!Y)return;const me=Mh(mt);Y.options.springLength=me.springLength,Y.options.repulsionStrength=me.repulsionStrength},[Ve,mt]),p.useEffect(()=>{Ve!=="force"&&$t&&ot(!1)},[Ve,$t]),p.useEffect(()=>{if(!$t||Ve!=="force"||Ct.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Lt.current||(Lt.current=wp(Ct,{seed:Qe,positions:It.current,...Mh(mt)}));let Y=0,me=0,Oe=0;const De=Ct.nodes.length<=140?2:1,Ye=1600,ht=.08,Wt=Dt=>{if(Y=window.requestAnimationFrame(Wt),Dt-me<33)return;me=Dt;const Bt=Lt.current;if(!Bt){ot(!1);return}f9(Bt,De),Oe+=De,ct(m9(Bt)),(h9(Bt)<=ht||Oe>=Ye)&&ot(!1)};return Y=window.requestAnimationFrame(Wt),()=>{window.cancelAnimationFrame(Y)}},[Ct,Ve,$t,Qe]);const $a=p.useMemo(()=>Ct.nodes.map(Y=>{var bn;const me=Bi.has(Y.id),Oe=dc.has(Y.id),De=vs===Y.id,Ye=Ss&&oi.nodes.has(Y.id),ht=Rh((bn=Y.data)==null?void 0:bn.kind),Wt="rgba(34, 211, 238, 0.88)",Dt=Oe?"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)":"",Bt=me?"rgba(168, 85, 247, 0.9)":Oe?Wt:ht.stroke,pn=De?"0 0 0 2px rgba(255,255,255,0.20), 0 18px 46px rgba(0,0,0,0.55)":Ye?"0 0 0 1px rgba(96, 165, 250, 0.28), 0 12px 34px rgba(0,0,0,0.45)":void 0,En=Dt&&pn?`${Dt}, ${pn}`:pn||Dt||void 0,Js=me?"rgba(168, 85, 247, 0.10)":Oe?"rgba(34, 211, 238, 0.08)":ht.bg,Ft=pr?me||De?1:.16:Ss?Ye||De?1:.1:1;return{...Y,position:jt[Y.id]?{x:jt[Y.id].x,y:jt[Y.id].y}:Y.position,style:{...Y.style||{},border:`1px solid ${Bt}`,borderRadius:10,background:Js,color:"rgba(255,255,255,0.92)",opacity:Ft,padding:8,fontSize:12,boxShadow:En,width:180,cursor:"pointer"}}}),[Ct.nodes,pr,dc,jt,vs,Bi,Ss,oi.nodes]),fl=p.useMemo(()=>Ct.edges.map(Y=>{const me=dl.has(Y.id),Oe=Ls===Y.id,De=Ss&&oi.edges.has(Y.id),Ye=me?"rgba(168, 85, 247, 0.9)":Ss?De||Oe?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",ht=me?2.75:Ss?De||Oe?2.25:1.25:1.5,Wt=Oe?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,Dt=me?"rgba(168, 85, 247, 0.9)":pr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",Bt=pr?me||Oe?1:.1:Ss?De||Oe?1:.08:1,pn=pr?me||Oe?1:0:Ss?De||Oe?1:0:1,En=pr?me||Oe?String(Y.label||""):"":String(Y.label||"");return{...Y,label:En,style:{...Y.style||{},stroke:Ye,strokeWidth:ht,filter:Wt,opacity:Bt},animated:!1,markerEnd:{type:pm.ArrowClosed,color:Dt,width:20,height:20},labelShowBg:!0,labelBgPadding:[6,3],labelBgBorderRadius:10,labelBgStyle:{fill:`rgba(0, 0, 0, ${.38*pn})`,stroke:`rgba(255, 255, 255, ${.14*pn})`,strokeWidth:1},labelStyle:{fill:`rgba(255, 255, 255, ${.92*pn})`,fontSize:10,fontWeight:600,letterSpacing:.2,textTransform:"lowercase"}}}),[Ct.edges,pr,Ls,dl,Ss,oi.edges]),hl=p.useMemo(()=>{if(!Ls)return[];const Y=Ct.edges.find(Oe=>Oe.id===Ls),me=Y&&Y.data&&Array.isArray(Y.data.assertions)?Y.data.assertions:[];return Array.isArray(me)?me:[]},[Ct.edges,Ls]),Tr=p.useMemo(()=>Ls&&Ct.edges.find(Y=>Y.id===Ls)||null,[Ct.edges,Ls]),fc=p.useMemo(()=>{const Y=String(vs||"").trim();return Y?sn.filter(me=>!me||typeof me!="object"||!(me.subject===Y||me.object===Y)?!1:B?!0:!gw(me.predicate,ws)):[]},[sn,vs,B,ws]),Wi=p.useMemo(()=>Ls?hl:fc,[hl,Ls,fc]),Ca=p.useMemo(()=>{const Y=new Map;for(const me of Wi){if(!me||typeof me!="object")continue;const Oe=me.provenance&&typeof me.provenance=="object"&&!Array.isArray(me.provenance)?me.provenance:null,De=Oe&&typeof Oe.span_id=="string"?Oe.span_id.trim():"",Ye=Oe&&typeof Oe.writer_run_id=="string"?Oe.writer_run_id.trim():"",ht=typeof me.owner_id=="string"?me.owner_id.trim():"",Wt=Ye||ht;if(!Wt||!De)continue;const Dt=`${Wt}|${De}`,Bt=Y.get(Dt),pn=typeof me.observed_at=="string"?me.observed_at.trim():"";Bt?(Bt.count+=1,pn&&(!Bt.last_observed_at||pn>Bt.last_observed_at)&&(Bt.last_observed_at=pn,Bt.last_observed_at_fmt=Lh(pn),Bt.assertion=me)):Y.set(Dt,{span_run_id:Wt,span_id:De,writer_run_id:Ye,count:1,last_observed_at:pn,last_observed_at_fmt:Lh(pn),assertion:me})}return Array.from(Y.values()).sort((me,Oe)=>String(Oe.last_observed_at||"").localeCompare(String(me.last_observed_at||"")))},[Wi]),ko=p.useMemo(()=>{const Y=new Map;for(const me of Wi){if(!me||typeof me!="object")continue;const Oe=me.provenance&&typeof me.provenance=="object"&&!Array.isArray(me.provenance)?me.provenance:null,De=Oe&&typeof Oe.span_id=="string"?Oe.span_id.trim():"",Ye=Oe&&typeof Oe.writer_run_id=="string"?Oe.writer_run_id.trim():"";if(!Ye||De)continue;const ht=Y.get(Ye),Wt=typeof me.observed_at=="string"?me.observed_at.trim():"";ht?(ht.count+=1,Wt&&(!ht.last_observed_at||Wt>ht.last_observed_at)&&(ht.last_observed_at=Wt,ht.last_observed_at_fmt=Lh(Wt),ht.assertion=me)):Y.set(Ye,{run_id:Ye,count:1,last_observed_at:Wt,last_observed_at_fmt:Lh(Wt),assertion:me})}return Array.from(Y.values()).sort((me,Oe)=>String(Oe.last_observed_at||"").localeCompare(String(me.last_observed_at||"")))},[Wi]),Fs=p.useCallback(Y=>{const me=String(Y.run_id||"").trim(),Oe=typeof Y.span_id=="string"?String(Y.span_id).trim():"";if(me){if(x){try{x({run_id:me,span_id:Oe||void 0,assertion:Y.assertion})}catch{}return}if(y&&Oe)try{y({run_id:me,span_id:Oe,assertion:Y.assertion})}catch{}}},[y,x]),zs=p.useCallback(async Y=>{var Oe;const me=String(Y??"");if(me){try{if(typeof((Oe=navigator.clipboard)==null?void 0:Oe.writeText)=="function"){await navigator.clipboard.writeText(me);return}}catch{}try{const De=document.createElement("textarea");De.value=me,De.style.position="fixed",De.style.left="-9999px",document.body.appendChild(De),De.select(),document.execCommand("copy"),document.body.removeChild(De)}catch{}}},[]),gr=p.useCallback(()=>{const Y=k.current;if(!(!Y||typeof Y.fitView!="function")){if(vs&&typeof Y.getNode=="function"){const me=Y.getNode(vs);if(me){Y.fitView({nodes:[me],padding:.55,duration:350});return}}Y.fitView({padding:.2,duration:350})}},[vs]),jo=p.useCallback(Y=>{const me=Y.kind,Oe=Math.trunc(Y.seed);ot(!1),Lt.current=null,ce.current=null,_t(me),it(Oe);const De=Md(Ct,{kind:me,seed:Oe});ct(De),me==="force"&&(Y.autoPlay??!0)&&Ct.nodes.length>0&&Ct.nodes.length<=320&&(Lt.current=wp(Ct,{seed:Oe,positions:De,...Mh(mt)}),ot(!0))},[Ct,mt]),qr=p.useCallback(()=>{if(Ve==="force"){if($t){ot(!1);return}Lt.current=wp(Ct,{seed:Qe,positions:It.current,...Mh(mt)}),ot(!0)}},[Ct,Ve,$t,Qe,mt]);p.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&le.current&&window.cancelAnimationFrame(le.current)},[]);const Mr=p.useCallback(()=>{const Y=k.current;if(!Y||typeof Y.getViewport!="function"||!zn.length)return null;const me=we.current;if(!me)return null;const Oe=me.getBoundingClientRect();if(!Number.isFinite(Oe.width)||!Number.isFinite(Oe.height)||Oe.width<64||Oe.height<64)return null;const De=Y.getViewport(),Ye=typeof(De==null?void 0:De.zoom)=="number"&&Number.isFinite(De.zoom)?De.zoom:null,ht=typeof(De==null?void 0:De.x)=="number"&&Number.isFinite(De.x)?De.x:null,Wt=typeof(De==null?void 0:De.y)=="number"&&Number.isFinite(De.y)?De.y:null;if(Ye===null||ht===null||Wt===null||Ye<=0)return null;const Dt=140,Bt=Math.min(zn.length,180),pn=It.current;let En=0,Js=0;for(const Ft of zn){const bn=pn[Ft];if(!bn||!Number.isFinite(bn.x)||!Number.isFinite(bn.y))continue;Js+=1;const ls=[{x:bn.x,y:bn.y},{x:bn.x+90,y:bn.y+24}];for(const Hn of ls){const Rr=Hn.x*Ye+ht,yr=Hn.y*Ye+Wt;if(Rr>-Dt&&Rr<Oe.width+Dt&&yr>-Dt&&yr<Oe.height+Dt)return!1}if(En++,En>=Bt)break}return Js?!0:null},[zn]),Vr=p.useCallback(Y=>{typeof window>"u"||typeof window.requestAnimationFrame!="function"||le.current||(le.current=window.requestAnimationFrame(()=>{le.current=0;const me=Mr();if(me===null){if(pe.current>=12)return;pe.current+=1,window.setTimeout(()=>Vr(`${Y}:probe`),120);return}if(me!==!0){pe.current=0,$e.current=0;return}pe.current=0;const Oe=k.current;if(Oe&&typeof Oe.fitView=="function")try{Oe.fitView({padding:.2,duration:0})}catch{try{Oe.fitView({padding:.2})}catch{}}if($e.current+=1,$e.current>=4&&fe.current<1){$e.current=0,fe.current+=1,ne(De=>De+1);return}$e.current<8&&window.setTimeout(()=>Vr(`${Y}:retry`),220)}))},[Mr]);p.useEffect(()=>{$e.current=0,fe.current=0,pe.current=0,Vr("mount")},[N,Vr]),p.useEffect(()=>{Vr("graph change")},[nr,Vr]),p.useEffect(()=>{const Y=we.current;if(!Y||typeof window>"u"||typeof ResizeObserver!="function")return;const me=new ResizeObserver(()=>Vr("resize"));return me.observe(Y),()=>me.disconnect()},[Vr]);const hc=p.useCallback(()=>{const Y=new Date().toISOString(),me={};for(const Wt of zn){const Dt=It.current[Wt];Dt&&typeof Dt.x=="number"&&typeof Dt.y=="number"&&(me[Wt]={x:Dt.x,y:Dt.y})}const Oe=k.current,De=Oe&&typeof Oe.toObject=="function"?Oe.toObject():null,Ye=De&&De.viewport?De.viewport:Oe&&typeof Oe.getViewport=="function"?Oe.getViewport():null,ht=kC(Ye,{minZoom:Lv,maxZoom:Iv,maxAbsTranslate:NC})??void 0;y9(je,{version:1,kind:Ve,seed:Qe,positions:me,viewport:ht,saved_at:Y}),st(!0),pt(Y),ot(!1)},[je,Ve,Qe,zn]),Hr=p.useCallback(()=>{const Y=mj(je);if(!Y)return;ot(!1),Lt.current=null,_t(Y.kind),it(Y.seed),st(!0),pt(Y.saved_at||""),ce.current=Y.viewport||null,Se.current=!Y.viewport;const me=Md(Ct,{kind:Y.kind,seed:Y.seed});if(ct(ul(Y.positions,me)),Y.viewport){const Oe=k.current;if(Oe&&typeof Oe.setViewport=="function"){try{Oe.setViewport(Y.viewport,{duration:0})}catch{try{Oe.setViewport(Y.viewport)}catch{}}ce.current=null}}},[ul,Ct,je]),ku=p.useCallback(()=>{w9(je),st(!1),pt("")},[je]),Ci=p.useCallback(Y=>{if(!Array.isArray(Y)||Y.length===0)return;let me=!1;ct(Oe=>{let De=Oe,Ye=!1;for(const ht of Y){const Wt=ht&&typeof ht=="object"&&"id"in ht&&typeof ht.id=="string"?String(ht.id):"",Dt=(ht==null?void 0:ht.type)==="position"?ht==null?void 0:ht.position:null;Wt&&Dt&&typeof Dt.x=="number"&&typeof Dt.y=="number"&&(Ye||(De={...Oe},Ye=!0),De[Wt]={x:Dt.x,y:Dt.y},ht!=null&&ht.dragging&&(me=!0))}return Ye?De:Oe}),me&&$t&&ot(!1)},[$t]),Zo=p.useMemo(()=>{const Y=new Map;for(const me of Ct.edges)Y.set(me.id,me);return Y},[Ct.edges]),ml=p.useMemo(()=>{var De;if(!js)return[];const Y=js.nodeIds||[],me=js.edgeIds||[],Oe=[];for(let Ye=0;Ye<Math.min(Y.length-1,me.length);Ye++){const ht=Y[Ye],Wt=Y[Ye+1],Dt=me[Ye],Bt=Zo.get(Dt),pn=String(((De=Bt==null?void 0:Bt.data)==null?void 0:De.predicateSummary)||(Bt==null?void 0:Bt.label)||"").trim(),En=Bt&&Bt.source===ht&&Bt.target===Wt?"forward":Bt&&Bt.source===Wt&&Bt.target===ht?"reverse":"unknown";Oe.push({from:ht,to:Wt,edgeId:Dt,predicate:pn,dir:En})}return Oe},[Zo,js]),So=p.useCallback(async()=>{if(_){J(""),M(""),P(!0);try{const Y=v9(xt),me=pw(Mt,{allowZero:!0,allowNegativeOne:!0}),Oe=pw(lt,{allowZero:!0}),De=await _({scope:rs,owner_id:void 0,recall_level:Le,query_text:re||void 0,subject:Ee||void 0,predicate:We||void 0,object:tt||void 0,min_score:Y,limit:me,max_input_tokens:Oe,model:vn||void 0});S(De),O("live query"),$==="replace"&&g&&De&&Array.isArray(De.items)&&g(De.items,{kind:"live query",result:De})}catch(Y){const me=Y instanceof Error?Y.message:String(Y);J(me||"Query failed")}finally{P(!1)}}},[Mt,lt,xt,vn,tt,g,_,We,$,re,Le,rs,Ee]),ai=p.useCallback(async()=>{if(!_)return;const Y=String(vt||"").trim(),me=String(wn||"").trim();if(!Y||!me)return;const Oe=Math.max(200,pw(Mt)??80),De=60;M(""),J(""),V(!0);try{const Ye=[],ht=new Set,Wt=Ft=>{if(!Ft||typeof Ft!="object"||typeof Ft.subject!="string"||typeof Ft.predicate!="string"||typeof Ft.object!="string")return;const bn=`${Ft.subject}|${Ft.predicate}|${Ft.object}|${String(Ft.observed_at||"")}|${String(Ft.scope||"")}|${String(Ft.owner_id||"")}`;ht.has(bn)||(ht.add(bn),Ye.push(Ft))};for(const Ft of sn)Wt(Ft);const Dt=z,Bt=new Set,pn=[Y],En=new Set([Y]),Js=async Ft=>{const bn=await _({scope:rs,recall_level:Le,min_score:0,limit:Oe,subject:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(bn&&Array.isArray(bn.items)){for(const ls of bn.items)if(Wt(ls),typeof ls.subject=="string"&&ls.subject.trim()===Ft&&typeof ls.object=="string"){const Hn=ls.object.trim();Hn&&!En.has(Hn)&&(En.add(Hn),pn.push(Hn))}}if(!Dt){const ls=await _({scope:rs,recall_level:Le,min_score:0,limit:Oe,object:Ft,query_text:void 0,max_input_tokens:0,model:void 0});if(ls&&Array.isArray(ls.items)){for(const Hn of ls.items)if(Wt(Hn),typeof Hn.object=="string"&&Hn.object.trim()===Ft&&typeof Hn.subject=="string"){const Rr=Hn.subject.trim();Rr&&!En.has(Rr)&&(En.add(Rr),pn.push(Rr))}}}};for(;pn.length&&Bt.size<De&&!En.has(me);){const Ft=pn.shift();!Ft||Bt.has(Ft)||(Bt.add(Ft),await Js(Ft))}S({ok:!0,count:Ye.length,items:Ye,active_memory_text:un,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:En.size,merged:Ye.length,directed:Dt}}),O("expanded neighborhood"),$==="replace"&&g&&g(Ye,{kind:"expanded neighborhood",result:{ok:!0,count:Ye.length,items:Ye,active_memory_text:un,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:En.size,merged:Ye.length,directed:Dt}}})}catch(Ye){const ht=Ye instanceof Error?Ye.message:String(Ye);M(ht||"Expand neighborhood failed")}finally{V(!1)}},[z,un,sn,Mt,g,_,wn,vt,$,Le,rs]),Ea=p.useCallback(()=>{S(null),O(null),J(""),P(!1),M(""),V(!1),nn(""),On(""),ri(""),ii("")},[]),qi="Search KG",rr=Ct.nodes.length,uf=Ct.edges.length,li=_r.length;return s.jsx("div",{className:"amx-host",children:s.jsxs("div",{className:"amx-root",children:[s.jsxs("div",{className:"amx-left",children:[s.jsx("div",{className:"amx-graphbar",role:"toolbar","aria-label":"Graph layout controls",children:s.jsxs("div",{className:"amx-graphbar-row",children:[s.jsx("span",{className:"amx-graphbar-title",children:"layout"}),s.jsxs("select",{value:Ve,onChange:Y=>_t(Ov(Y.target.value,Ve)),disabled:!zn.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)"})]}),Ve==="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:mt,onChange:Y=>et(SC(Number(Y.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[mt.toFixed(1),"×"]})]}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>jo({kind:Ve,seed:Qe}),disabled:!zn.length,children:"Apply"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:qr,disabled:!zn.length||Ve!=="force",children:$t?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:we,children:[s.jsx(Wx,{children:s.jsxs(yC,{nodes:$a,edges:fl,defaultViewport:{x:0,y:0,zoom:1},minZoom:Lv,maxZoom:Iv,onInit:Y=>{k.current=Y;const me=ce.current;if(me&&typeof Y.setViewport=="function")try{Y.setViewport(me,{duration:0})}catch{try{Y.setViewport(me)}catch{}}if(Se.current&&typeof Y.fitView=="function")try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}ce.current=null,Se.current=!1,Vr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:Ci,onNodeClick:(Y,me)=>{ii(""),ri(me.id)},onEdgeClick:(Y,me)=>{ri(""),ii(me.id)},onPaneClick:()=>{ri(""),ii("")},children:[s.jsx(QB,{className:"amx-flow-controls",children:s.jsx(zd,{type:"button",className:`amx-control-legend ${Ne?"amx-control-legend-active":""}`,onClick:()=>ae(Y=>!Y),title:Ne?"Hide node color legend":"Show node color legend","aria-label":Ne?"Hide node color legend":"Show node color legend",children:s.jsx(p9,{})})}),s.jsx(hm,{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:()=>Me(Y=>!Y),title:be?"Hide minimap preview":"Show minimap preview","aria-label":be?"Hide minimap preview":"Show minimap preview",children:be?"minimap on":"minimap off"})})}),be?s.jsx(HB,{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:de?120:160,height:de?80:110,marginBottom:56},nodeColor:Y=>{var me;return Rh((me=Y.data)==null?void 0:me.kind).minimap}}):null,Ne?s.jsxs(hm,{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:Y,label:me})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:Rh(Y).stroke},children:me},Y))})]}):null,s.jsx(i9,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},He),s.jsxs("details",{className:"amx-panel amx-controls",children:[s.jsxs("summary",{children:[s.jsx("span",{className:"amx-controls-title",children:qi}),s.jsxs("span",{className:"amx-small",children:[li," assertions · ",rr," nodes · ",uf," 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:I,onChange:Y=>L(Y.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(K),onChange:Y=>H(Y.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(B),onChange:Y=>te(Y.target.value==="true"),children:[s.jsx("option",{value:"true",children:"all assertions"}),s.jsx("option",{value:"false",children:"hide rdf:type / labels"})]})]}),s.jsxs("label",{children:["path mode",s.jsxs("select",{value:String(z),onChange:Y=>ee(Y.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:Ve,onChange:Y=>_t(Ov(Y.target.value,Ve)),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:Qe,onChange:Y=>it(Math.trunc(Number(Y.target.value||0)||0))})]})]}),s.jsxs("div",{className:"amx-actions",style:{marginTop:10},children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>jo({kind:Ve,seed:Qe}),disabled:!zn.length,children:"Apply layout"}),Ve==="force"?s.jsx("button",{type:"button",className:"amx-btn",onClick:qr,disabled:!zn.length,children:$t?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:hc,disabled:!zn.length,children:"Save layout"}),ze?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:Hr,children:"Load saved"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:ku,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.",ze?s.jsxs("span",{children:[" ","(saved",kt?`: ${kt}`:"",")"]}):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:vt,onChange:Y=>nn(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),zn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const me=$i.get(Y)||Y;return me===Y?me:`${me} (${Y})`})()},Y))]})]}),s.jsxs("label",{children:["path end",s.jsxs("select",{value:wn,onChange:Y=>On(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),zn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const me=$i.get(Y)||Y;return me===Y?me:`${me} (${Y})`})()},Y))]})]})]}),js?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:ml.map((Y,me)=>{const Oe=$i.get(Y.from)||Y.from,De=$i.get(Y.to)||Y.to,Ye=Y.dir==="reverse"?" ← ":" → ",ht=Y.predicate?` (${Y.predicate})`:"";return s.jsxs("div",{children:[me===0?s.jsx("span",{children:Oe}):null,Ye,s.jsxs("span",{children:[De,ht]})]},`${Y.edgeId}:${me}`)})}):vt&&wn?s.jsxs("div",{className:"amx-small",style:{marginTop:10,opacity:.9},children:["No path found in the current subgraph (",(Rs==null?void 0:Rs.assertions)??li," assertions · ",(Rs==null?void 0:Rs.nodes)??Ct.nodes.length," nodes ·"," ",(Rs==null?void 0:Rs.edges)??Ct.edges.length," edges). Start reaches ",(Rs==null?void 0:Rs.reachableFromStart)??0," nodes.",_?s.jsx("div",{style:{marginTop:10},children:s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void ai(),disabled:G,children:G?"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:re,onChange:Y=>he(Y.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:Ee,onChange:Y=>Ie(Y.target.value),placeholder:"e.g. ex:person-data"})]}),s.jsxs("label",{children:["predicate (exact)",s.jsx("input",{value:We,onChange:Y=>Ue(Y.target.value),placeholder:"e.g. schema:about"})]}),s.jsxs("label",{children:["object (exact)",s.jsx("input",{value:tt,onChange:Y=>ut(Y.target.value),placeholder:"e.g. ex:concept-emotion-chip"})]}),s.jsxs("label",{children:["min_score",s.jsx("input",{type:"number",step:"any",value:xt,onChange:Y=>bt(Y.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["limit",s.jsx("input",{type:"number",min:"-1",step:"1",value:Mt,onChange:Y=>zt(Y.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:rs,onChange:Y=>ge(hj(Y.target.value,rs)),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:Le,onChange:Y=>yt(Y.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:lt,onChange:Y=>Yt(Y.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:vn,onChange:Y=>mn(Y.target.value),placeholder:"qwen/qwen3-next-80b"})]})]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void So(),disabled:!_||A,children:A?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ea,disabled:!C&&!W&&!A,children:"Reset to step output"}),C?s.jsxs("span",{className:"amx-small",children:["showing: ",D||"live query"]}):s.jsx("span",{className:"amx-small",children:"showing: step output"}),W?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:W}):null,R?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:R}):null]})]})]})]})]}),s.jsxs("div",{className:"amx-right",children:[s.jsxs("div",{className:"amx-panel",children:[s.jsx("h3",{children:"Details"}),s.jsx("div",{className:"amx-small",style:{marginBottom:8},children:"Derived from `memory_kg_query` packetization (max_input_tokens); safe to inject into an LLM system prompt."}),(()=>{const Y=x9(Ar);return Y?s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:Y}):null})(),(()=>{const Y=As;if(!Y)return null;const me=typeof Y=="string"?Y:Array.isArray(Y)?Y.map(Oe=>String(Oe)).join(" · "):JSON.stringify(Y);return!me||!me.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:me})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const Y=(C==null?void 0:C.packets_version)??Be,me=(C==null?void 0:C.packed_count)??Qt,Oe=(C==null?void 0:C.dropped)??Ot,De=(C==null?void 0:C.estimated_tokens)??Fn,Ye=[];return typeof Y=="number"&&Ye.push(`packets_v${Y}`),typeof me=="number"&&Ye.push(`packed=${me}`),typeof Oe=="number"&&Ye.push(`dropped=${Oe}`),typeof De=="number"&&Ye.push(`est_tokens=${De}`),Ye.length?Ye.join(" · "):"No packetization stats (set max_input_tokens > 0)."})()}),s.jsx("div",{className:"amx-active-memory",children:k9(un||"(empty)",I)}),(()=>{const Y=C!=null&&C.packets&&Array.isArray(C.packets)?C.packets:is;return!Array.isArray(Y)||Y.length===0?null:s.jsxs("div",{style:{marginTop:10},children:[s.jsxs("button",{type:"button",className:"amx-btn",onClick:()=>In(me=>!me),children:[Ui?"Hide":"Show"," packets (",Y.length,")"]}),Ui?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:Y.slice(0,120).map((me,Oe)=>{const De=me&&typeof me=="object"&&!Array.isArray(me)?me:null,Ye=De&&typeof De.statement=="string"?De.statement:typeof me=="string"?me:"",ht=De&&(typeof De.retrieval_score=="number"||typeof De.retrieval_score=="string")?De.retrieval_score:null,Wt=De&&typeof De.observed_at=="string"?De.observed_at:null;return s.jsxs("div",{className:"amx-item",children:[s.jsx("div",{className:"amx-mono",children:Ye||"(packet)"}),Wt||ht!==null?s.jsxs("div",{className:"amx-small",children:[Wt?`[${Wt}]`:null,Wt&&ht!==null?" ":null,ht!==null?`score:${ht}`:null]}):null]},Oe)})}):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."}),vs?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:$i.get(vs)||vs}),s.jsxs("div",{className:"amx-small",children:["kind=",sr.get(vs)||"entity"," · id=",vs]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void zs(vs),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Focus"})]})]}):Tr&&Tr.source&&Tr.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:[Tr.source," —",String(Tr.label||((Kn=Tr.data)==null?void 0:Kn.predicateSummary)||"").trim()||"?","→ ",Tr.target]}),s.jsxs("div",{className:"amx-small",children:["edge_id=",Tr.id]})]}),s.jsxs("div",{className:"amx-actions",children:[s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>void zs(Tr.id),children:"Copy id"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:gr,children:"Fit"})]})]}):s.jsx("div",{className:"amx-small",style:{marginBottom:10,opacity:.9},children:"(no selection)"}),s.jsx("div",{className:"amx-list",children:Wi.slice(0,80).map((Y,me)=>{const Oe=String(Y.subject||"").trim(),De=String(Y.predicate||"").trim(),Ye=String(Y.object||"").trim(),ht=$i.get(Oe)||Oe,Wt=$i.get(Ye)||Ye,Dt=sr.get(Oe)||"entity",Bt=sr.get(Ye)||"entity",pn=Rh(Dt),En=Rh(Bt),Js=Lh(Y.observed_at),Ft=b9(Y),bn=Y.provenance&&typeof Y.provenance=="object"&&!Array.isArray(Y.provenance)?Y.provenance:null,ls=bn&&typeof bn.span_id=="string"?bn.span_id.trim():"",Hn=bn&&typeof bn.writer_run_id=="string"?bn.writer_run_id.trim():"",Rr=typeof Y.owner_id=="string"?Y.owner_id.trim():"",yr=Hn||Rr,Vi=!!((x||y)&&ls&&yr),_l=!!(x&&Hn&&!ls),Hi=Vi||_l;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:pn.stroke,background:pn.bg},title:Oe,onClick:()=>{Oe&&(ii(""),ri(Oe))},children:ht||Oe||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:De,children:$C(De)||"(predicate)"}),s.jsx("span",{className:"amx-arrow",children:"→"}),s.jsx("button",{type:"button",className:"amx-term",style:{borderColor:En.stroke,background:En.bg},title:Ye,onClick:()=>{Ye&&(ii(""),ri(Ye))},children:Wt||Ye||"(object)"})]}),s.jsxs("div",{className:"amx-triple-meta",children:[Js?s.jsxs("span",{className:"amx-small",title:String(Y.observed_at||""),children:["[",Js,"]"]}):null,Ft?s.jsx("span",{className:"amx-small",children:Ft}):null]}),ls||Hn?s.jsxs("div",{className:"amx-triple-actions",children:[ls?s.jsxs("span",{className:"amx-small",children:["span:",ls]}):null,Hn?s.jsxs("span",{className:"amx-small",children:["run:",Hn]}):null,Hi?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>{if(Vi&&ls&&yr){Fs({run_id:yr,span_id:ls,assertion:Y});return}_l&&Hn&&Fs({run_id:Hn,assertion:Y})},children:"Open transcript"}):null]}):null]},me)})})]}),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)."}),Ca.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:Ca.slice(0,60).map(Y=>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:",Y.span_id]}),s.jsxs("div",{className:"amx-small",children:["run_id=",Y.span_run_id," · assertions=",Y.count,Y.last_observed_at_fmt?` · last=[${Y.last_observed_at_fmt}]`:""]})]}),y||x?s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Fs({run_id:Y.span_run_id,span_id:Y.span_id,assertion:Y.assertion}),children:"Open transcript"}):null]},`${Y.span_run_id}|${Y.span_id}`))})]}):null,x&&ko.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:ko.slice(0,40).map(Y=>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:",Y.run_id]}),s.jsxs("div",{className:"amx-small",children:["assertions=",Y.count,Y.last_observed_at_fmt?` · last=[${Y.last_observed_at_fmt}]`:""]})]}),s.jsx("button",{type:"button",className:"amx-btn",onClick:()=>Fs({run_id:Y.run_id,assertion:Y.assertion}),children:"Open transcript"})]},Y.run_id))})]}):null,!Ca.length&&!(x&&ko.length)?s.jsx("div",{className:"amx-small",children:"(no provenance)"}):null]})]})]})})}function tc({open:e,title:t,children:n,actions:r,variant:i="default",onClose:o}){const c=p.useId();if(p.useEffect(()=>{if(!e)return;const d=h=>{h.key==="Escape"&&o()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e,o]),!e)return null;const l=i==="fullscreen";return s.jsx("div",{className:`modal_backdrop${l?" fullscreen":""}`,onMouseDown:d=>{d.target===d.currentTarget&&o()},children:s.jsxs("div",{className:`modal_panel${l?" 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:o,children:"Close"})]}),s.jsx("div",{className:"modal_body",children:n}),r?s.jsx("div",{className:"modal_footer",children:r}):null]})})}function yw(e,t="session"){const n=String(e||"").trim().toLowerCase();return n==="run"||n==="session"||n==="global"||n==="all"?n:t}function Xl(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 su(e){if(typeof e!="number"||!Number.isFinite(e))return"—";const t=new Date(e),n=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),c=String(t.getUTCMinutes()).padStart(2,"0");return`${n}/${r}/${i} ${o}:${c}`}function $9(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=Xl(t);return n!==null?su(n):t}function Vx(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,`
157
+ `).replace(/\\n/g,`
158
+ `).replace(/\\t/g," "):""}function CC(e){return String(e??"").replace(/[*_`~]/g,"")}function vp(e,t){const n=!!(t!=null&&t.strip_punct),r=Vx(e);let i=CC(r).replace(/\s+/g," ").trim().toLowerCase();return n&&(i=i.replace(/[^\p{L}\p{N}\s]+/gu,"").replace(/\s+/g," ").trim()),i}function xp(e,t){const n=String(t??"").trim();if(!n)return!1;const r=vp(n,{strip_punct:!1});if(!r)return!1;if(vp(String(e??""),{strip_punct:!1}).includes(r))return!0;const o=vp(n,{strip_punct:!0});return o?vp(String(e??""),{strip_punct:!0}).includes(o):!1}function _j(e){const t=Vx(e).trim();if(!t)return[];const n=[],r=c=>{const l=String(c??"").replace(/\s+/g," ").trim();l&&(l.length<6||n.includes(l)||n.push(l))},i=t.search(/[`*_~]/);if(i>0){const c=t.slice(0,i);c.replace(/\s+/g," ").trim().length>=10&&r(c)}const o=[/`([^`]+)`/g,/\*\*([^*]+)\*\*/g,/__([^_]+)__/g,/\*([^*]+)\*/g,/_([^_]+)_/g];for(const c of o){let l;for(;(l=c.exec(t))!==null;){const d=String(l[1]??"").trim();d&&r(d)}}return r(CC(t)),n}function C9(e){const t=String(e??"").replace(/\r\n/g,`
159
+ `).replace(/\r/g,`
160
+ `);if(!t)return null;const n=t.split(`
161
+ `);let r;const i=[],o=[];let c=null,l=[],d=!1;const h=()=>{if(!c)return;const g=l.join(`
162
+ `).trim();g&&o.push({role:c,lines:[g]}),c=null,l=[]};for(const g of n){const y=r?null:g.match(/^\s*created_at\s*=\s*(.+)\s*$/i);if(y&&y[1]){r=y[1].trim();continue}const x=g.match(/^\s*(USER|ASSISTANT|SYSTEM)\s*:\s*(.*)$/i);if(x){d=!0,h();const k=String(x[1]||"").trim().toLowerCase();c=k==="user"?"user":k==="assistant"?"assistant":"system";const v=String(x[2]??"");l=v?[v]:[];continue}c?l.push(g):i.push(g)}if(h(),!d||!o.length)return null;const m=i.join(`
163
+ `).trim(),_={messages:[]};r&&(_.created_at=r),m&&_.messages.push({role:"system",content:m});for(const g of o)_.messages.push({role:g.role,content:g.lines.join(`
164
+ `)});return _.messages.length?_:null}function pj(e,t){const n=String(e||""),r=String(t||"");return r>n?r:n}function gj(e){const t=String((e==null?void 0:e.subject)||"").trim(),n=String((e==null?void 0:e.predicate)||"").trim(),r=String((e==null?void 0:e.object)||"").trim(),i=String((e==null?void 0:e.observed_at)||"").trim(),o=String((e==null?void 0:e.scope)||"").trim(),c=String((e==null?void 0:e.owner_id)||"").trim();return`${t}|${n}|${r}|${i}|${o}|${c}`}function E9(e){const t=String((e==null?void 0:e.observed_at)||"").trim(),n=String((e==null?void 0:e.subject)||"").trim(),r=String((e==null?void 0:e.predicate)||"").trim(),i=String((e==null?void 0:e.object)||"").trim(),o=String((e==null?void 0:e.scope)||"").trim(),c=String((e==null?void 0:e.owner_id)||"").trim(),l=[];o&&l.push(`scope=${o}`),c&&l.push(`owner=${c}`);const d=l.length?` (${l.join(", ")})`:"";return`${t?`[${t}] `:""}${n} --${r}--> ${i}${d}`}function A9({gateway:e,selected_run_id:t,selected_session_id:n}){const[r,i]=p.useState(String(t||"").trim()),[o,c]=p.useState(String(n||"").trim()),[l,d]=p.useState("all"),h=l==="all",[m,_]=p.useState(!0),[g,y]=p.useState(750),[x,k]=p.useState(5e3),[v,N]=p.useState([]),[$,C]=p.useState(void 0),[S,D]=p.useState(""),[O,A]=p.useState(!1),[P,W]=p.useState([]),[J,G]=p.useState(!1),[V,R]=p.useState(!1),[M,I]=p.useState(""),[L,K]=p.useState(""),[H,z]=p.useState(""),[ee,B]=p.useState(""),[te,se]=p.useState("artifact"),[de,be]=p.useState(null),[Me,Ne]=p.useState(""),[ae,je]=p.useState(null),Te=p.useRef(!1),Ve=p.useMemo(()=>{const ge=ae,Le=ge!=null&&ge.attributes&&typeof ge.attributes=="object"&&!Array.isArray(ge.attributes)?ge.attributes:null;return(Le&&typeof Le.evidence_quote=="string"?String(Le.evidence_quote):"").trim()},[ae]),_t=p.useMemo(()=>{const ge=de,Le=ge&&typeof ge=="object"&&!Array.isArray(ge)?ge:null,yt=Le&&typeof Le.note=="string"?String(Le.note):"";return Vx(yt).trim()},[de]),Qe=p.useMemo(()=>{const ge=de&&typeof de=="object"&&!Array.isArray(de)?de:null,Le=ge&&Array.isArray(ge.messages)?ge.messages:null;return Array.isArray(Le)?Le:null},[de]),it=p.useMemo(()=>{const ge=_t,Le=Ve;return!ge||!Le?!1:xp(ge,Le)},[Ve,_t]),$t=p.useMemo(()=>{const ge=Qe,Le=Ve;if(!ge||!Le)return[];const yt=[];for(let re=0;re<Math.min(ge.length,500);re++){const he=ge[re],Ee=(he==null?void 0:he.content)==null?"":String(he.content);xp(Ee,Le)&&yt.push(re)}return yt},[Ve,Qe]),ot=p.useMemo(()=>new Set($t),[$t]),mt=$t.length?$t[0]:null,et=p.useCallback(ge=>{const Le=document.getElementById(`source_msg_${ge}`);Le&&typeof Le.scrollIntoView=="function"&&Le.scrollIntoView({block:"center",behavior:"smooth"})},[]),Lt=p.useCallback(()=>{const ge=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");ge&&typeof ge.scrollIntoView=="function"&&ge.scrollIntoView({block:"center",behavior:"smooth"})},[]);p.useEffect(()=>{if(J&&!(V||M)&&!Te.current){if(mt!==null){Te.current=!0,window.setTimeout(()=>et(mt),0);return}if(it){Te.current=!0,window.setTimeout(()=>Lt(),0);return}}},[et,Lt,M,mt,V,it,J]);const ce=p.useRef(new Set),Se=p.useRef(""),He=p.useRef(null),ne=p.useRef(null);p.useEffect(()=>{i(String(t||"").trim())},[t]),p.useEffect(()=>{c(String(n||"").trim())},[n]);const we=p.useMemo(()=>{const ge=String(r||"").trim(),Le=String(o||"").trim();return`mindmap:${l}:${ge}:${Le}`},[r,o,l]),fe=p.useMemo(()=>{let ge=null,Le=null;for(const yt of v){const re=Xl(yt==null?void 0:yt.observed_at);re!==null&&(ge=ge===null?re:Math.min(ge,re),Le=Le===null?re:Math.max(Le,re))}return{min_ms:ge,max_ms:Le}},[v]),$e=1e3,pe=p.useMemo(()=>{const ge=fe.min_ms,Le=fe.max_ms;if(typeof ge!="number"||typeof Le!="number"||!Number.isFinite(ge)||!Number.isFinite(Le))return null;if(Le<=ge)return{min_ms:ge,max_ms:ge,real_max_ms:Le};const yt=ge+Math.ceil((Le-ge)/$e)*$e;return{min_ms:ge,max_ms:yt,real_max_ms:Le}},[fe.max_ms,fe.min_ms]),[le,ze]=p.useState(!0),[st,kt]=p.useState(null);p.useEffect(()=>{le&&pe&&kt(pe.max_ms)},[le,pe]);const pt=p.useMemo(()=>{const ge=typeof st=="number"?st:null;return ge===null?v:v.filter(Le=>{const yt=Xl(Le==null?void 0:Le.observed_at);return yt===null?!0:yt<=ge})},[v,st]),jt=p.useCallback((ge,Le)=>{const yt=Array.isArray(ge)?ge:[],re=String(Se.current||"").trim(),he=new Set,Ee=[];let Ie="";for(const We of yt){if(!We||typeof We!="object"||typeof We.subject!="string"||typeof We.predicate!="string"||typeof We.object!="string")continue;const Ue=gj(We);if(he.has(Ue))continue;he.add(Ue),Ee.push(We);const tt=String(We.observed_at||"").trim();tt&&(Ie=pj(Ie,tt))}N(Ee),C(Le==null?void 0:Le.warnings),ce.current=he,Se.current=Ie||re},[]),ct=p.useCallback(async ge=>{const Le=yw(ge.scope,"session"),yt=String(ge.subject||"").trim(),re=String(ge.predicate||"").trim(),he=String(ge.object||"").trim(),Ee=String(ge.since||"").trim(),Ie=String(ge.until||"").trim(),We=String(ge.active_at||"").trim(),Ue=String(ge.query_text||"").trim(),tt=typeof ge.min_score=="number"&&Number.isFinite(ge.min_score)?Number(ge.min_score):void 0,ut=ge.order==="asc"?"asc":"desc",xt=typeof ge.limit=="number"&&Number.isFinite(ge.limit)?Number(ge.limit):0,bt=String(r||"").trim(),Mt=String(o||"").trim(),zt={scope:Le,all_owners:h,limit:xt,order:ut};yt&&(zt.subject=yt),re&&(zt.predicate=re),he&&(zt.object=he),Ee&&(zt.since=Ee),Ie&&(zt.until=Ie),We&&(zt.active_at=We),Ue&&(zt.query_text=Ue),typeof tt=="number"&&(zt.min_score=tt),h||(Le==="run"?bt&&(zt.run_id=bt):Le==="session"?Mt?zt.session_id=Mt:bt&&(zt.run_id=bt):Le==="all"&&(bt?zt.run_id=bt:Mt&&(zt.session_id=Mt)));try{const lt=await e.kg_query(zt),Yt=Array.isArray(lt==null?void 0:lt.items)?lt.items:[],vn=lt==null?void 0:lt.warnings;return{ok:(lt==null?void 0:lt.ok)!==!1,count:Number((lt==null?void 0:lt.count)||Yt.length),items:Yt,warnings:vn,raw:lt}}catch(lt){const Yt=lt instanceof Error?lt.message:String(lt);if(Yt.includes("Run '")&&Yt.includes("not found")&&!Mt&&(Le==="session"||Le==="all")&&bt){const mn=await e.kg_query({...zt,run_id:void 0,session_id:bt}),rn=Array.isArray(mn==null?void 0:mn.items)?mn.items:[],Ht=mn==null?void 0:mn.warnings;return{ok:(mn==null?void 0:mn.ok)!==!1,count:Number((mn==null?void 0:mn.count)||rn.length),items:rn,warnings:Ht,raw:mn}}throw new Error(Yt||"KG query failed")}},[h,e,r,o]),It=p.useCallback(async ge=>{var re;const Le=String(ge.run_id||"").trim(),yt=String(ge.span_id||"").trim();if(!(!Le||!yt)){G(!0),R(!0),I(""),z(Le),B(yt),se("artifact"),K(`source span:${yt}`),be(null),Ne(""),je(ge.assertion&&typeof ge.assertion=="object"?ge.assertion:null),Te.current=!1;try{const he=[Le],Ee=typeof((re=ge.assertion)==null?void 0:re.owner_id)=="string"?String(ge.assertion.owner_id).trim():"";Ee&&Ee!==Le&&he.push(Ee);let Ie=null,We=null;for(const Ue of he)try{We=await(await e.download_run_artifact_content(Ue,yt)).text(),Ue!==Le&&z(Ue);break}catch(tt){Ie=tt instanceof Error?tt.message:String(tt)}if(We==null)throw new Error(Ie||"Failed to load source span");Ne(We);try{const Ue=JSON.parse(We);be(Ue)}catch{be(null)}}catch(he){const Ee=he instanceof Error?he.message:String(he);I(Ee||"Failed to load source span")}finally{R(!1)}}},[e]),vt=p.useCallback(async ge=>{const Le=String(ge.run_id||"").trim();if(!Le)return null;try{const yt=await e.list_run_artifacts(Le,{limit:200}),he=(Array.isArray(yt==null?void 0:yt.items)?yt.items:[]).map(tt=>{const ut=typeof(tt==null?void 0:tt.artifact_id)=="string"?String(tt.artifact_id).trim():"",xt=tt!=null&&tt.tags&&typeof tt.tags=="object"&&!Array.isArray(tt.tags)?tt.tags:null,bt=xt&&typeof xt.kind=="string"?String(xt.kind).trim():"";return{artifact_id:ut,kind:bt}}).filter(tt=>!!(tt.artifact_id&&(tt.kind==="conversation_span"||tt.kind==="memory_note")));if(!he.length)return null;if(he.length===1)return he[0].artifact_id;const Ee=ge.assertion,Ie=Ee!=null&&Ee.attributes&&typeof Ee.attributes=="object"&&!Array.isArray(Ee.attributes)?Ee.attributes:null,Ue=(Ie&&typeof Ie.evidence_quote=="string"?String(Ie.evidence_quote):"").trim();if(!Ue)return null;for(const tt of he.slice(0,10))try{const xt=await(await e.download_run_artifact_content(Le,tt.artifact_id)).text(),bt=JSON.parse(xt);if(bt&&typeof bt=="object"){const Mt=typeof bt.note=="string"?String(bt.note):"";if(Mt&&Mt.includes(Ue))return tt.artifact_id;const zt=Array.isArray(bt.messages)?bt.messages:null;if(zt){for(const lt of zt.slice(0,200))if(((lt==null?void 0:lt.content)==null?"":String(lt.content)).includes(Ue))return tt.artifact_id}}}catch{}}catch{}return null},[e]),nn=p.useCallback(async ge=>{const Le=String(ge.run_id||"").trim();if(Le){G(!0),R(!0),I(""),z(Le),B(""),se("run_input"),K(`transcript run:${Le}`),be(null),Ne(""),je(ge.assertion&&typeof ge.assertion=="object"?ge.assertion:null),Te.current=!1;try{const yt=await vt({run_id:Le,assertion:ge.assertion});if(yt){await It({run_id:Le,span_id:yt,assertion:ge.assertion});return}const re=await e.get_run_input_data(Le),he=re&&typeof re=="object"&&!Array.isArray(re)?re.input_data:null,Ee={kind:"run_input_data",run_id:Le};if(re&&typeof(re==null?void 0:re.workflow_id)=="string"&&(Ee.workflow_id=String(re.workflow_id)),he&&typeof he=="object"&&!Array.isArray(he)){const Ie=he.context,Ue=(Ie&&typeof Ie=="object"&&Array.isArray(Ie.messages)?Ie.messages:null)||(Array.isArray(he.messages)?he.messages:null);Array.isArray(Ue)&&(Ee.messages=Ue);const tt=["text","prompt","task","message"];for(const ut of tt){const xt=he[ut];if(typeof xt=="string"&&xt.trim()){Ee.note=xt.trim();break}}Ee.input_data=he}!Ee.messages&&!Ee.note&&(Ee.note=JSON.stringify(he??re??{},null,2));try{const Ie=await e.get_run(Le),We=Ie&&typeof(Ie==null?void 0:Ie.created_at)=="string"?String(Ie.created_at):"";We&&(Ee.created_at=We)}catch{}be(Ee),Ne(JSON.stringify(re,null,2))}catch(yt){const re=yt instanceof Error?yt.message:String(yt);I(re||"Failed to load run input transcript")}finally{R(!1)}}},[e,It,vt]),wn=p.useCallback(async()=>{D(""),A(!0);try{const ge=l==="all"?"all":l,Le=await ct({scope:ge,limit:0,order:"desc"});jt(Le.items||[],{warnings:Le.warnings}),He.current={scope:ge}}catch(ge){const Le=ge instanceof Error?ge.message:String(ge);D(Le||"Load failed")}finally{A(!1)}},[ct,jt,l]);p.useEffect(()=>{v.length||wn()},[]);const On=p.useCallback(async ge=>{const Le=yw(ge.scope,"session");return ne.current=ge,await ct({scope:Le,subject:ge.subject,predicate:ge.predicate,object:ge.object,query_text:ge.query_text,min_score:ge.min_score,since:ge.since,until:ge.until,active_at:ge.active_at,limit:typeof ge.limit=="number"?ge.limit:0,order:"desc"})},[ct]),Ks=p.useCallback((ge,Le)=>{var yt;if((Le==null?void 0:Le.kind)==="live query"){const re=ne.current;re&&(He.current={scope:yw(re.scope,"session"),subject:typeof re.subject=="string"?re.subject:void 0,predicate:typeof re.predicate=="string"?re.predicate:void 0,object:typeof re.object=="string"?re.object:void 0})}jt(ge,{warnings:(yt=Le==null?void 0:Le.result)==null?void 0:yt.warnings})},[jt]),rs=p.useCallback(async()=>{const ge=He.current;if(!ge)return;const Le=String(Se.current||"").trim(),yt=await ct({scope:ge.scope,subject:ge.subject,predicate:ge.predicate,object:ge.object,since:Le||void 0,order:"asc",limit:0}),re=Array.isArray(yt.items)?yt.items:[];if(!re.length)return;const Ee=Date.now()+Math.max(250,Math.min(2e4,x)),Ie=ce.current,We=[],Ue=[];let tt=String(Se.current||"").trim();for(const ut of re){if(!ut||typeof ut!="object"||typeof ut.subject!="string"||typeof ut.predicate!="string"||typeof ut.object!="string")continue;const xt=gj(ut);if(Ie.has(xt))continue;Ie.add(xt),We.push(ut),Ue.push({id:xt,assertion:ut,expires_at_ms:Ee});const bt=String(ut.observed_at||"").trim();bt&&(tt=pj(tt,bt))}We.length&&(Se.current=tt,N(ut=>{const xt=ut.concat(We);return xt.sort((bt,Mt)=>String((Mt==null?void 0:Mt.observed_at)||"").localeCompare(String((bt==null?void 0:bt.observed_at)||""))),xt}),W(ut=>{const xt=ut.concat(Ue);return xt.sort((bt,Mt)=>Mt.expires_at_ms-bt.expires_at_ms),xt.slice(0,30)}))},[x,ct]);return p.useEffect(()=>{if(!m)return;let ge=!1,Le=null;const yt=async()=>{if(!ge){try{await rs()}catch{}ge||(Le=window.setTimeout(()=>void yt(),Math.max(250,Math.min(6e4,g))))}};return yt(),()=>{ge=!0,Le!==null&&window.clearTimeout(Le)}},[m,g,rs]),p.useEffect(()=>{if(!P.length)return;const ge=window.setInterval(()=>{const Le=Date.now();W(yt=>yt.filter(re=>re.expires_at_ms>Le))},250);return()=>window.clearInterval(ge)},[P.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void wn(),disabled:O,children:O?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:l,onChange:ge=>{const Le=String(ge.target.value||"").trim();(Le==="all"||Le==="global"||Le==="session"||Le==="run")&&d(Le)},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(YP,{checked:m,onChange:_}),l==="session"?s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"session_id"}),s.jsx("input",{className:"mono",value:o,onChange:ge=>c(String(ge.target.value||"")),placeholder:"(required)"})]}):null,l==="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:ge=>i(String(ge.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:g,onChange:ge=>y(Math.max(250,Number(ge.target.value||0)||750))}),s.jsx("span",{className:"mono muted",children:"highlight_ms"}),s.jsx("input",{type:"number",min:250,max:2e4,step:250,value:x,onChange:ge=>k(Math.max(250,Number(ge.target.value||0)||5e3))})]})})]})]}),S?s.jsx("div",{className:"mindmap_error mono",children:S}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(N9,{title:"mindmap",resetKey:we,queryMode:"replace",items:pt,warnings:$,onQuery:On,onItemsReplace:Ks,onOpenSpan:({run_id:ge,span_id:Le,assertion:yt})=>{It({run_id:ge,span_id:Le,assertion:yt})},onOpenTranscript:({run_id:ge,span_id:Le,assertion:yt})=>{const re=String(ge||"").trim(),he=typeof Le=="string"?String(Le).trim():"";re&&(he?It({run_id:re,span_id:he,assertion:yt}):nn({run_id:re,assertion:yt}))}},we),P.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:P.slice().sort((ge,Le)=>Le.expires_at_ms-ge.expires_at_ms).slice(0,12).map(ge=>s.jsx("div",{className:"mindmap_recent_item mono",children:E9(ge.assertion)},ge.id))})]}):null,pe?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:su(Math.min(typeof st=="number"?st:pe.max_ms,pe.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:pe.min_ms,max:pe.max_ms,step:$e,value:typeof st=="number"?st:pe.max_ms,onChange:ge=>{const Le=Number(ge.target.value||0);kt(Le),ze(Le>=pe.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[pt.length.toLocaleString(),"/",v.length.toLocaleString()]})]})}):null]}),s.jsxs(tc,{open:J,title:L||"source",onClose:()=>{G(!1)},children:[V?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,M?s.jsx("div",{className:"mindmap_error mono",children:M}):null,!V&&!M?s.jsxs("div",{className:"source_span",children:[(()=>{const ge=ae;if(!ge)return null;const Le=String(ge.subject||"").trim(),yt=String(ge.predicate||"").trim(),re=String(ge.object||"").trim(),he=su(Xl(ge.observed_at)),Ee=ge.attributes&&typeof ge.attributes=="object"&&!Array.isArray(ge.attributes)?ge.attributes:null,Ie=Ee&&typeof Ee.evidence_quote=="string"?String(Ee.evidence_quote):"",We=Ee&&typeof Ee.original_context=="string"?String(Ee.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${Le} --${yt}--> ${re}`,children:[Le," ",s.jsxs("span",{className:"muted",children:["—",yt,"→"]})," ",re," ",he?s.jsxs("span",{className:"muted",children:["[",he,"]"]}):null]}),Ie?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:Ie}),We?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:We})]}):null]}):null]})})(),s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["run_id=",H," · ",te==="artifact"?`span_id=${ee}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[mt!==null?s.jsx("button",{className:"btn",onClick:()=>et(mt),children:"Jump to evidence"}):null,mt===null&&it?s.jsx("button",{className:"btn",onClick:()=>Lt(),children:"Jump to evidence"}):null]}),(()=>{const ge=de,Le=ge&&typeof ge=="object"&&!Array.isArray(ge)?ge:null,yt=Qe,re=_t,he=Le&&typeof Le.created_at=="string"?String(Le.created_at):"",Ee=he?Xl(he):null,Ie=Ee!==null?su(Ee):he,We=Le&&Le.span&&typeof Le.span=="object"&&!Array.isArray(Le.span)?Le.span:null,Ue=We&&typeof We.from_timestamp=="string"?String(We.from_timestamp):"",tt=We&&typeof We.to_timestamp=="string"?String(We.to_timestamp):"",ut=Ue?Xl(Ue):null,xt=tt?Xl(tt):null,bt=ut!==null&&xt!==null?`${su(ut)} → ${su(xt)}`:"";if(re){const Mt=C9(re);if(Mt){const zt=Ve,lt=zt?Mt.messages.findIndex(rn=>xp(rn.content,zt)):-1,Yt=zt?_j(zt):[],vn=Mt.created_at||he,mn=vn?$9(vn):he?Ie:"";return s.jsx("div",{className:"source_chat",children:Mt.messages.map((rn,Ht)=>{const is=rn.role,Be=!!(zt&&xp(rn.content,zt)),Qt=is==="user"?"USER":is==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Ht===lt?"source_note_msg_hit_0":void 0,className:`source_msg source_${is} ${Be?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Ht+1," · ",Qt,Be?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null]}),mn?s.jsx("span",{title:vn||"",children:mn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:rn.content,highlights:Be&&Yt.length?Yt:void 0,highlightClassName:"source_note_hit",highlightId:Ht===lt?"source_note_hit_0":void 0})})]},`note_msg:${Ht}`)})})}return s.jsxs("div",{className:"source_note",children:[he?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:he,children:["created_at=",Ie]})}):null,s.jsx(Ni,{text:re,highlights:Ve?_j(Ve):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(yt){const Mt=new Map;for(const lt of yt){const Yt=typeof(lt==null?void 0:lt.role)=="string"?String(lt.role):"unknown";Mt.set(Yt,(Mt.get(Yt)||0)+1)}const zt=Array.from(Mt.entries()).sort((lt,Yt)=>Yt[1]-lt[1]||lt[0].localeCompare(Yt[0])).map(([lt,Yt])=>`${lt}×${Yt}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[he?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:he,children:["created_at=",Ie]})," · messages=",yt.length]}):null,bt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["span=",bt]}):null,zt?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:["participants: ",zt]}):null,yt.slice(0,200).map((lt,Yt)=>{var Ot,Fn;const vn=typeof(lt==null?void 0:lt.role)=="string"?String(lt.role):"unknown",mn=(lt==null?void 0:lt.content)==null?"":String(lt.content),rn=typeof(lt==null?void 0:lt.timestamp)=="string"?String(lt.timestamp):"",Ht=rn?Xl(rn):null,is=Ht!==null?su(Ht):rn,Be=typeof(lt==null?void 0:lt.message_id)=="string"?String(lt.message_id):typeof((Ot=lt==null?void 0:lt.metadata)==null?void 0:Ot.message_id)=="string"?String(lt.metadata.message_id):typeof((Fn=lt==null?void 0:lt.metadata)==null?void 0:Fn.id)=="string"?String(lt.metadata.id):"",Qt=ot.has(Yt);return s.jsxs("div",{id:`source_msg_${Yt}`,className:`source_msg source_${vn} ${Qt?"source_match":""}`,children:[s.jsxs("div",{className:"source_msg_meta mono muted",children:[s.jsxs("span",{children:["#",Yt+1," · ",vn,Qt?s.jsx("span",{className:"source_match_badge",children:"evidence"}):null,Be?s.jsx("span",{className:"source_msg_id",children:Be}):null]}),rn?s.jsx("span",{title:rn,children:is}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:mn})})]},Yt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof ge=="string"?ge:Me)||"(empty)"})})()]}):null]})]})}const T9=6e4,M9=10*6e4;function R9(e){return Math.min(M9,T9*2**Math.max(0,e-1))}function Jg(){return{value_version:"",value:null,has_value:!1,attempt_version:"",inflight:!1,failures:0,failed_at:null,error:""}}function L9(e,t,n,r){const i=[],o=new Set;for(const c of e||[]){const l=String((c==null?void 0:c.id)||"").trim();if(!l||o.has(l))continue;o.add(l);const d=t.get(l);if(!d){i.push({id:l,version:String(c.version||"")});continue}if(!d.inflight){if(d.failed_at!==null){n-d.failed_at>=R9(d.failures)&&i.push({id:l,version:String(c.version||"")});continue}r!=null&&r.immutable&&d.has_value||d.value_version!==String(c.version||"")&&i.push({id:l,version:String(c.version||"")})}}return i}function I9(e,t){const n=e.get(t.id)||Jg();e.set(t.id,{...n,attempt_version:t.version,inflight:!0})}function O9(e,t,n){const r=e.get(t.id)||Jg();e.set(t.id,{...r,value:n,has_value:!0,value_version:t.version,attempt_version:t.version,inflight:!1,failures:0,failed_at:null,error:""})}function P9(e,t,n,r){const i=e.get(t.id)||Jg();e.set(t.id,{...i,attempt_version:t.version,inflight:!1,failures:i.failures+1,failed_at:r,error:String((n==null?void 0:n.message)||n||"failed")})}function D9(e,t,n){const r=new Map;for(const i of e||[]){const o=t.get(i.id);!o||!o.has_value||o.value===null||n!=null&&n.current_only&&o.value_version!==i.version||r.set(i.id,o.value)}return r}function F9(e,t){var i;let n=0;const r=new Set;for(const o of e||[])r.has(o.id)||(r.add(o.id),(i=t.get(o.id))!=null&&i.inflight&&(n+=1));return n}function z9(e,t,n){const r=new Set;for(const i of e||[]){const o=String((i==null?void 0:i.id)||"").trim();if(!o||r.has(o))continue;const c=t.get(o);if(!c||c.inflight){r.add(o);continue}c.failed_at===null&&(!c.has_value||n!=null&&n.current_only&&c.value_version!==String(i.version||""))&&r.add(o)}return r}function ks(e){return String((e==null?void 0:e.run_id)||"").trim()}function yj(e){const t=e!=null&&e.waiting&&typeof e.waiting=="object"?e.waiting:null;return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function B9(e){const t=new Map;for(const n of e||[]){const r=String((n==null?void 0:n.automation_id)||"").trim();if(!r)continue;String((n==null?void 0:n.role)||"").trim()==="controller"?t.set(r,String((n==null?void 0:n.updated_at)||"")):t.has(r)||t.set(r,"")}return Array.from(t,([n,r])=>({id:n,version:r}))}function U9(e){if(String((e==null?void 0:e.automation_id)||"").trim())return!1;const t=String((e==null?void 0:e.role)||"").trim();return t==="occurrence"||t==="descendant"||t==="controller"?!1:String((e==null?void 0:e.session_kind)||"").trim()!=="automation"}function W9(e){return(e||[]).filter(t=>ks(t)&&U9(t)).map(t=>({id:ks(t),version:""}))}const q9=6e4;function V9(e,t=Date.now(),n=q9){const r=[];for(const i of e||[]){if(!ks(i)||String((i==null?void 0:i.status)||"").trim().toLowerCase()!=="running")continue;const o=typeof(i==null?void 0:i.ledger_len)=="number"?i.ledger_len:null;if(o===null||o<1)continue;const c=Vt((i==null?void 0:i.updated_at)||(i==null?void 0:i.created_at)||"");c!==null&&t-c<n||r.push({id:ks(i),version:String(o)})}return r}function H9(e){return{after:Math.max(0,Math.floor(e)-1),limit:1}}function G9(e,t){const n=[],r=new Set,i=o=>{r.has(ks(o))||(r.add(ks(o)),n.push({id:ks(o),version:String((o==null?void 0:o.updated_at)||"")}))};for(const o of e||[]){if(!ks(o)||String((o==null?void 0:o.status)||"").trim().toLowerCase()!=="waiting")continue;const c=yj(o);(c==="user"||t&&c==="subworkflow")&&i(o)}if(t){const o=new Set;for(const l of t){const d=String((l==null?void 0:l.parent_run_id)||"").trim();d&&!hs(String((l==null?void 0:l.status)||""))&&o.add(d)}let c=0;for(const l of t){if(c>=K9)break;!ks(l)||String((l==null?void 0:l.status)||"").trim().toLowerCase()!=="waiting"||yj(l)==="subworkflow"&&!o.has(ks(l))&&(i(l),c+=1)}}return n}const K9=50,J9=e=>({run_id:e,status:"missing",updated_at:"",workflow_id:"",error:"not found"});function Y9(e,t){return{run_id:e,status:String((t==null?void 0:t.status)||"").trim().toLowerCase(),updated_at:String((t==null?void 0:t.updated_at)||(t==null?void 0:t.created_at)||"").trim(),workflow_id:String((t==null?void 0:t.workflow_id)||"").trim(),error:String((t==null?void 0:t.error)||"").trim()}}function X9(e,t){var i,o;const n=[],r=new Set;for(const c of e.values()){const l=String(((o=(i=c==null?void 0:c.waiting)==null?void 0:i.details)==null?void 0:o.sub_run_id)||"").trim();!l||t.has(l)||r.has(l)||(r.add(l),n.push({id:l,version:""}))}return n}function Z9(e,t){var c;const n=Array.isArray(t==null?void 0:t.pin_ids)?t.pin_ids.map(l=>String(l)):[],r=(c=t==null?void 0:t.input_data)==null?void 0:c.prompt,o=(n.includes("prompt")||n.length===0)&&typeof r=="string"?r.trim():"";return{run_id:e,excerpt:o}}const Q9=12;function wj(e,t,n=Q9){const r=[],i=new Set;for(const o of e||[]){let c=0;for(const l of o||[]){const d=ks(l);!d||i.has(d)||(t===null?c>=n:!t.has(d))||(i.add(d),r.push(l),c+=1)}}return r}const wg="abstractobserver_board_cache_v1:",eU=400,Pv=6e5;function tU(e,t){const n=new Map;if(!e)return n;try{const r=e.getItem(wg+t);if(!r)return n;const i=JSON.parse(r);if(!Array.isArray(i))return n;for(const o of i){const c=String((o==null?void 0:o.id)||"").trim();!c||o.value===null||o.value===void 0||n.set(c,{...Jg(),value:o.value,has_value:!0,value_version:String(o.version??"")})}}catch{return new Map}return n}function nU(e,t,n){if(e)try{let r=[];for(const[o,c]of n)!c.has_value||c.value===null||c.inflight||c.failed_at!==null||r.push({id:o,version:c.value_version,value:c.value});r=r.slice(-eU);let i=JSON.stringify(r);for(;i.length>Pv&&r.length;)r=r.slice(Math.max(1,Math.floor(r.length/4))),i=JSON.stringify(r);r.length?e.setItem(wg+t,i):e.removeItem(wg+t)}catch{}}function EC(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}const sU=4,lf={automation:0,wait_detail:1,pulse:1,run_brief:2,outcome:3};class rU{constructor(t=sU){jn(this,"queue",[]);jn(this,"seq",0);jn(this,"active",0);jn(this,"peak",0);this.limit=t}get queued(){return this.queue.length}submit(t,n){this.queue.push({priority:t,seq:this.seq++,task:n}),this.queue.sort((r,i)=>r.priority-i.priority||r.seq-i.seq),this.pump()}pump(){for(;this.active<this.limit&&this.queue.length;){const t=this.queue.shift();this.active+=1,this.peak=Math.max(this.peak,this.active),Promise.resolve().then(t.task).catch(()=>{}).finally(()=>{this.active-=1,this.pump()})}}}const vj=new WeakMap;function iU(e){let t=vj.get(e);return t||(t=new rU,vj.set(e,t)),t}const xj=new WeakMap;function oU(e){let t=xj.get(e);return t||(t=e.automations_client(),xj.set(e,t)),t}function aU(e){return e.map(t=>`${t.id}@${t.version}`).sort().join("|")}const bj=new WeakMap;function lU(e,t,n){let r=bj.get(e);r||(r=new Map,bj.set(e,r));let i=r.get(t);return i||(i=n!=null&&n.persist?tU(n.storage===void 0?EC():n.storage,t):new Map,r.set(t,i)),i}const ww=new Map;function cU(e,t){if(typeof setTimeout>"u")return;const n=ww.get(e);n!==void 0&&clearTimeout(n),ww.set(e,setTimeout(()=>{ww.delete(e),nU(EC(),e,t)},250))}function cf(e,t,n,r){const i=p.useRef({client:null,entries:new Map,gen:0});i.current.client!==(e||null)&&(i.current={client:e||null,entries:e?lU(e,r.scope,{persist:r.persist}):new Map,gen:i.current.gen+1});const[o,c]=p.useReducer(x=>x+1,0),l=aU(t),d=Math.floor(Date.now()/3e4),h=p.useRef(n);h.current=n,p.useEffect(()=>{const x=i.current;if(!x.client)return;const k=x.client,v=x.gen,N=L9(t,x.entries,Date.now(),{immutable:r.immutable});if(!N.length)return;const $=iU(k);for(const C of N)I9(x.entries,C),$.submit(r.priority,async()=>{try{const S=await h.current(k,C);if(i.current.gen!==v)return;O9(x.entries,C,S),r.persist&&cU(r.scope,x.entries)}catch(S){if(i.current.gen!==v)return;P9(x.entries,C,S,Date.now())}c()});c()},[e,l,d,o,r.priority,r.immutable]);const m=p.useMemo(()=>D9(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),_=p.useMemo(()=>F9(t,i.current.entries),[l,o,e]),g=p.useMemo(()=>z9(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),y=p.useMemo(()=>x=>{const k=i.current.entries.get(x);k&&!k.inflight&&i.current.entries.set(x,{...k,value_version:"\0stale",failed_at:null,failures:0}),c()},[]);return{map:m,pending:_,loading:g,invalidate:y}}function uU(e){var r;const t=Rm(e);if(!t)return null;const n=typeof(e==null?void 0:e.active_revision)=="number"?e.active_revision:typeof((r=e==null?void 0:e.definition)==null?void 0:r.revision)=="number"?e.definition.revision:null;return{brief:t,revision:n,raw:e}}function dU(e){var l,d,h;const t=e!=null&&e.definition&&typeof e.definition=="object"?e.definition:{},n=(l=e==null?void 0:e.summary)!=null&&l.trigger&&typeof e.summary.trigger=="object"?e.summary.trigger:t!=null&&t.trigger&&typeof t.trigger=="object"?t.trigger:{},r=n!=null&&n.config&&typeof n.config=="object"?n.config:{},i=(d=t==null?void 0:t.policy)!=null&&d.retry&&typeof t.policy.retry=="object"?t.policy.retry:null,o=i!=null&&i.backoff&&typeof i.backoff=="object"?i.backoff:{},c=typeof r.count=="number"&&Number.isFinite(r.count)&&r.count>0?r.count:null;return{trigger_source:String((n==null?void 0:n.source_id)||"").trim(),stop_after:c,stop_at_ms:Vt(typeof r.until=="string"?r.until:""),workflow_id:String(((h=t==null?void 0:t.target)==null?void 0:h.workflow_id)||"").trim(),retry:i?{max_attempts:typeof i.max_attempts=="number"?i.max_attempts:null,initial:String(o.initial??"").trim(),factor:typeof o.factor=="number"?o.factor:null,max:String(o.max??"").trim()}:null}}function fU(e,t){const n=p.useMemo(()=>B9(t),[t]),r=cf(e,n,async(o,c)=>uU(await oU(o).getAutomation(c.id)),{scope:"automation",priority:lf.automation}),i=p.useMemo(()=>{const o=new Map,c=new Map;for(const[l,d]of r.map)o.set(l,d.brief),d.revision!==null&&c.set(l,d.revision);return{map:o,revisions:c}},[r.map]);return{map:i.map,revisions:i.revisions,records:r.map,pending:r.pending,loading:r.loading,invalidate:r.invalidate}}function hU(e,t){const n=p.useMemo(()=>W9(t),[t]),r=cf(e,n,async(i,o)=>Z9(o.id,await i.get_run_input_data(o.id)),{scope:"excerpt_v2",priority:lf.run_brief,immutable:!0,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function mU(e,t){const n=p.useMemo(()=>V9(t,Date.now()),[t]),r=cf(e,n,async(i,o)=>{const c=Number(String(o.version).split(":")[0]||0),l=await i.get_ledger(o.id,H9(c)),d=Array.isArray(l==null?void 0:l.items)?l.items:[];return d.length?YD(o.id,c,d[d.length-1]):null},{scope:"pulse",priority:lf.pulse});return{map:r.map,pending:r.pending,loading:r.loading}}const _U=!0;function pU(e,t,n){const r=p.useMemo(()=>G9(t,n),[t,n]),i=cf(e,r,async(o,c)=>await o.get_run(c.id),{scope:"wait_detail",priority:lf.wait_detail,current_only:_U});return{map:i.map,pending:i.pending,loading:i.loading}}function gU(e,t,n){const r=p.useMemo(()=>X9(t,n),[t,n]),i=cf(e,r,async(o,c)=>{try{return Y9(c.id,await o.get_run(c.id))}catch(l){if(/\b404\b|not found/i.test(String((l==null?void 0:l.message)||l||"")))return J9(c.id);throw l}},{scope:"subrun_fate",priority:lf.wait_detail});return{map:i.map,pending:i.pending,loading:i.loading}}const yU=!0;function wU(e){return(e||[]).filter(t=>ks(t)&&hs(String((t==null?void 0:t.status)||""))).map(t=>({id:ks(t),version:""}))}function vU(e){const t=e!=null&&e.output&&typeof e.output=="object"?e.output:null;return typeof(t==null?void 0:t.response)=="string"?t.response.trim():typeof(t==null?void 0:t._last_output)=="string"?t._last_output.trim():""}function xU(e){const t=e==null?void 0:e.total;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}async function bU(e,t){const[n,r]=await Promise.all([e.get_run(t),e.list_run_artifacts(t,{limit:1}).then(xU,()=>null)]);return{answer:vU(n),artifacts:r}}function kU(e,t){const n=p.useMemo(()=>wU(t),[t]),r=cf(e,n,async(i,o)=>await bU(i,o.id),{scope:"outcome",priority:lf.outcome,immutable:yU,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function jU(){const e=typeof IntersectionObserver<"u",[t,n]=p.useState(()=>e?new Set:null),r=p.useRef(new Map),i=p.useRef(new Set),o=p.useMemo(()=>(l,d)=>{const h=r.current.get(l);if(h&&h.el===d||(h&&(h.observer.disconnect(),r.current.delete(l)),!d||!e))return;const m=new IntersectionObserver(_=>{let g=!1;for(const y of _){const x=String(y.target.dataset.runId||"").trim();x&&(y.isIntersecting?!i.current.has(x):i.current.has(x))&&(y.isIntersecting?i.current.add(x):i.current.delete(x),g=!0)}g&&n(new Set(i.current))},{root:d,rootMargin:"100% 0px 100% 0px"});r.current.set(l,{el:d,observer:m});for(const _ of Array.from(d.querySelectorAll("[data-run-id]")))m.observe(_)},[e]),c=p.useMemo(()=>()=>{for(const{el:l,observer:d}of r.current.values()){d.disconnect();for(const h of Array.from(l.querySelectorAll("[data-run-id]")))d.observe(h)}},[]);return p.useEffect(()=>()=>{for(const{observer:l}of r.current.values())l.disconnect();r.current.clear()},[]),{visible:t,attach:o,refresh:c}}const kj=200,jj=500,SU=6e4,NU=1e4,$U=15e3,CU=["llm_calls","tool_calls","tokens_total"];function EU(e,t){if(!t)return e;const n={...e};for(const r of CU){const i=e[r];i==null&&(n[r]=t[r]??null)}return t.archived===!0&&(n.archived=!0),n}function vw(e){return!String((e==null?void 0:e.parent_run_id)||"").trim()||String((e==null?void 0:e.role)||"").trim()==="occurrence"}class AU{constructor(t){jn(this,"sweep_rows",[]);jn(this,"sweep_at",null);jn(this,"sweep_started_at",null);jn(this,"sweep_inflight",!1);jn(this,"active_rows",[]);jn(this,"active_complete",!1);jn(this,"early",!1);jn(this,"active_at",null);jn(this,"seeded",!1);this.epoch=t}sweep_due(t,n=!1){if(this.sweep_inflight)return!1;if(this.sweep_started_at===null)return!0;const r=t-this.sweep_started_at;return r>=SU||this.early&&r>=$U?!0:n&&r>=NU}begin_sweep(t){this.sweep_inflight=!0,this.sweep_started_at=t,this.early=!1}apply_sweep(t,n){this.sweep_inflight=!1,this.sweep_rows=(t||[]).filter(r=>!!ks(r)),this.sweep_at=n}fail_sweep(){this.sweep_inflight=!1}adopt_sweep(t){this.sweep_rows=t.sweep_rows,this.sweep_at=t.sweep_at}adopt_active(t){t.active_at!==null&&(this.active_rows=t.active_rows,this.active_at=t.active_at,this.active_complete=t.active_complete,this.seeded=t.seeded)}snapshot(){return{active_rows:this.active_rows,sweep_rows:this.sweep_rows,active_at:this.active_at,sweep_at:this.sweep_at}}seed(t){return!t||this.active_at!==null||!Array.isArray(t.active_rows)?!1:(this.active_rows=t.active_rows.filter(n=>!!ks(n)),this.sweep_rows=Array.isArray(t.sweep_rows)?t.sweep_rows.filter(n=>!!ks(n)):[],this.active_at=typeof t.active_at=="number"?t.active_at:null,this.sweep_at=typeof t.sweep_at=="number"?t.sweep_at:null,this.active_complete=!1,this.seeded=!0,this.active_rows.length>0||this.sweep_rows.length>0)}apply_active(t,n,r){this.active_at=Date.now(),this.seeded=!1;const i=new Set(this.active_rows.map(ks)),o=new Set,c=[];for(const l of[...t||[],...n||[]]){const d=ks(l);!d||o.has(d)||(o.add(d),c.push(l))}if(this.active_rows=c,this.active_complete=r,r)for(const l of i)o.has(l)||(this.early=!0)}view(){const t=new Map;for(const l of this.sweep_rows)t.set(ks(l),l);const n=new Set,r=[];for(const l of this.active_rows)n.add(ks(l)),r.push(EU(l,t.get(ks(l))));const i=new Map(r.map(l=>[ks(l),l])),o=[...r],c=r.filter(l=>vw(l)&&!t.has(ks(l)));for(const l of this.sweep_rows){const d=ks(l),h=i.get(d);if(h){vw(h)&&c.push(h);continue}this.active_complete&&!hs(String((l==null?void 0:l.status)||""))||o.push(l),vw(l)&&c.push(l)}return{roots:c,all:o}}}function TU(e,t){return`${wg}runs:${String(e||"").trim()}:${String(t||"").trim()}`}function MU(e,t){if(!e)return null;try{const n=e.getItem(t);if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"||!Array.isArray(r.active_rows)?null:{active_rows:r.active_rows,sweep_rows:Array.isArray(r.sweep_rows)?r.sweep_rows:[],active_at:typeof r.active_at=="number"?r.active_at:null,sweep_at:typeof r.sweep_at=="number"?r.sweep_at:null}}catch{return null}}function RU(e,t,n){if(e)try{let r=JSON.stringify(n);if(r.length>Pv&&(r=JSON.stringify({...n,sweep_rows:[]})),r.length>Pv){e.removeItem(t);return}e.setItem(t,r)}catch{}}function Sj(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}const Dv=new WeakMap;let Fv=null;function LU(e,t){let n=Dv.get(e);if(!n||n.epoch!==t){const r=Fv;n=new AU(t),r&&r.epoch===t&&(r.sweep_at!==null&&n.adopt_sweep(r),n.adopt_active(r)),Dv.set(e,n)}return Fv=n,n}function IU(e){return Dv.get(e)||null}function Nj(e){return Fv===e}const bp=["needs_you","working","waiting_on","scheduled","done"],AC={needs_you:"Needs you",working:"Working",waiting_on:"Waiting on…",scheduled:"Scheduled",done:"Done"},OU={needs_you:"only you can move these",working:"an agent is on it",waiting_on:"something else must happen first",scheduled:"will start by itself",done:"read the outcome"},PU={needs_you:"nothing needs you",working:"no agent is working",waiting_on:"nothing is blocked",scheduled:"nothing scheduled",done:"no recent runs"},DU=8;function FU(){return{needs_you:[],working:[],waiting_on:[],scheduled:[],done:[]}}function Qs(e){return String((e==null?void 0:e.run_id)||"").trim()}function xw(e){const t=String((e==null?void 0:e.role)||"").trim();return!String((e==null?void 0:e.parent_run_id)||"").trim()||t==="occurrence"||t==="controller"}function zU(e,t,n,r){const i=(e==null?void 0:e.paused)===!0||(n==null?void 0:n.paused)===!0;return V1({...e,paused:i},t,tg(n),r??null)}function va(e,t){const n=String(e||"").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function kp(e,t,n,r){var x,k;const i=Qs(e),o=(x=t.details)==null?void 0:x.get(i),c=(o==null?void 0:o.waiting)??(e==null?void 0:e.waiting),l=c&&typeof c=="object"?c:null,d=af(l),h=String((e==null?void 0:e.status)||"").trim().toLowerCase(),m=String((e==null?void 0:e.automation_id)||"").trim(),_=m?((k=t.automations)==null?void 0:k.get(m))??null:null,g=n.actor_run_id?t.by_id.get(n.actor_run_id):void 0,y=Vt((l==null?void 0:l.until)||"");return{run_id:i,lane:n.lane,line:n,title:G1(e,t,r),subject:H1(e,t),status_word:zU(e,n,o,_),workflow_id:String((e==null?void 0:e.workflow_id)||"").trim(),role:String((e==null?void 0:e.role)||"").trim(),wait_key:String((l==null?void 0:l.wait_key)||"").trim(),tool_names:d.map(v=>String((v==null?void 0:v.name)||"tool")).filter(Boolean),pending_calls:d.map(v=>({name:String((v==null?void 0:v.name)||"tool"),arguments:(v==null?void 0:v.arguments)??null})),prompt:String((l==null?void 0:l.prompt)||"").trim(),allow_free_text:(l==null?void 0:l.allow_free_text)!==!1,since_ms:Vt((l==null?void 0:l.since)||(e==null?void 0:e.updated_at)||(e==null?void 0:e.created_at)||""),duration_ms:Tm(e,t.now_ms),tokens_total:typeof(e==null?void 0:e.tokens_total)=="number"?e.tokens_total:null,llm_calls:typeof(e==null?void 0:e.llm_calls)=="number"?e.llm_calls:null,tool_calls:typeof(e==null?void 0:e.tool_calls)=="number"?e.tool_calls:null,failed:h==="failed",error:String((e==null?void 0:e.error)||(o==null?void 0:o.error)||"").trim(),paused:n.verb==="paused",archived:(e==null?void 0:e.archived)===!0,automation_id:m,tag:Dg(e),tag_label:l1(e),actor_run_label:g?si(String(g.workflow_id||""))||"subrun":"",blocks:[],chain:[],asks:[],stuck:!!n.stuck,next_fire_ms:String((e==null?void 0:e.role)||"").trim()==="controller"?(_==null?void 0:_.next_fire_ms)??y:y,automation:_,task:(_==null?void 0:_.task)||String((r==null?void 0:r.excerpt)||"").trim(),row:e}}function BU(e){const t=new Date(e),n=r=>String(r).padStart(2,"0");return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}const jp=(e,t)=>e===null?t===null?0:1:t===null?-1:e-t,$j=(e,t)=>e===null?t===null?0:1:t===null?-1:t-e;function UU(e){return e.needs_you.sort((t,n)=>Number(t.stuck&&!t.asks.length)-Number(n.stuck&&!n.asks.length)||jp(t.since_ms,n.since_ms)),e.working.sort((t,n)=>Number(n.line.stalled)-Number(t.line.stalled)||$j(t.line.stale_ms,n.line.stale_ms)||jp(t.since_ms,n.since_ms)),e.waiting_on.sort((t,n)=>jp(t.since_ms,n.since_ms)),e.scheduled.sort((t,n)=>jp(t.next_fire_ms,n.next_fire_ms)),e.done.sort((t,n)=>Number(n.failed)-Number(t.failed)||$j(t.since_ms,n.since_ms)),e}function Cj(e){var y,x,k;const t=FU(),n=[],r=[],i=new Set;for(const v of e.active||[]){const N=Qs(v);!N||i.has(N)||(i.add(N),(hs(v==null?void 0:v.status)?r:n).push(v))}for(const v of e.done||[]){const N=Qs(v);!N||i.has(N)||(i.add(N),hs(v==null?void 0:v.status)&&r.push(v))}const o=Sx([...n,...r],{details:e.details,fates:e.fates,pulses:e.pulses,automations:e.automations,now_ms:e.now_ms,stall_after_ms:e.stall_after_ms}),c=new Map(n.map(v=>[Qs(v),v])),l=new Map,d=v=>{const N=Qs(v);let $=l.get(N);return $||($=ef(v,o),l.set(N,$)),$},h=v=>xw(v)||!c.has(String((v==null?void 0:v.parent_run_id)||"").trim()),m=v=>Vt(String((v==null?void 0:v.updated_at)||(v==null?void 0:v.created_at)||""))??0,_=v=>(o.children_of.get(v)||[]).filter(N=>c.has(Qs(N))&&!xw(N)).sort((N,$)=>m($)-m(N)),g=new Set;for(const v of n){if(!h(v))continue;const N=d(v);if(String((v==null?void 0:v.role)||"").trim()==="controller"){const J=String((v==null?void 0:v.automation_id)||"").trim()||Qs(v);if(g.has(J))continue;g.add(J);const G=kp(v,o,N,(y=e.run_briefs)==null?void 0:y.get(Qs(v)));t[G.lane].push(G);continue}const $=kp(v,o,N,(x=e.run_briefs)==null?void 0:x.get(Qs(v))),C=[],S=[];let D=N.verb==="running",O=!!N.stuck,A=0;const P=(J,G)=>{var I;const V=d(J),R=G<6?_(Qs(J)):[],M=R.length>0;if(C.length>=DU)A+=1;else{const L=M?q1(J,o):"";C.push({run_id:Qs(J),depth:G,name:Bg(String((J==null?void 0:J.workflow_id)||""))||Qd(Qs(J)),title:KD(String((J==null?void 0:J.workflow_id)||""))||Qs(J),words:M?L?`waits at ${L} ↓`:"waits for ↓":V.brief||V.text,stuck:!!V.stuck,asks:V.lane==="needs_you"&&!V.stuck,running:V.verb==="running"&&!M,stuck_facts:V.stuck_facts,since_ms:Vt(String((J==null?void 0:J.updated_at)||(J==null?void 0:J.created_at)||""))})}G>0?(V.lane==="needs_you"&&!V.stuck&&S.push(kp(J,o,V,(I=e.run_briefs)==null?void 0:I.get(Qs(J)))),V.stuck&&(O=!0),V.verb==="running"&&(D=!0)):M&&V.lane==="needs_you"&&!V.stuck&&S.push($);for(const L of R)P(L,G+1)};P(v,0),A&&C.push({run_id:"",depth:1,name:`+${A} more`,title:"",words:"",stuck:!1,asks:!1,running:!1}),O&&!S.length&&($.status_word="stuck"),$.chain=C.length>1?C:[],$.asks=S,$.stuck=O;const W=N.lane==="needs_you"&&!N.stuck;if($.lane=W||S.length||O?"needs_you":D?"working":N.lane,S.length){const J=S.map(G=>G.since_ms).filter(G=>G!==null);J.length&&($.since_ms=Math.min(...J))}t[$.lane].push($)}for(const v of r){if(!xw(v)&&o.by_id.has(String((v==null?void 0:v.parent_run_id)||"").trim()))continue;const N=kp(v,o,d(v),(k=e.run_briefs)==null?void 0:k.get(Qs(v)));t.done.push(N)}return UU(t)}function WU(e,t){const r=(t&&t.length?t:e||[]).filter(o=>Qs(o)&&!hs(o==null?void 0:o.status)),i=[...t||[],...e||[]].filter(o=>Qs(o)&&hs(o==null?void 0:o.status));return{active:r,done:i}}const TC="board_stall_after_ms",Hx=[{ms:5*6e4,label:"5m"},{ms:15*6e4,label:"15m"},{ms:60*6e4,label:"1h"}];function MC(e){try{const t=Number(e==null?void 0:e.getItem(TC));return Hx.some(n=>n.ms===t)?t:mv}catch{return mv}}function RC(e){var t;return((t=Hx.find(n=>n.ms===e))==null?void 0:t.label)||er(e)}function qU(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function LC(e){const t=String((e==null?void 0:e.actor_id)||"").trim();return t&&t.toLowerCase()!=="gateway"?t:""}const IC=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],vg=e=>String(e).padStart(2,"0");function fu(e,t=Date.now()){const n=new Date(e),r=n.getFullYear()===new Date(t).getFullYear()?"":` ${n.getFullYear()}`;return`${IC[n.getMonth()]} ${n.getDate()}${r}, ${vg(n.getHours())}:${vg(n.getMinutes())}`}function VU(e){const t=new Date(e);return`${IC[t.getUTCMonth()]} ${t.getUTCDate()}, ${vg(t.getUTCHours())}:${vg(t.getUTCMinutes())} UTC`}function zv(e,t=Date.now()){const n=e-t;return n>0?`in ${er(n)}`:`${er(-n)} ago`}function HU(e){if(!e.length)return"a tool call";const t=new Map;for(const r of e)t.set(r,(t.get(r)||0)+1);const n=Array.from(t,([r,i])=>i>1?`${r} ×${i}`:r);return`${n.slice(0,3).join(", ")}${n.length>3?` and ${n.length-3} more`:""}`}const ic=e=>e.split(" ").join(" ");function Gx(e,t){const n=e.since_ms!==null?` since ${ic(fu(e.since_ms,t))} ${ic(`(${er(Math.max(0,t-e.since_ms))})`)}`:"",r=e.line.action;if(e.line.verb==="paused")return{who:"",text:`paused${n}`};if(e.line.stuck)return{who:"",text:`stuck${n}`};const i=LC(e.row);return r==="approve"?{who:i,text:`needs approval for ${HU(e.tool_names)}${n}`}:r==="answer"?{who:i,text:`${e.prompt?"asks":"waits for an answer"}${n}`}:e.line.unresolved?{who:i,text:`needs you${n} · question, approval or pause`}:{who:i,text:`needs you${n}`}}function Xh(e){if(typeof e=="string")return e;if(e==null||typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Bv(e,t=0){const r=(e.arguments&&typeof e.arguments=="object"&&!Array.isArray(e.arguments)?Object.entries(e.arguments):[]).map(([i,o])=>`${i}: ${t>0?va(Xh(o),t):Xh(o)}`);return`${e.name}(${r.join(", ")})`}function GU(e){const t=e.arguments;return t==null?"":typeof t!="object"||Array.isArray(t)?Xh(t):Object.entries(t).map(([n,r])=>Array.isArray(r)&&r.length&&r.every(i=>i===null||typeof i!="object")?`${n}:
165
+ ${r.map(i=>Xh(i)).join(`
166
+ `)}`:`${n}: ${Xh(r)}`).join(`
167
+ `)}const zp=600,Bp=4e3;function OC(e,t){var n;if(e.lane!=="needs_you")return null;if(e.line.verb==="paused"){const r=String((t==null?void 0:t.pause_reason)||((n=e.row)==null?void 0:n.pause_reason)||"").trim();return r?{text:va(r,zp),full:va(r,Bp)}:null}if(e.line.action==="approve"&&e.pending_calls.length){const r=e.pending_calls.map(o=>Bv(o,120)).join(" · "),i=e.pending_calls.map(o=>Bv(o)).join(`
168
+ `);return{text:va(r,zp),full:va(i,Bp)}}return e.prompt?{text:va(e.prompt,zp),full:va(e.prompt,Bp)}:null}function KU(e,t){if(e.lane!=="done"||e.failed)return null;const n=String((t==null?void 0:t.answer)||"").trim();return n?{text:va(n,zp),full:va(n,Bp)}:null}function PC(e,t){const n=[];return e.role==="controller"||(e.duration_ms>=0&&n.push(er(e.duration_ms)),e.tokens_total!==null&&n.push(`${e.tokens_total.toLocaleString("en-US")} tk`),e.tool_calls!==null&&n.push(`${e.tool_calls} tool${e.tool_calls===1?"":"s"}`),e.lane==="done"&&typeof(t==null?void 0:t.artifacts)=="number"&&n.push(`${t.artifacts} artifact${t.artifacts===1?"":"s"}`)),n}function Kx(e){var n;const t=String(((n=e.row)==null?void 0:n.session_id)||"").trim();return!t||e.automation_id||e.subject.kind==="automation"||t.startsWith("automation:")?"":t}function JU(e,t,n){return`${String(e||"").split("#")[0]}#session=${encodeURIComponent(t)}&run=${encodeURIComponent(n)}`}const Ej="Install the AbstractCode web app (npx @abstractframework/code) to open this conversation";function Aj(e){return e.lane!=="done"&&e.role!=="controller"}const YU={automation:"automation",brief:"run brief",excerpt:"prompt",workflow:"untitled"};function xg(e){var t;if(e.title.source==="excerpt"&&e.task)return e.task;if(e.title.source==="brief"){const n=(t=e.row)==null?void 0:t.brief;return String((n==null?void 0:n.title)||(n==null?void 0:n.task_excerpt)||e.title.text).trim()}return e.title.text}const XU=[25e3,5e4,1e5,2e5];function DC(e,t){var C;const n=e.trigger_text||e.schedule_rule_text||(e.trigger?Nx(e.trigger):"")||e.cadence||"",r=e.current&&!hs(e.current.status)?e.current:null,i=((C=e.trigger)==null?void 0:C.source_id)==="manual";let o="",c="";if(e.status==="paused")o="paused",c=e.paused_reason||"scheduled runs are skipped while paused";else if(r)o=`run #${r.index} in progress`,c=e.next_fire_ms!==null?`next run ${fu(e.next_fire_ms,t)}`:"";else if(e.next_fire_ms!==null)o=`next ${ic(zv(e.next_fire_ms,t))}`,c=`next run ${fu(e.next_fire_ms,t)}${e.next_run_local?` · ${e.next_run_local} (owner's zone)`:""}`;else if(e.status==="completed"||e.status==="failed")o=`${e.status}: no next run`;else if(e.event_driven){const S=e.last&&e.last.fired_ms!==null?Qh(new Date(e.last.fired_ms).toISOString(),{timeZone:e.time_zone||null,nowMs:t,style:"day"}):"";o=S?`listening · last: ${ic(S)}`:"listening",c="runs every time something new arrives"}else i||(o="no next run");const l=[n,o].filter(Boolean),d={text:bw(l),title:[n,c].filter(Boolean).join(" · "),parts:l},h=ic(`${e.occurrence_count} turn${e.occurrence_count===1?"":"s"}`);if(!e.last)return{schedule:d,last:{text:bw(["no run yet",h]),title:"this automation has not run",failed:!1,parts:["no run yet",h],failure:""}};const m=e.last,_=m.status==="failed",g=m.fired_ms!==null?ic(zv(m.fired_ms,t)):"",y=_?String(e.last_notification_text||e.last_excerpt||"").trim():"",k=!!(r&&r.index===m.index)?`#${m.index} started${g?` ${g}`:""}`:`last #${m.index} ${_?"✗ failed":m.status}${g?` ${g}`:""}`,v=m.fired_ms!==null&&m.finished_ms!==null&&m.finished_ms>=m.fired_ms?er(m.finished_ms-m.fired_ms):"",N=[k,h],$=[`#${m.index} ${m.status}`,m.fired_ms!==null?`fired ${fu(m.fired_ms,t)}`:"",v?`took ${v}`:"",y].filter(Boolean).join(" · ");return{schedule:d,last:{text:bw(N),title:$,failed:_,parts:N,failure:y}}}function bw(e){return e.join(" · ").split(" ").join(" ")}function ZU(e){const t=String(e.context_mode||"").trim();if(t!=="growing")return{mode:t,used:null,budget:null,label:t?`${t} context`:"",ratio:null};const n=typeof e.growing_max_tokens=="number"&&e.growing_max_tokens>0?e.growing_max_tokens:null,r=typeof e.context_used_tokens=="number"&&e.context_used_tokens>=0?e.context_used_tokens:null,i=n===null?"context":r===null?`context · ${lc(n)} budget`:`context ${lc(r)} / ${lc(n)}`;return{mode:t,used:r,budget:n,label:i,ratio:r!==null&&n!==null?Math.min(1,r/n):null}}function QU(e){return{context:{mode:"growing",growing:{max_tokens:e}}}}function eW(e){const t=String(e??"").trim();if(!/^\d+$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}const tW={phase:"idle",custom:"",error:"",optimistic:null};function nW(e,t){switch(t.type){case"open":return e.phase==="idle"?{...e,phase:"choose",error:""}:e;case"close":return e.phase==="choose"?{...e,phase:"idle",custom:""}:e;case"custom":return{...e,custom:t.value};case"save":return e.phase==="choose"?{phase:"saving",custom:"",error:"",optimistic:{value:t.value,base:t.base}}:e;case"saved":return e.phase==="saving"?{...e,phase:"idle"}:e;case"failed":return e.phase==="saving"?{phase:"idle",custom:"",error:t.error||"the change was not saved",optimistic:null}:e}}function sW(e,t){const n=t.optimistic;return n&&n.base===e.growing_max_tokens?n.value:e.growing_max_tokens}async function rW(e,t,n,r){try{return await e(t,QU(r),n),{type:"saved"}}catch(i){return{type:"failed",error:Pi(i).message||"the change was not saved"}}}function iW(e,t){if(!e){const l={enabled:!1,reason:"automation details are loading"};return{run_now:l,toggle:{command:"automation.pause",label:"Pause schedule",state:l}}}const n=e.current&&!hs(e.current.status)?e.current:null,r={automation_id:e.automation_id,title:e.title,status:e.status,capabilities:e.capabilities,legacy:e.legacy,current_occurrence:n?{index:n.index,run_id:n.run_id,status:n.status}:null,occurrence_count:e.occurrence_count},i=em(r,[],t),o=e.status==="paused",c=o&&e.paused_reason&&i.resume.enabled?{enabled:!0,reason:`paused by the gateway: ${e.paused_reason}`}:i.resume;return{run_now:i.run_now,toggle:o?{command:"automation.resume",label:"Resume schedule",state:c}:{command:"automation.pause",label:"Pause schedule",state:i.pause}}}async function oW(e,t,n){try{return await e(t,n),null}catch(r){return Pi(r).message||"the command was not sent"}}const eu={run:"Run",spend:"Spend",automation:"Automation",schedule:"Schedule",policy:"Policy",after:"After each run",where:"Where"};function Uv(e,t){return`${e.toLocaleString("en-US")} ${t}${e===1?"":"s"}`}function Ih(e,t,n,r,i=!1){return n===null?null:{id:e,label:t,value:i?VU(n):fu(n,r),aside:zv(n,r),copy:new Date(n).toISOString()}}function aW(e){const t=e.line;return t.verb==="paused"?"you, to resume it":t.action==="approve"?`your approval of ${Uv(e.pending_calls.length||e.tool_names.length||1,"tool call")}`:t.action==="answer"?e.prompt?"your answer to a question":"your answer":t.unresolved?"you: a question, an approval or a resume":t.actor==="clock"?"the clock":t.actor==="external"?t.object||"an external event":t.actor==="run"?t.object||"a subrun":t.object||"unknown"}function Tj(e,t){if(!t)return null;const n=si(t);return{id:e,label:"Workflow",value:n||t,aside:n&&n!==t?t:"",aside_mono:!0,copy:t}}const _n=(e,t)=>{t&&e.push(t)};function lW(e,t){var h,m,_,g;const{now_ms:n}=t,r=e.automation,i=t.facts??null,o=e.row,c=e.role==="controller",l=[];if(!c){const y=[];if(!e.automation_id){const $=xg(e);_n(y,{id:"title",label:"Title",value:$,long:!0,source:YU[e.title.source]}),e.task&&e.task!==$&&_n(y,{id:"task",label:"Task",value:e.task,long:!0,source:"prompt"})}_n(y,Tj("workflow",e.workflow_id)),_n(y,{id:"run_id",label:"Run id",value:e.run_id,mono:!0});const x=String((o==null?void 0:o.session_id)||"").trim();x&&_n(y,{id:"session",label:"Session",value:x,mono:!0}),_n(y,Ih("started","Started",Vt((o==null?void 0:o.created_at)||""),n)),_n(y,Ih("last_activity","Last activity",Vt((o==null?void 0:o.updated_at)||""),n));const k=String((o==null?void 0:o.actor_id)||"").trim();if(_n(y,k?{id:"started_by",label:"Started by",value:k,source:LC(o)?"":"not a person"}:{id:"started_by",label:"Started by",value:"not on this row"}),_n(y,{id:"state",label:"State",value:e.failed&&e.error?`failed: ${e.error}`:e.lane==="needs_you"?e.line.brief:e.line.text,long:!0}),e.lane==="needs_you"||e.lane==="waiting_on")if(_n(y,{id:"wait_kind",label:"Waiting for",value:aW(e)}),_n(y,Ih("wait_since","Since",e.since_ms,n)),e.line.verb==="paused"){const $=String(((h=t.detail)==null?void 0:h.pause_reason)||(o==null?void 0:o.pause_reason)||"").trim();$&&_n(y,{id:"pause_reason",label:"Reason",value:$,long:!0})}else e.pending_calls.length?e.pending_calls.forEach(($,C)=>_n(y,{id:`tool_call_${C}`,label:C===0?"Tool calls":"",value:GU($),chips:[$.name],long:!0,copy:Bv($)})):e.prompt&&_n(y,{id:"question",label:"Question",value:e.prompt,long:!0});e.lane==="working"&&_n(y,{id:"no_progress",label:"No progress",value:`marked after ${RC(t.stall_after_ms)} without a ledger step`,source:"board header"}),l.push({id:"run",title:eu.run,rows:y});const v=[],N=e.lane!=="done";e.duration_ms>=0&&_n(v,{id:"duration",label:"Duration",value:er(e.duration_ms),aside:N?"so far":""}),e.tokens_total!==null&&_n(v,{id:"tokens",label:"Tokens",value:e.tokens_total.toLocaleString("en-US"),source:"whole run tree"}),e.llm_calls!==null&&_n(v,{id:"llm_calls",label:"LLM calls",value:e.llm_calls.toLocaleString("en-US")}),e.tool_calls!==null&&_n(v,{id:"tool_calls",label:"Tool calls",value:e.tool_calls.toLocaleString("en-US")}),typeof((m=t.outcome)==null?void 0:m.artifacts)=="number"&&_n(v,{id:"artifacts",label:"Artifacts",value:t.outcome.artifacts.toLocaleString("en-US")}),e.tokens_total===null&&e.llm_calls===null&&e.tool_calls===null&&_n(v,{id:"metrics",label:"Metrics",value:"not measured yet: the 60 s metrics sweep fills them"}),l.push({id:"spend",title:eu.spend,rows:v})}if(r){const y=[];_n(y,{id:"title",label:"Title",value:r.title||"untitled",long:!0,source:r.title?"automation":""}),r.task&&_n(y,{id:"task",label:"Task",value:r.task,long:!0}),_n(y,{id:"automation_id",label:"Automation id",value:r.automation_id,mono:!0}),_n(y,Tj("target_workflow",(i==null?void 0:i.workflow_id)||(c?"":e.workflow_id))),typeof t.revision=="number"&&_n(y,{id:"revision",label:"Revision",value:String(t.revision)}),r.status&&_n(y,{id:"status",label:"Status",value:r.status}),l.push({id:"automation",title:eu.automation,rows:y});const x=[];_n(x,{id:"trigger",label:"Trigger",value:r.trigger_text||(r.trigger?Nx(r.trigger,r.schedule_rule_text):"")||r.cadence||"not on the record",source:(i==null?void 0:i.trigger_source)||""}),r.status==="paused"?_n(x,{id:"next",label:"Next run",value:"none while paused: scheduled runs are skipped"}):_n(x,Ih("next","Next run",r.next_fire_ms,n,!0)||{id:"next",label:"Next run",value:r.event_driven?"when something new arrives":((_=r.trigger)==null?void 0:_.source_id)==="manual"?"when someone presses Run now":"none scheduled"});const k=r.current&&!hs(r.current.status)?r.current:null;if(k&&_n(x,{id:"current",label:"In progress",value:`#${k.index} ${k.status}`}),r.last&&!(k&&k.index===r.last.index)){const $=r.last.fired_ms!==null&&r.last.finished_ms!==null&&r.last.finished_ms>=r.last.fired_ms?er(r.last.finished_ms-r.last.fired_ms):"",C=r.last.fired_ms!==null?fu(r.last.fired_ms,n):"";_n(x,{id:"last",label:"Last run",value:`#${r.last.index} ${r.last.status}`,aside:[$,C].filter(Boolean).join(" · ")})}_n(x,{id:"turns",label:"Turns",value:String(r.occurrence_count)}),(i==null?void 0:i.stop_after)!==null&&(i==null?void 0:i.stop_after)!==void 0&&_n(x,{id:"stop_after",label:"Stop after",value:Uv(i.stop_after,"run")}),(i==null?void 0:i.stop_at_ms)!==null&&(i==null?void 0:i.stop_at_ms)!==void 0&&_n(x,Ih("stop_at","Stop at",i.stop_at_ms,n,!0)),l.push({id:"schedule",title:eu.schedule,rows:x});const v=[];if(r.context_mode){const $=r.context_mode==="growing"&&typeof r.growing_max_tokens=="number"&&r.growing_max_tokens>0?`capped at ${lc(r.growing_max_tokens)} tokens`:"";_n(v,{id:"context",label:"Context",value:r.context_mode,aside:$})}_n(v,r.tools.length?{id:"tools",label:"Tools",value:r.tools.join(", "),chips:r.tools}:{id:"tools",label:"Tools",value:"flow default",source:"flow"});const N=[r.model,r.provider].filter(Boolean).join(" · ");if(N&&_n(v,{id:"model",label:"Model",value:N}),r.max_iterations!==null&&_n(v,{id:"max_iterations",label:"Max iterations",value:String(r.max_iterations)}),r.tool_approval&&_n(v,{id:"tool_approval",label:"Tool approval",value:r.tool_approval}),r.untrusted_input_tools&&_n(v,r.untrusted_input_tools.length?{id:"untrusted",label:"Untrusted input",value:r.untrusted_input_tools.join(", "),chips:r.untrusted_input_tools}:{id:"untrusted",label:"Untrusted input",value:"no tool marked"}),r.email_allowed_recipients&&_n(v,{id:"recipients",label:"Email to",value:r.email_allowed_recipients.length?r.email_allowed_recipients.join(", "):"nobody"}),i!=null&&i.retry){const $=i.retry,C=[$.initial?`backoff ${$.initial}`:"",$.factor!==null?`× ${$.factor}`:"",$.max?`up to ${$.max}`:""].filter(Boolean).join(" ");_n(v,{id:"retry",label:"Retry",value:$.max_attempts!==null?Uv($.max_attempts,"attempt"):"on failure",aside:C})}l.push({id:"policy",title:eu.policy,rows:v}),l.push({id:"after",title:eu.after,rows:[r.notify_channels.length?{id:"notify",label:"Notify",value:r.notify_channels.join(", "),chips:r.notify_channels}:{id:"notify",label:"Notify",value:"nobody"}]})}const d=String(((g=t.detail)==null?void 0:g.workspace_root)||(r==null?void 0:r.workspace_root)||"").trim();return d&&l.push({id:"where",title:eu.where,rows:[{id:"workspace",label:"Workspace",value:d,mono:!0,source:r!=null&&r.workspace_access_mode?r.workspace_access_mode.split("_").join(" "):""}]}),l.filter(y=>y.rows.length>0)}const Wv={"12h":12*36e5,"24h":24*36e5,"48h":48*36e5,"72h":72*36e5,"7d":7*864e5,"14d":14*864e5,"1m":30*864e5,all:null},kw={"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"},Mj="48h";function Rj(e,t,n=Date.now()){const r=Wv[t]??null;if(r===null)return{visible:e,hidden_count:0};const i=n-r,o=[];let c=0;for(const l of e)l.since_ms===null||l.since_ms>=i?o.push(l):c+=1;return{visible:o,hidden_count:c}}const jw=4;function cW(e){var o;const t=(o=e==null?void 0:e.discoveries)==null?void 0:o.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(l=>typeof l=="string").map(l=>l.trim()).filter(Boolean):[],i=typeof t.dreams=="number"&&Number.isInteger(t.dreams)&&t.dreams>0?t.dreams:null;return{count:n,kinds:r(t.kinds),felt_tones:r(t.felt_tones),dreams:i}}function Lj(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 uW(e){var l,d;const t=h=>{var _;const m=(_=e==null?void 0:e[h])==null?void 0:_.open;return Array.isArray(m)?m.map(Lj).filter(g=>g!==null):[]},n=t("questions"),r=t("problems"),i=(l=e==null?void 0:e.lessons)==null?void 0:l.lessons,o=Array.isArray(i)?i.map(Lj).filter(h=>h!==null):[],c=typeof((d=e==null?void 0:e.lessons)==null?void 0:d.total)=="number"?e.lessons.total:o.length;return{questions:n.slice(0,jw),questions_total:n.length,problems:r.slice(0,jw),problems_total:r.length,lessons:o.slice(0,jw),lessons_total:c}}function lc(e){return e===null||!Number.isFinite(e)||e<0?"":e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(1)}M`}function dW(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 fW=6e4;function Sw(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 Nw(e){const t=String(e||"").trim();return t.length>72?`${t.slice(0,70)}…`:t}function Up(e){return e.toLowerCase().replace(/[_-]+/g," ")}function hW(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(_=>_&&typeof _=="string");if(!r.length)return null;const i=[];for(const _ of r){i.push({needle:Up(_),phase:_});const g=(h=n[_])==null?void 0:h.spoken_synonyms;if(Array.isArray(g))for(const y of g){const x=Up(String(y||"").trim());x&&i.push({needle:x,phase:_})}}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 l=[],d=(m=t==null?void 0:t.state_mode_axis)==null?void 0:m.words;if(d&&typeof d=="object"&&!Array.isArray(d))for(const[_,g]of Object.entries(d)){const y=String((g==null?void 0:g.phase)||"").trim(),x=Up(String(_||"").trim());x&&r.includes(y)&&l.push({needle:x,phase:y})}return{phases:r,synonyms:i,modes:l,initial:c,version:typeof t.version=="number"?t.version:null,sha256:String((e==null?void 0:e.sha256)||"").trim()}}const mW=["asleep","sleep","dream"],_W=["rest"],pW=["awake","idle"];function gW(e,t){const n=String(e||"").trim().toLowerCase();if(!n)return"unknown";if(t){const r=Up(n),i=t.synonyms.filter(c=>r.includes(c.needle)).sort((c,l)=>l.needle.length-c.needle.length);if(i.length)return i[0].phase;const o=t.modes.filter(c=>r.includes(c.needle)).sort((c,l)=>l.needle.length-c.needle.length);return o.length?o[0].phase:n.includes("task")&&!n.includes("no_task")&&t.phases.includes("work")?"work":mW.some(c=>n.includes(c))?t.initial:_W.some(c=>n.includes(c))&&t.phases.includes("personal")?"personal":pW.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 yW=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),wW=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function vW(e){if(!e)return yW;const t=e.phases.filter(n=>wW.has(n));return new Set([...t,"paused","stopped","unknown"])}const xW={needs_you:3,working:3,waiting_on:2,scheduled:2,done:3};function go(e){return s.jsx("span",{className:`mc_sk${e.className?` ${e.className}`:""}`,style:e.width?{width:e.width}:void 0,"aria-hidden":"true"})}function bW(e){return s.jsx(s.Fragment,{children:Array.from({length:e.n},(t,n)=>s.jsxs("div",{className:"mc_card mc_card_skeleton","aria-hidden":"true",children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx(go,{className:"mc_sk_title",width:n%2?"72%":"58%"}),s.jsx(go,{className:"mc_sk_pill"})]}),s.jsx(go,{width:"88%"}),s.jsx(go,{width:"46%"})]},n))})}function wm(e){return s.jsx("div",{className:"mc_sk_row",role:"status","aria-busy":"true","aria-label":`loading ${e.what}`,title:`loading ${e.what}…`,children:s.jsx(go,{width:e.width||"84%"})})}const kW="mc_entities mc_entities_reserved",jW="mc_entities mc_entities_empty",SW=4,FC=12;function NW(e){return s.jsx(s.Fragment,{children:Array.from({length:e.n},(t,n)=>s.jsxs("div",{className:"mc_entity_cell",children:[s.jsxs("div",{className:"mc_entity mc_entity_skeleton","aria-hidden":"true",children:[s.jsx(go,{className:"mc_sk_title",width:n%2?"64%":"48%"}),s.jsx(go,{className:"mc_sk_chip"}),s.jsx(go,{width:"70%"}),s.jsx(go,{width:"42%"}),s.jsx(go,{width:"56%"})]}),s.jsx(go,{className:"mc_sk_hints",width:"120px"})]},n))})}const rl={},$W=["needs_you","working","waiting_on"];function CW(e,t){switch(t.type){case"ask":return e.phase==="idle"?{phase:"confirm",total:t.total}:e;case"keep":return e.phase==="confirm"?{phase:"idle"}:e;case"start":return e.phase==="confirm"?{phase:"busy",total:t.total,done:0,failed:0}:e;case"progress":return e.phase==="busy"?{...e,done:t.done,failed:t.failed}:e;case"finish":return e.phase==="busy"?{phase:"sent",total:e.total,failed:e.failed}:e;case"dismiss":return e.phase==="sent"?{phase:"idle"}:e}}async function zC(e,t,n){var d;const r=Math.max(1,Math.floor((n==null?void 0:n.concurrency)??3)),i=n!=null&&n.waves&&n.waves.length?n.waves.map(h=>[...h]):[[...e]];let o=0,c=0;const l=[];for(const h of i){if(!h.length)continue;if(n!=null&&n.batch){const g=o,y=c;let x=[];try{x=await n.batch(h,(k,v)=>{var N;return(N=n.on_progress)==null?void 0:N.call(n,g+k,y+v)})}catch(k){x=h.map(v=>({run_id:v,error:String((k==null?void 0:k.message)||k||"cancel failed")}))}for(const k of x)o+=1,k.error&&(c+=1,l.push({run_id:k.run_id,error:k.error}));(d=n.on_progress)==null||d.call(n,o,c);continue}let m=0;const _=async()=>{var g;for(;m<h.length;){const y=h[m++],x=await Zx(t,y);o+=1,x.type==="failed"&&(c+=1,l.push({run_id:y,error:x.error})),(g=n==null?void 0:n.on_progress)==null||g.call(n,o,c)}};await Promise.all(Array.from({length:Math.min(r,h.length)},_))}return{done:o,failed:c,failures:l}}function EW(e,t,n,r=0){const i=n??t,o=`Cancel all ${i} task${i===1?"":"s"} in ${AC[e]}`;return i<t||r>0?`${o} (${t} run${t===1?"":"s"} asked)`:o}function AW(e,t,n,r){const[i,o]=p.useReducer(CW,{phase:"idle"}),c=t.length,l=r==null?void 0:r.targets,d=l?l.ids:[...t],h=d.length,m=!!n&&c>0&&$W.includes(e),_=EW(e,l?l.cards:c,h,(l==null?void 0:l.parents)??0);return{state:i,enabled:m,label:_,ask:()=>o({type:"ask",total:h}),keep:()=>o({type:"keep"}),run:async()=>{n&&(o({type:"start",total:h}),await zC(d,n,{batch:r==null?void 0:r.on_cancel_runs,waves:l==null?void 0:l.waves,on_progress:(y,x)=>o({type:"progress",done:y,failed:x})}),o({type:"finish"}),window.setTimeout(()=>o({type:"dismiss"}),4e3))}}}function TW(e){return s.jsx("button",{type:"button",className:`btn mc_icon_btn mc_cancel mc_lane_cancel${e.open?" is_active":""}`,title:e.label,"aria-label":e.label,"aria-expanded":e.open,onClick:e.on_ask,children:s.jsx(qe,{name:"x",size:14})})}function MW(e){const{state:t}=e;if(t.phase==="confirm")return s.jsxs("div",{className:"mc_lane_band mc_lane_band_confirm",role:"group","aria-label":e.label,children:[s.jsxs("span",{className:"mc_lane_band_q",children:[e.label,"?"]}),s.jsx("span",{className:"mc_lane_band_reach",children:UW}),s.jsxs("span",{className:"mc_lane_band_actions",children:[s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",onClick:e.on_run,children:"Cancel all"}),s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:e.on_keep,children:"Keep"})]})]});if(t.phase==="busy")return s.jsxs("div",{className:"mc_lane_band mc_lane_band_progress",role:"status","aria-live":"polite",children:[s.jsx(qe,{name:"loader",size:14,className:"mc_spin"}),s.jsxs("span",{children:["cancelling ",t.done," / ",t.total,t.failed?` · ${t.failed} failed`:""]})]});if(t.phase==="sent"){const n=t.total-t.failed;return s.jsx("div",{className:"mc_lane_band mc_lane_band_progress",role:"status","aria-live":"polite",children:s.jsxs("span",{children:["cancel asked for ",n," task",n===1?"":"s",t.failed?` · ${t.failed} refused`:""]})})}return null}function RW(e){var i,o,c,l,d;(i=rl.lane)==null||i.call(rl,e.col);const t=`mc_column_title_${e.col}`,n=AW(e.col,((o=e.cancel)==null?void 0:o.run_ids)??[],(c=e.cancel)==null?void 0:c.on_cancel_run,{targets:(l=e.cancel)==null?void 0:l.targets,on_cancel_runs:(d=e.cancel)==null?void 0:d.on_cancel_runs}),r=e.count===null?" is_loading":e.count?"":" is_zero";return s.jsxs("section",{className:`mc_column mc_column_${e.col}`,"aria-labelledby":t,children:[s.jsxs("header",{className:"mc_column_head",children:[s.jsx("h2",{className:"mc_column_title",id:t,children:e.title}),n.enabled?s.jsx(TW,{label:n.label,open:n.state.phase!=="idle",on_ask:n.ask}):null,e.tools,s.jsx("span",{className:`mc_column_count${r}`,title:e.count===null?"loading":e.count_title,"aria-busy":e.count===null||void 0,children:e.count===null?"…":e.count}),e.after]}),n.enabled?s.jsx(MW,{state:n.state,label:n.label,on_run:()=>void n.run(),on_keep:n.keep}):null,e.children]})}const Ds=e=>e.stopPropagation(),LW=typeof window>"u"?p.useEffect:p.useLayoutEffect;function IW(e){const{line:t}=e.card;if(t.actor==="run"){const n=e.card.actor_run_label,r=n&&!t.text.includes(n)?`run ${va(n,28)}`:"subrun";return t.actor_run_id?s.jsx("button",{type:"button",className:"mc_actor mc_actor_run",title:`Open the subrun ${e.card.actor_run_label||""}`.trim(),onClick:i=>{i.stopPropagation(),e.on_open_run(t.actor_run_id)},onKeyDown:Ds,children:r}):s.jsx("span",{className:"mc_actor mc_actor_run",title:"Another run ends this wait; it is not listed yet",children:"run"})}return t.actor==="external"?s.jsx("span",{className:"mc_actor mc_actor_external",title:`An external system ends this wait: ${t.object||"an event"}`,children:"external"}):t.actor==="unknown"?s.jsx("span",{className:"mc_actor mc_actor_unknown",title:"Nothing on the wire says what ends this wait",children:"unknown"}):null}function OW(){return s.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[s.jsx("rect",{x:"5.5",y:"5.5",width:"8.5",height:"8.5",rx:"1.6"}),s.jsx("path",{d:"M10.5 3.6V3.1a1.6 1.6 0 0 0-1.6-1.6H3.1a1.6 1.6 0 0 0-1.6 1.6v5.8a1.6 1.6 0 0 0 1.6 1.6h.5"})]})}function Jx(e){const[t,n]=p.useState("");return s.jsx("button",{type:"button",className:`mc_copy${t?` is_${t}`:""}`,title:e.title??`Copy ${e.label}`,"aria-label":`Copy ${e.label}`,onClick:async r=>{r.stopPropagation(),n(await Mm(e.text)?"copied":"failed"),window.setTimeout(()=>n(""),1500)},onKeyDown:Ds,children:t==="copied"?"copied":t==="failed"?"copy failed":s.jsx(OW,{})})}const PW=320,DW=6;function FW(e){const[t,n]=p.useState(!1),r=e.text,i=r.length>PW||r.split(`
169
+ `).length>DW;return s.jsxs("div",{className:`mc_long${i&&!t?" is_folded":""}`,children:[s.jsx("div",{className:"mc_long_text",children:r}),i?s.jsx("button",{type:"button",className:"mc_long_toggle","aria-expanded":t,onClick:()=>n(!t),children:t?"show less":`show all (${r.length.toLocaleString("en-US")} chars)`}):null]})}function zW(e){var r,i;const t=e.row,n=!!((r=t.chips)!=null&&r.length)&&!t.long;return s.jsxs("div",{className:"mc_info_row","data-row":t.id,children:[s.jsxs("dt",{className:"mc_info_label",children:[t.label,t.source?s.jsx("span",{className:"mc_source",children:t.source}):null]}),s.jsxs("dd",{className:"mc_info_value",children:[(i=t.chips)!=null&&i.length?s.jsx("span",{className:"mc_tags",children:t.chips.map((o,c)=>s.jsx("code",{className:"mc_tag",children:o},`${o}:${c}`))}):null,n||!t.value?null:t.long?s.jsx(FW,{text:t.value}):s.jsx("span",{className:`mc_info_text${t.mono?" mono":""}`,children:t.value}),t.aside?s.jsx("span",{className:`mc_info_aside${t.aside_mono?" mono":""}`,children:t.aside}):null]}),s.jsx("dd",{className:"mc_info_copy",children:t.value||t.copy?s.jsx(Jx,{text:t.copy??t.value,label:(t.label||"value").toLowerCase()}):null})]})}function Ij(e,t){var d,h;const n=new Map;for(const m of t){const _=Qs(m);_&&n.set(_,m)}const r=m=>{var _;return String(((_=n.get(m))==null?void 0:_.role)||"").trim()==="controller"},i=Array.from(new Set(e.map(m=>String(m||"").trim()).filter(Boolean))),o=[];let c=0,l=0;for(const m of i){if(r(m))continue;c+=1;let _=m,g=String(((d=n.get(m))==null?void 0:d.parent_run_id)||"").trim();const y=new Set([m]);for(;g&&n.has(g)&&!y.has(g)&&!r(g);)_=g,y.add(g),g=String(((h=n.get(g))==null?void 0:h.parent_run_id)||"").trim();_!==m&&(l+=1),o.includes(_)||o.push(_)}return{ids:o,waves:o.length?[o]:[],cards:c,tasks:o.length,runs:c,parents:l}}const BW="Cancel this task: this run, its parents below the automation, and everything working under them";function BC(e,t){const n=e==null?void 0:e.ids[0];return!!(e&&n&&t&&n!==t)?"Cancel this task? Its parents and everything working under them stop too":"Cancel this run? Everything working under it stops too"}const UW="Everything working under those tasks stops too; automation schedules are not touched.";function WW(e){const[t,n]=p.useState(e.current),[r,i]=p.useState(!1),[o,c]=p.useState(""),l=!!e.on_rename,d=t.trim();return s.jsxs("div",{className:"mc_info_row mc_name_it_row","data-row":"name_it",children:[s.jsx("dt",{className:"mc_info_label",children:"Name it"}),s.jsxs("dd",{className:"mc_info_value",children:[s.jsxs("form",{className:"mc_name_it",onSubmit:async h=>{var m;if(h.preventDefault(),!(!e.on_rename||!d)){i(!0),c("");try{await e.on_rename(e.automation_id,d,e.revision),c("renamed"),(m=e.on_renamed)==null||m.call(e,e.automation_id)}catch(_){c(String((_==null?void 0:_.message)||(_==null?void 0:_.code)||_||"rename failed"))}finally{i(!1)}}},children:[s.jsx("input",{className:"mc_name_it_input","aria-label":"The automation's title",value:t,maxLength:200,disabled:!l||r,title:l?"The automation's title (the Automations page shows the same)":"Renaming is not available here",onChange:h=>n(h.target.value)}),s.jsx("button",{type:"submit",className:"btn mc_btn_sm",disabled:!l||r||!d||d===e.current,title:l?"Save the automation's title":"Renaming is not available here: this host does not wire automation revisions",children:r?"Saving":"Save"})]}),o?s.jsx("span",{className:"mc_name_it_msg",children:o}):null]}),s.jsx("dd",{className:"mc_info_copy"})]})}function UC(e){var i;const t=Kx(e.card);if(!t)return null;const n=String(((i=e.code_app)==null?void 0:i.url)||"").trim(),r=e.variant==="icon";return n?s.jsx("a",{className:r?"btn mc_icon_btn mc_open_code":"btn mc_btn_sm mc_btn_quiet mc_open_code",href:JU(n,t,e.card.run_id),target:"_blank",rel:"noreferrer",title:"Open this conversation in the AbstractCode web app (new tab)","aria-label":"Open in Code",onClick:Ds,onKeyDown:Ds,children:r?s.jsx(qe,{name:"terminal",size:15}):"Open in Code"}):s.jsx("span",{className:"mc_btn_wrap",title:Ej,children:s.jsx("button",{type:"button",className:r?"btn mc_icon_btn":"btn mc_btn_sm mc_btn_quiet",disabled:!0,title:Ej,"aria-label":"Open in Code",children:r?s.jsx(qe,{name:"terminal",size:15}):"Open in Code"})})}function Yx(e,t){switch(t.type){case"ask":return e.phase==="idle"?{phase:"confirm",error:""}:e;case"keep":return e.phase==="confirm"?{phase:"idle",error:""}:e;case"send":return e.phase==="confirm"?{phase:"busy",error:""}:e;case"done":return e.phase==="busy"?{phase:"sent",error:""}:e;case"failed":return e.phase==="busy"?{phase:"idle",error:t.error||"cancel failed"}:e}}const Xx={phase:"idle",error:""};async function Zx(e,t){try{const n=await e(t);return typeof n=="string"&&n?{type:"failed",error:n}:{type:"done"}}catch(n){return{type:"failed",error:String((n==null?void 0:n.message)||n||"cancel failed")}}}function Qx(e){const{phase:t,error:n}=e.state,r=e.question||"Cancel this run?",i=r.startsWith("Cancel this task")?"Cancel task":r.startsWith("Stop this subrun")?"Stop subrun":"Cancel run";return[t==="confirm"||t==="busy"?s.jsxs("span",{className:"mc_confirm",role:"group","aria-label":r,children:[s.jsx("span",{className:"mc_confirm_q",children:r}),s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",disabled:t==="busy",onClick:e.on_send,children:t==="busy"?"Cancelling":i}),s.jsx("button",{type:"button",className:"btn mc_btn_sm",disabled:t==="busy",onClick:()=>e.on_event({type:"keep"}),children:"Keep"})]},"confirm"):t==="sent"?s.jsx("span",{className:"mc_cancel_sent",children:"cancel requested"},"sent"):null,n?s.jsx("div",{className:"mc_act_error",role:"alert",children:n},"error"):null]}function WC(e){return s.jsx("button",{type:"button",className:e.variant==="icon"?"btn mc_icon_btn mc_cancel":"btn mc_btn_sm mc_btn_quiet mc_cancel",title:BW,"aria-label":"Cancel this task",onClick:()=>e.on_event({type:"ask"}),children:e.variant==="icon"?s.jsx(qe,{name:"x",size:15}):"Cancel"})}function qW(e){return s.jsxs(s.Fragment,{children:[e.state.phase==="idle"?WC(e):null,Qx(e)]})}function VW(e){var o;const[t,n]=p.useReducer(Yx,Xx),r=t.phase!=="idle"?(o=e.cancel_targets)==null?void 0:o.call(e,e.run_id):void 0,i=async()=>{n({type:"send"}),n(await qC(e.on_cancel_run,e.run_id,r,e.on_cancel_runs))};return s.jsx(qW,{state:t,on_event:n,on_send:()=>void i(),variant:e.variant,question:BC(r,e.run_id)})}async function qC(e,t,n,r){var o;if(!n||n.ids.length<=1)return Zx(e,(n==null?void 0:n.ids[0])||t);const i=await zC(n.ids,e,{batch:r,waves:n.waves});return i.failed?{type:"failed",error:`${i.failed} of ${i.done} cancels failed: ${((o=i.failures[0])==null?void 0:o.error)||"cancel failed"}`}:{type:"done"}}function HW(e){const{card:t}=e,n=t.automation,r=lW(t,{now_ms:e.now_ms,stall_after_ms:e.stall_after_ms,detail:e.detail,outcome:e.outcome,facts:e.facts,revision:e.revision}),i=t.role==="controller",o=t.automation_id&&e.on_open_automation?e.on_open_automation:null,c=!!(o||!i&&e.on_open_run||Kx(t)||Aj(t)&&e.on_cancel_run);return s.jsxs("div",{className:"mc_info_body",children:[r.map(l=>s.jsxs("section",{className:"mc_info_section","data-section":l.id,children:[s.jsx("h3",{className:"mc_info_section_title",children:l.title}),s.jsx("dl",{className:"mc_info_rows",children:l.rows.map(d=>s.jsxs(Ae.Fragment,{children:[s.jsx(zW,{row:d}),l.id==="automation"&&d.id==="title"&&(n!=null&&n.can_revise)?s.jsx(WW,{automation_id:t.automation_id,current:n.title,revision:e.revision??null,on_rename:e.on_rename_automation,on_renamed:e.on_renamed},`${t.automation_id}:${n.title}`):null]},d.id))})]},l.id)),t.automation_id&&!n?s.jsx("p",{className:"mc_info_note",children:"automation details are loading"}):null,c?s.jsxs("div",{className:"mc_info_actions",children:[o?s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>o(t.automation_id),children:"Open automation"}):null,!i&&e.on_open_run?s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>e.on_open_run(t.run_id),children:"Open run"}):null,s.jsx(UC,{card:t,code_app:e.code_app}),Aj(t)&&e.on_cancel_run?s.jsx(VW,{run_id:t.run_id,on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs,cancel_targets:e.cancel_targets}):null]}):null]})}const GW=500,KW=580;let hu=null;function ba(){hu!==null&&window.clearTimeout(hu),hu=null}function Oj(e,t=GW){var l;const n=e.getBoundingClientRect(),r=window.innerWidth,i=Math.min(t,r-16),o=(l=e.closest(".mc_card"))==null?void 0:l.getBoundingClientRect();if(o&&o.right+8+i<=r-8)return{top:Math.max(8,o.top),left:o.right+8,width:i,side:!0};if(o&&o.left-8-i>=8)return{top:Math.max(8,o.top),left:o.left-8-i,width:i,side:!0};const c=Math.min(Math.max(8,n.right-i),r-i-8);return{top:n.bottom+6,left:c,width:i,side:!1}}function JW(e){const{anchor:t,on_close:n,on_hover:r,...i}=e;return s.jsx(VC,{anchor:t,on_close:n,on_hover:r,label:`About ${e.card.title.text}`,children:s.jsx(HW,{...i})})}function VC(e){const t=p.useRef(null),n=e.width,[r,i]=p.useState(()=>e.anchor.current?Oj(e.anchor.current,n):null),o=p.useRef(e);return o.current=e,LW(()=>{var g;const c=t.current,l=(g=e.anchor.current)==null?void 0:g.getBoundingClientRect();if(!c||!l||!r)return;const d=c.offsetHeight,h=window.innerHeight;if(r.top+d<=h-8)return;const m=l.top-6-d,_=r.side?Math.max(8,h-8-d):m>=8?m:Math.max(8,h-8-d);_!==r.top&&i({...r,top:_})},[r==null?void 0:r.left,r==null?void 0:r.width,r==null?void 0:r.top,r==null?void 0:r.side]),p.useEffect(()=>{const c=h=>{h.key==="Escape"&&o.current.on_close(!0)},l=h=>{var _,g;const m=h.target;m&&((_=o.current.anchor.current)!=null&&_.contains(m)||(g=t.current)!=null&&g.contains(m))||o.current.on_close(!1)},d=()=>{const h=o.current.anchor.current;h&&i(Oj(h,o.current.width))};return document.addEventListener("keydown",c,!0),document.addEventListener("pointerdown",l,!0),window.addEventListener("resize",d),window.addEventListener("scroll",d,!0),()=>{document.removeEventListener("keydown",c,!0),document.removeEventListener("pointerdown",l,!0),window.removeEventListener("resize",d),window.removeEventListener("scroll",d,!0)}},[]),r?jg.createPortal(s.jsx("div",{ref:t,className:`mc_info_pop${e.className?` ${e.className}`:""}`,role:"dialog","aria-label":e.label,style:{top:r.top,left:r.left,width:r.width},onMouseEnter:()=>e.on_hover(!0),onMouseLeave:()=>e.on_hover(!1),onClick:Ds,onKeyDown:Ds,children:e.children}),document.body):null}function YW(e){const t=e.kind==="answer"?"Answer":e.kind==="task"?"Task":"Request",n=e.text.trim().split(/\s+/).filter(Boolean).length;return s.jsxs("div",{className:"mc_gp",children:[s.jsxs("div",{className:"mc_gp_head",children:[s.jsxs("span",{className:`mc_gp_kind mc_gp_kind_${e.kind}`,children:[s.jsx(qe,{name:e.kind==="answer"?"sparkle":"chat",size:14}),s.jsx("span",{children:t})]}),e.about?s.jsx("span",{className:"mc_gp_about",title:e.about,children:e.about}):null,s.jsxs("span",{className:"mc_gp_meta",children:[n.toLocaleString("en-US")," words · ",e.text.length.toLocaleString("en-US")," chars"]}),s.jsx(Jx,{text:e.text,label:`the full ${t.toLowerCase()}`,title:`Copy the full ${t.toLowerCase()}`}),e.on_close?s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_gp_close",title:"Close","aria-label":"Close",onClick:e.on_close,children:s.jsx(qe,{name:"x",size:14})}):null]}),s.jsx("div",{className:"mc_gp_body",children:s.jsx(Ni,{text:e.text,images:"link",className:"mc_pop_md"})}),e.on_open?s.jsx("div",{className:"mc_gp_foot",children:s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:e.on_open,children:"Open the run →"})}):null]})}function Wp(e){const[t,n]=p.useState(""),r=p.useRef(null),i=()=>{ba(),hu=window.setTimeout(()=>n(c=>c==="hover"?"":c),200)},o=e.kind==="answer"?"answer":e.kind==="task"?"task":"request";return s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:r,className:e.as_title?"mc_card_title mc_title_glimpse":`mc_glimpse mc_glimpse_${e.kind}`,title:`Read the full ${o}`,onMouseEnter:()=>{ba(),t||(hu=window.setTimeout(()=>n(c=>c||"hover"),150))},onMouseLeave:()=>t==="hover"?i():ba(),onClick:c=>{c.stopPropagation(),ba(),n(t==="pinned"?"":"pinned")},children:e.children}),t&&typeof document<"u"?s.jsx(VC,{anchor:r,label:`The full ${o}`,width:KW,className:"mc_pop_text",on_close:()=>n(""),on_hover:c=>c?ba():t==="hover"?i():void 0,children:s.jsx(YW,{kind:e.kind,text:e.full,about:e.about,on_open:e.on_open,on_close:()=>n("")})}):null]})}function XW(e){const[t,n]=p.useState(""),r=p.useRef(null),i=()=>{ba(),hu=window.setTimeout(()=>n(c=>c==="hover"?"":c),200)},o=e.card.role==="controller"?"About this automation":"About this run";return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:r,type:"button",className:"btn mc_icon_btn mc_info_btn",title:o,"aria-label":o,"aria-haspopup":"dialog","aria-expanded":t!=="",onClick:c=>{c.stopPropagation(),ba(),n(t==="pinned"?"":"pinned")},onKeyDown:Ds,onMouseEnter:()=>{ba(),t||(hu=window.setTimeout(()=>n(c=>c||"hover"),150))},onMouseLeave:()=>t==="hover"?i():ba(),children:s.jsx(qe,{name:"info",size:15})}),t&&typeof document<"u"?s.jsx(JW,{...e,anchor:r,on_close:c=>{var l;n(""),c&&((l=r.current)==null||l.focus())},on_hover:c=>c?ba():t==="hover"?i():void 0}):null]})}function ZW(e){const t=e.title.text;if(e.subject.kind==="agent"||e.subject.kind==="run"){const r=si(e.workflow_id);return{label:"",secondary:r&&r!==t?r:""}}const n=e.subject.label&&e.subject.label!==t?e.subject.label:"";return e.role==="controller"?{label:n,secondary:""}:{label:n,secondary:e.subject.secondary!==t?e.subject.secondary:""}}function HC(e){const{card:t}=e,n=e.busy||e.stale===!0,r=t.line.action,i=()=>e.on_open_run(t.run_id);return s.jsxs("div",{className:"mc_card_review_body",onClick:Ds,onKeyDown:Ds,children:[r==="approve"&&!t.wait_key?s.jsx("div",{className:"mc_card_line",title:"The wait has not registered a wait_key yet — open the run to inspect.",children:"wait key not published yet — open the run"}):null,s.jsx("div",{className:"mc_card_actions",children:r==="approve"&&t.wait_key?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn success mc_btn_sm",disabled:n,onClick:()=>e.on_act(t,{approved:!0}),children:n?"Resuming…":"Approve"}),s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",disabled:n,onClick:()=>e.on_act(t,{approved:!1}),children:"Reject"})]}):r==="resume"&&e.on_resume?s.jsx("button",{type:"button",className:"btn primary mc_btn_sm",disabled:n,onClick:()=>e.on_resume(t),children:n?"Resuming…":"Resume"}):r==="answer"?s.jsx("button",{type:"button",className:"btn primary mc_btn_sm",onClick:i,children:"Review & answer →"}):s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:i,children:"Open the run →"})})]})}function $w(e){const t=e.state.enabled&&!e.busy,n=e.busy?`${e.label}…`:e.state.enabled?[e.hint||e.label,e.state.reason].filter(Boolean).join(" — "):e.state.reason||"not available",r=s.jsx("button",{type:"button",className:`btn mc_icon_btn${e.className?` ${e.className}`:""}`,disabled:!t,title:n,"aria-label":e.label,onClick:e.onClick,children:s.jsx(qe,{name:e.busy?"loader":e.icon,size:15,className:e.busy?"mc_spin":void 0})});return t?r:s.jsx("span",{className:"mc_btn_wrap",title:n,children:r})}function qv(e){const t=e.parts.length;return s.jsx(s.Fragment,{children:e.parts.map((n,r)=>s.jsxs(Ae.Fragment,{children:[r?" ":null,s.jsxs("span",{className:"mc_unit",children:[n,r<t-1?s.jsx("span",{className:"mc_sep",children:" ·"}):null]})]},r))})}function QW(e){const{card:t}=e,n=t.automation,[r,i]=p.useReducer(nW,tW),o=n?DC(n,e.now_ms):null,c=n?sW(n,r):null,l=n?ZU({...n,growing_max_tokens:c}):null,d=!!(n!=null&&n.can_revise&&e.on_revise_automation),h=eW(r.custom),m=_=>{if(!n||!e.on_revise_automation||r.phase!=="choose")return;const g=e.on_revise_automation;i({type:"save",value:_,base:n.growing_max_tokens}),rW(g,n.automation_id,e.revision??null,_).then(y=>{var x;i(y),y.type==="saved"&&((x=e.on_renamed)==null||x.call(e,n.automation_id))})};return s.jsxs(s.Fragment,{children:[o?s.jsxs("div",{className:"mc_facts",children:[s.jsx("div",{className:"mc_fact_cell mc_fact_schedule",title:o.schedule.title||void 0,children:s.jsx(qv,{parts:o.schedule.parts})}),s.jsx("div",{className:`mc_fact_cell mc_fact_last${o.last.failed?" is_failed":""}`,title:o.last.title||void 0,children:s.jsx(qv,{parts:o.last.parts})}),o.last.failure?s.jsx("div",{className:"mc_fact_fail",title:o.last.failure,children:o.last.failure}):null]}):e.automation_loading?s.jsxs("div",{className:"mc_facts","aria-busy":"true",children:[s.jsx(wm,{what:"the schedule",width:"90%"}),s.jsx(wm,{what:"the last run",width:"80%"})]}):s.jsx("div",{className:"mc_card_state",children:s.jsx("span",{className:"mc_state_text",title:t.line.text,children:t.line.text})}),l&&l.mode==="growing"?s.jsxs("div",{className:"mc_ctx",onClick:Ds,onKeyDown:Ds,children:[s.jsxs("button",{type:"button",className:`mc_ctx_bar${r.phase==="saving"?" is_saving":""}`,"aria-expanded":r.phase!=="idle","aria-label":`${l.label}: change the budget`,disabled:!d||r.phase==="saving",title:d?`${l.used!==null?`${l.used.toLocaleString("en-US")} tokens of history were replayed into the last run`:"the last run recorded no history size"} · budget ${(c==null?void 0:c.toLocaleString("en-US"))??"unset"} tokens · click to change`:`${l.label} · the budget is changed on the Automations page`,onClick:()=>i({type:r.phase==="idle"?"open":"close"}),children:[l.ratio!==null?s.jsx("span",{className:"mc_ctx_track","aria-hidden":"true",children:s.jsx("span",{className:"mc_ctx_fill",style:{width:`${Math.round(l.ratio*100)}%`}})}):null,s.jsx("span",{className:"mc_ctx_label",children:l.label})]}),r.phase==="choose"?s.jsxs("div",{className:"mc_ctx_chooser",role:"group","aria-label":"Context budget",children:[XU.map(_=>s.jsx("button",{type:"button",className:`btn mc_btn_sm${_===c?" is_current":" mc_btn_quiet"}`,"aria-pressed":_===c,title:`${_.toLocaleString("en-US")} tokens`,onClick:()=>m(_),children:lc(_)},_)),s.jsxs("form",{className:"mc_ctx_custom",onSubmit:_=>{_.preventDefault(),h!==null&&m(h)},children:[s.jsx("input",{type:"number",className:"mc_ctx_input",min:1,step:1e3,placeholder:"custom","aria-label":"Custom context budget, in tokens",value:r.custom,onChange:_=>i({type:"custom",value:_.target.value})}),s.jsx("button",{type:"submit",className:"btn mc_btn_sm",disabled:h===null,title:h===null?"a whole number of tokens":`set the budget to ${h.toLocaleString("en-US")} tokens`,children:"Set"})]}),s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_ctx_close","aria-label":"Close",title:"Close",onClick:()=>i({type:"close"}),children:s.jsx(qe,{name:"x",size:15})})]}):null,r.error?s.jsx("div",{className:"mc_act_error",role:"alert",children:r.error}):null]}):l&&l.label?s.jsx("span",{className:"mc_ctx_chip",title:`${l.mode} context: every run starts from the task alone`,children:l.label}):null]})}const eq={busy:"",error:""},Pj={enabled:!1,reason:"commands are not wired on this host"},tq={enabled:!0},nq="Stop this subrun and everything under it? Its parent continues and may delegate again",sq="Stop this subrun and everything under it: its parent continues and may delegate again";function rq(e){if(!e)return"a subrun ended and this run was not resumed";if(e.status==="missing")return`its subrun ${e.subrun} no longer exists on the gateway, so this run cannot be resumed`;const t=e.status==="cancelled"?"was cancelled":e.status==="failed"?"failed":`ended ${e.status}`,n=e.ended_ms!==null?` ${er(e.ended_ms)} ago`:"";return`its subrun ${e.subrun} ${t}${n} and this run was not resumed`}function GC(e){const t=typeof e.since_ms=="number"?` since ${ic(fu(e.since_ms,e.now_ms))} ${ic(`(${er(Math.max(0,e.now_ms-e.since_ms))})`)}`:"";return s.jsxs("div",{className:"mc_ask mc_ask_stuck","data-run-id":e.run_id,role:"group","aria-label":"stuck",children:[s.jsxs("div",{className:"mc_ask_head",children:[s.jsx("button",{type:"button",className:"mc_ask_who",onClick:()=>e.on_open_run(e.run_id),onKeyDown:Ds,children:e.name})," ",s.jsxs("span",{className:"mc_ask_words",children:["stuck",t]})]}),s.jsxs("div",{className:"mc_stuck_why",children:[iq(rq(e.facts)),"."]}),s.jsxs("div",{className:"mc_card_actions",children:[e.on_cancel_task?s.jsx("button",{type:"button",className:"btn danger mc_btn_sm",onClick:e.on_cancel_task,children:"Cancel task"}):null,s.jsx("button",{type:"button",className:"btn mc_btn_sm",onClick:()=>e.on_open_run(e.run_id),children:"Open the run →"})]})]})}function iq(e){return e&&e[0].toUpperCase()+e.slice(1)}function oq(e){const{row:t}=e,[n,r]=p.useReducer(Yx,Xx),i=async()=>{e.on_cancel_run&&(r({type:"send"}),r(await Zx(e.on_cancel_run,t.run_id)))},o=!t.run_id;return s.jsxs("div",{className:`mc_chain_row${t.stuck?" is_stuck":""}${t.asks?" is_ask":""}${t.running?" is_running":""}`,style:{paddingLeft:`${Math.min(t.depth,5)*14}px`},"data-run-id":t.run_id||void 0,children:[s.jsxs("div",{className:"mc_chain_main",children:[t.depth>0?s.jsx("span",{className:"mc_chain_glyph","aria-hidden":"true",children:"└"}):null,o?s.jsx("span",{className:"mc_chain_name is_more",children:t.name}):s.jsx("button",{type:"button",className:"mc_chain_name",title:`Open ${t.title||t.name}`,onClick:()=>e.on_open_run(t.run_id),onKeyDown:Ds,children:t.name}),t.words?s.jsx("span",{className:"mc_chain_words",title:t.words,children:t.words}):null,e.on_cancel_run&&t.depth>0&&!o&&n.phase==="idle"?s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_cancel mc_chain_cancel",title:sq,"aria-label":`Stop subrun ${t.name} only`,onClick:()=>r({type:"ask"}),children:s.jsx(qe,{name:"x",size:13})}):null]}),n.phase!=="idle"||n.error?s.jsx("div",{className:"mc_chain_confirm",children:Qx({state:n,on_event:r,on_send:()=>void i(),question:nq})}):null]})}function aq(e){const{card:t}=e,n=t.stuck&&!t.asks.length?t.chain.find(o=>o.stuck):void 0,r=new Set((e.ask_loading||"").split(",").filter(Boolean)),i=o=>!!e.busy_wait&&e.busy_wait===`${o.run_id}:${o.wait_key}:${o.since_ms??""}`;return s.jsxs("div",{className:"mc_chain",onClick:Ds,onKeyDown:Ds,children:[t.chain.map((o,c)=>s.jsx(oq,{row:o,on_open_run:e.on_open_run,on_cancel_run:e.on_cancel_run},o.run_id||`more-${c}`)),t.asks.map(o=>{var h;const c=(h=e.ask_detail)==null?void 0:h[o.run_id],l=OC(o,c),d=Gx(o,e.now_ms);return s.jsxs("div",{className:"mc_ask","data-run-id":o.run_id,children:[s.jsxs("div",{className:"mc_ask_head",title:o.line.text,children:[s.jsx("button",{type:"button",className:"mc_ask_who",onClick:()=>e.on_open_run(o.run_id),onKeyDown:Ds,children:Bg(o.workflow_id)||Qd(o.run_id)})," ",s.jsxs("span",{className:"mc_ask_words",children:[d.who?`${d.who} · `:"",d.text]})]}),!l&&r.has(o.run_id)?s.jsx(wm,{what:"the request"}):l?s.jsx(Wp,{kind:"request",text:l.text,full:l.full,about:t.title.text,on_open:()=>e.on_open_run(o.run_id),children:l.text}):null,s.jsx(HC,{...e,card:o,detail:c,busy:i(o)})]},o.run_id)}),n?s.jsx(GC,{run_id:n.run_id,name:n.name,facts:n.stuck_facts,since_ms:n.since_ms,now_ms:e.now_ms,on_open_run:e.on_open_run,on_cancel_task:e.on_cancel_task}):null]})}function lq(e){var V,R;const{card:t}=e;(V=rl.card)==null||V.call(rl,t.run_id);const[n,r]=p.useReducer(Yx,Xx),[i,o]=p.useState(eq),c=t.status_word,l=ZW(t),d=t.role==="controller",h=t.chain.length>0,m=!d&&t.lane==="needs_you"&&!h,_=!d&&(t.lane==="needs_you"||t.lane==="working"||t.lane==="waiting_on"),g=m?OC(t,e.detail):null,y=d?null:KU(t,e.outcome),x=PC(t,e.outcome),k=m?Gx(t,e.now_ms):null,v=m&&!g&&e.detail_loading===!0,N=!d&&t.lane==="done"&&!y&&!t.failed&&e.outcome_loading===!0,$=t.title.untitled&&e.brief_loading===!0,C=_?e.on_cancel_run:void 0,S=n.phase!=="idle"&&C?(R=e.cancel_targets)==null?void 0:R.call(e,t.run_id):void 0,D=async()=>{C&&(r({type:"send"}),r(await qC(C,t.run_id,S,e.on_cancel_runs)))},O=M=>{!e.on_automation_command||i.busy||(o({busy:M,error:""}),oW(e.on_automation_command,t.automation_id,M).then(I=>{var L;o({busy:"",error:I||""}),I||(L=e.on_renamed)==null||L.call(e,t.automation_id)}))},A=d?iW(t.automation,i.busy!==""):null,P=n.phase!=="idle"||n.error||i.error,J=!(d||_&&(!!Kx(t)||!!C))&&x.length>0,G=x.length?s.jsx("div",{className:`mc_card_metrics${J?" mc_foot_metrics":""}`,title:t.lane==="done"?"run time · tokens of the run tree · tool calls · artifacts":"time since the run started · tokens of the run tree · tool calls",children:s.jsx(qv,{parts:x})}):null;return s.jsxs("div",{className:`mc_card mc_card_${t.lane}${t.failed?" mc_card_failed":""}${t.line.stalled?" mc_card_stalled":""}${d?" mc_card_automation":""}`,"data-lane":t.lane,"data-run-id":t.run_id,onClick:()=>e.on_open_run(t.run_id),role:"button",tabIndex:0,onKeyDown:M=>{M.key==="Enter"&&M.target===M.currentTarget&&e.on_open_run(t.run_id)},children:[s.jsxs("div",{className:"mc_card_head",children:[s.jsx("span",{className:`mc_card_glyph mc_glyph_${t.subject.kind}`,"aria-hidden":"true",children:t.subject.glyph}),$?s.jsx("span",{className:"mc_card_title",title:"loading the title…",children:s.jsx(go,{className:"mc_sk_title",width:"64%"})}):h||t.task?s.jsxs(Wp,{kind:"task",text:t.title.text,full:t.task||xg(t),about:t.subject.label||t.subject.secondary,on_open:()=>e.on_open_run(t.run_id),as_title:!0,children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(vb,{tone:"muted",size:"sm",className:"mc_untitled",title:"No title on the wire yet: the workflow id stands in",children:"untitled"})]}):null]}):s.jsxs("span",{className:"mc_card_title",title:xg(t),children:[t.title.text,t.title.untitled?s.jsxs(s.Fragment,{children:[" ",s.jsx(vb,{tone:"muted",size:"sm",className:"mc_untitled",title:"No title on the wire yet: the workflow id stands in",children:"untitled"})]}):null]}),s.jsx("span",{className:`mc_status ${Sa(c)}`,children:c==="unknown"?"?":c})]}),(l.label||l.secondary||t.archived)&&!(h&&!l.label&&!t.archived&&t.chain[0]&&(l.secondary===t.chain[0].name||l.secondary===si(t.workflow_id)))?s.jsxs("div",{className:"mc_card_subject",children:[l.label?s.jsx("span",{className:"mc_subject_label",title:l.label,children:l.label}):null,l.secondary?s.jsx("span",{className:"mc_subject_secondary",title:l.secondary,children:l.secondary}):null,t.archived?s.jsx("span",{className:"mc_pill","data-tag":"archived",title:"This conversation is archived: hidden from chat lists, kept here and in the ledger",children:"Archived"}):null]}):null,d?s.jsx(QW,{...e}):h?s.jsx(aq,{...e,on_cancel_task:C?()=>r({type:"ask"}):void 0}):N?s.jsx(wm,{what:"the answer"}):y?s.jsx(Wp,{kind:"answer",text:y.text,full:y.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:s.jsx(Ni,{text:y.text,images:"link",className:"mc_glimpse_md"})}):s.jsxs("div",{className:"mc_card_state",children:[s.jsx(IW,{card:t,on_open_run:e.on_open_run}),k?s.jsxs("span",{className:"mc_state_text",title:t.line.text,children:[k.who?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mc_who",title:`Started by ${k.who}`,children:k.who})," · "]}):null,k.text]}):s.jsx("span",{className:"mc_state_text",title:t.failed&&t.error?t.error:t.line.text!==t.line.brief?t.line.text:void 0,children:t.line.text}),t.line.stalled?s.jsx("span",{className:"mc_stall",role:"img","aria-label":"no progress",title:`No ledger step for ${er(t.line.stale_ms??0)}: past the ${RC(e.stall_after_ms)} threshold set in the Working lane's head`,children:" ⚠"}):null,t.line.action==="inspect"?s.jsxs(s.Fragment,{children:[" ",s.jsx("button",{type:"button",className:"mc_inspect",onClick:M=>{M.stopPropagation(),e.on_open_run(t.run_id)},onKeyDown:Ds,children:"Inspect →"})]}):null]}),v?s.jsx(wm,{what:"the request"}):g?s.jsx(Wp,{kind:"request",text:g.text,full:g.full,about:t.title.text,on_open:()=>e.on_open_run(t.run_id),children:g.text}):null,m&&t.line.stuck?s.jsx(GC,{run_id:t.run_id,name:Bg(t.workflow_id)||Qd(t.run_id),facts:t.line.stuck_facts,since_ms:t.since_ms,now_ms:e.now_ms,on_open_run:e.on_open_run,on_cancel_task:C?()=>r({type:"ask"}):void 0}):m?s.jsx(HC,{...e}):null,J?null:G,P?s.jsxs("div",{className:"mc_card_notice",onClick:Ds,onKeyDown:Ds,children:[Qx({state:n,on_event:r,on_send:()=>void D(),question:BC(S,t.run_id)}),i.error?s.jsx("div",{className:"mc_act_error",role:"alert",children:i.error}):null]}):null,s.jsxs("div",{className:`mc_card_foot${d?" mc_auto_foot":""}`,onClick:Ds,onKeyDown:Ds,children:[d&&A?s.jsxs(s.Fragment,{children:[s.jsx($w,{state:e.on_open_automation?tq:{enabled:!1,reason:"not available here"},label:"Open automation",hint:"Open this automation on the Automations page",icon:"loop",onClick:()=>{var M;return(M=e.on_open_automation)==null?void 0:M.call(e,t.automation_id)}}),s.jsx($w,{state:e.on_automation_command?A.run_now:Pj,label:"Run now",icon:"playCircle",busy:i.busy==="automation.run_now",onClick:()=>O("automation.run_now")}),s.jsx($w,{state:e.on_automation_command?A.toggle.state:Pj,label:A.toggle.label,icon:A.toggle.command==="automation.resume"?"play":"pause",busy:i.busy===A.toggle.command,onClick:()=>O(A.toggle.command)})]}):s.jsxs(s.Fragment,{children:[_?s.jsx(UC,{card:t,code_app:e.code_app,variant:"icon"}):null,C?n.phase==="idle"?WC({on_event:r,variant:"icon"}):s.jsx("span",{className:"mc_btn_wrap",title:n.phase==="sent"?"cancel requested":"Cancel this task? Answer just above",children:s.jsx("button",{type:"button",className:"btn mc_icon_btn mc_cancel is_active",disabled:!0,"aria-label":"Cancel this task",children:s.jsx(qe,{name:"x",size:15})})}):null]}),J?G:s.jsx("span",{className:"mc_spacer"}),d?null:s.jsx(Jx,{text:t.run_id,label:"the run id",title:t.run_id}),s.jsx(XW,{card:t,now_ms:e.now_ms,stall_after_ms:e.stall_after_ms,revision:e.revision,detail:e.detail,outcome:e.outcome,facts:e.facts,code_app:e.code_app,on_open_run:e.on_open_run,on_open_automation:e.on_open_automation,on_rename_automation:e.on_rename_automation,on_renamed:e.on_renamed,on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs,cancel_targets:e.cancel_targets})]})]})}const Dj=new WeakMap;let Fj=0;function cq(e){if(!e||typeof e!="object")return String(e??"");let t=Dj.get(e);return t===void 0&&(Fj+=1,t=Fj,Dj.set(e,t)),`#${t}`}function uq(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function dq(e,t){const n=e.line,r=e.row||{},i=e.role==="controller"&&e.automation?DC(e.automation,t):null;return[e.run_id,e.lane,e.status_word,e.role,e.workflow_id,e.wait_key,e.prompt,e.allow_free_text,e.failed,e.error,e.paused,e.archived,e.automation_id,e.actor_run_label,e.task,e.title.text,e.title.untitled,e.title.source,xg(e),e.subject.kind,e.subject.glyph,e.subject.label,e.subject.secondary,n.text,n.brief,n.verb,n.action,n.actor,n.actor_run_id,n.object,n.stalled,n.unresolved,typeof n.stale_ms=="number"?er(n.stale_ms):"",e.tool_names.join(","),uq(e.pending_calls),e.blocks.map(o=>`${o.run_id}:${o.title}`).join("|"),e.chain.map(o=>`${o.run_id}:${o.depth}:${o.words}:${o.stuck}:${o.asks}:${o.running}`).join("|"),e.asks.map(o=>Vv(o,t)).join("|"),String(e.stuck),e.since_ms,e.next_fire_ms,PC(e).join("·"),e.llm_calls,r.session_id,r.actor_id,r.pause_reason,r.created_at,r.updated_at,r.status,cq(e.automation),e.lane==="needs_you"?Gx(e,t).text:"",i?`${i.schedule.text}|${i.schedule.title}|${i.last.text}|${i.last.title}`:""].join("")}const zj=new WeakMap;function Vv(e,t){const n=zj.get(e);if(n&&n.now_ms===t)return n.sig;const r=dq(e,t);return zj.set(e,{now_ms:t,sig:r}),r}function fq(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(!(r==="card"||r==="now_ms")){if(r==="ask_detail"){const i=e[r]||{},o=t[r]||{},c=Object.keys(i),l=Object.keys(o);if(c.length!==l.length||c.some(d=>!Object.is(i[d],o[d])))return!1;continue}if(!Object.is(e[r],t[r]))return!1}return e.card===t.card&&e.now_ms===t.now_ms?!0:Vv(e.card,e.now_ms)===Vv(t.card,t.now_ms)}const hq=Ae.memo(lq,fq),Cw=8;function mq(e){var $t,ot,mt,et,Lt,ce,Se,He;($t=rl.page)==null||$t.call(rl);const t=Date.now(),[n,r]=p.useState(()=>MC(qU())),i=p.useMemo(()=>WU(e.runs,e.all_runs),[e.runs,e.all_runs]),o=p.useMemo(()=>[...i.active,...i.done],[i]),c=fU(e.client,o),l=mU(e.client,i.active),d=jU(),h=p.useMemo(()=>Object.fromEntries(bp.map(ne=>[ne,we=>d.attach(ne,we)])),[d.attach]),[m,_]=p.useState(""),[g,y]=p.useState(""),[x,k]=p.useState(!1),[v,N]=p.useState(()=>{try{const ne=localStorage.getItem("abstractobserver_done_window_v1");return ne&&ne in Wv?ne:Mj}catch{return Mj}}),$=p.useMemo(()=>Cj({active:i.active,done:i.done,pulses:l.map,automations:c.map,now_ms:Date.now(),stall_after_ms:n}),[i,l.map,c.map,n]),C=p.useMemo(()=>Rj($.done,v,Date.now()).visible,[$,v]),S=p.useMemo(()=>(x?C:C.slice(0,Cw)).map(ne=>ne.row),[C,x]),D=p.useMemo(()=>wj(bp.map(ne=>ne==="done"?S:$[ne].flatMap(we=>[we.row,...we.asks.map(fe=>fe.row)])),d.visible),[$,S,d.visible]),O=pU(e.client,D,i.active),A=p.useMemo(()=>new Set(i.active.map(ne=>Qs(ne))),[i.active]),P=gU(e.client,O.map,A),W=hU(e.client,D),J=p.useMemo(()=>wj([S],d.visible),[S,d.visible]),G=kU(e.client,J),V=p.useRef(new WeakMap),R=p.useMemo(()=>{const ne=new Map;for(const[we,fe]of c.records){const $e=fe.raw&&typeof fe.raw=="object"?fe.raw:null;let pe=$e?V.current.get($e):void 0;pe||(pe=dU(fe.raw),$e&&V.current.set($e,pe)),ne.set(we,pe)}return ne},[c.records]),M=p.useMemo(()=>W.map.size||O.map.size?Cj({active:i.active,done:i.done,details:O.map,fates:P.map,pulses:l.map,automations:c.map,run_briefs:W.map,now_ms:Date.now(),stall_after_ms:n}):$,[$,W.map,i,O.map,l.map,c.map,n]),I=p.useMemo(()=>Rj(M.done,v,t),[M.done,v]),L=bp.map(ne=>M[ne].map(we=>[we.run_id,...we.asks.map(fe=>fe.run_id)].join("+")).join(",")).join("|")+`|${x}|${v}`;p.useEffect(()=>{d.refresh()},[L,d.refresh]);const[K,H]=p.useState(""),[z,ee]=p.useState(null),B=e.entities===null,te=e.entities??[],se=ne=>`${ne.run_id}:${ne.wait_key}:${ne.since_ms??""}`;p.useEffect(()=>{m&&(M.needs_you.some(ne=>se(ne)===m||ne.asks.some(we=>se(we)===m))||_(""))},[M,m]);async function de(ne,we){_(se(ne)),y("");try{await e.on_resume_wait(ne.run_id,ne.wait_key,we)}catch(fe){y(`${ne.title.text}: ${String((fe==null?void 0:fe.message)||fe||"resume failed")}`),_("")}}async function be(ne){if(e.on_resume_run){_(se(ne)),y("");try{const we=await e.on_resume_run(ne.run_id);if(typeof we=="string"&&we)throw new Error(we)}catch(we){y(`${ne.title.text}: ${String((we==null?void 0:we.message)||we||"resume failed")}`),_("")}}}const Me=p.useRef(e);Me.current=e;const Ne=p.useRef(de);Ne.current=de;const ae=p.useRef(be);ae.current=be;const je=p.useRef(i.active);je.current=i.active;const Te=p.useMemo(()=>({open_run:ne=>Me.current.on_open_run(ne),open_automation:ne=>Me.current.on_open_automation(ne),rename:((ne,we,fe)=>Me.current.on_rename_automation(ne,we,fe)),revise:((ne,we,fe)=>Me.current.on_revise_automation(ne,we,fe)),command:((ne,we)=>Me.current.on_automation_command(ne,we)),cancel:(ne=>Me.current.on_cancel_run(ne)),cancel_batch:((ne,we)=>Me.current.on_cancel_runs(ne,we)),cancel_targets:ne=>Ij([ne],je.current),act:(ne,we)=>void Ne.current(ne,we),resume:ne=>void ae.current(ne)}),[]),Ve=String(((ot=e.code_app)==null?void 0:ot.url)||"").trim(),_t=p.useMemo(()=>Ve?{url:Ve}:null,[Ve]),Qe=p.useMemo(()=>ne=>{c.invalidate(ne),window.setTimeout(()=>c.invalidate(ne),2e3)},[c.invalidate]),it=ne=>({now_ms:t,stall_after_ms:n,busy:m===se(ne),on_open_run:Te.open_run,on_act:Te.act,on_resume:e.on_resume_run?Te.resume:void 0,on_open_automation:Te.open_automation,on_rename_automation:e.on_rename_automation?Te.rename:void 0,on_renamed:Qe,revision:ne.automation_id?c.revisions.get(ne.automation_id)??null:null,detail:O.map.get(ne.run_id),outcome:G.map.get(ne.run_id)??null,facts:ne.automation_id?R.get(ne.automation_id)??null:null,code_app:_t,on_cancel_run:e.on_cancel_run?Te.cancel:void 0,on_cancel_runs:e.on_cancel_runs?Te.cancel_batch:void 0,cancel_targets:Te.cancel_targets,ask_detail:ne.asks.length?Object.fromEntries(ne.asks.map(we=>[we.run_id,O.map.get(we.run_id)])):void 0,ask_loading:ne.asks.length?ne.asks.filter(we=>O.loading.has(we.run_id)).map(we=>we.run_id).join(","):void 0,busy_wait:ne.asks.length?m:void 0,stale:e.runs_stale===!0?!0:void 0,on_automation_command:e.on_automation_command?Te.command:void 0,on_revise_automation:e.on_revise_automation?Te.revise:void 0,detail_loading:O.loading.has(ne.run_id),brief_loading:W.loading.has(ne.run_id),outcome_loading:G.loading.has(ne.run_id),automation_loading:ne.automation_id?c.loading.has(ne.automation_id):!1});return s.jsxs("div",{className:"page page_scroll mc_page",children:[g?s.jsx("div",{className:"mc_error",children:g}):null,s.jsxs("div",{className:!B&&!te.length?jW:kW,"aria-busy":B||void 0,children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",!B&&e.entities_total>te.length?` (${te.length} of ${e.entities_total} — open the entity app for all)`:"",!B&&!te.length?s.jsx("span",{className:"muted mc_entities_none",children:" — no entities"}):null]}),s.jsx("a",{className:"mc_entity_link",href:e.entity_app_href,target:"_blank",rel:"noreferrer",children:"open the entity app →"})]}),e.entities_error?s.jsx("div",{className:"muted",children:e.entities_error}):null,B?s.jsxs("div",{className:"mc_entities_row",role:"status","aria-label":"loading entities",children:[s.jsx(ol,{what:"entities"}),s.jsx(NW,{n:e.entities_total?Math.min(e.entities_total,FC):SW})]}):null,te.length?s.jsx("div",{className:"mc_entities_row",children:te.map(ne=>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(ne.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[ne.error,ne.age_days!==null?`${ne.age_days.toFixed(0)} days old`:"",ne.last_moment].filter(Boolean).join(" — ")||ne.name,children:[s.jsx("span",{className:"mc_entity_name",children:ne.name}),(()=>{var st;const we=String(ne.live_phase||ne.state||"").trim(),fe=gW(we,e.phase_graph),$e=vW(e.phase_graph).has(fe)?fe:"other",pe=((st=e.phase_graph)==null?void 0:st.initial)??"sleep",le=/awake|idle/i.test(we)&&fe===pe,ze=we&&we.toLowerCase()!==fe?` — wire word: ${we}${le?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${$e}`,title:(ne.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+ze,children:fe})})(),ne.last_moment?s.jsx("span",{className:"mc_entity_moment",title:ne.last_moment,children:ne.last_moment.replace(/_/g," ")}):null,(()=>{if(ne.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 we=dW(ne.last_moment_at,t);return ne.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",we!==null?` · ${Sw(t-we,t)} ago`:""]}):we===null?null:we<=fW?s.jsx("span",{className:"mc_entity_live",title:`last moment ${Sw(t-we,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[Sw(t-we,t)," ago"]})})(),ne.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${ne.live_visit_tokens!==null?`; open visit: ${lc(ne.live_visit_tokens)} tk`:""}${ne.spend_warning?`; ${ne.spend_warning}`:""}`,children:[lc(ne.tokens_total)," tk",ne.live_visit_tokens!==null?` (+${lc(ne.live_visit_tokens)})`:"",ne.spend_warning?"*":""]}):null]}),ne.open_questions_total||ne.open_problems_total||ne.lessons_total||ne.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":K===ne.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>H(K===ne.name?"":ne.name),children:[ne.open_questions_total?`${ne.open_questions_total} question${ne.open_questions_total>1?"s":""}`:"",ne.open_problems_total?`${ne.open_problems_total} problem${ne.open_problems_total>1?"s":""}`:"",ne.lessons_total?`${ne.lessons_total} lesson${ne.lessons_total>1?"s":""}`:"",ne.dreams_brief?`night: ${ne.dreams_brief.count} signal${ne.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},ne.name))}):null,(()=>{if(!K)return null;const ne=te.find($e=>$e.name===K);if(!ne||!ne.open_questions.length&&!ne.open_problems.length&&!ne.lessons.length&&!ne.dreams_brief)return null;const we=e.on_read_diary?async $e=>{const pe=await e.on_read_diary(ne.name,$e);ee({entity:ne.name,entry:(pe==null?void 0:pe.entry)??pe,seq:typeof(pe==null?void 0:pe.read_recorded_at_seq)=="number"?pe.read_recorded_at_seq:null})}:void 0,fe=ne.open_questions_total-ne.open_questions.length+(ne.open_problems_total-ne.open_problems.length)+(ne.lessons_total-ne.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[ne.open_questions.map(($e,pe)=>s.jsx(ky,{kind:"question",label:$e.title||Nw($e.statement),entryId:$e.entry_id,onOpen:we,title:$e.statement||$e.title},`q_${$e.record_id||pe}`)),ne.open_problems.map(($e,pe)=>s.jsx(ky,{kind:"problem",label:$e.title||Nw($e.statement),entryId:$e.entry_id,onOpen:we,title:$e.statement||$e.title},`p_${$e.record_id||pe}`)),ne.lessons.map(($e,pe)=>s.jsx(ky,{kind:"lesson",label:$e.title||Nw($e.statement),entryId:$e.entry_id,onOpen:we,title:$e.statement||$e.title},`l_${$e.record_id||pe}`)),ne.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: ",ne.dreams_brief.count,ne.dreams_brief.dreams?` across ${ne.dreams_brief.dreams} dream${ne.dreams_brief.dreams>1?"s":""}`:"",ne.dreams_brief.kinds.length?` — ${ne.dreams_brief.kinds.slice(0,6).join(", ")}${ne.dreams_brief.kinds.length>6?` +${ne.dreams_brief.kinds.length-6} more`:""}`:"",ne.dreams_brief.felt_tones.length?` · felt: ${ne.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,fe>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",fe," more — open the entity app"]}):null]})})()]}),z?s.jsx(tc,{open:!0,title:`${z.entity} — diary entry`,onClose:()=>ee(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(mt=z.entry)!=null&&mt.kind?`kind: ${z.entry.kind}`:"",(et=z.entry)!=null&&et.visibility?`visibility: ${z.entry.visibility}`:"",(Lt=z.entry)!=null&&Lt.written_at?`written: ${z.entry.written_at}`:"",(ce=z.entry)!=null&&ce.entry_id?`id: ${z.entry.entry_id}`:""].filter(Boolean).join(" · ")}),s.jsxs("div",{className:"mc_diary_recorded muted",children:["this read was recorded in ",z.entity,"’s stream",z.seq!==null?` (seq ${z.seq})`:""]}),(Se=z.entry)!=null&&Se.gist?s.jsx("div",{className:"mc_diary_gist",children:String(z.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((He=z.entry)==null?void 0:He.text)||"(entry carries no text)")})]})}):null,!e.gateway_connected||e.runs_refreshed_at===null||e.runs_stale||e.notice?s.jsxs("div",{className:"mc_status_line",children:[e.gateway_connected?e.runs_refreshed_at===null?s.jsx("span",{className:"mc_notice mc_loading",role:"status",children:"loading runs…"}):e.runs_stale?s.jsxs("span",{className:"mc_notice mc_loading",role:"status",children:["board as of ",BU(e.runs_refreshed_at)," — refreshing…"]}):null:s.jsx("span",{className:"mc_notice is_bad",role:"status",children:"gateway unreachable: the lanes show the last runs read"}),e.gateway_connected&&e.notice?s.jsx("span",{className:"mc_notice is_bad",role:"status",children:e.notice}):null]}):null,s.jsx("div",{className:"mc_board",children:bp.map(ne=>{const we=ne==="done"?I.visible:M[ne],fe=ne==="done"&&!x?we.slice(0,Cw):we,$e=e.runs_refreshed_at===null||ne==="done"&&e.done_loaded===!1;return s.jsxs(RW,{col:ne,title:AC[ne],count:$e?null:we.length,count_title:ne==="done"&&I.hidden_count?`${I.hidden_count} older run(s) outside this window`:ne==="needs_you"&&we.length?`${we.length} task${we.length===1?"":"s"} · ${we.reduce((pe,le)=>pe+(le.asks.length||(le.line.lane==="needs_you"&&!le.stuck?1:0)),0)} asks`:void 0,cancel:{run_ids:we.map(pe=>pe.run_id),targets:Ij(we.map(pe=>pe.run_id),i.active),on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs},after:ne==="working"?s.jsxs("label",{className:"mc_stall_control",title:"No progress after: a running card whose last ledger step is older than this gets the mark ⚠ and floats to the top of Working",children:[s.jsxs("span",{className:"mc_stall_word","aria-hidden":"true",children:[s.jsx("span",{className:"mc_stall_mark",children:"⚠"})," after"]}),s.jsx("select",{className:"mc_window_select mc_stall_select","aria-label":"no progress after",value:String(n),onChange:pe=>{const le=Number(pe.target.value);r(le);try{localStorage.setItem(TC,String(le))}catch{}},children:Hx.map(pe=>s.jsx("option",{value:String(pe.ms),children:pe.label},pe.ms))})]}):null,tools:ne==="done"?s.jsx("select",{className:"mc_window_select",value:v,title:"Show terminal runs from this time window",onClick:pe=>pe.stopPropagation(),onChange:pe=>{const le=pe.target.value;N(le),k(!1);try{localStorage.setItem("abstractobserver_done_window_v1",le)}catch{}},children:Object.keys(Wv).map(pe=>s.jsx("option",{value:pe,children:kw[pe]},pe))}):null,children:[s.jsx("div",{className:"mc_column_hint muted",children:OU[ne]}),s.jsxs("div",{className:"mc_column_cards",ref:h[ne],"aria-busy":$e||void 0,children:[$e&&!fe.length?s.jsxs(s.Fragment,{children:[s.jsx(ol,{what:ne==="done"&&e.runs_refreshed_at!==null?"finished runs":"runs"}),s.jsx(bW,{n:xW[ne]})]}):null,fe.map(pe=>s.jsx(hq,{card:pe,...it(pe)},pe.run_id)),!we.length&&!$e?s.jsx("div",{className:"mc_empty muted",children:ne==="done"&&I.hidden_count?`none in the ${kw[v]} — ${I.hidden_count} older`:PU[ne]}):null,ne==="done"&&we.length>Cw&&!x?s.jsxs("button",{className:"btn mc_more",onClick:()=>k(!0),children:["show all ",we.length]}):null,ne==="done"&&I.hidden_count&&we.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",I.hidden_count," older outside ",kw[v]]}):null]})]},ne)})})]})}function Tt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function cn(e){return typeof e=="string"?e.trim():""}function Gn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function qp(e){return typeof e=="boolean"?e:null}function ti(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():String(t??"").trim()).filter(Boolean):null}function Bj(e){return typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):ti(e)}function mu(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function as(e){return Math.round(e).toLocaleString("en-US")}function KC(e){const t=Tt(e);return!!t&&(mu(t,"definition")||mu(t,"summary"))}function _q(e,t,n){var v,N,$,C;const r=Tt((v=Tt(t))==null?void 0:v.input_data),i=Tt((N=Tt(t))==null?void 0:N.workspace),o=KC(n)?n:null,c=o?Rm(o):n??null,l=Tt(o==null?void 0:o.definition),d=Tt(($=Tt(l==null?void 0:l.target))==null?void 0:$.input_data),h=Tt(d==null?void 0:d._runtime),m=Tt(l==null?void 0:l.policy),_={},g=(S,...D)=>{for(const[O,A]of D){const P=cn(A);if(P)return _[S]=O,P}return _[S]="",""},y=(S,D,...O)=>{for(const[A,P]of O){const W=D(P);if(W!==null)return _[S]=A,W}return _[S]="",[]},x=(S,...D)=>{for(const[O,A]of D){const P=Gn(A);if(P!==null)return _[S]=O,P}return _[S]="",null},k=S=>S&&S.length?S:null;return{model:g("model",["run",r==null?void 0:r.model],["automation",d==null?void 0:d.model],["automation",c==null?void 0:c.model]),provider:g("provider",["run",r==null?void 0:r.provider],["automation",d==null?void 0:d.provider],["automation",c==null?void 0:c.provider]),tools:y("tools",ti,["run",r==null?void 0:r.tools],["automation",d==null?void 0:d.tools],["automation",k(c==null?void 0:c.tools)]),tool_approval:g("tool_approval",["automation",m==null?void 0:m.tool_approval],["automation",c==null?void 0:c.tool_approval]),workspace_access_mode:g("workspace_access_mode",["run",i==null?void 0:i.workspace_access_mode],["run",r==null?void 0:r.workspace_access_mode],["automation",d==null?void 0:d.workspace_access_mode]),workspace_root:g("workspace_root",["run",(C=Tt(e))==null?void 0:C.workspace_root],["run",i==null?void 0:i.workspace_root],["run",r==null?void 0:r.workspace_root],["automation",c==null?void 0:c.workspace_root],["automation",d==null?void 0:d.workspace_root]),workspace_allowed_paths:y("workspace_allowed_paths",Bj,["run",i==null?void 0:i.workspace_allowed_paths],["automation",d==null?void 0:d.workspace_allowed_paths]),workspace_ignored_paths:y("workspace_ignored_paths",Bj,["run",i==null?void 0:i.workspace_ignored_paths],["automation",d==null?void 0:d.workspace_ignored_paths]),allowed_tools:y("allowed_tools",ti,["automation",h==null?void 0:h.allowed_tools]),max_iterations:x("max_iterations",["run",r==null?void 0:r.max_iterations],["automation",d==null?void 0:d.max_iterations],["automation",c==null?void 0:c.max_iterations]),untrusted_input_tools:y("untrusted_input_tools",ti,["automation",m==null?void 0:m.untrusted_input_tools]),email_allowed_recipients:y("email_allowed_recipients",ti,["automation",m==null?void 0:m.email_allowed_recipients]),source:_}}function JC(e){const t=Tt(e);if(!t)return null;if(Array.isArray(t.nodes))return t;const n=Tt(t.flow);return n&&Array.isArray(n.nodes)?n:null}function Hv(e){const t=Tt(e==null?void 0:e.data)||{};return cn(t.nodeType)||cn(e==null?void 0:e.type)}const pq=new Set(["exec-out","exec-in","exec"]);function Gv(e,t){const n=Tt(e==null?void 0:e.data)||{};return(Array.isArray(n[t])&&n[t].length?n[t]:Array.isArray(e==null?void 0:e[t])?e[t]:[]).filter(i=>{const o=Tt(i);if(!o)return!1;const c=cn(o.id);return!!c&&cn(o.type)!=="execution"&&!pq.has(c)})}function Uj(e,t,n,r){const i=cn(e.id),o=cn(e.type)||"any";return{id:i,label:cn(e.label)||i,type:o,typed:!0,required:e.required===!0,description:cn(e.description),state:t,value:n,flow_default:r}}function Wj(e,t,n){return{id:e,label:e,type:"any",typed:!1,required:!1,description:"",state:t,value:n,flow_default:null}}function gq(e,t,n){var A;const r=JC(e),i=r?r.nodes:[],o=i.find(P=>Hv(P)==="on_flow_start")||null,c=i.filter(P=>Hv(P)==="on_flow_end"),l=Tt(t),d=Tt(l==null?void 0:l.input_data),h=Tt((A=Tt(o==null?void 0:o.data))==null?void 0:A.pinDefaults)||{},m=[],_=new Set,g=P=>d?mu(d,P)?{state:"value",value:d[P]}:{state:"not_provided",value:void 0}:{state:"unknown",value:void 0};for(const P of o?Gv(o,"outputs"):[]){const W=cn(P.id);if(_.has(W))continue;_.add(W);const{state:J,value:G}=g(W),V=J==="not_provided"&&mu(h,W)?{value:h[W]}:null;m.push(Uj(P,J,G,V))}for(const P of Array.isArray(l==null?void 0:l.pin_ids)?l.pin_ids:[]){const W=cn(P);if(!W||_.has(W))continue;_.add(W);const{state:J,value:G}=g(W);m.push(Wj(W,J,G))}const y=d?Object.keys(d).filter(P=>!_.has(P)).map(P=>[P,d[P]]):[],x=Tt(n),k=!!x&&hs(x.status),v=x?x.output:void 0,N=Tt(v),$=P=>x?N&&mu(N,P)?{state:"value",value:N[P]}:{state:"absent",value:void 0}:{state:"unknown",value:void 0},C=[],S=new Set;for(const P of c)for(const W of Gv(P,"inputs")){const J=cn(W.id);if(S.has(J))continue;S.add(J);const{state:G,value:V}=$(J);C.push(Uj(W,G,V,null))}const D=c.length>0&&S.size===0;let O=[];if(D){const P=!!x&&v!==null&&v!==void 0;C.push(Wj("output",x?P?"value":"absent":"unknown",P?v:void 0))}else N?O=Object.keys(N).filter(P=>!S.has(P)).map(P=>[P,N[P]]):x&&v!==null&&v!==void 0&&(O=[["output",v]]);return{inputs:m,outputs:C,also_sent:y,also_returned:O,end_is_passthrough:D,flow_found:!!r,start_found:!!o,end_found:c.length>0,outputs_final:k}}function Ew(e,t,n=`${t}s`){return e===1?t:n}function yq(e){const t=[],n=e.dropped_counts_complete!==!1;if(e.replayed_messages!==null){const r=e.dropped_messages!==null&&n?e.replayed_messages+e.dropped_messages:null;let i=r!==null?`replayed ${as(e.replayed_messages)} of ${as(r)} ${Ew(r,"message")}`:`replayed ${as(e.replayed_messages)} ${Ew(e.replayed_messages,"message")}`;e.replayed_tokens!==null?i+=` (${as(e.replayed_tokens)}${e.max_tokens!==null?` of ${as(e.max_tokens)}`:""} tokens)`:e.max_tokens!==null&&(i+=` (budget ${as(e.max_tokens)} tokens)`),t.push(i)}else e.max_tokens!==null&&t.push(`history budget ${as(e.max_tokens)} tokens`);if(e.dropped_messages!==null)if(e.dropped_messages>0){const r=e.dropped_tokens!==null&&e.dropped_tokens>0?` (${as(e.dropped_tokens)} tokens)`:"";t.push(`${n?"":"at least "}${as(e.dropped_messages)} older ${Ew(e.dropped_messages,"message")} left out${r}`)}else t.push(n?"nothing left out":"left-out count incomplete");else e.dropped_counts_complete===!1&&t.push("left-out count incomplete");return e.oversize_turn_kept===!0&&t.push("the newest turn alone exceeds the budget and was kept whole"),t.join("; ")}function Kv(e){var l;const t=Tt(e),n=Tt(t==null?void 0:t.session_history),r=Tt((l=Tt(t==null?void 0:t.limits))==null?void 0:l.tokens);let i=null;if(r){const d=Gn(r.estimated_used),h=Gn(r.max_tokens),m=Gn(r.max_input_tokens),_=m??h,g=Gn(r.pct),y=g!==null?g*100:d!==null&&_!==null&&_>0?d/_*100:null,x=Gn(r.warn_tokens_pct);i={used:d,max_tokens:h,max_input_tokens:m,budget:_,pct:y,warn_pct:x,over_warn:y!==null&&x!==null&&y>=x}}const o=(ti(t==null?void 0:t.flow_warnings)||[]).filter(Boolean),c={replayed_messages:Gn(n==null?void 0:n.replayed_messages),replayed_tokens:Gn(n==null?void 0:n.replayed_tokens),max_tokens:Gn(n==null?void 0:n.max_tokens),dropped_messages:Gn(n==null?void 0:n.dropped_messages),dropped_tokens:Gn(n==null?void 0:n.dropped_tokens),dropped_counts_complete:qp(n==null?void 0:n.dropped_counts_complete),oversize_turn_kept:qp(n==null?void 0:n.oversize_turn_kept)};return{has_history:!!n,policy:cn(n==null?void 0:n.policy),...c,strict:qp(n==null?void 0:n.strict),token_estimator:cn(n==null?void 0:n.token_estimator),session_kind:cn(n==null?void 0:n.session_kind),tokens:i,flow_warnings:o,window_note:n?yq(c):""}}const wq=16;function ji(e){return String((e==null?void 0:e.run_id)||"").trim()}function Jv(e){return String((e==null?void 0:e.role)||"").trim()}function qj(e){return Vt(e.created_at||e.updated_at||"")??0}function vq(e,t){const n=String(e||"").trim();let r=t.get(n);if(!r)return n;const i=new Set;for(;r;){const o=ji(r);if(i.add(o),Jv(r)==="occurrence")return o;const c=String(r.parent_run_id||"").trim(),l=c?t.get(c):void 0;if(!l||i.has(c)||Jv(l)==="controller")return o;r=l}return n}function YC(e,t){const n=String(e||"").trim(),r=new Map,i=new Map;for(const y of t||[]){const x=ji(y);x&&r.set(x,y)}for(const y of r.values()){const x=String(y.parent_run_id||"").trim();if(!x||x===ji(y))continue;const k=i.get(x)||[];k.push(y),i.set(x,k)}if(!r.has(n))return{subject_id:n,root:null,controller:null,controller_id:"",subject_found:!1,size:0};const o=vq(n,r),c=r.get(o);let l=0;const d=new Set,h=(y,x)=>{const k=ji(y);d.add(k),l+=1;const v=x<wq?[...i.get(k)||[]].filter(N=>!d.has(ji(N))):[];return v.sort((N,$)=>qj(N)-qj($)||ji(N).localeCompare(ji($))),{run:y,depth:x,is_subject:k===n,children:v.map(N=>h(N,x+1))}},m=h(c,0);let _=null,g="";return Jv(c)==="occurrence"&&(g=String(c.parent_run_id||c.automation_id||"").trim(),_=g&&r.get(g)||null),{subject_id:n,root:m,controller:_,controller_id:g,subject_found:!0,size:l}}function XC(e){const t=[],n=r=>{t.push(r);for(const i of r.children)n(i)};return e&&n(e),t}function xq(e,t,n=Date.now()){const r=e&&"children"in e?e:(e==null?void 0:e.root)??null,i=new Map;for(const c of t||[]){const l=ji(c);l&&i.set(l,c)}const o=XC(r).map(c=>{const l=ji(c.run),d=i.get(l)??c.run,h=Gn(d==null?void 0:d.tokens_total),m=Gn(d==null?void 0:d.llm_calls),_=Gn(d==null?void 0:d.tool_calls),g=Gn(d==null?void 0:d.steps),y=Tm(c.run,n),x=String(c.run.status||"").trim().toLowerCase();return{run_id:l,depth:c.depth,workflow_id:String(c.run.workflow_id||"").trim(),status:x,is_subject:c.is_subject,duration_ms:y>=0?y:null,running:!hs(x),tokens_total:h,llm_calls:m,tool_calls:_,steps:g,has_metrics:h!==null||m!==null||_!==null||g!==null,inclusive:!0}});return{rows:o,inclusive:!0,any_metrics:o.some(c=>c.has_metrics)}}function gn(e,t){return{value:e,source:t,why:""}}function ts(e,t=""){return{value:null,source:t,why:e}}const Ps={wire:"not on this wire",no_default:"not provided, no default",not_automation:"not an automation run",automation_not_loaded:"automation definition not loaded",ledger_not_loaded:"ledger not loaded here",ledger_no_records:"no ledger records for this run in what is loaded",not_ended:"the run has not ended",flow_not_loaded:"flow not loaded",gateway_default:"gateway default (not reported on this wire)"};function Rd(e){return`${new Date(e).toISOString().slice(0,19).replace("T"," ")} UTC`}function bq(e){var r,i,o,c;const t=Cm(e),n=Tt((o=Tt((i=Tt((r=e.record)==null?void 0:r.result))==null?void 0:i.metadata))==null?void 0:o._provider_request);return{provider:t.provider||cn(n==null?void 0:n.provider),model:t.model||cn(n==null?void 0:n.model)||cn((c=Tt(n==null?void 0:n.payload))==null?void 0:c.model)}}function kq(e){var c,l,d,h,m;const t=Tt((l=Tt((c=e.started)==null?void 0:c.effect))==null?void 0:l.payload),n=Tt((h=Tt((d=e.record)==null?void 0:d.effect))==null?void 0:h.payload),r=Tt(t==null?void 0:t.vars)&&!((m=Tt(t==null?void 0:t.vars))!=null&&m.$slim)?Tt(t==null?void 0:t.vars):Tt(n==null?void 0:n.vars),i=Tt(r==null?void 0:r._runtime),o=Tt(r==null?void 0:r._limits);return{run_id:Am(e.record),workflow_id:cn(t==null?void 0:t.workflow_id)||cn(n==null?void 0:n.workflow_id),from_run_id:e.run_id,provider:cn(i==null?void 0:i.provider),model:cn(i==null?void 0:i.model),allowed_tools:ti(i==null?void 0:i.allowed_tools),max_iterations:Gn(o==null?void 0:o.max_iterations)}}function jq(e,t,n=[]){var _,g,y,x,k,v,N;const r={loaded:Array.isArray(e),subject_found:!1,runs:[],missing_run_ids:[],llm_calls:0,tool_calls:0,tool_failures:0,models:[],tools:[],subruns:[],allowlist:null,first_ms:null,last_ms:null};if(!Array.isArray(e))return r;const i=String(t||"").trim(),o=new Set;for(const $ of e){const C=String(($==null?void 0:$.run_id)||((_=$==null?void 0:$.record)==null?void 0:_.run_id)||"").trim();C&&($!=null&&$.record)&&o.add(C)}const c=new Map,l=new Map,d=[i,...n.map($=>String($||"").trim()).filter(Boolean)],h=new Set,m=[];for(;d.length;){const $=d.shift();if(!$||h.has($))continue;if(h.add($),!o.has($)){$!==i&&m.push($);continue}$===i&&(r.subject_found=!0);const C={run_id:$,llm_calls:0,tool_calls:0,tool_failures:0,steps:0};for(const S of Pg(e,$)){C.steps+=1;const D=Vt(S.started_at),O=Vt(S.ended_at);for(const A of[D,O])A!==null&&((r.first_ms===null||A<r.first_ms)&&(r.first_ms=A),(r.last_ms===null||A>r.last_ms)&&(r.last_ms=A));if(S.kind==="llm_call"){C.llm_calls+=1;const A=bq(S),P=`${A.provider}\0${A.model}`,W=c.get(P)||{provider:A.provider,model:A.model,calls:0,run_ids:[]};W.calls+=1,W.run_ids.includes($)||W.run_ids.push($),c.set(P,W)}else if(S.kind==="tool"){const A=Em(S),P=new Map;for(const J of A.calls){const G=P.get(J.name)||{calls:0,results:0,failures:0};G.calls+=1,P.set(J.name,G)}for(const J of A.results){const G=P.get(J.name)||{calls:0,results:0,failures:0};G.results+=1,J.success===!1&&(G.failures+=1),P.set(J.name,G)}for(const[J,G]of P){const V=Math.max(G.calls,G.results);C.tool_calls+=V,C.tool_failures+=G.failures;const R=l.get(J)||{name:J,calls:0,failures:0,run_ids:[],outside_declared:null};R.calls+=V,R.failures+=G.failures,R.run_ids.includes($)||R.run_ids.push($),l.set(J,R)}const W=ti((x=Tt((y=(g=S.started)==null?void 0:g.effect)==null?void 0:y.payload))==null?void 0:x.allowed_tools)??ti((N=Tt((v=(k=S.record)==null?void 0:k.effect)==null?void 0:v.payload))==null?void 0:N.allowed_tools);W!==null&&r.allowlist===null&&(r.allowlist=W)}else if(S.kind==="subflow"){const A=kq(S);r.subruns.push(A),A.run_id&&d.push(A.run_id)}}r.llm_calls+=C.llm_calls,r.tool_calls+=C.tool_calls,r.tool_failures+=C.tool_failures,r.runs.push(C)}return r.missing_run_ids=m,r.models=[...c.values()].sort(($,C)=>C.calls-$.calls||$.model.localeCompare(C.model)),r.tools=[...l.values()].sort(($,C)=>C.calls-$.calls||$.name.localeCompare(C.name)),r}function Sp(e,t){for(const[n,r]of e)if(r!=null)return gn(r,n);return ts(t)}function Cd(e){const t=cn(e);return t||null}function tu(e,t){const n=cn(e),r=cn(t);return n||r?{provider:n,model:r,calls:null}:null}const Sq=new Set(["controller","occurrence","descendant","discussion"]);function Nq(e,t,n,r,i,o,c=Date.now(),l={}){var mn,rn,Ht,is,Be,Qt,Ot,Fn,hn;const d=Tt(e),h=Tt(t),m=Tt(h==null?void 0:h.input_data),_=String(l.subject_run_id||(d==null?void 0:d.run_id)||(h==null?void 0:h.run_id)||((mn=l.row)==null?void 0:mn.run_id)||"").trim(),g=Array.isArray(o)?o:[],y=Xe=>g.find(sn=>String((sn==null?void 0:sn.run_id)||"").trim()===Xe),x={...y(_)||{},...l.row||{}};for(const Xe of["workflow_id","status","created_at","updated_at","role","occurrence_index","automation_id","parent_run_id","session_id","session_kind"])d&&d[Xe]!==void 0&&d[Xe]!==null&&d[Xe]!==""&&(x[Xe]=d[Xe]);const k=KC(r)?r:null,v=k?Rm(k):r??null,N=Tt(k==null?void 0:k.definition),$=Tt(k==null?void 0:k.summary),C=Tt((rn=Tt(N==null?void 0:N.target))==null?void 0:rn.input_data),S=Tt(C==null?void 0:C._runtime),D=Tt(N==null?void 0:N.policy),O=cn(x.role),A=!!cn(x.automation_id)||Sq.has(O)||cn(x.session_kind)==="automation",P=A?v?Ps.wire:Ps.automation_not_loaded:Ps.not_automation,W=JC(n),J=W&&W.nodes.find(Xe=>Hv(Xe)==="on_flow_start")||null,G=Tt((Ht=Tt(J==null?void 0:J.data))==null?void 0:Ht.pinDefaults),V=new Set(J?Gv(J,"outputs").map(Xe=>cn(Xe.id)):[]),R=Xe=>m&&mu(m,Xe)?void 0:G&&mu(G,Xe)?G[Xe]:void 0,M=YC(_,g),I=XC(M.root).filter(Xe=>ji(Xe.run)!==_&&$q(Xe,_,M.root)).map(Xe=>ji(Xe.run)),L=jq(i,_,I),K=L.loaded?Ps.ledger_no_records:Ps.ledger_not_loaded,H=L.loaded&&L.subject_found,z=_q(e,t,k??v),ee=Xe=>z.source[Xe]==="run"?"run":z.source[Xe]==="automation"?"automation":"",B=Tt(d==null?void 0:d.output),te=Tt(B==null?void 0:B.meta),se=cn(x.workflow_id)||cn(h==null?void 0:h.workflow_id),de=cn(h==null?void 0:h.bundle_version)||(se.includes("@")?se.split("@")[1].split(":")[0]:""),be=se?gn({id:se,name:si(se),version:de,flow_name:cn(W==null?void 0:W.name)},"run"):ts(Ps.wire),Me=A?v?gn({kind:"automation",title:v.title,id:v.automation_id},"automation"):ts(Ps.automation_not_loaded):cn(x.session_id)?gn({kind:"session",title:"",id:cn(x.session_id)},"run"):gn({kind:"run",title:"",id:_},"run"),Ne=cn(x.parent_run_id),ae=Ne?y(Ne):void 0,je=Gn(x.occurrence_index);let Te="";if(O==="occurrence")Te=je!==null?`run #${je}`:"automation run";else if(O==="controller")Te="automation controller (the schedule's own run)";else if(O==="discussion")Te="discussion of the automation";else if(Ne){const Xe=cn(ae==null?void 0:ae.role),sn=Gn(ae==null?void 0:ae.occurrence_index);Te=`subrun of ${Xe==="occurrence"&&sn!==null?`run #${sn}`:si(cn(ae==null?void 0:ae.workflow_id))||"a parent run (row not loaded)"}`}else Te=cn(x.session_id)?"run in a session":"top-level run";const Ve=gn({text:Te,parent_run_id:Ne},"run"),Qe=[["run",tu(m==null?void 0:m.provider,m==null?void 0:m.model)],["flow default",tu(R("provider"),R("model"))],["automation",tu(C==null?void 0:C.provider,C==null?void 0:C.model)],["automation",tu(S==null?void 0:S.provider,S==null?void 0:S.model)],["automation",k?null:tu(v==null?void 0:v.provider,v==null?void 0:v.model)]].find(([,Xe])=>Xe!==null)||null;let it;H&&L.models.length?it=gn(L.models.map(Xe=>({provider:Xe.provider,model:Xe.model,calls:Xe.calls})),"used"):tu(te==null?void 0:te.provider,te==null?void 0:te.model)?it=gn([tu(te==null?void 0:te.provider,te==null?void 0:te.model)],"output"):Qe?it=gn([Qe[1]],Qe[0]):it=ts(Ps.gateway_default,"gateway");let $t=null;if((it.source==="used"||it.source==="output")&&Qe&&it.value){const Xe=Qe[1];it.value.some(un=>(!Xe.provider||un.provider===Xe.provider)&&(!Xe.model||un.model===Xe.model))||($t=gn(Xe,Qe[0]))}const ot=m&&typeof m.system=="string"?gn(m.system,"run"):W?Cd(R("system"))!==null?gn(String(R("system")),"flow default"):V.has("system")?ts("none declared: not provided and the flow has no default","flow"):ts("the flow has no system pin","flow"):ts(Ps.flow_not_loaded),mt=Sp([["run",m&&typeof m.prompt=="string"&&m.prompt.trim()?m.prompt:null],["run",Cd((is=Tt(m==null?void 0:m.context))==null?void 0:is.task)],["flow default",Cd(R("prompt"))],["automation",Cd(C==null?void 0:C.prompt)],["automation",k?null:Cd(v==null?void 0:v.task)]],Ps.no_default),et=Sp([["run",ti(m==null?void 0:m.tools)],["flow default",ti(R("tools"))],["automation",ti(C==null?void 0:C.tools)],["automation",ti(S==null?void 0:S.allowed_tools)],["automation",k?null:(Be=v==null?void 0:v.tools)!=null&&Be.length?v.tools:null]],Ps.no_default),Lt=((Qt=L.subruns.find(Xe=>Xe.allowed_tools!==null))==null?void 0:Qt.allowed_tools)??null,ce=Sp([["used",H?L.allowlist:null],["used",H?Lt:null],["automation",ti(S==null?void 0:S.allowed_tools)],["automation",k?null:(v==null?void 0:v.allowed_tools)??null]],A?P:H?"the ledger shows no enforced allowlist":K),Se=et.value,He=H?gn(L.tools.map(Xe=>({...Xe,outside_declared:Se===null?null:!Se.includes(Xe.name)})),"used"):ts(K),ne=(Xe,sn)=>Xe!==null&&z.source[sn]?gn(Xe,ee(sn)):ts(P),we=ne(Cd(z.tool_approval),"tool_approval"),fe=ne(z.source.untrusted_input_tools?z.untrusted_input_tools:null,"untrusted_input_tools"),$e=ne(z.source.email_allowed_recipients?z.email_allowed_recipients:null,"email_allowed_recipients"),pe=(Xe,sn)=>z.source[sn]?gn(Xe,ee(sn)):ts(Ps.wire),le={mode:pe(z.workspace_access_mode,"workspace_access_mode"),root:pe(z.workspace_root,"workspace_root"),allowed_paths:pe(z.workspace_allowed_paths,"workspace_allowed_paths"),ignored_paths:pe(z.workspace_ignored_paths,"workspace_ignored_paths")},ze=y(_)||x,st=H?gn(L.llm_calls,"used"):Gn(ze==null?void 0:ze.llm_calls)!==null?gn(Gn(ze.llm_calls),"listing"):ts(K),kt=H?gn({calls:L.tool_calls,failures:L.tool_failures},"used"):Gn(ze==null?void 0:ze.tool_calls)!==null?gn({calls:Gn(ze.tool_calls),failures:null},"listing"):ts(K),pt=M.root?((Ot=bg(M.root,_))==null?void 0:Ot.children)||[]:[],jt=H?gn(L.subruns,"used"):pt.length?gn(pt.map(Xe=>({run_id:ji(Xe.run),workflow_id:cn(Xe.run.workflow_id),from_run_id:_,provider:"",model:"",allowed_tools:null,max_iterations:null})),"listing"):ts(L.loaded?Ps.ledger_no_records:"none among the loaded rows; ledger not loaded here"),ct=[];if(B)for(const[Xe,sn]of Object.entries(B)){const un=Tt(sn);un&&Object.keys(un).length===1&&typeof un.$artifact=="string"&&un.$artifact.trim()&&ct.push({pin:Xe,id:un.$artifact.trim()})}const It=hs(x.status);let vt;d?It?B&&typeof B.response=="string"&&B.response.trim()?vt=gn(B.response,"output"):typeof d.output=="string"&&d.output.trim()?vt=gn(d.output,"output"):cn(d.error)?vt=gn(cn(d.error),"run"):vt=ts("the output carries no response text"):vt=ts(Ps.not_ended):vt=ts("run detail not loaded");const nn=Vt(x.created_at||""),wn=It?Vt(x.updated_at||""):null,On=Tm(x,c),Ks=On>=0?gn(On,"run"):L.first_ms!==null&&L.last_ms!==null?gn(L.last_ms-L.first_ms,"used"):ts(Ps.wire),rs=H?((Fn=L.subruns.find(Xe=>Xe.max_iterations!==null))==null?void 0:Fn.max_iterations)??null:null,ge=Sp([["used",rs],["run",Gn(m==null?void 0:m.max_iterations)],["flow default",Gn(R("max_iterations"))],["automation",Gn(C==null?void 0:C.max_iterations)],["automation",k?null:(v==null?void 0:v.max_iterations)??null]],Ps.no_default),Le=Gn(te==null?void 0:te.iterations)!==null?gn(Gn(te==null?void 0:te.iterations),"output"):ts(It?"the output carries no iteration count":Ps.not_ended),yt=Kv(e).tokens,re=Tt($==null?void 0:$.trigger)||Tt(N==null?void 0:N.trigger),he=Tt(re==null?void 0:re.config),Ee=v!=null&&v.cadence?gn({text:v.cadence,start_ms:Vt((he==null?void 0:he.start_at)||"")},"automation"):ts(P),Ie=A?gn({index:je,count:v?v.occurrence_count:null},v?"automation":"run"):ts(Ps.not_automation),We=Gn(he==null?void 0:he.count)!==null?gn(Gn(he==null?void 0:he.count),"automation"):ts(A&&re?"no count limit":P,A&&re?"automation":""),Ue=Vt((he==null?void 0:he.until)||""),tt=Ue!==null?gn(Ue,"automation"):ts(A&&re?"no end date":P,A&&re?"automation":""),ut=Tt(D==null?void 0:D.retry),xt=Tt(ut==null?void 0:ut.backoff),bt=D?gn({max_attempts:Gn(ut==null?void 0:ut.max_attempts),backoff_initial:cn(xt==null?void 0:xt.initial),backoff_factor:Gn(xt==null?void 0:xt.factor),backoff_max:cn(xt==null?void 0:xt.max),failure:cn(D.failure),misfire:cn(D.misfire),serial:qp(D.serial)},"automation"):ts(P),Mt=N&&Array.isArray((hn=Tt(N.notify))==null?void 0:hn.channels)?gn(ti(N.notify.channels),"automation"):ts(P),zt=Kv(e),lt=v!=null&&v.context_mode||zt.has_history?gn({mode:(v==null?void 0:v.context_mode)||"",growing_max_tokens:(v==null?void 0:v.growing_max_tokens)??null,replayed_messages:zt.replayed_messages,replayed_tokens:zt.replayed_tokens,dropped_messages:zt.dropped_messages,dropped_tokens:zt.dropped_tokens},v!=null&&v.context_mode?"automation":"run"):ts(A?P:"no session history on this run"),Yt=le.root.value?gn(le.root.value,le.root.source):ts(Ps.wire);let vn;if(!A)vn=ts(Ps.not_automation);else if(!v)vn=ts(Ps.automation_not_loaded);else{const Xe=v.status;if(Xe==="paused")vn=gn({kind:"none",at_ms:null,text:"no next run (paused)"},"automation");else if(Xe==="completed")vn=gn(v.last&&je!==null&&v.last.index===je?{kind:"last",at_ms:null,text:"this was the last (stop reached)"}:{kind:"none",at_ms:null,text:"no next run (completed: stop reached)"},"automation");else if(Xe==="archived")vn=gn({kind:"none",at_ms:null,text:"no next run (archived)"},"automation");else if(Xe==="failed")vn=gn({kind:"none",at_ms:null,text:"no next run (the automation failed)"},"automation");else if(v.next_fire_ms!==null){const sn=sm(v.next_fire_ms-c);vn=gn({kind:"next_at",at_ms:v.next_fire_ms,text:`next run at ${Rd(v.next_fire_ms)}${sn?` (in ${sn})`:""}`},"automation")}else if(cn(re==null?void 0:re.source_id)==="manual")vn=gn({kind:"on_trigger",at_ms:null,text:"next run when someone runs it"},"automation");else if(v.event_driven||uc(re)){const sn=v.cadence||"when something new arrives";vn=gn({kind:"on_trigger",at_ms:null,text:`next run ${sn.charAt(0).toLowerCase()}${sn.slice(1)}`},"automation")}else vn=ts("no next fire time on this wire","automation")}return{subject_id:_,is_automation:A,who:{workflow:be,subject:Me,role:Ve,model:it,model_declared:$t,system_prompt:ot,task:mt},access:{tools_allowed:et,runtime_allowlist:ce,tools_called:He,tool_approval:we,untrusted_input_tools:fe,email_recipients:$e,operator_email:cn(S==null?void 0:S.operator_email),workspace:le},does:{llm_calls:st,tool_calls:kt,subruns:jt,artifacts:ct,outcome:vt,children_not_loaded:L.missing_run_ids},how_long:{started_ms:nn,finished_ms:wn,running:!It,duration:Ks,max_iterations:ge,iterations_used:Le,tokens:yt,cadence:Ee,next_fire_ms:(v==null?void 0:v.next_fire_ms)??null,occurrence:Ie,stop_after:We,stop_at:tt,retry:bt},after:{notify:Mt,context:lt,outputs_to:Yt,next:vn},ledger:L}}function bg(e,t){if(ji(e.run)===t)return e;for(const n of e.children){const r=bg(n,t);if(r)return r}return null}function $q(e,t,n){const r=n?bg(n,t):null;return!!r&&r!==e&&!!bg(r,ji(e.run))}const Cq=["status","updated_at","current_node","paused","error","waiting"],Eq=["workflow_id","created_at","parent_run_id","session_id","automation_id","role","occurrence_index","session_kind"];function ZC(e,t){if(!t||typeof t!="object"||String(t.run_id||"").trim()&&String(t.run_id).trim()!==String(e.run_id||"").trim())return!1;const n=Vt(e.updated_at||""),r=Vt(t.updated_at||"");return n===null||r===null?!0:r>=n}function QC(e,t){if(!t||typeof t!="object")return e;const n={...e};for(const r of Eq)(n[r]===void 0||n[r]===null||n[r]==="")&&t[r]!==void 0&&t[r]!==null&&(n[r]=t[r]);if(ZC(e,t))for(const r of Cq)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function Aq(e,t){const n=String(t.run_id||"").trim();let r=!1;const i=(e||[]).map(o=>String((o==null?void 0:o.run_id)||"").trim()!==n?o:(r=!0,{...o,...t}));return r||i.push(t),i}function ns(e){return s.jsx("p",{className:`ap_note ap_note_${e.kind}`,role:e.kind==="error"?"alert":void 0,children:e.children})}function cc(e){return s.jsxs("section",{className:"ap_block","data-block":e.id,"aria-labelledby":`ap_${e.id}_title`,children:[s.jsxs("header",{className:"ap_block_head",children:[s.jsx("h2",{id:`ap_${e.id}_title`,className:"ap_block_title",children:e.title}),e.meta?s.jsx("span",{className:"ap_block_meta",children:e.meta}):null]}),e.children]})}const Tq={approve:"Review approval",answer:"Answer",resume:"Resume",open_subrun:"Open subrun",inspect:"Inspect"};function eE(e,t,n,r){return V1(e,t,n??null,r??null)}function Mq(e,t){const n=Tq[e.action],r=e.action==="open_subrun"?e.actor_run_id:t;return n&&r?{action:e.action,label:n,run_id:r}:null}function Rq(e){const{line:t}=e;if(t.actor==="none")return null;if(t.actor==="run"&&t.actor_run_id){const r=e.ctx.by_id.get(t.actor_run_id),i=si(String((r==null?void 0:r.workflow_id)||""))||"subrun (row not loaded)";return s.jsxs("button",{type:"button",className:"ap_actor ap_actor_run",title:`Ended by run ${t.actor_run_id}`,onClick:()=>e.on_open_run(t.actor_run_id),children:["run ",i]})}const n=t.actor==="run"?"a run":t.actor;return s.jsx("span",{className:`ap_actor ap_actor_${t.actor}`,title:"Who ends this state",children:n})}function Lq(e){return s.jsx("button",{type:"button",className:"btn btn_icon ap_copy",title:`Copy run id ${e.run_id}`,"aria-label":"Copy run id",onClick:()=>{e.on_copy?e.on_copy(e.run_id):Mm(e.run_id)},children:"⧉"})}const Iq={used:"Read from the run's ledger: what it actually did",output:"Read from the run's own output",run:"Read from this run's detail and inputs","flow default":"The flow's default for a pin the run was not sent (the runtime applies it)",flow:"Read from the flow declaration",automation:"Read from the automation definition, not from this run's inputs",listing:"Read from the run listing: counts include every run below this one",gateway:"The gateway's own default; this wire does not report it"};function tE(e){return e.source?s.jsx("span",{className:"ap_source","data-source":e.source,title:Iq[e.source],children:e.source}):null}function Oq(e){return s.jsx("span",{className:"ap_absent",children:e.fact.source==="gateway"?e.fact.why:`— ${e.fact.why||"not on this wire"}`})}function ka(e){return s.jsxs("div",{className:"ap_prow ap_copyable","data-row":e.id,children:[s.jsx("dt",{className:"ap_prow_label",children:e.label}),s.jsx("dd",{className:"ap_prow_value",children:e.children}),s.jsxs("dd",{className:"ap_prow_meta",children:[s.jsx(tE,{source:e.source||""}),e.copy?s.jsx(zg,{text:e.copy,label:e.label.toLowerCase()}):null]})]})}function es(e){const{fact:t}=e,n=t.value!==null;return s.jsx(ka,{id:e.id,label:e.label,source:t.source,copy:n?e.copy?e.copy(t.value):al(t.value):null,children:n?e.render?e.render(t.value):s.jsx(am,{value:t.value}):s.jsx(Oq,{fact:t})})}function Jl(e){return e.items.length?s.jsx("span",{className:"ap_tags",children:e.items.map((t,n)=>s.jsx("code",{className:"ap_tag",children:t},`${t}:${n}`))}):s.jsx("span",{className:"ap_muted",children:e.empty||"none"})}function Oh(e){return s.jsxs("section",{className:"ap_pgroup","data-group":e.id,"aria-labelledby":`ap_pg_${e.id}`,children:[s.jsxs("h3",{className:"ap_pgroup_title",id:`ap_pg_${e.id}`,children:[e.title," ",s.jsx("span",{className:"ap_pgroup_q",children:e.question})]}),s.jsx("dl",{className:"ap_ptable",children:e.children})]})}function Aw(e){return[e.provider,e.model].filter(Boolean).join(" · ")||"model not recorded on the call"}function Pq(e,t){if(e.length!==t.length)return!1;const n=new Set(e);return t.every(r=>n.has(r))}function ga(e,t,n=`${t}s`){return`${as(e)} ${e===1?t:n}`}function Dq(e){var D,O;const{prof:t,p:n,line:r,ctx:i}=e,o=[];n.loading.input_data&&o.push(s.jsx(ns,{kind:"loading",children:"loading the run's inputs…"},"li")),n.errors.input_data&&o.push(s.jsxs(ns,{kind:"error",children:["inputs unavailable: ",n.errors.input_data]},"ei")),n.loading.detail&&o.push(s.jsx(ns,{kind:"loading",children:"loading the run detail…"},"ld")),n.errors.detail&&o.push(s.jsxs(ns,{kind:"error",children:["run detail unavailable: ",n.errors.detail]},"ed")),n.loading.flow&&o.push(s.jsx(ns,{kind:"loading",children:"loading the flow (its defaults)…"},"lf")),n.loading.records&&o.push(s.jsx(ns,{kind:"loading",children:"loading the ledger…"},"lr")),n.errors.records&&o.push(s.jsxs(ns,{kind:"error",children:["ledger unavailable: ",n.errors.records]},"er")),t.is_automation&&!n.automation_body&&!n.automation&&o.push(s.jsx(ns,{kind:"absent",children:"automation definition not loaded: tool policy unknown"},"na"));const c=A=>{const P=i.by_id.get(A);return si(String((P==null?void 0:P.workflow_id)||""))||"a run (row not loaded)"},l=(A,P)=>s.jsx("button",{type:"button",className:"ap_link_btn ap_run_link",title:`Open run ${A}`,"data-run-id":A,onClick:()=>n.on_open_run(A),children:P}),{who:d,access:h,does:m,how_long:_,after:g}=t,y=h.workspace,x=y.root.value&&n.on_reveal_workspace?s.jsx("button",{type:"button",className:"ap_link_btn",onClick:()=>{var A;return(A=n.on_reveal_workspace)==null?void 0:A.call(n)},children:"show folder"}):null,k=t.ledger.runs,v=A=>k.length>1?s.jsx("span",{className:"ap_breakdown",children:k.map((P,W)=>s.jsxs("span",{"data-run-id":P.run_id,children:[W?" · ":"",as(A(P))," ",P.run_id===t.subject_id?"in this run":s.jsxs(s.Fragment,{children:["in ",l(P.run_id,c(P.run_id))]})]},P.run_id))}):null,N=m.children_not_loaded,$=N.length?s.jsxs("span",{className:"ap_breakdown","data-children-not-loaded":N.length,children:["children's calls live in their own view (",ga(N.length,"subrun")," not loaded here:"," ",N.map((A,P)=>s.jsxs("span",{children:[P?", ":"",l(A,c(A))]},A)),")"]}):null,C=A=>A.source==="listing"?s.jsx("span",{className:"ap_breakdown",children:"tree-inclusive: this run and every run below it"}):null,S=A=>s.jsx(Jl,{items:A.map(P=>P==="self"&&h.operator_email?`self (${h.operator_email})`:P),empty:"none"});return s.jsxs(cc,{id:"profile",title:"Agent profile",meta:"who it is · what it can reach · what it does · for how long · what comes after",children:[o,s.jsxs("div",{className:"ap_profile",children:[s.jsxs(Oh,{id:"who",title:"Who",question:"is this agent",children:[s.jsx(es,{id:"workflow",label:"Workflow",fact:d.workflow,render:A=>s.jsxs("span",{children:[A.name||A.id,A.flow_name?s.jsxs("span",{className:"ap_muted",children:[" · flow “",A.flow_name,"”"]}):null]}),copy:A=>A.id}),s.jsx(es,{id:"subject",label:"Subject",fact:d.subject,render:A=>A.kind==="automation"?s.jsx(am,{value:A.title||"untitled automation"}):s.jsx("span",{children:A.kind==="session"?"a session (id on copy)":"a standalone run (id on copy)"}),copy:A=>A.id}),s.jsx(es,{id:"role",label:"Role",fact:d.role,render:A=>{var P,W;return s.jsxs("span",{children:[A.text,A.parent_run_id&&t.is_automation&&((P=_.occurrence.value)==null?void 0:P.count)!==null&&((W=_.occurrence.value)==null?void 0:W.count)!==void 0&&A.text.startsWith("run #")?s.jsxs("span",{className:"ap_muted",children:[" of ",as(_.occurrence.value.count)," so far"]}):null,A.parent_run_id?s.jsxs(s.Fragment,{children:[" · ",l(A.parent_run_id,"open parent")]}):null]})},copy:A=>A.parent_run_id||A.text}),s.jsx(es,{id:"model",label:"Model · provider",fact:d.model,render:A=>{var P;return s.jsxs("span",{className:"ap_stack",children:[A.map((W,J)=>s.jsxs("span",{children:[Aw(W),W.calls!==null?s.jsxs("span",{className:"ap_muted",children:[" × ",ga(W.calls,"call")]}):null]},J)),(P=d.model_declared)!=null&&P.value?s.jsxs("span",{className:"ap_finding",children:["asked for ",Aw(d.model_declared.value)," ",s.jsx(tE,{source:d.model_declared.source})]}):null]})},copy:A=>A.map(Aw).join(`
170
+ `)}),s.jsx(es,{id:"system",label:"System prompt",fact:d.system_prompt}),s.jsx(es,{id:"task",label:"Task",fact:d.task})]}),s.jsxs(Oh,{id:"access",title:"Access",question:"what it may use",children:[s.jsx(es,{id:"tools_allowed",label:"May call",fact:h.tools_allowed,render:A=>s.jsx(Jl,{items:A})}),s.jsx(es,{id:"runtime_allowlist",label:"Runtime allowlist",fact:h.runtime_allowlist,render:A=>h.tools_allowed.value&&A.length&&Pq(A,h.tools_allowed.value)?s.jsxs("span",{children:["the same ",ga(A.length,"tool")," as above"]}):s.jsx(Jl,{items:A})}),s.jsx(es,{id:"tools_called",label:"Did call",fact:h.tools_called,render:A=>s.jsxs("span",{className:"ap_stack",children:[A.length?s.jsx("span",{className:"ap_tags",children:A.map(P=>s.jsxs("span",{className:`ap_tool_use ${P.outside_declared?"ap_tool_outside":""}`,"data-tool":P.name,children:[s.jsxs("code",{className:"ap_tag",children:[P.name," × ",as(P.calls),P.failures?`, ${as(P.failures)} failed`:""]}),P.outside_declared?s.jsx("span",{className:"ap_finding",children:"called outside the declared list"}):null]},P.name))}):s.jsx("span",{className:"ap_muted",children:"none in the loaded ledger"}),$]})}),s.jsx(es,{id:"tool_approval",label:"Tool approval",fact:h.tool_approval,render:A=>s.jsx("span",{children:A})}),s.jsx(es,{id:"untrusted_input_tools",label:"Untrusted-input tools",fact:h.untrusted_input_tools,render:A=>s.jsx(Jl,{items:A})}),s.jsx(es,{id:"email_recipients",label:"Email recipients",fact:h.email_recipients,render:S}),s.jsx(es,{id:"workspace",label:"Workspace",fact:y.mode,render:A=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("span",{children:A||"mode not set"}),y.root.value?s.jsx("code",{className:"ap_path",children:y.root.value}):null,x]}),copy:A=>y.root.value?`${A}
171
+ ${y.root.value}`:A}),y.allowed_paths.value!==null?s.jsx(es,{id:"allowed_paths",label:"Allowed paths",fact:y.allowed_paths,render:A=>s.jsx(Jl,{items:A})}):null,y.ignored_paths.value!==null?s.jsx(es,{id:"ignored_paths",label:"Ignored paths",fact:y.ignored_paths,render:A=>s.jsx(Jl,{items:A})}):null]}),s.jsxs(Oh,{id:"does",title:"Does",question:"what it did",children:[s.jsx(ka,{id:"now",label:"Now",source:"run",copy:r.text,children:s.jsx("span",{className:r.stalled?"ap_stalled_text":void 0,children:r.text})}),s.jsx(es,{id:"llm_calls",label:"LLM calls",fact:m.llm_calls,render:A=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:as(A)}),m.llm_calls.source==="used"?v(P=>P.llm_calls):C(m.llm_calls)]})}),s.jsx(es,{id:"tool_calls",label:"Tool calls",fact:m.tool_calls,render:A=>s.jsxs("span",{className:"ap_stack",children:[s.jsxs("span",{children:[as(A.calls),A.failures?`, ${as(A.failures)} failed`:A.failures===0&&A.calls?", none failed":""]}),m.tool_calls.source==="used"?v(P=>P.tool_calls):C(m.tool_calls),m.tool_calls.source==="used"?$:null]})}),s.jsx(es,{id:"subruns",label:"Delegated subruns",fact:m.subruns,render:A=>A.length?s.jsx("span",{className:"ap_stack",children:A.map((P,W)=>{const J=[[P.provider,P.model].filter(Boolean).join(" · "),P.allowed_tools!==null?ga(P.allowed_tools.length,"tool"):"",P.max_iterations!==null?`max ${as(P.max_iterations)} iterations`:""].filter(Boolean),G=si(P.workflow_id)||"subrun";return s.jsxs("span",{className:"ap_subrun",children:[P.run_id?l(P.run_id,G):s.jsxs("span",{children:[G," (not started yet)"]}),J.length?s.jsxs("span",{className:"ap_muted",children:[" · handed ",J.join(" · ")]}):null]},`${P.run_id}:${W}`)})}):s.jsx("span",{className:"ap_muted",children:"none"})}),m.artifacts.length?s.jsx(ka,{id:"artifacts",label:"Artifacts",source:"output",copy:m.artifacts.map(A=>A.id).join(`
172
+ `),children:s.jsxs("span",{children:[ga(m.artifacts.length,"artifact"),": ",s.jsx(Jl,{items:m.artifacts.map(A=>A.pin)})]})}):null,s.jsx(es,{id:"outcome",label:"Outcome",fact:m.outcome})]}),s.jsxs(Oh,{id:"how_long",title:"How long",question:"it runs and may run",children:[s.jsx(ka,{id:"started",label:"Started",source:_.started_ms!==null?"run":"",copy:_.started_ms!==null?new Date(_.started_ms).toISOString():null,children:_.started_ms!==null?s.jsx("span",{children:Rd(_.started_ms)}):s.jsx("span",{className:"ap_absent",children:"— not on this wire"})}),s.jsx(ka,{id:"finished",label:"Finished",source:_.finished_ms!==null?"run":"",copy:_.finished_ms!==null?new Date(_.finished_ms).toISOString():null,children:_.finished_ms!==null?s.jsx("span",{children:Rd(_.finished_ms)}):s.jsx("span",{className:"ap_muted",children:_.running?"so far (still active)":"— not on this wire"})}),s.jsx(es,{id:"duration",label:"Duration",fact:_.duration,render:A=>s.jsxs("span",{children:[bu(A),_.running?" so far":""]}),copy:A=>String(A)}),s.jsx(es,{id:"max_iterations",label:"Max iterations",fact:_.max_iterations}),s.jsx(es,{id:"iterations_used",label:"Iterations used",fact:_.iterations_used}),s.jsx(ka,{id:"token_limit",label:"Token limit",source:_.tokens?"run":"",copy:_.tokens?al(((O=(D=n.detail)==null?void 0:D.limits)==null?void 0:O.tokens)??_.tokens):null,children:_.tokens&&(_.tokens.used!==null||_.tokens.budget!==null)?s.jsxs("span",{children:[_.tokens.used!==null?as(_.tokens.used):"—",_.tokens.budget!==null?` of ${as(_.tokens.budget)}`:""," tokens",_.tokens.pct!==null?` (${_.tokens.pct<10&&_.tokens.pct>0?_.tokens.pct.toFixed(1):Math.round(_.tokens.pct)}%)`:""]}):s.jsx("span",{className:"ap_absent",children:"— no token estimate on this run"})}),s.jsx(es,{id:"cadence",label:"Cadence",fact:_.cadence,render:A=>s.jsxs("span",{children:[A.text,A.start_ms!==null?s.jsxs("span",{className:"ap_muted",children:[" · since ",Rd(A.start_ms)]}):null,_.next_fire_ms!==null?s.jsxs("span",{children:[" · next ",Rd(_.next_fire_ms)]}):null]})}),s.jsx(es,{id:"occurrences",label:"Occurrences",fact:_.occurrence,render:A=>s.jsxs("span",{children:[A.index!==null?`#${as(A.index)}`:"this run",A.count!==null?` of ${as(A.count)} so far`:""," · ",_.stop_after.value!==null?`stops after ${ga(_.stop_after.value,"scheduled occurrence")}`:_.stop_after.why," · ",_.stop_at.value!==null?`stops at ${Rd(_.stop_at.value)}`:_.stop_at.why]})}),s.jsx(es,{id:"retry",label:"Retry policy",fact:_.retry,render:A=>s.jsx("span",{children:[A.max_attempts!==null?ga(A.max_attempts,"attempt"):"",A.backoff_initial?`backoff ${A.backoff_initial}${A.backoff_factor!==null?` ×${A.backoff_factor}`:""}${A.backoff_max?` up to ${A.backoff_max}`:""}`:"",A.failure?`on failure: ${A.failure}`:"",A.misfire?`misfire: ${A.misfire}`:"",A.serial===!0?"serial":A.serial===!1?"may overlap":""].filter(Boolean).join(" · ")||"no retry fields set"})})]}),s.jsxs(Oh,{id:"after",title:"After",question:"what it may do next",children:[s.jsx(es,{id:"notify",label:"Notifies",fact:g.notify,render:A=>s.jsx(Jl,{items:A.map(P=>P==="email"?"email → the owner's registered address (not on this wire)":P),empty:"nobody (no channel)"})}),s.jsx(es,{id:"context_plan",label:"Context",fact:g.context,render:A=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:A.mode==="growing"?`growing${A.growing_max_tokens!==null?` (cap ${as(A.growing_max_tokens)} tokens)`:""}: each occurrence replays the session so far`:A.mode==="independent"?"independent: each occurrence starts fresh":A.mode||"session history"}),A.replayed_messages!==null||A.replayed_tokens!==null?s.jsxs("span",{className:"ap_muted",children:["this run replayed ",A.replayed_messages!==null?ga(A.replayed_messages,"message"):"?",A.replayed_tokens!==null?` (${as(A.replayed_tokens)} tokens)`:"",A.dropped_messages!==null?`, left out ${ga(A.dropped_messages,"message")}${A.dropped_tokens?` (${as(A.dropped_tokens)} tokens)`:""}`:""]}):null]})}),s.jsx(es,{id:"outputs_to",label:"Outputs go to",fact:g.outputs_to,render:A=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("code",{className:"ap_path",children:A}),x,m.artifacts.length?s.jsxs("span",{className:"ap_muted",children:["· ",ga(m.artifacts.length,"artifact")," in the output"]}):null]})}),s.jsx(es,{id:"next",label:"Next",fact:g.next,render:A=>s.jsx("span",{children:A.text}),copy:A=>A.at_ms!==null?new Date(A.at_ms).toISOString():A.text})]})]})]})}function Fq(e){const{p:t}=e,n=p.useMemo(()=>gq(t.flow,t.input_data,t.detail),[t.flow,t.input_data,t.detail]),r=n.inputs.filter(l=>l.state==="value").length,i=t.loading.flow?s.jsx(ns,{kind:"loading",children:"loading the flow…"}):t.errors.flow?s.jsxs(ns,{kind:"error",children:["the flow did not load (",t.errors.flow,"): pin types unknown"]}):n.flow_found?n.start_found?null:s.jsx(ns,{kind:"absent",children:"the flow has no On Flow Start node"}):s.jsx(ns,{kind:"absent",children:"no flow JSON for this run: pin types unknown"}),o=t.loading.input_data?s.jsx(ns,{kind:"loading",children:"loading the run's inputs…"}):t.errors.input_data?s.jsxs(ns,{kind:"error",children:["inputs unavailable: ",t.errors.input_data]}):t.input_data?s.jsx(ns,{kind:"info",children:"values as the run holds them now: the gateway reads the run's current variables, so a pin the run writes back (context) shows its latest value"}):null,c=t.loading.detail?s.jsx(ns,{kind:"loading",children:"loading the run detail…"}):t.errors.detail?s.jsxs(ns,{kind:"error",children:["output unavailable: ",t.errors.detail]}):n.flow_found&&!n.end_found?s.jsx(ns,{kind:"absent",children:"the flow has no On Flow End node"}):n.end_is_passthrough?s.jsx(ns,{kind:"info",children:"the end declares no pins: the run returns its last node's output"}):t.detail&&!n.outputs_final?s.jsx(ns,{kind:"info",children:"values appear when the run ends"}):null;return s.jsxs(cc,{id:"pins",title:"Inputs → Outputs",children:[i,s.jsxs("div",{className:"ap_io",children:[s.jsxs("div",{className:"ap_io_col",children:[s.jsxs("h3",{className:"ap_io_title",children:["Inputs",n.inputs.length?s.jsxs("span",{className:"ap_io_meta",children:[n.inputs.length," pin",n.inputs.length===1?"":"s",t.input_data?` · ${r} provided`:""]}):null]}),o,s.jsx(uk,{side:"in",label:"Inputs",pins:n.inputs,also:n.also_sent,also_label:"also sent",empty_text:n.flow_found||t.input_data?"no input pins":"—"})]}),s.jsx("div",{className:"ap_io_arrow","aria-hidden":"true",children:"→"}),s.jsxs("div",{className:"ap_io_col",children:[s.jsxs("h3",{className:"ap_io_title",children:["Outputs",n.outputs.length?s.jsx("span",{className:"ap_io_meta",children:n.end_is_passthrough?"pass-through":`${n.outputs.length} pin${n.outputs.length===1?"":"s"}`}):null]}),c,s.jsx(uk,{side:"out",label:"Outputs",pins:n.outputs,also:n.also_returned,also_label:"also returned",outputs_final:n.outputs_final,empty_text:n.flow_found?"no output pins":"—"})]})]})]})}function zq(e){var l,d,h;const{p:t}=e,n=p.useMemo(()=>Kv(t.detail),[t.detail]);if(t.loading.detail&&!t.detail)return s.jsx(cc,{id:"context",title:"Context",children:s.jsx(ns,{kind:"loading",children:"loading the run detail…"})});if(!t.detail)return s.jsx(cc,{id:"context",title:"Context",children:t.errors.detail?s.jsxs(ns,{kind:"error",children:["run detail unavailable: ",t.errors.detail]}):s.jsx(ns,{kind:"absent",children:"run detail not loaded"})});const r=n.tokens,i=(r==null?void 0:r.pct)!==null&&(r==null?void 0:r.pct)!==void 0?`${r.pct<10&&r.pct>0?r.pct.toFixed(1):Math.round(r.pct)}%`:"",o=[n.policy,n.strict===!0?"strict":"",n.session_kind?`${n.session_kind} session`:""].filter(Boolean),c=(l=t.detail)==null?void 0:l.session_history;return s.jsx(cc,{id:"context",title:"Context",children:s.jsxs("dl",{className:"ap_ptable",children:[s.jsx(ka,{id:"window",label:"Window",source:n.has_history?"run":"",copy:n.has_history?al(c):null,children:n.has_history?s.jsx("span",{className:"ap_window_note",children:n.window_note||"the session-history receipt carries no counts"}):s.jsx("span",{className:"ap_absent",children:"— no session history replayed into this run"})}),n.has_history?s.jsxs(ka,{id:"history_policy",label:"History policy",source:"run",copy:o.length?o.join(" · "):null,children:[o.length?o.join(" · "):s.jsx("span",{className:"ap_absent",children:"— not on this wire"}),n.token_estimator?s.jsx("span",{className:"ap_source",title:n.token_estimator,children:"estimated"}):null]}):null,s.jsx(ka,{id:"tokens",label:"Tokens",source:r?"run":"",copy:r?al(((h=(d=t.detail)==null?void 0:d.limits)==null?void 0:h.tokens)??r):null,children:r&&(r.used!==null||r.budget!==null)?s.jsxs("span",{className:`ap_gauge_wrap ${r.over_warn?"ap_gauge_over":""}`,children:[s.jsxs("span",{className:"ap_gauge_text",children:[r.used!==null?as(r.used):"—",r.budget!==null?` of ${as(r.budget)}`:"",r.max_input_tokens!==null?" input":""," tokens",i?` (${i})`:"",r.warn_pct!==null?` · warns at ${r.warn_pct}%`:""]}),r.pct!==null?s.jsxs("span",{className:"ap_gauge",role:"meter","aria-label":"Context tokens used","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(Math.min(100,r.pct)),children:[s.jsx("span",{className:"ap_gauge_fill",style:{width:`${Math.min(100,Math.max(0,r.pct))}%`}}),r.warn_pct!==null?s.jsx("span",{className:"ap_gauge_warn",style:{left:`${Math.min(100,Math.max(0,r.warn_pct))}%`}}):null]}):null]}):s.jsx("span",{className:"ap_absent",children:"— no token estimate on this run"})}),s.jsx(ka,{id:"flow_warnings",label:"Flow warnings",source:t.detail?"run":"",copy:n.flow_warnings.length?n.flow_warnings.join(`
173
+ `):null,children:n.flow_warnings.length?s.jsx("ul",{className:"ap_warnings",children:n.flow_warnings.map((m,_)=>s.jsx("li",{children:m},_))}):s.jsx("span",{className:"ap_muted",children:"none"})})]})})}function nE(e){const t=si(String(e.workflow_id||""))||"(workflow?)";return String(e.role||"").trim()==="occurrence"&&typeof e.occurrence_index=="number"?`run #${e.occurrence_index} · ${t}`:t}function sE(e){const{node:t,ctx:n}=e,r=t.run,i=ef(r,n),o=eE(r,i),c=String(r.run_id||"");return s.jsxs("li",{className:"ap_tree_item",children:[s.jsxs("button",{type:"button",className:`ap_tree_node ${t.is_subject?"ap_tree_subject":""}`,"aria-current":t.is_subject?"true":void 0,title:`Open run ${c}`,"data-run-id":c,onClick:()=>e.on_open_run(c),children:[s.jsx("span",{className:`chip ${Sa(o)}`,children:o}),s.jsx("span",{className:"ap_tree_name",children:nE(r)}),s.jsx("span",{className:`ap_tree_line ${i.stalled?"ap_stalled":""}`,children:i.text})]}),t.children.length?s.jsx("ul",{className:"ap_tree_children",children:t.children.map(l=>s.jsx(sE,{node:l,ctx:n,on_open_run:e.on_open_run},String(l.run.run_id)))}):null]})}function Np(e){return e===null?"—":as(e)}function Bq(e){var C,S;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=p.useMemo(()=>QC(e.run,e.detail),[e.run,e.detail]),r=String(n.run_id||"").trim(),i=ZC(e.run,e.detail),o=p.useMemo(()=>e.automation??(e.automation_body?Rm(e.automation_body):null),[e.automation,e.automation_body]),c=p.useMemo(()=>Aq(e.runs||[],n),[e.runs,n]),l=p.useMemo(()=>{const D=new Map;e.detail&&i&&D.set(r,e.detail);const O=new Map;return o!=null&&o.automation_id&&O.set(o.automation_id,o),Sx(c,{now_ms:t,details:D,pulses:e.pulses,automations:O,stall_after_ms:e.stall_after_ms})},[c,e.detail,i,r,o,t,e.pulses,e.stall_after_ms]),d=ef(n,l),h=H1(n,l),m=String(((S=(C=e.input_data)==null?void 0:C.input_data)==null?void 0:S.prompt)||"").trim(),_=G1(n,l,m?{excerpt:m}:null),g=eE(n,d,tg(e.detail),e.automation),y=[h.label&&h.label!==_.text?h.label:"",h.secondary].filter(Boolean),x=Mq(d,r),k=p.useMemo(()=>Nq(e.detail,e.input_data,e.flow,e.automation_body??o,e.records,c,t,{subject_run_id:r,row:n}),[e.detail,e.input_data,e.flow,e.automation_body,o,e.records,c,t,r,n]),v=p.useMemo(()=>YC(r,c),[r,c]),N=p.useMemo(()=>xq(v,c,t),[v,c,t]),$=(o==null?void 0:o.title)||"automation";return s.jsxs("article",{className:"ap_page","data-run-id":r,children:[s.jsxs("header",{className:"ap_header",children:[s.jsxs("div",{className:"ap_title_row",children:[s.jsx("span",{className:`ap_mark ap_mark_${h.kind}`,title:h.kind,children:h.glyph}),s.jsx("h1",{className:`ap_title ${_.untitled?"ap_untitled":""}`,title:`Title from: ${_.source}`,children:_.text}),_.untitled?s.jsx("span",{className:"ap_untitled_tag",children:"untitled"}):null,s.jsx("span",{className:`chip ${Sa(g,tg(e.detail))}`,children:g}),s.jsx(Lq,{run_id:r,on_copy:e.on_copy})]}),y.length?s.jsx("div",{className:"ap_subject_line",children:y.join(" · ")}):null,s.jsxs("div",{className:`ap_state ap_verb_${d.verb} ${d.stalled?"ap_stalled":""}`,"data-lane":d.lane,children:[s.jsx("span",{className:"ap_state_text",children:d.text}),s.jsx(Rq,{line:d,ctx:l,on_open_run:e.on_open_run}),x?s.jsx("button",{type:"button",className:`btn ${d.actor==="you"?"primary":""} ap_action`,onClick:()=>e.on_action(x.action,x.run_id),children:x.label}):null]}),e.loading.detail?s.jsx(ns,{kind:"loading",children:"reading the run detail… (the line above is from the listing row)"}):null,e.errors.detail?s.jsxs(ns,{kind:"error",children:["run detail unavailable: ",e.errors.detail," (the line above is from the listing row)"]}):null,e.detail&&!i?s.jsx(ns,{kind:"info",children:"the listing row is newer than the detail: the line above is from the row"}):null]}),s.jsx(Dq,{prof:k,p:e,line:d,ctx:l}),s.jsx(Fq,{p:e}),s.jsx(zq,{p:e}),s.jsx(cc,{id:"tree",title:"Run tree",meta:v.size?`${v.size} run${v.size===1?"":"s"}`:void 0,children:v.root?s.jsxs(s.Fragment,{children:[v.controller_id?s.jsxs("button",{type:"button",className:"ap_tree_parent",title:`Open the automation's controller run ${v.controller_id}`,"data-run-id":v.controller_id,onClick:()=>e.on_open_run(v.controller_id),children:[s.jsx("span",{className:"ap_mark ap_mark_automation",children:"⟳"}),s.jsx("span",{className:"ap_tree_name",children:$}),s.jsxs("span",{className:"ap_tree_line",children:[v.controller?ef(v.controller,l).text:"controller (row not loaded)"," · other occurrences not shown"]})]}):null,s.jsx("ul",{className:`ap_tree ${v.controller_id?"ap_tree_under_parent":""}`,children:s.jsx(sE,{node:v.root,ctx:l,on_open_run:e.on_open_run})})]}):s.jsx(ns,{kind:"absent",children:"this run is not among the loaded rows"})}),s.jsxs(cc,{id:"spend",title:"Spend",meta:"tree-inclusive",children:[N.any_metrics?null:s.jsx(ns,{kind:"absent",children:"token and call counts not loaded: these rows were listed without metrics"}),N.rows.length?s.jsx("div",{className:"ap_table_wrap",children:s.jsxs("table",{className:"ap_spend",children:[s.jsx("caption",{children:"Tree-inclusive: each row counts its own run and every run below it, so rows do not add up."}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{scope:"col",children:"Run"}),s.jsx("th",{scope:"col",children:"Time"}),s.jsx("th",{scope:"col",children:"Tokens"}),s.jsx("th",{scope:"col",children:"LLM calls"}),s.jsx("th",{scope:"col",children:"Tool calls"}),s.jsx("th",{scope:"col",children:"Steps"})]})}),s.jsx("tbody",{children:N.rows.map(D=>{const O=l.by_id.get(D.run_id);return s.jsxs("tr",{className:D.is_subject?"ap_spend_subject":void 0,"data-run-id":D.run_id,children:[s.jsxs("th",{scope:"row",className:"ap_copyable",style:{"--ap-depth":D.depth},children:[s.jsx("span",{className:"ap_spend_name",children:O?nE(O):"run (row not loaded)"}),s.jsx(zg,{text:D.run_id,label:"run id"})]}),s.jsx("td",{children:D.duration_ms===null?"—":`${bu(D.duration_ms)}${D.running?" so far":""}`}),s.jsx("td",{children:Np(D.tokens_total)}),s.jsx("td",{children:Np(D.llm_calls)}),s.jsx("td",{children:Np(D.tool_calls)}),s.jsx("td",{children:Np(D.steps)})]},D.run_id)})})]})}):s.jsx(ns,{kind:"absent",children:"no rows"})]}),s.jsxs(cc,{id:"ask",title:"Ask",children:[s.jsx("p",{className:"ap_window_note",children:e.ask_window_note||"Ask a question about this run and the runs below it."}),s.jsx("button",{type:"button",className:"btn primary ap_ask",onClick:()=>e.on_ask(),children:"Ask about this run"})]})]})}const Vj={key:"",loading:!1,input_data:null,input_error:"",flow:null,flow_error:"",automation_body:null,automation:null,automation_error:"",runs:[],runs_error:""},$p=500,kg="http://127.0.0.1:8080";function Hj(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 Ph(e){const t=String(e||"").trim();return t.startsWith("abstractcode.")?`abstract.${t.slice(13)}`:t}function Tw(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 Mw(e){const t=String(e||"").trim();return t.startsWith("abstract.")||t.startsWith("abstractcode.")}function Uq(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 Wq(e){if(!e||typeof e!="object")return[];const t=Array.isArray(e.nodes)?e.nodes:[];if(!t.length)return[];let n=null;for(const l of t){if(!l||typeof l!="object")continue;const d=l.data&&typeof l.data=="object"?l.data:{};if(String(d.nodeType||l.type||"").trim()==="on_flow_start"){n=l;break}}if(!n)return[];const r=n.data&&typeof n.data=="object"?n.data:{},i=Array.isArray(r.outputs)?r.outputs:[],o=r.pinDefaults&&typeof r.pinDefaults=="object"?r.pinDefaults:{},c=[];for(const l of i){if(!l||typeof l!="object")continue;const d=String(l.id||"").trim();if(!d)continue;const h=String(l.type||"").trim();if(h==="execution"||d==="exec-out"||d==="exec")continue;const m=String(l.label||d).trim()||d,_={id:d,label:m,type:h||"unknown"};o&&Object.prototype.hasOwnProperty.call(o,d)&&(_.default=o[d]),c.push(_)}return c}function Rw(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 qq(){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)||kg),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:kg,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 Vq(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function Hq(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=[],n=(i,o)=>{const c=String(o??"").trim();c&&(t.some(l=>l.label===i&&l.value===c)||t.push({label:i,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 Gj(e){const t=Hq(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 Gq(){return typeof window>"u"?"":rO(window.location)}function Kq(){try{const e="abstractobserver_session_id_v1",t=window.sessionStorage.getItem(e);if(t&&t.trim())return t.trim();const n=`obs_${Zs()}`;return window.sessionStorage.setItem(e,n),n}catch{return""}}function Jq(){var D_,qo,dh,_d,ma,pd,_a,fh,hh,gd,Kc,F_,z_,mh,_h;const[e,t]=p.useState("board"),[n,r]=p.useState(()=>qq()),i=typeof window<"u"&&((D_=window.__ABSTRACT_UI_CONFIG__)==null?void 0:D_.monitor_gpu)===!0,o=typeof window<"u"&&(((qo=window.__ABSTRACT_UI_CONFIG__)==null?void 0:qo.entity_app_url)||"").trim().replace(/\/+$/,"")||"http://127.0.0.1:3007",c=p.useRef(null),[l,d]=p.useState(""),[h,m]=p.useState(""),[_,g]=p.useState(()=>Gq()),[y,x]=p.useState(""),[k,v]=p.useState(""),[N,$]=p.useState(""),[C,S]=p.useState("{}"),[D]=p.useState(()=>Kq()),[O,A]=p.useState(null),[P,W]=p.useState(!1),[J,G]=p.useState(""),[V,R]=p.useState(!1),[M,I]=p.useState(""),[L,K]=p.useState(!1),H=e2({appName:"AbstractObserver",variant:"dismissable",defaultGatewayUrl:typeof window<"u"&&((dh=window.__ABSTRACT_UI_CONFIG__)==null?void 0:dh.gateway_url)||kg,onStatusChange:b=>Vf(b)}),[z,ee]=p.useState(null),[B,te]=p.useState(null),[se,de]=p.useState(!1),[be,Me]=p.useState(null),[Ne,ae]=p.useState("once"),[je,Te]=p.useState(!1),[Ve,_t]=p.useState(null);function Qe(b){ae(b),Te(!0)}const[it,$t]=p.useState(""),[ot,mt]=p.useState(iv),[et,Lt]=p.useState([]),[ce,Se]=p.useState(null),[He,ne]=p.useState(!1),[we,fe]=p.useState([]),$e=p.useRef(new f3(Zs)),[pe,le]=p.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[ze,st]=O2("abstractobserver",{legacyKey:"abstractobserver_settings"}),[kt,pt]=p.useState(!1),[jt,ct]=p.useState(!1),[It,vt]=p.useState([]),[nn,wn]=p.useState([]),[On,Ks]=p.useState([]),[rs,ge]=p.useState(!1),[Le,yt]=p.useState(null),[re,he]=p.useState(null),[Ee,Ie]=p.useState(0),[We,Ue]=p.useState(""),tt=p.useRef(!1),ut=p.useRef(0),xt=p.useRef(0),[bt,Mt]=p.useState(!1),[zt,lt]=p.useState([]),[Yt,vn]=p.useState([]),[mn,rn]=p.useState({}),[Ht,is]=p.useState(!1),[Be,Qt]=p.useState(!1),[Ot,Fn]=p.useState(!1),[hn,Xe]=p.useState([]),[sn,un]=p.useState([]),Ar=p.useRef(0),As=p.useRef(null);As.current||(As.current=new sk(b=>window.setTimeout(b,40),b=>Xe(T=>T.concat(b))));const ws=p.useRef(null);ws.current||(ws.current=new sk(b=>window.setTimeout(b,40),b=>un(T=>T.concat(b))));const _r=p.useRef({scanned:0,found:null}),[ve,Ct]=p.useState(null),[zn,nr]=p.useState(""),[$i,sr]=p.useState(!1),bo=p.useRef(null),[dc,ul]=p.useState({}),[js,pr]=p.useState({}),[Rs,Bi]=p.useState(!1),[dl,vs]=p.useState(""),[ri,Ls]=p.useState(!0),[ii,Ss]=p.useState(""),[oi,Ui]=p.useState(!1),[In,$a]=p.useState(!1),[fl,hl]=p.useState(6),[Tr,fc]=p.useState("standard"),[Wi,Ca]=p.useState(""),[ko,Fs]=p.useState(""),[zs,gr]=p.useState(!1),[jo,qr]=p.useState(!1),[Mr,Vr]=p.useState("pause"),[hc,Hr]=p.useState(""),[ku,Ci]=p.useState(""),[Zo,ml]=p.useState(""),So=p.useRef(null),ai=p.useRef(null),[Ea,qi]=p.useState(!1),rr=p.useRef(null),[uf,li]=p.useState(""),[Kn,Y]=p.useState(Vj),me=p.useRef(0),[Oe,De]=p.useState(""),[Ye,ht]=p.useState(""),[Wt,Dt]=p.useState(""),[Bt,pn]=p.useState(!1),[En,Js]=p.useState("idle"),[Ft,bn]=p.useState([]),[ls,Hn]=p.useState(null),Rr=p.useRef(null),[yr,Vi]=p.useState(!1),[_l,Hi]=p.useState(""),[df,mc]=p.useState(""),[Aa,Ta]=p.useState(""),[ff,_c]=p.useState([]),[pc,ju]=p.useState(!1),[hf,Su]=p.useState(""),[mf,Nu]=p.useState(""),[$u,pl]=p.useState(!1),[Pm,Ma]=p.useState(""),Dm=p.useMemo(()=>{if(!Ft.length)return"";try{return JSON.stringify(Ft.map(b=>({role:b.role,content:b.content,ts:b.ts})))}catch{return"1"}},[Ft]),Cu=p.useMemo(()=>Ft.length?Aa?Dm!==Aa:!0:!1,[Dm,Ft.length,Aa]),_f=p.useMemo(()=>ff.map(b=>{const T=String(b.title||"").trim()||`Chat ${String(b.thread_id||"").slice(0,8)}`,F=String(b.created_at||"").trim(),U=F?F.replace("T"," ").slice(0,19):"",Z=String(b.run_id||"").trim()?String(b.run_id).slice(0,8):"",X=[T,U&&`(${U})`,Z&&`run ${Z}`].filter(Boolean).join(" • ");return{value:String(b.thread_id||""),label:X}}),[ff]);p.useEffect(()=>{i&&u4()},[i]),p.useEffect(()=>{if(!i)return;const b=c.current;b&&(b.token=n.gateway_auth_mode==="direct"&&n.auth_token||"")},[i,n.auth_token,n.gateway_auth_mode]);const[,pf]=p.useState([]),[gl,Fm]=p.useState([]),zm=(b,T)=>{const F=Date.now();Fm(U=>{const Z=U.findIndex(Q=>Q.title===b);if(Z<0)return[...U,{title:b,preview:T,count:1,at:F}].slice(-4);const X=[...U];return X[Z]={title:b,preview:T,count:X[Z].count+1,at:F},X})},gf=gl.length?gl.map(b=>{const T=new Date(b.at),F=`${String(T.getHours()).padStart(2,"0")}:${String(T.getMinutes()).padStart(2,"0")}`;return`${b.title}: ${b.preview} · ${F}${b.count>1?` ×${b.count}`:""}`}).join(" — "):"",[Yg,Eu]=p.useState(!1),yl=p.useRef(""),Xg=p.useRef("");p.useEffect(()=>{var T,F;const b=String(((F=(T=z==null?void 0:z.gateway)==null?void 0:T.principal)==null?void 0:F.user_id)||"").trim();yl.current=b||(L&&n.gateway_auth_mode==="direct"?"direct":"")},[z,L,n.gateway_auth_mode]);const[Au,An]=p.useState(""),[Tu,Bm]=p.useState(""),[Mu,wl]=p.useState("all"),[yf,Zg]=p.useState("status"),[Ns,No]=p.useState("ledger"),wf=mb(gy.md),gc=mb(`${gy.sm}, ${gy.short}`),Gi=YI({is_drawer:wf,page:e}),vf=Gi.open,Qo=Gi.set_open,[Um,Wm]=ng("observe_runs"),xf=Gi.toggle_ref,bf=Gi.sidebar_ref,kf=p.useRef(null),[qm,jf]=p.useState(()=>j0(typeof window<"u"?window.location.hash:"")),[Qg,Vm]=p.useState(""),[Hm,Sf]=p.useState(""),[vl,wr]=p.useState(""),[Ki,xl]=p.useState(null),[yc,Ru]=p.useState({}),[Nf,Ra]=p.useState(!1),[Gm,wc]=p.useState(""),[Ji,$f]=p.useState(!1),[La,Cf]=p.useState(!1),[Lu,Ia]=p.useState(()=>Date.now()),[Lr,ea]=p.useState(""),[Km,Oa]=p.useState({}),[Jm,Iu]=p.useState({}),bl=p.useRef([]),Gr=p.useRef(null),$o=p.useRef(""),vc=p.useRef({}),Kr=p.useRef({}),xc=p.useRef({}),Pa=p.useRef(new Set),[Co,Ou]=p.useState([]),Eo=p.useRef(""),kl=p.useRef({}),Ao=p.useRef(null),vr=p.useRef(null),Bn=p.useRef(0),ta=p.useRef({}),Da=p.useRef(!1),Ei=p.useRef(new Set),[Pu,jl]=p.useState(""),[Ir,Ai]=p.useState(""),xr=p.useRef(""),Ef=()=>({artifact_id:"",kind:"binary",render_kind:"",text:"",url:"",loading:!1,error:""}),[bc,Ym]=p.useState("activity"),[Du,kc]=p.useState([]),[jc,Fu]=p.useState(0),[Af,zu]=p.useState(0),[Tf,Xm]=p.useState({}),[Zm,Qm]=p.useState({}),[ey,Bu]=p.useState(!1),[na,Mf]=p.useState(""),[Yi,Xi]=p.useState(""),[To,Ti]=p.useState("all"),[Sl,e_]=p.useState(""),[Nl,Fa]=p.useState([]),[sa,$l]=p.useState("all"),[Mo,Rf]=p.useState("type"),[Ro,ra]=p.useState("newest"),[Pn,Xn]=p.useState(""),[ci,Ts]=p.useState(""),[br,Lo]=p.useState(""),[Zi,ir]=p.useState(0),[Io,Uu]=p.useState(()=>Ef()),[t_,Cl]=p.useState(!1),[Wu,Oo]=p.useState(""),[qu,ia]=p.useState(""),[or,Vu]=p.useState(""),[Qi,El]=p.useState("text"),[Al,Tl]=p.useState(null),[Hu,kr]=p.useState(!1),[Jr,eo]=p.useState(""),[to,no]=p.useState(""),[za,Lf]=p.useState(""),[Gu,Ku]=p.useState(!1),[Yr,Or]=p.useState(""),[Zn,Mi]=p.useState("run_ledger"),[n_,s_]=p.useState(""),[If,Sc]=p.useState([]),[r_,Ml]=p.useState(""),[i_,Ba]=p.useState(!1),[Of,Pf]=p.useState(""),Ke=p.useMemo(()=>new Xy({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]),Un=p.useMemo(()=>new N3(Ke.automations_client(),k3(Ke,Zs,an)),[Ke]),ui=p.useSyncExternalStore(b=>Un.subscribe(b),()=>Un.state),Df=QO(n.gateway_url),Po=Df?()=>{window.open(Df,"_blank","noopener,noreferrer")}:void 0,Ff=p.useCallback(b=>o3(b,{connections:ui.trigger_connections,mailboxes:ui.mailboxes}),[ui.trigger_connections,ui.mailboxes]),Do=p.useMemo(()=>!it&&N.trim()&&k.trim()?s3(O,N.trim(),k.trim()):null,[O,N,k,it]),Rl=p.useRef("");p.useEffect(()=>{if(!je||Ne!=="automate"||!Do)return;const b=`${N.trim()}:${k.trim()}`;if(Rl.current===b)return;Rl.current=b;let T={};try{const U=JSON.parse(C||"{}");U&&typeof U=="object"&&!Array.isArray(U)&&(T=U)}catch{T={}}const F=i3(ot,T,Do);mt(F.form),S(JSON.stringify(F.input_data,null,2))},[je,Ne,Do,N,k]);const Ll=ZS(je&&Ne==="automate"&&L?c3(ot,Do):null,Un.preview_schedule);p.useEffect(()=>{je&&Ne==="automate"&&L&&(Un.load_email_status(),Un.load_trigger_vocab())},[e,Ne,L,Un]),p.useEffect(()=>{L&&Un.load_trigger_vocab()},[L,Un]),p.useEffect(()=>{const b=()=>{const T=t3(window.location.hash);if(T){if(T.page==="run"){g(T.run_id),jf(j0(window.location.hash));return}if(T.page==="launch"){Qe(T.mode);return}t(T.page)}};return b(),window.addEventListener("hashchange",b),()=>window.removeEventListener("hashchange",b)},[]);const zf=p.useMemo(()=>{const b={};for(const T of ui.items)b[T.automation_id]=T.title;return b},[ui.items]),Bf=p.useMemo(()=>QP(),[]),[Uf,Ju]=p.useState(B0),Ua=p.useRef(0);function di(){const b=++Ua.current;Ju(B0),e4(Ke).then(T=>{b===Ua.current&&Ju(T)})}const so=p.useMemo(()=>n.worker_url.trim()?new cD({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Yu=p.useMemo(()=>oD(Ke.fetch_gateway,dv),[Ke]),ar=hn.length?hn[hn.length-1].record:null,dn=p.useMemo(()=>Za(ar),[ar]),_s=p.useMemo(()=>{const b=N.trim();if(!O||!b||String(O.bundle_id||"").trim()&&String(O.bundle_id||"").trim()!==b)return null;const T=Array.isArray(O.entrypoints)?O.entrypoints:[];if(!T.length)return null;const F=k.trim();if(F)return T.find(Z=>String(Z.flow_id||"").trim()===F)||null;if(T.length===1)return T[0];const U=String(O.default_entrypoint||"").trim();return U&&T.find(Z=>String(Z.flow_id||"").trim()===U)||null},[O,N,k]),Nc=p.useMemo(()=>{const b=_s==null?void 0:_s.inputs;return Array.isArray(b)?b:[]},[_s]),Wf=p.useMemo(()=>Wq(Ki),[Ki]),Xr=p.useMemo(()=>Nc.length?Nc:Wf,[Nc,Wf]),Zr=p.useMemo(()=>{const b=typeof(ve==null?void 0:ve.workflow_id)=="string"?String(ve.workflow_id):"",T=Hj(b);if(T&&O&&String(O.bundle_id||"").trim()===T.bundle_id){const Z=(Array.isArray(O.entrypoints)?O.entrypoints:[]).find(X=>String((X==null?void 0:X.flow_id)||"").trim()===T.flow_id);if(Z&&Z.node_index&&typeof Z.node_index=="object")return Z.node_index}const F=_s==null?void 0:_s.node_index;return F&&typeof F=="object"?F:{}},[ve,O,_s]);p.useEffect(()=>{Vq(n)},[n]),p.useEffect(()=>()=>{Ao.current&&Ao.current.abort(),vr.current&&vr.current.abort(),So.current&&window.clearTimeout(So.current),ai.current&&window.clearTimeout(ai.current),Gr.current&&window.clearTimeout(Gr.current),rr.current&&window.clearTimeout(rr.current)},[]);const on=p.useMemo(()=>{const b=C.trim();if(!b)return{};try{const T=JSON.parse(b);return typeof T!="object"||T===null||Array.isArray(T)?null:T}catch{return null}},[C]),o_=typeof(on==null?void 0:on.prompt)=="string"?String(on.prompt):"",Il=typeof(on==null?void 0:on.provider)=="string"?String(on.provider):"",a_=typeof(on==null?void 0:on.model)=="string"?String(on.model):"",$c=typeof(on==null?void 0:on.workspace_root)=="string"?String(on.workspace_root):"",ro=p.useMemo(()=>{const b=on==null?void 0:on.workspace;return b&&typeof b=="object"&&!Array.isArray(b)?b:null},[on]),Cc=Xr.length>0&&!!N.trim(),Wa=b=>{const T=String(b||"").trim().toLowerCase();return T==="object"||T==="memory"||T==="assertion"||T==="assertions"||T==="any"};p.useEffect(()=>{pr({})},[N,k]),p.useEffect(()=>{on!==null&&ul(b=>{const T={};for(const F of Xr){if(!F||typeof F!="object")continue;const U=String(F.id||"").trim();if(!U)continue;const Z=String(F.type||"").trim();if(!Wa(Z))continue;if(String(js[U]||"").trim()){T[U]=typeof b[U]=="string"?b[U]:"";continue}const Q=on==null?void 0:on[U];Q===void 0?T[U]="":T[U]=AO(Q)}return T})},[Xr,on,js]);const jr=it?{kind:"default",interface:it}:N.trim()&&k.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:k.trim()}:null,Xu=JO(jr),fi=Array.isArray(on==null?void 0:on.skills)?on.skills.map(b=>String(b||"").trim()).filter(Boolean):[],hi=p.useMemo(()=>{const b={};for(const T of It){const F=String(T.workflow_id||"").trim(),U=String(T.label||"").trim();F&&U&&(b[F]=U)}return b},[It]),Ol=sN({interfaceId:null,defaultInterface:Ud,request:(b,T)=>Ke.get_gateway_json(b,T.signal),enabled:L,reloadKey:It}),ps=p.useMemo(()=>{const b=new Set;for(const T of Array.isArray(Yt)?Yt:[]){const F=String((T==null?void 0:T.name)||"").trim();F&&b.add(F)}return Array.from(b).sort()},[Yt]),Zu=p.useMemo(()=>{const b=[];for(const T of Array.isArray(Yt)?Yt:[]){const F=String((T==null?void 0:T.name)||"").trim();if(!F)continue;const U=String((T==null?void 0:T.display_name)||"").trim();b.push({name:F,display_name:U||void 0})}return b},[Yt]),Ec=p.useMemo(()=>{const b=new Set;for(const T of zt||[]){if(!T||typeof T!="object")continue;const F=String(T.name||"").trim();F&&b.add(F)}return Array.from(b).sort()},[zt]),Qu=p.useMemo(()=>{const b=n.maintenance_ai_provider.trim();if(!b)return{models:[],error:""};const T=mn[b];return T?{models:(Array.isArray(T.models)?T.models:[]).map(U=>String(U||"").trim()).filter(Boolean),error:String(T.error||"")}:{models:[],error:""}},[mn,n.maintenance_ai_provider]),Pl=n.maintenance_ai_provider.trim(),qf=!!(Pl&&L&&!Object.prototype.hasOwnProperty.call(mn,Pl));p.useEffect(()=>{const b=Il.trim();if(!b||mn[b]||kl.current[b])return;kl.current[b]=!0;let T=!1;return(async()=>{try{const U=await Ke.discovery_provider_models(b);if(T)return;const Z=Array.isArray(U==null?void 0:U.models)?U.models:[],X=typeof(U==null?void 0:U.error)=="string"?String(U.error):"";rn(Q=>({...Q,[b]:{models:Z,error:X||void 0}}))}catch(U){if(T)return;rn(Z=>({...Z,[b]:{models:[],error:String((U==null?void 0:U.message)||U||"Failed to load models")}}))}finally{delete kl.current[b]}})(),()=>{T=!0}},[Il,mn,Ke]),p.useEffect(()=>{const b=n.maintenance_ai_provider.trim();if(!b||!L||mn[b]||kl.current[b])return;kl.current[b]=!0;let T=!1;return(async()=>{try{const U=await Ke.discovery_provider_models(b);if(T)return;const Z=Array.isArray(U==null?void 0:U.models)?U.models:[],X=typeof(U==null?void 0:U.error)=="string"?String(U.error):"";rn(Q=>({...Q,[b]:{models:Z,error:X||void 0}}))}catch(U){if(T)return;rn(Z=>({...Z,[b]:{models:[],error:String((U==null?void 0:U.message)||U||"Failed to load models")}}))}finally{delete kl.current[b]}})(),()=>{T=!0}},[n.maintenance_ai_provider,mn,Ke,L]);function Qn(b,T){const F=String(b||"").trim();if(!F)return;let U={};try{const Z=JSON.parse(C||"{}");typeof Z=="object"&&Z!==null&&!Array.isArray(Z)&&(U=Z)}catch{U={}}if(T==null){delete U[F],S(JSON.stringify(U,null,2));return}if(typeof T=="string")T?U[F]=T:delete U[F];else if(Array.isArray(T)){const Z=T.map(X=>X).filter(X=>X!=null);Z.length?U[F]=Z:delete U[F]}else U[F]=T;S(JSON.stringify(U,null,2))}async function cs(b){const T=String(b||"").trim();if(!T)return G("Missing bundle_id"),null;G(""),W(!0);try{const F=await Ke.get_bundle(T);return A(F),kn({ts:an(),kind:"info",title:`Loaded bundle ${T}`}),F}catch(F){return A(null),G(String((F==null?void 0:F.message)||F||"Failed to load bundle")),null}finally{W(!1)}}function $s(b){const T=[],F=Array.isArray(b==null?void 0:b.items)?b.items:[];for(const U of F){const Z=String((U==null?void 0:U.bundle_id)||"").trim();if(!Z)continue;const X=Array.isArray(U==null?void 0:U.entrypoints)?U.entrypoints:[];if(X.length)for(const Q of X){const oe=String((Q==null?void 0:Q.flow_id)||"").trim();if(!oe||(Q==null?void 0:Q.deprecated)===!0)continue;const Ge=`${Z}:${oe}`,ke=String((Q==null?void 0:Q.name)||"").trim(),ye=ke?`${Z} · ${ke}`:`${Z} · ${oe}`,Fe=String((Q==null?void 0:Q.description)||"").trim(),rt=(Array.isArray(Q==null?void 0:Q.interfaces)?Q.interfaces:[]).some(dt=>String(dt||"").trim().length>0),gt=Array.isArray(Q==null?void 0:Q.agent_default_interfaces)?Q.agent_default_interfaces.map(dt=>String(dt||"").trim()).filter(Boolean):[];T.push({workflow_id:Ge,bundle_id:Z,bundle_ref:String((U==null?void 0:U.bundle_ref)||"").trim(),flow_id:oe,label:ye,description:Fe||void 0,has_interface:rt,agent_default_interfaces:gt})}}return T.sort((U,Z)=>U.label.localeCompare(Z.label)),T}async function Dn(b=Ke,T){if(tt.current&&!(T!=null&&T.force))return;tt.current=!0;const F=io.current;ge(!0);const U=ye=>ye.map(op).filter(Fe=>!!Fe.run_id),Z=ye=>Array.isArray(ye==null?void 0:ye.items)?ye.items:[],X=LU(b,F),Q=()=>{const ye=X.view();wn(ye.roots),Ks(ye.all)},oe=(ye,Fe)=>{if(String((ye==null?void 0:ye.name)||"")==="Superseded")return;const Pe=String((ye==null?void 0:ye.message)||ye||"");if(kn({ts:an(),kind:"error",title:Fe,preview:tn(Pe)}),zm(Fe,tn(Pe)),(/\b40[13]\b/.test(Pe)||/unauthorized|forbidden/i.test(Pe))&&H.refresh().catch(()=>{}),/\b429\b/.test(Pe)||/too many requests/i.test(Pe)){const rt=Math.min(12e4,Math.max(15e3,xt.current*2||15e3));xt.current=rt,ut.current=Date.now()+rt,kn({ts:an(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(rt/1e3)}s`})}},Ge=yl.current,ke=Ge?TU(String(n.gateway_url||""),Ge):"";Xg.current=ke,ke&&X.active_at===null&&X.seed(MU(Sj(),ke))&&X.active_at!==null&&(Q(),yt(X.active_at),Eu(!0));try{const[ye,Fe]=await Promise.allSettled([b.list_runs({status:"running",limit:kj}),b.list_runs({status:"waiting",limit:jj})]);if(F!==io.current)return;if(ye.status==="rejected"&&Fe.status==="rejected")throw ye.reason;ye.status==="rejected"&&oe(ye.reason,"Runs listing (running) failed"),Fe.status==="rejected"&&oe(Fe.reason,"Runs listing (waiting) failed");const Pe=ye.status==="fulfilled"?ye.value:null,rt=Fe.status==="fulfilled"?Fe.value:null,gt=Pe?Z(Pe):X.active_rows.filter(ft=>String(ft.status||"")==="running"),dt=rt?Z(rt):X.active_rows.filter(ft=>String(ft.status||"")==="waiting"),xn=!!(Pe&&rt)&&gt.length<kj&&dt.length<jj&&(Pe==null?void 0:Pe.has_more)!==!0&&(rt==null?void 0:rt.has_more)!==!0,qt=X.seeded;X.apply_active(U(gt),U(dt),xn),!(Pe&&rt)&&qt&&(X.seeded=!0),Q(),yt(Date.now()),Eu(!(Pe&&rt)&&qt),Pe&&rt&&Fm([]),xt.current=0,ut.current=0,ke&&Pe&&rt&&window.setTimeout(()=>RU(Sj(),ke,X.snapshot()),0)}catch(ye){oe(ye,"Refresh runs failed");return}finally{tt.current=!1,ge(!1)}X.sweep_due(Date.now(),(T==null?void 0:T.force)===!0)&&(X.begin_sweep(Date.now()),b.list_runs({limit:200,root_only:!0,include_metrics:!0}).then(async ye=>{const Fe=Number(ye==null?void 0:ye.archived_sessions);if(Number.isFinite(Fe)&&Fe<=0)return[ye,{items:[]}];const Pe=await b.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0});return[ye,Pe]}).then(([ye,Fe])=>{if(F!==io.current||!Nj(X))return X.fail_sweep();const Pe=m3(Z(ye),Z(Fe));X.apply_sweep(U(Pe),Date.now()),Q()},ye=>{X.fail_sweep(),!(F!==io.current||!Nj(X))&&oe(ye,"Refresh run metrics failed")}))}async function Ac(b){var oe,Ge,ke;const T=io.current;K(!0),rn({}),b.list_apps().then(ye=>{if(T!==io.current)return;const Pe=(Array.isArray(ye==null?void 0:ye.apps)?ye.apps:[]).find(gt=>String((gt==null?void 0:gt.id)||"")==="code"),rt=Pe&&Pe.installed===!0&&Pe.running===!0?String(Pe.url||"").trim():"";_t(rt?{url:rt}:null)}).catch(()=>{T===io.current&&_t(null)});const[F,,U,Z,X]=await Promise.allSettled([b.list_bundles(),Dn(b),b.discovery_tools(),b.discovery_providers({include_models:!1}),b.discovery_capabilities()]);if(T!==io.current)return;if(F.status==="rejected"&&U.status==="rejected"&&Z.status==="rejected"){K(!1),I(Rw(F.reason,n)),kn({ts:an(),kind:"error",title:"Discovery failed",preview:tn(String(F.reason||""))});return}le(X.status==="fulfilled"?_3(X.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((oe=X.reason)==null?void 0:oe.message)||X.reason)}`});let Q=0;if(F.status==="fulfilled"){const ye=$s(F.value);Q=ye.length,vt(ye)}else vt([]),kn({ts:an(),kind:"error",title:"Discovery bundles failed",preview:tn(String(F.reason||""))});if(U.status==="fulfilled"){const ye=Array.isArray((Ge=U.value)==null?void 0:Ge.items)?U.value.items:[];lt(ye)}else lt([]),kn({ts:an(),kind:"error",title:"Discovery tools failed",preview:tn(String(U.reason||""))});if(Z.status==="fulfilled"){const ye=Array.isArray((ke=Z.value)==null?void 0:ke.items)?Z.value.items:[];vn(ye)}else vn([]),kn({ts:an(),kind:"error",title:"Discovery providers failed",preview:tn(String(Z.reason||""))});kn({ts:an(),kind:"info",title:"Gateway discovery loaded",preview:tn(`workflows: ${Q}`)})}async function Fo(b){var T,F;I(""),K(!1),R(!0);try{if(!(b!=null&&b.prefer_direct)&&(await H.refresh(),qa.current))return;const U=String(n.auth_token||"").trim();if(!U){b!=null&&b.open_modal_if_needed&&H.openModal();return}const Z=String(n.gateway_url||"").trim();if(Z){const Q=Z.toLowerCase();if(!Q.startsWith("http://")&&!Q.startsWith("https://"))throw new Error("Gateway URL must start with http:// or https:// (or leave it blank to use same origin / dev proxy).");try{if(String(((T=window==null?void 0:window.location)==null?void 0:T.protocol)||"")==="https:"&&Q.startsWith("http://"))throw new Error("Gateway URL is http:// but this page is https:// (mixed content is blocked). Use https:// or leave Gateway URL blank to use same origin /api proxy.");const Ge=new URL(Z),ke=String(((F=window==null?void 0:window.location)==null?void 0:F.hostname)||"").trim().toLowerCase(),ye=String(Ge.hostname||"").trim().toLowerCase(),Fe=Pe=>Pe==="localhost"||Pe==="127.0.0.1"||Pe==="::1";if(Fe(ye)&&ke&&!Fe(ke))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(oe){throw new Error(String((oe==null?void 0:oe.message)||oe||"Invalid Gateway URL"))}}const X=new Xy({base_url:Z,auth_token:U});await X.list_bundles(),r(Q=>({...Q,gateway_auth_mode:"direct"})),await Ac(X)}catch(U){I(Rw(U,n))}finally{R(!1)}}const qa=p.useRef(!1),io=p.useRef(0),Bs=p.useRef(!1);function Vf(b){var F,U,Z;ee(b);const T=!!(b&&b.has_session&&((F=b.gateway)!=null&&F.ok));if(qa.current=T,T){if(Bs.current=!1,L&&n.gateway_auth_mode==="direct")return;const X=String(((Z=(U=b==null?void 0:b.gateway)==null?void 0:U.principal)==null?void 0:Z.user_id)||"").trim();if(r(Q=>({...Q,gateway_auth_mode:"session",auth_token:"",gateway_user:X||Q.gateway_user})),L&&n.gateway_auth_mode==="session")return;I(""),R(!0),Ac(new Xy({base_url:"",auth_token:""})).catch(Q=>I(Rw(Q,n))).finally(()=>R(!1));return}b&&!b.has_session&&(n.gateway_auth_mode==="session"&&mi({keep_session:!0}),String(n.auth_token||"").trim()&&!L&&!Bs.current&&(Bs.current=!0,Fo({prefer_direct:!0})))}async function Hf(){if(!(bt||V)){Mt(!0);try{await Ke.reload_bundles();const b=await Ke.list_bundles(),T=$s(b);vt(T),kn({ts:an(),kind:"info",title:"Bundles reloaded",preview:tn(`workflows: ${T.length}`)})}catch(b){const T=String((b==null?void 0:b.message)||b||"Bundle reload failed");kn({ts:an(),kind:"error",title:"Bundle reload failed",preview:tn(T),data:{error:T}})}finally{Mt(!1)}}}async function Gf(b){if($i||V||!L)return;const T=b;if(T){sr(!0),An("");try{const F=await Ke.upload_bundle(T,{overwrite:!1,reload:!0});kn({ts:an(),kind:"info",title:"Bundle uploaded",preview:tn(String((F==null?void 0:F.bundle_ref)||""))});const U=await Ke.list_bundles(),Z=$s(U);vt(Z)}catch(F){const U=String((F==null?void 0:F.message)||F||"Upload failed");An(U),kn({ts:an(),kind:"error",title:"Upload .flow failed",preview:tn(U),data:{error:U}})}finally{sr(!1);try{bo.current&&(bo.current.value="")}catch{}}}}function mi(b){io.current+=1,b!=null&&b.keep_session||(H.signOut().catch(()=>{}),qa.current=!1),Fl(),$(""),v(""),wr(""),A(null),G(""),W(!1),vt([]),wn([]),Ks([]),yt(null),he(null),Ie(0),lt([]),vn([]),rn({}),I(""),K(!1),ee(null),r(T=>({...T,auth_token:""})),kn({ts:an(),kind:"info",title:"Gateway disconnected"})}async function Pr(b){const T=String(b??"");T&&Us(await Mm(T)?"Copied to clipboard":f1,2)}p.useEffect(()=>{const b=l.trim();if(!Ht||!b)return;let T=!1;const F=async()=>{if(!(ut.current>Date.now()))try{const Z=await Ke.get_run(b);T||Ct(Z)}catch{}};F();const U=window.setInterval(F,2e3);return()=>{T=!0,window.clearInterval(U)}},[Ht,l,Ke]),p.useEffect(()=>{if(!L)return;let b=null,T=!1,F=!1;const U=Q=>{T||(b!==null&&window.clearTimeout(b),b=window.setTimeout(()=>void Z(),Q))},Z=async()=>{if(F)return;const Q=ut.current-Date.now();if(Q>0){U(Q+500);return}F=!0;const oe=Date.now();try{await Dn(Ke)}finally{F=!1;const Ge=Date.now()-oe,ke=document.visibilityState==="hidden"?3e4:5e3;U(Math.max(ke,Ge*3))}},X=()=>{document.visibilityState==="visible"&&Z()};return Z(),document.addEventListener("visibilitychange",X),()=>{T=!0,b!==null&&window.clearTimeout(b),document.removeEventListener("visibilitychange",X)}},[L,Ke]);const[Tc,Mc]=p.useState(null);p.useEffect(()=>{if(!L){Mc(null);return}let b=!1;return(async()=>{try{const T=await Ke.get_entity_phases_spec();if(b)return;const F=hW(T);if(Mc(F),F)try{const U=localStorage.getItem("abstractobserver_phase_graph_id_v1"),Z=U?JSON.parse(U):null;Z&&Z.sha256&&F.sha256&&Z.sha256!==F.sha256&&Z.version===F.version&&kn({ts:an(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:tn(`v${F.version}: ${String(Z.sha256).slice(0,12)}… -> ${String(F.sha256).slice(0,12)}…`),data:{prev:Z,now:{sha256:F.sha256,version:F.version}}}),localStorage.setItem("abstractobserver_phase_graph_id_v1",JSON.stringify({sha256:F.sha256,version:F.version}))}catch{}}catch(T){if(!b){Mc(null);const F=String((T==null?void 0:T.message)||T||"");/404|not found/i.test(F)||kn({ts:an(),kind:"info",title:"Phase-graph fetch failed — pre-wire fallback vocabulary in use (#FALLBACK)",preview:tn(F),data:{error:F}})}}})(),()=>{b=!0}},[L]),p.useEffect(()=>{if(!L){he(null),Ie(0),Ue("");return}let b=!1,T=null;const F=async()=>{if(!(ut.current>Date.now())){try{const U=await Ke.list_entities();b||Ie(U.entities.length);const Z=U.entities.map(Q=>String((Q==null?void 0:Q.name)||(Q==null?void 0:Q.slug)||"").trim()).filter(Boolean).slice(0,FC),X=await Promise.all(Z.map(async Q=>{var oe,Ge;try{const[ke,ye]=await Promise.all([Ke.get_entity_card(Q),Ke.get_entity_cognition(Q).catch(()=>null)]),Fe=ke!=null&&ke.state&&typeof ke.state=="object"?ke.state:null,Pe=Array.isArray(ke==null?void 0:ke.moments)?ke.moments:[],rt=Pe.length?Pe[Pe.length-1]:null,gt=(oe=ye==null?void 0:ye.spend)==null?void 0:oe.lifetime,dt=(Ge=ye==null?void 0:ye.spend)==null?void 0:Ge.live_visit,xn=Array.isArray(ye==null?void 0:ye.warnings)?ye.warnings.map(ft=>String(ft||"")).filter(Boolean):[],qt=uW(ke);return{name:Q,state:String((Fe==null?void 0:Fe.state)??(typeof(ke==null?void 0:ke.state)=="string"?ke.state:"")).trim(),age_days:typeof(ke==null?void 0:ke.age_days)=="number"?ke.age_days:null,last_moment:String((rt==null?void 0:rt.kind)||"").trim(),last_moment_at:String((rt==null?void 0:rt.at)||"").trim(),working:typeof(ye==null?void 0:ye.working)=="boolean"?ye.working:null,tokens_total:typeof(gt==null?void 0:gt.tokens_total)=="number"?gt.tokens_total:null,live_visit_tokens:typeof(dt==null?void 0:dt.tokens_total)=="number"?dt.tokens_total:null,spend_warning:xn.join(" | "),live_phase:typeof(ye==null?void 0:ye.phase)=="string"?ye.phase:"",open_questions:qt.questions,open_questions_total:qt.questions_total,open_problems:qt.problems,open_problems_total:qt.problems_total,lessons:qt.lessons,lessons_total:qt.lessons_total,dreams_brief:cW(ke),error:""}}catch(ke){return{name:Q,state:"",age_days:null,last_moment:"",last_moment_at:"",working:null,tokens_total:null,live_visit_tokens:null,spend_warning:"",live_phase:"",open_questions:[],open_questions_total:0,open_problems:[],open_problems_total:0,lessons:[],lessons_total:0,dreams_brief:null,error:String((ke==null?void 0:ke.message)||ke||"card failed")}}}));b||(he(X),Ie(U.entities.length),Ue(""))}catch(U){if(!b){he([]);const Z=String((U==null?void 0:U.message)||U||"");Ue(/404|not found/i.test(Z)?"":Z)}}b||(T=window.setTimeout(()=>void F(),3e4))}};return F(),()=>{b=!0,T!==null&&window.clearTimeout(T)}},[L,Ke]);async function Kf(b,T,F){const U=String(T||"").trim();if(!b||!U)throw new Error("This wait has no wait_key yet — open the run to inspect.");await Ke.submit_command({command_id:Zs(),run_id:b,type:"resume",payload:{wait_key:U,payload:F||{}},client_id:"web_pwa"}),kn({ts:an(),kind:"info",title:"Board resume submitted",preview:tn(`run ${b} · wait ${U}`),data:{run_id:b,wait_key:U}}),Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),1200)}const oa=p.useMemo(()=>{const b=ve==null?void 0:ve.session_id;return typeof b=="string"?b.trim():b==null?"":String(b||"").trim()},[ve]),l_=p.useMemo(()=>{const b=String(oa||"").trim();return b||String(D||"").trim()},[oa,D]);p.useEffect(()=>{L||Dt("")},[L]);const[Rc,c_]=_1(),Jf=p1(L?Ke:null,L),oo=g1({gateway:L?Ke:null,session_id:l_,prefs:Rc,on_error:Dt,on_transcript:b=>{const T=String(b||"").trim();T&&(De(F=>{const U=String(F||"");return U.trim()?`${U.trimEnd()}
174
+ ${T}`:T}),window.setTimeout(()=>{var F;return(F=Rr.current)==null?void 0:F.focus()},0))}}),u_=p.useMemo(()=>{for(let b=Ft.length-1;b>=0;b-=1){const T=Ft[b];if(T.role==="assistant")return T.local_error?null:{key:String(T.id||T.ts||""),text:String(T.content||"")}}return null},[Ft]);y1(oo,Rc.read_aloud===!0,u_);function d_(b,T){try{const F=URL.createObjectURL(b),U=document.createElement("a");U.href=F,U.download=T||"download",U.rel="noreferrer",document.body.appendChild(U),U.click(),document.body.removeChild(U),window.setTimeout(()=>URL.revokeObjectURL(F),5e3)}catch{}}async function Dl(){const b=Hm.trim();if(!b){Us("This run recorded no workspace",2);return}try{const T=await fetch(eO,{method:"POST",headers:{"Content-Type":"application/json",...dv()},body:JSON.stringify({path:b})}),F=await T.json().catch(()=>({}));T.ok&&(F!=null&&F.ok)?Us(`Opened ${String(F.path||b)}`,2):Us(String((F==null?void 0:F.error)||`Folder reveal failed (${T.status})`),3)}catch(T){Us(String((T==null?void 0:T.message)||T||"Folder reveal failed"),3)}}async function f_(b){const T=String((b==null?void 0:b.run_id)||"").trim(),F=String((b==null?void 0:b.artifact_id)||"").trim();if(!T||!F){Us("Artifact download needs a run id",3);return}const U=og(b)||F;try{const Z=await Ke.download_run_artifact_content(T,F,{access:"preview"});d_(Z,$0(U)),Us("Downloaded artifact",2)}catch(Z){Us(String((Z==null?void 0:Z.message)||Z||"Download failed"),3)}}async function ed(b){const T=String((b==null?void 0:b.run_id)||"").trim(),F=String((b==null?void 0:b.artifact_id)||"").trim();if(!T||!F){Us("Artifact preview needs a run id",3);return}const U=og(b),Z=String((b==null?void 0:b.content_type)||"").trim().toLowerCase(),X=Yh(b);if(Oo(U||F),ia(""),eo(""),El(X),Tl(b),Cl(!0),or&&(URL.revokeObjectURL(or),Vu("")),X==="binary"){ia(`(Binary artifact: ${Z||"unknown"}; download to view.)`);return}if(X==="text"&&typeof b.size_bytes=="number"&&b.size_bytes>15e5){ia(`(Text artifact is ${b.size_bytes.toLocaleString()} bytes; download to view.)`);return}kr(!0);try{const Q=await Ke.download_run_artifact_content(T,F,{access:"preview"});if(X==="text"){const oe=await Q.text(),Ge=ig(b,oe),ke=Ge==="json"?15e5:Ge==="markdown"?25e4:Ge==="html"?3e5:22e3;ia(oe.length>ke&&Ge!=="text"?`${ru(b.size_bytes??oe.length)} ${Ge.toUpperCase()} artifact. Download to inspect it.`:oe.length>ke?`${oe.slice(0,Math.max(0,ke-1))}…`:oe)}else Vu(URL.createObjectURL(Q))}catch(Q){eo(String((Q==null?void 0:Q.message)||Q||"Preview failed"))}finally{kr(!1)}}p.useEffect(()=>()=>{or&&URL.revokeObjectURL(or)},[or]);async function td(b){const T=String(b.artifact_id||"").trim(),F=String(b.run_id||"").trim(),U=Yh(b);if(!F||!T)return{artifact_id:T,kind:U,render_kind:"",text:"Preview needs artifact run metadata.",url:"",loading:!1,error:""};if(U==="binary")return{artifact_id:T,kind:U,render_kind:"",text:`Preview unavailable for ${b.content_type||b.modality||"this artifact"}. Download to inspect it.`,url:"",loading:!1,error:""};if(U==="text"&&typeof b.size_bytes=="number"&&b.size_bytes>5e5)return{artifact_id:T,kind:U,render_kind:"",text:`${ru(b.size_bytes)} text artifact. Use Preview for a larger view or Download to inspect locally.`,url:"",loading:!1,error:""};try{const Z=await Ke.download_run_artifact_content(F,T,{access:"preview"});if(U==="text"){const X=await Z.text(),Q=ig(b,X),oe=Q==="json"?5e5:Q==="markdown"?12e4:Q==="html"?3e5:8e3;return{artifact_id:T,kind:U,render_kind:Q,text:X.length>oe&&Q!=="text"?`${ru(b.size_bytes??X.length)} ${Q.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:X.length>oe?`${X.slice(0,Math.max(0,oe-1))}…`:X,url:"",loading:!1,error:""}}return{artifact_id:T,kind:U,render_kind:"",text:"",url:URL.createObjectURL(Z),loading:!1,error:""}}catch(Z){return{artifact_id:T,kind:U,render_kind:"",text:"",url:"",loading:!1,error:String((Z==null?void 0:Z.message)||Z||"Preview failed")}}}async function h_(b){if(Io.url&&URL.revokeObjectURL(Io.url),!b){Uu(Ef());return}const T=String(b.artifact_id||"").trim(),F=Yh(b);Uu({artifact_id:T,kind:F,render_kind:"",text:"",url:"",loading:!0,error:""}),Uu(await td(b))}function kn(b){const T=String(b.id||"").trim()||Zs();pf(F=>[{...b,id:T},...F].slice(0,800))}function Us(b,T){ml(b),ai.current&&window.clearTimeout(ai.current),qi(!1),window.requestAnimationFrame(()=>qi(!0)),ai.current=window.setTimeout(()=>{qi(!1),ai.current=null},1500),So.current&&(window.clearTimeout(So.current),So.current=null),T>0&&(So.current=window.setTimeout(()=>{ml(""),So.current=null},Math.max(1,T)*1e3))}function lr(b,T){const F=String(b||"").trim(),U=String(T||"").trim();if(!U)return"";const Z=F?String(vc.current[F]||"").trim():"";return Z?`${Z}::${U}`:U}function nd(b,T,F){const U=String(b||"").trim(),Z=String(T||"").trim(),X=String(F||"").trim();if(!U||!Z||!X)return;const Q=lr(U,Z);Q&&(vc.current[X]=Q,Kr.current[X]=U,xc.current[X]={parent_run_id:U,parent_node_id:Z},Pa.current.has(X)||(Pa.current.add(X),Ou(oe=>oe.includes(X)?oe:[...oe,X])))}function Lc(b){const T=String(b||"").trim();if(!T)return;const F=Date.now(),U=$o.current;$o.current=T,Ia(F),Oa(Z=>{const X={};for(const[ke,ye]of Object.entries(Z))typeof ye=="number"&&ye>F&&(X[ke]=ye);X[T]=Math.max(X[T]||0,F+2e3),U&&U!==T&&(X[U]=Math.max(X[U]||0,F+2e3));const Q=Object.keys(X);if(Q.length<=200)return X;const oe=Q.sort((ke,ye)=>(X[ye]||0)-(X[ke]||0)).slice(0,200),Ge={};for(const ke of oe)Ge[ke]=X[ke]||0;return Ge}),Iu(Z=>{if(typeof Z[T]=="number")return Z;const X={...Z,[T]:F};if(bl.current.push(T),bl.current.length>8e3){const Q=bl.current.splice(0,1500);for(const oe of Q)delete X[oe]}return X}),Gr.current&&window.clearTimeout(Gr.current),Gr.current=window.setTimeout(()=>{const Z=Date.now();Oa(X=>{const Q={};for(const[oe,Ge]of Object.entries(X))typeof Ge=="number"&&Ge>Z&&(Q[oe]=Ge);return Q}),Ia(Z),Gr.current=null},2200)}function sd(b,T){var dt,xn,qt;const F=String(T||"").trim()||l.trim();Ar.current=b.cursor,(dt=As.current)==null||dt.push({cursor:b.cursor,record:b.record}),F&&Ei.current.add(`${F}:${b.cursor}`);const U=cp(b.record),Z=U&&U.name?Ph(U.name):"",X=b.record,Q=typeof(X==null?void 0:X.node_id)=="string"?X.node_id:"",oe=typeof(X==null?void 0:X.status)=="string"?X.status:"",Ge=typeof((xn=X==null?void 0:X.effect)==null?void 0:xn.type)=="string"?X.effect.type:"",ke=typeof(X==null?void 0:X.run_id)=="string"?X.run_id:"",ye=ke||F;if(Z==="abstract.status"&&ye===F){const{text:ft,duration:en}=kd(U==null?void 0:U.payload);Us(ft,en)}const Fe=Q?lr(ye,Q):"";if(oe==="waiting"){const ft=Za(X);if(String((ft==null?void 0:ft.reason)||"").trim()==="subworkflow"){const Yn=typeof((qt=ft==null?void 0:ft.details)==null?void 0:qt.sub_run_id)=="string"?String(ft.details.sub_run_id):"";Yn&&Q&&nd(ye,Q,Yn)}}if(Q&&(Lc(lr(ye,Q)),oe==="waiting"||oe==="running")){const ft=lr(ye,Q);ft&&($o.current=ft,ea(ft))}let Pe="step",rt=Fe||Q||"(node?)",gt="";if(U&&U.name&&Mw(U.name))Pe=Z==="abstract.message"?"message":"event",rt=Z||U.name,gt=tn(Z==="abstract.steer_seen"?Tw(U==null?void 0:U.payload):kd(U==null?void 0:U.payload).text);else if(X!=null&&X.error)Pe="error",rt="error",gt=tn(Br(X.error,360));else if(oe==="waiting"){const ft=Za(X),en=String((ft==null?void 0:ft.reason)||"").trim();gt=tn(en?`waiting • ${en}`:"waiting")}else X!=null&&X.result?gt=tn(Br(X.result,360)):Ge?gt=tn(Ge):gt=tn(Lp(X));kn({id:`step:${ke||F||"?"}:${b.cursor}`,ts:String((X==null?void 0:X.ended_at)||(X==null?void 0:X.started_at)||an()),kind:Pe,title:rt,preview:gt,data:X,cursor:b.cursor,run_id:ke||F||void 0,node_id:Fe||Q,status:oe,effect_type:Ge,emit_name:Z||(U==null?void 0:U.name)||void 0})}function m_(b,T){var gt,dt,xn;Bn.current=Math.max(Bn.current,T.cursor);const F=`${b}:${T.cursor}`;if(!!Ei.current.has(F))return;Ei.current.add(F),(gt=ws.current)==null||gt.push({run_id:b,cursor:T.cursor,record:T.record});const Z=cp(T.record),X=Z&&Z.name?Ph(Z.name):"",Q=T.record,oe=typeof(Q==null?void 0:Q.node_id)=="string"?Q.node_id:"",Ge=oe?lr(b,oe):"",ke=typeof(Q==null?void 0:Q.status)=="string"?Q.status:"",ye=typeof((dt=Q==null?void 0:Q.effect)==null?void 0:dt.type)=="string"?Q.effect.type:"";if(ke==="waiting"){const qt=Za(Q);if(String((qt==null?void 0:qt.reason)||"").trim()==="subworkflow"){const en=typeof((xn=qt==null?void 0:qt.details)==null?void 0:xn.sub_run_id)=="string"?String(qt.details.sub_run_id):"";en&&oe&&nd(b,oe,en),en&&xr.current.trim()===String(b||"").trim()&&(xr.current=en,Ai(en))}}if(oe&&(Lc(lr(b,oe)),ke==="waiting"||ke==="running")){const qt=lr(b,oe);qt&&($o.current=qt,ea(qt))}if((ke==="completed"||ke==="failed")&&xr.current.trim()===String(b||"").trim()){const qt=String(Kr.current[String(b||"").trim()]||"").trim();qt&&qt!==l.trim()?(xr.current=qt,Ai(qt)):(xr.current="",Ai(""))}if(X==="abstract.status"&&b===l.trim()){const{text:qt,duration:ft}=kd(Z==null?void 0:Z.payload);Us(qt,ft)}let Fe="step",Pe=Ge||oe||"(node?)",rt="";if(Z&&Z.name&&Mw(Z.name))Fe=X==="abstract.message"?"message":"event",Pe=`subrun • ${X||Z.name}`,rt=tn(X==="abstract.steer_seen"?Tw(Z==null?void 0:Z.payload):kd(Z==null?void 0:Z.payload).text);else if(Q!=null&&Q.error)Fe="error",Pe="error",rt=tn(Br(Q.error,360));else if(ke==="waiting"){const qt=Za(Q),ft=String((qt==null?void 0:qt.reason)||"").trim();rt=tn(ft?`waiting • ${ft}`:"waiting")}else Q!=null&&Q.result?rt=tn(Br(Q.result,360)):ye?rt=tn(ye):rt=tn(Lp(Q));kn({id:`step:${b}:${T.cursor}`,ts:String((Q==null?void 0:Q.ended_at)||(Q==null?void 0:Q.started_at)||an()),kind:Fe,title:Pe,preview:rt,data:Q,cursor:T.cursor,run_id:b,node_id:Ge||oe,status:ke,effect_type:ye,emit_name:X||(Z==null?void 0:Z.name)||""})}function __(b,T){var dt,xn,qt;const F=String(b||"").trim();if(!F)return;const U=`${F}:${T.cursor}`;if(!!Ei.current.has(U))return;Ei.current.add(U),(dt=ws.current)==null||dt.push({run_id:F,cursor:T.cursor,record:T.record});const X=cp(T.record),Q=X&&X.name?Ph(X.name):"",oe=T.record,Ge=typeof(oe==null?void 0:oe.node_id)=="string"?oe.node_id:"",ke=Ge?lr(F,Ge):"",ye=typeof(oe==null?void 0:oe.status)=="string"?oe.status:"",Fe=typeof((xn=oe==null?void 0:oe.effect)==null?void 0:xn.type)=="string"?oe.effect.type:"";if(ye==="waiting"){const ft=Za(oe);if(String((ft==null?void 0:ft.reason)||"").trim()==="subworkflow"){const Yn=typeof((qt=ft==null?void 0:ft.details)==null?void 0:qt.sub_run_id)=="string"?String(ft.details.sub_run_id):"";Yn&&Ge&&nd(F,Ge,Yn)}}if(Ge&&(Lc(lr(F,Ge)),ye==="waiting"||ye==="running")){const ft=lr(F,Ge);ft&&($o.current=ft,ea(ft))}if(Q==="abstract.status"&&F===l.trim()){const{text:ft,duration:en}=kd(X==null?void 0:X.payload);Us(ft,en)}let Pe="step",rt=ke||Ge||"(node?)",gt="";if(X&&X.name&&Mw(X.name))Pe=Q==="abstract.message"?"message":"event",rt=`subrun • ${Q||X.name}`,gt=tn(Q==="abstract.steer_seen"?Tw(X==null?void 0:X.payload):kd(X==null?void 0:X.payload).text);else if(oe!=null&&oe.error)Pe="error",rt="error",gt=tn(Br(oe.error,360));else if(ye==="waiting"){const ft=Za(oe),en=String((ft==null?void 0:ft.reason)||"").trim();gt=tn(en?`waiting • ${en}`:"waiting")}else oe!=null&&oe.result?gt=tn(Br(oe.result,360)):Fe?gt=tn(Fe):gt=tn(Lp(oe));kn({id:`step:${F}:${T.cursor}`,ts:String((oe==null?void 0:oe.ended_at)||(oe==null?void 0:oe.started_at)||an()),kind:Pe,title:rt,preview:gt,data:oe,cursor:T.cursor,run_id:F,node_id:ke||Ge,status:ye,effect_type:Fe,emit_name:Q||(X==null?void 0:X.name)||""})}async function Yf(b,T){var U,Z;let F=T.after;for(;;){if((U=T.signal)!=null&&U.aborted)return F;const X=await Ke.get_ledger(b,{after:F,limit:200,signal:T.signal});if((Z=T.signal)!=null&&Z.aborted)return F;const Q=Array.isArray(X.items)?X.items:[];if(!Q.length)return Ar.current=F,F;const oe=F;for(let Ge=0;Ge<Q.length;Ge++){const ke=Q[Ge];sd({cursor:oe+Ge+1,record:ke},b)}F=typeof X.next_after=="number"?X.next_after:F}}async function rd(b){var X,Q,oe,Ge;const T=String(b||"").trim();An(""),Qt(!0),is(!1),(X=As.current)==null||X.reset(),(Q=ws.current)==null||Q.reset(),_r.current={scanned:0,found:null},Xe([]),Ar.current=0,un([]),Ei.current=new Set,pf([]),Vm(""),ml(""),Ct(null),li(""),Sf(""),ea(""),$o.current="",Oa({}),Iu({}),bl.current=[],Ia(Date.now()),vc.current=T?{[T]:""}:{},Kr.current={},xc.current={},Pa.current=new Set,Ou([]),Eo.current="",xr.current="",Ai(""),ta.current={},Gr.current&&window.clearTimeout(Gr.current),Gr.current=null,rr.current&&window.clearTimeout(rr.current),rr.current=null,Ao.current&&Ao.current.abort(),vr.current&&vr.current.abort(),vr.current=null,Bn.current=0,jl("");const F=new AbortController;Ao.current=F;let U=!1;try{let ke="",ye="";try{const Fe=await Ke.get_run(T);Ct(Fe);const Pe=typeof(Fe==null?void 0:Fe.workflow_id)=="string"?String(Fe.workflow_id):"",rt=Hj(Pe);rt&&(ke=rt.bundle_id,ye=rt.flow_id)}catch{}try{const Fe=await Ke.get_run_input_data(T);typeof(Fe==null?void 0:Fe.bundle_id)=="string"&&(ke=String(Fe.bundle_id||"").trim()||ke),typeof(Fe==null?void 0:Fe.flow_id)=="string"&&(ye=String(Fe.flow_id||"").trim()||ye);const Pe=Fe&&typeof Fe.input_data=="object"&&Fe.input_data&&!Array.isArray(Fe.input_data)?Fe.input_data:null;Pe&&S(JSON.stringify(Pe,null,2));const rt=Fe==null?void 0:Fe.workspace,gt=typeof(rt==null?void 0:rt.workspace_root)=="string"?String(rt.workspace_root).trim():"";Sf(gt)}catch{Sf("")}ke&&ye&&($(ke),v(ye),wr(ye),await cs(ke)),await Yf(T,{after:0,signal:F.signal});try{const Fe=await Ke.get_run_history_bundle(T,{include_subruns:!0,include_session:!1,ledger_mode:"tail",ledger_max_items:1}),Pe=Fe&&typeof Fe=="object"?Fe.ledgers:null,gt=(Pe&&typeof Pe=="object"?Object.keys(Pe):[]).map(dt=>String(dt||"").trim()).filter(Boolean).filter(dt=>dt!==T);if(gt.length){for(const dt of gt)Pa.current.add(dt);Ou(dt=>Array.from(new Set([...dt,...gt])));try{const dt=typeof((oe=Pe==null?void 0:Pe[T])==null?void 0:oe.total)=="number"?Number(Pe[T].total):0;let xn="",qt=-1;for(const ft of gt){const en=typeof((Ge=Pe==null?void 0:Pe[ft])==null?void 0:Ge.total)=="number"?Number(Pe[ft].total):0;en>qt&&(xn=ft,qt=en)}xn&&qt>Math.max(dt*3,dt+20)&&(xr.current=xn,Ai(xn))}catch{}}}catch{}is(!0),kn({ts:an(),kind:"info",title:`Attached to run ${T}`,data:{run_id:T}}),U=!0}catch(ke){if(F.signal.aborted||String((ke==null?void 0:ke.name)||"")==="Superseded")return;const ye=String((ke==null?void 0:ke.message)||ke||"unknown error");An(ye),kn({ts:an(),kind:"error",title:"Connection error",preview:tn(ye),data:{error:ye}}),is(!1)}finally{F.signal.aborted||Qt(!1)}if(!U||F.signal.aborted)return;(async()=>{let ke=250;for(;!F.signal.aborted;){try{const ye=await Yf(T,{after:Ar.current,signal:F.signal});await Ke.stream_ledger(T,{after:ye,on_step:Fe=>sd(Fe,T),signal:F.signal})}catch(ye){if(F.signal.aborted)break;const Fe=String((ye==null?void 0:ye.message)||ye||"stream error");kn({ts:an(),kind:"error",title:"Ledger stream error (will retry)",preview:tn(Fe),data:{error:Fe}})}if(F.signal.aborted)break;await new Promise(ye=>setTimeout(ye,ke)),ke=Math.min(5e3,Math.floor(ke*1.6))}})()}async function p_(){const b=jr,T=(b==null?void 0:b.kind)==="bundle"?b.flow_id:(b==null?void 0:b.kind)==="default"?"@default":"",F=(b==null?void 0:b.kind)==="bundle"?b.bundle_id:"";if(!b){const U="Select a workflow first (Launch → pick a workflow).";return An(U),U}An(""),Qt(!0);try{let U={};const Z=C.trim();if(Z)try{if(U=JSON.parse(Z),typeof U!="object"||U===null||Array.isArray(U))throw new Error("input_data must be a JSON object")}catch(Fe){const Pe=`Invalid input_data JSON: ${String((Fe==null?void 0:Fe.message)||Fe)}`;return An(Pe),Pe}for(const[Fe,Pe]of Object.entries(U)){if(typeof Pe!="string")continue;const rt=Pe.trim();rt?U[Fe]=rt:delete U[Fe]}const X=(Xr||[]).find(Fe=>Fe&&typeof Fe=="object"&&Fe.id==="prompt"),Q=X&&typeof X=="object"&&Object.prototype.hasOwnProperty.call(X,"default"),oe=U==null?void 0:U.prompt,Ge=typeof oe=="string"?oe.trim():"";if(X&&!Q&&!Ge){const Fe="Missing required input_data.prompt";return An(Fe),Fe}const ke=U.workspace&&typeof U.workspace=="object"?U.workspace:null;delete U.workspace;const ye=await Ke.start_run(T,U,{...ke?{workspace:ke}:{},...F?{bundle_id:F}:{},...b.kind==="default"?{interface:b.interface}:{},session_id:String(D||"").trim()||null});return m(ye),d(ye),nr(""),await rd(ye),Dn(),null}catch(U){const Z=String((U==null?void 0:U.message)||U||"start failed");return An(Z),Z}finally{Qt(!1)}}async function ty(){if(Lt([]),Se(null),!pe.available){Lt([pe.reason]);return}const b=h3(ot,{choice:jr,bundle_ref_for:T=>{var F;return((F=It.find(U=>U.bundle_id===T))==null?void 0:F.bundle_ref)||""},input_data:on,email_usable:Un.email_usable,defaults:Do,mailboxes:ui.mailboxes,connections:ui.trigger_connections},$e.current);if(!b.ok){Lt(b.errors);return}ne(!0);try{const T=await Ke.automations_client().createAutomation(b.body);$e.current.reset(),fe([]),mt(iv),Rl.current="",kn({ts:an(),kind:"info",title:"Automation created",preview:tn(`${b.body.title} · ${T.automation_id}`)}),Te(!1),t("automations"),await Un.refresh(),await Un.select(T.automation_id)}catch(T){const F=(T&&typeof T=="object"&&typeof T.code=="string"?T:null)||{status:0,code:"client_error",message:String((T==null?void 0:T.message)||T||"Create failed")};Se(F)}finally{ne(!1)}}async function ny(){if(nr(""),Ne==="automate"){await ty();return}const b=await p_();if(b){nr(b);return}Te(!1),No("ledger"),t("observe")}async function Xf(b){if(Qn("skills",void 0),!!b){if(b.kind==="default"){$t(b.interface),$(""),v(""),A(null);return}$t(""),$(b.bundle_id),v(b.flow_id),wr(b.flow_id),await cs(b.bundle_id)}}async function Zf(b){const[T,F]=await Promise.all([Ke.get_run(b),Ke.get_run_input_data(b)]),U=x3(T,F);await Xf(U.choice),S(JSON.stringify(U.input_data,null,2)),mt(U.form),fe([`Recreating the legacy schedule ${Ln(b,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...U.notes]),$e.current.reset(),Qe("automate")}async function Ri(b,T){const F=String(b||"").trim();if(!F)return;if(Be){Us(`Still attaching — retry in a moment (${Ln(F,14)})`,2500);return}An(""),x("");const U=String((T==null?void 0:T.root_run_id)||F).trim()||F;m(U),d(F),await rd(F)}p.useEffect(()=>{const b=String(_||"").trim();if(!b)return;let T=!1;return(async()=>{try{if(L||await Fo({open_modal_if_needed:!0}),T)return;No("ledger"),t("observe");const F=await Ke.find_run(b);if(T)return;if(F===null){Fl(),x(b);return}await Ri(b),ql()}catch(F){T||An(String((F==null?void 0:F.message)||F||"Failed to attach run from URL"))}finally{T||g("")}})(),()=>{T=!0}},[_]);function Fl(){var b,T;Ao.current&&Ao.current.abort(),Ao.current=null,vr.current&&vr.current.abort(),vr.current=null,Bn.current=0,jl(""),d(""),m(""),vc.current={},Kr.current={},xc.current={},Pa.current=new Set,Ou([]),Eo.current="",xr.current="",Ai(""),ta.current={},li(""),Gr.current&&window.clearTimeout(Gr.current),Gr.current=null,rr.current&&window.clearTimeout(rr.current),rr.current=null,is(!1),Qt(!1),Fn(!1),Ar.current=0,(b=As.current)==null||b.reset(),(T=ws.current)==null||T.reset(),_r.current={scanned:0,found:null},Xe([]),un([]),Ei.current=new Set,Ct(null),pf([]),ea(""),$o.current="",Oa({}),Iu({}),bl.current=[],Ia(Date.now()),Us("",-1),An(""),bn([]),Hn(null),De(""),ht(""),pn(!1),Vi(!1),Hi(""),mc(""),Ta(""),_c([]),ju(!1),Su(""),Nu(""),pl(!1),Ma("")}p.useEffect(()=>{bn([]),Hn(null),De(""),ht(""),pn(!1),Vi(!1),Hi(""),mc(""),Ta(""),_c([]),ju(!1),Su(""),Nu(""),pl(!1),Ma("")},[l]),p.useEffect(()=>{Ns==="chat"&&l.trim()&&L&&Oc()},[Ns,l,L,ve==null?void 0:ve.workflow_id]);async function Ic(b,T,F){const U=String(b||"").trim();if(!U)return An("Missing run_id"),"Missing run_id";An("");try{const Z={},X=String((F==null?void 0:F.reason)||"").trim();X&&(Z.reason=X),await Ke.submit_command({command_id:Zs(),run_id:U,type:T,payload:Z,client_id:"web_pwa"}),kn({ts:an(),kind:"info",title:`${T} submitted`,preview:X?`reason: ${X}`:"",data:{run_id:U,type:T,reason:X}});try{if(U===l.trim()){const Q=await Ke.get_run(U);Ct(Q)}}catch{}return Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),900),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400),null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||`${T} failed`);return An(X),X}}async function sy(b,T){const F=b.map(Ge=>String(Ge||"").trim()).filter(Boolean),U=[];let Z=0,X=0,Q=0;const oe=async()=>{for(;Q<F.length;){const Ge=F[Q++];try{await Ke.submit_command({command_id:Zs(),run_id:Ge,type:"cancel",payload:{},client_id:"web_pwa"}),U.push({run_id:Ge,error:null})}catch(ke){X+=1,U.push({run_id:Ge,error:String((ke==null?void 0:ke.message)||ke||"cancel failed")})}Z+=1,T==null||T(Z,X)}};return await Promise.all(Array.from({length:Math.min(4,F.length)},oe)),kn({ts:an(),kind:X?"error":"info",title:`cancel submitted ×${F.length}${X?` · ${X} failed`:""}`,preview:"",data:{run_ids:F,failed:X}}),F.length&&(Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400)),U}async function Qf(b,T){return Ic(l.trim(),b,T)}async function _i(b,T="Stopped from AbstractObserver"){const F=String(b||"").trim();if(!F||!window.confirm(`Cancel run ${Ln(F,24)}?`))return;await Ic(F,"cancel",{reason:T})||Us("Cancel submitted",2)}async function eh(){var F;const b=l.trim();if(!b){An("Select a run first.");return}if(!L){An("Connect to the gateway first.");return}if(Ot)return;const T=String(((F=ve==null?void 0:ve.waiting)==null?void 0:F.reason)||"").trim().toLowerCase()||String(Ws||"").trim().toLowerCase();if(!Jn||pi||xs||Cs.toLowerCase()!=="waiting"||T!=="until"){An("This run is not a scheduled wait that can be triggered now.");return}An(""),Fn(!0);try{const U={payload:{mode:"run_now",requested_at:an()}},Z=String(cr||"").trim();Z&&(U.wait_key=Z),await Ke.submit_command({command_id:Zs(),run_id:b,type:"resume",payload:U,client_id:"web_pwa"}),kn({ts:an(),kind:"info",title:"Scheduled run triggered",preview:tn(`run ${b}`),data:{run_id:b,until:ao||null}});try{const X=await Ke.get_run(b);Ct(X)}catch{}}catch(U){An(String((U==null?void 0:U.message)||U||"Failed to trigger scheduled run"))}finally{Fn(!1)}}async function id(b){const T=l.trim();if(!T)return An("Missing run_id"),"Missing run_id";if(oi)return"Schedule update already in progress";const F=String(b.interval||"").trim();if(!/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)\s*$/i.test(F)){const Z="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return Ss(Z),Z}Ss(""),An(""),Ui(!0),Qt(!0);try{await Ke.submit_command({command_id:Zs(),run_id:T,type:"update_schedule",payload:{interval:F,apply_immediately:b.apply_immediately!==!1},client_id:"web_pwa"}),kn({ts:an(),kind:"info",title:"Schedule updated",preview:tn(`interval: ${F}`),data:{interval:F},run_id:T});try{const Z=await Ke.get_run(T);Ct(Z)}catch{}return null}catch(Z){const X=String((Z==null?void 0:Z.message)||Z||"update_schedule failed");return Ss(X),An(X),X}finally{Qt(!1),Ui(!1)}}async function g_(b){const T=l.trim();if(!T)return An("Missing run_id"),"Missing run_id";if(zs)return"Compaction already in progress";const F=typeof(b==null?void 0:b.preserve_recent)=="number"?b.preserve_recent:fl,U=Math.max(0,Math.min(500,Math.floor(Number.isFinite(F)?F:6))),Z=(b==null?void 0:b.compression_mode)||Tr,X=String((b==null?void 0:b.focus)??Wi??"").trim();Fs(""),An(""),gr(!0),Qt(!0);try{const Q={preserve_recent:U,compression_mode:Z};return X&&(Q.focus=X),await Ke.submit_command({command_id:Zs(),run_id:T,type:"compact_memory",payload:Q,client_id:"web_pwa"}),kn({ts:an(),kind:"info",title:"Compaction requested",preview:tn(`mode: ${Z} • preserve_recent: ${U}`),data:Q,run_id:T}),null}catch(Q){const oe=String((Q==null?void 0:Q.message)||Q||"compact_memory failed");return Fs(oe),An(oe),oe}finally{Qt(!1),gr(!1)}}async function y_(){const b=l.trim();if(!b){ht("Select a run first.");return}if(!L){ht("Connect to the gateway first.");return}const T=Oe.trim();if(!T||Bt)return;if(oo.voice_ptt_busy){Dt("Wait for transcription to finish.");return}ht(""),Dt(""),pn(!0);const U={id:`local:${Zs()}`,role:"user",content:T,ts:an()};bn(Z=>[...Z,U]),De("");try{const Z=XI(Ft,U),X=n.maintenance_ai_provider.trim(),Q=n.maintenance_ai_model.trim(),oe=await Ke.run_chat(b,{provider:X||void 0,model:Q||void 0,include_subruns:!0,messages:Z}),Ge=String((oe==null?void 0:oe.answer)||"").trim()||"(empty response)",ke=String((oe==null?void 0:oe.generated_at)||"").trim()||an();Hn((oe==null?void 0:oe.history)??null),bn(ye=>[...ye,{id:`local:${Zs()}`,role:"assistant",content:Ge,ts:ke}])}catch(Z){const X=LO(Z);ht(X),bn(Q=>[...Q,{id:`local:${Zs()}`,role:"assistant",content:`(error: ${X})`,ts:an(),local_error:!0}])}finally{pn(!1)}}function w_(b){const T=String(b.id||b.ts||"").trim(),F=String(b.content||"").trim();!T||!F||(Dt(""),oo.toggle_tts(T,F))}function th(b){const T=String(b.id||b.ts||"").trim(),F=oo.tts_playback;return!T||!F.key||F.key!==T?"idle":F.status}function Va(b){if(!Ft.length)return;const T=l.trim(),F=T?`Run ${T}`:"Chat",U=hN(Ft.map(Z=>({role:Z.role,content:Z.content,ts:Z.ts})),{heading:F});if(b==="download"){const Z=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),X=`abstractobserver-chat-${$0(T||"run")}-${Z}.md`;mN({filename:X,text:U,mime:"text/markdown;charset=utf-8"});return}(async()=>{const Z=await il(U);Js(Z?"copied":"failed"),window.setTimeout(()=>Js("idle"),900)})()}async function Oc(){const b=typeof(ve==null?void 0:ve.workflow_id)=="string"?String(ve.workflow_id).trim():"";if(!b){_c([]);return}if(L&&!pc){Su(""),ju(!0);try{const T=await Ke.list_runs({limit:200,workflow_id:b,root_only:!0}),F=Array.isArray(T==null?void 0:T.items)?T.items:[],U=[];for(const ke of F){const ye=typeof(ke==null?void 0:ke.run_id)=="string"?String(ke.run_id).trim():"";if(!ye)continue;const Fe=typeof(ke==null?void 0:ke.ledger_len)=="number"?Number(ke.ledger_len):0;U.push({run_id:ye,ledger_len:Number.isFinite(Fe)?Fe:0})}if(!U.length){_c([]);return}const Z=400,X=U.map(ke=>({run_id:ke.run_id,after:Math.max(0,(ke.ledger_len||0)-Z)})),Q=await Ke.get_ledger_batch({runs:X,limit:Z}),oe=[],Ge=new Set;for(const ke of U){const ye=Q!=null&&Q.runs&&typeof Q.runs=="object"?Q.runs[ke.run_id]:null,Fe=Array.isArray(ye==null?void 0:ye.items)?ye.items:[];for(const Pe of Fe){const rt=Pe==null?void 0:Pe.effect;if(!rt||typeof rt!="object"||String(rt.type||"")!=="emit_event")continue;const gt=rt.payload;if(!gt||typeof gt!="object"||String(gt.name||"")!=="abstract.chat.thread")continue;const dt=gt.payload;if(!dt||typeof dt!="object")continue;const xn=typeof dt.thread_id=="string"?String(dt.thread_id).trim():"";if(!xn||Ge.has(xn))continue;Ge.add(xn);const qt=typeof dt.created_at=="string"?String(dt.created_at):"",ft=typeof dt.title=="string"?String(dt.title):"",en=typeof dt.workflow_id=="string"?String(dt.workflow_id):b,Yn=typeof dt.run_id=="string"?String(dt.run_id):ke.run_id,ds=typeof dt.provider=="string"?String(dt.provider):"",dr=typeof dt.model=="string"?String(dt.model):"",wi=typeof dt.message_count=="number"?Number(dt.message_count):null,vi=dt.chat_artifact,Vl=vi&&typeof vi=="object"&&typeof vi.$artifact=="string"?String(vi.$artifact):"";Vl&&oe.push({thread_id:xn,created_at:qt,title:ft||`Chat ${xn.slice(0,8)}`,run_id:Yn,workflow_id:en,message_count:wi,provider:ds,model:dr,artifact_id:Vl})}}oe.sort((ke,ye)=>String(ye.created_at||"").localeCompare(String(ke.created_at||""))),_c(oe)}catch(T){Su(String((T==null?void 0:T.message)||T||"Failed to load saved discussions"))}finally{ju(!1)}}}async function nh(){const b=l.trim();if(!b){Hi("Select a run first.");return}if(!L){Hi("Connect to the gateway first.");return}if(Ft.length&&!yr){Hi(""),Vi(!0);try{const T=n.maintenance_ai_provider.trim(),F=n.maintenance_ai_model.trim(),U=await Ke.save_chat_thread(b,{provider:T||void 0,model:F||void 0,include_subruns:!0,messages:Ft.map(Q=>({role:Q.role,content:Q.content,ts:Q.ts}))}),Z=typeof(U==null?void 0:U.created_at)=="string"?String(U.created_at):an();mc(Z);try{const Q=JSON.stringify(Ft.map(oe=>({role:oe.role,content:oe.content,ts:oe.ts})));Ta(Q)}catch{Ta("1")}typeof(U==null?void 0:U.thread_id)=="string"&&String(U.thread_id).trim()&&Nu(String(U.thread_id).trim());const X=!!(U!=null&&U.duplicate);Us(X?"Already saved":"Saved discussion",2),await Oc()}catch(T){Hi(String((T==null?void 0:T.message)||T||"Failed to save discussion"))}finally{Vi(!1)}}}async function ry(){const b=String(mf||"").trim();if(!b)return;const T=ff.find(Z=>String(Z.thread_id||"").trim()===b)||null;if(!T){Ma("Saved discussion not found (refresh list).");return}if(!L){Ma("Connect to the gateway first.");return}if($u)return;const F=Ft.length>0,U=(()=>{if(!F)return!1;if(!Aa)return!0;try{return JSON.stringify(Ft.map(X=>({role:X.role,content:X.content,ts:X.ts})))!==Aa}catch{return!0}})();if(!(F&&U&&!window.confirm("Replace the current chat with the selected saved discussion? Unsaved changes will be lost."))){Ma(""),pl(!0);try{const X=await(await Ke.download_run_artifact_content(T.run_id,T.artifact_id)).text(),Q=JSON.parse(X),oe=Array.isArray(Q==null?void 0:Q.messages)?Q.messages:[],Ge=typeof(Q==null?void 0:Q.created_at)=="string"?String(Q.created_at):String(T.created_at||""),ke=[];for(let ye=0;ye<oe.length;ye++){const Fe=oe[ye];if(!Fe||typeof Fe!="object")continue;const Pe=String(Fe.role||"").trim()==="assistant"?"assistant":"user",rt=typeof Fe.content=="string"?String(Fe.content):"";if(!rt.trim())continue;const gt=typeof Fe.ts=="string"?String(Fe.ts):Ge||an();ke.push({id:`thread:${b}:${ye}`,role:Pe,content:rt.trim(),ts:gt})}bn(ke),Hn(null),De(""),ht(""),Hi(""),mc(Ge||"");try{const ye=JSON.stringify(ke.map(Fe=>({role:Fe.role,content:Fe.content,ts:Fe.ts})));Ta(ye)}catch{Ta("1")}Us("Loaded discussion",2)}catch(Z){Ma(String((Z==null?void 0:Z.message)||Z||"Failed to load saved discussion"))}finally{pl(!1)}}}async function Pc(b){const T=l.trim(),F=String((dn==null?void 0:dn.wait_key)||"").trim();if(!T||!F){An("No active wait to resume");return}if(String((dn==null?void 0:dn.reason)||"").trim()==="subworkflow"){An("This run is waiting on a subworkflow; attach to the child run instead of resuming manually.");return}An(""),Fn(!0);try{await Ke.submit_command({command_id:Zs(),run_id:T,type:"resume",payload:{wait_key:F,payload:b||{}},client_id:"web_pwa"}),kn({ts:an(),kind:"info",title:"Resume submitted",preview:tn(`wait_key: ${F}`),data:{wait_key:F,payload:b||{}}}),li(F);try{const U=await Ke.get_run(T);Ct(U)}catch{}Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),900),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400),rr.current&&window.clearTimeout(rr.current),rr.current=window.setTimeout(()=>{li(U=>U===F?"":U)},2e3)}catch(U){An(String((U==null?void 0:U.message)||U||"resume failed"))}finally{Fn(!1)}}async function v_(b){if(!so){An("No worker configured");return}if(!Ot){An(""),Fn(!0);try{const T=[];for(const F of b){const U=await so.call_tool(F);T.push(U)}await Pc({mode:"executed",results:T})}finally{Fn(!1)}}}const aa=p.useMemo(()=>af(dn),[dn]),cr=String((dn==null?void 0:dn.wait_key)||"").trim(),Ws=String((dn==null?void 0:dn.reason)||"").trim(),ao=typeof(dn==null?void 0:dn.until)=="string"?String(dn.until):"",Cs=typeof(ve==null?void 0:ve.status)=="string"?String(ve.status):"",xs=!!(ve!=null&&ve.paused),pi=Cs==="completed"||Cs==="failed"||Cs==="cancelled",x_=Ws==="until"&&!!ao,Dc=!pi&&O4(ar)&&(!!cr||x_),b_=Ws==="user",od=Ws==="event"?Ph(Uq(cr)):"",sh=Ws==="event"&&od==="abstract.ask",k_=aa.length>0,ad=Dc&&cr&&(b_||sh||k_)&&uf!==cr&&e!=="board"&&!(e==="observe"&&Ns==="agent"),la=typeof((_d=dn==null?void 0:dn.details)==null?void 0:_d.sub_run_id)=="string"?String(dn.details.sub_run_id):"",zl={run_id:l.trim(),workflow_id:typeof(ve==null?void 0:ve.workflow_id)=="string"?String(ve.workflow_id):null,status:Cs,created_at:typeof(ve==null?void 0:ve.created_at)=="string"?String(ve.created_at):null,updated_at:typeof(ve==null?void 0:ve.updated_at)=="string"?String(ve.updated_at):null,session_id:typeof(ve==null?void 0:ve.session_id)=="string"?String(ve.session_id):null,current_node:typeof(ve==null?void 0:ve.current_node)=="string"?String(ve.current_node):null},ld=hn.slice(-10).map(b=>{var T,F,U,Z,X,Q;return{cursor:b.cursor,node_id:String(((T=b.record)==null?void 0:T.node_id)||"").trim(),status:String(((F=b.record)==null?void 0:F.status)||"").trim(),effect_type:String(((Z=(U=b.record)==null?void 0:U.effect)==null?void 0:Z.type)||"").trim(),ts:String(((X=b.record)==null?void 0:X.ended_at)||((Q=b.record)==null?void 0:Q.started_at)||"").trim(),summary:L1(b.record)}}),cd=xx(dn,aa),j_=A1(dn,aa),ud=T1(dn,on),zo=ud.text,iy=ud.runtime_metadata,Fc=String((dn==null?void 0:dn.prompt)||"").trim(),dd=x4(on,6),S_=!!(Fc&&$1(Fc)),Bl=!!(Fc&&!S_),Bo=Bl?"Question from workflow":zo&&zo!==Fc?"Closest prior user request":"Request context",oy=j4(on,C),N_=!!C.trim(),Sr=ve!=null&&ve.schedule&&typeof ve.schedule=="object"?ve.schedule:null,Ha=typeof(Sr==null?void 0:Sr.interval)=="string"?String(Sr.interval).trim():"",$_=typeof(Sr==null?void 0:Sr.share_context)=="boolean"?!!Sr.share_context:null,Ul=typeof(Sr==null?void 0:Sr.repeat_count)=="number"?Number(Sr.repeat_count):null,Jn=!!(ve!=null&&ve.is_scheduled)||!!Sr,rh=Jn&&!!Ha,C_=Cs==="running"&&!xs?"Pause":"Resume",zc=Jn?xs?"resume":"pause":C_==="Pause"?"pause":"resume",ur=Jn?!l.trim()||Be||Ot||pi:!l.trim()||Be||Ot||pi||zc==="resume"&&!xs,ay=l.trim()?pi?"The schedule has ended.":null:"No run selected.",Nt=Jn&&!xs&&!pi&&!Be&&!Ot&&Cs.toLowerCase()==="waiting"&&(String(((ma=ve==null?void 0:ve.waiting)==null?void 0:ma.reason)||"").trim().toLowerCase()==="until"||Ws==="until")&&!!String(ao||"").trim(),qs=(pd=ve==null?void 0:ve.limits)==null?void 0:pd.tokens,Ga=typeof(qs==null?void 0:qs.pct)=="number"?Number(qs.pct):null,ih=qs==null?void 0:qs.estimated_used,E_=(qs==null?void 0:qs.max_input_tokens)??(qs==null?void 0:qs.max_tokens),lo=p.useMemo(()=>{const b=_r.current;hn.length<b.scanned&&(b.scanned=0,b.found=null);for(let T=b.scanned;T<hn.length;T++){const F=hn[T],U=F==null?void 0:F.record;if(!U)continue;const Z=cp(U);if((Z&&Z.name?Ph(Z.name):"")!=="abstract.summary")continue;const Q=Z!=null&&Z.payload&&typeof Z.payload=="object"?Z.payload:{},oe=typeof(Q==null?void 0:Q.text)=="string"?String(Q.text):"";oe.trim()&&(b.found={cursor:F.cursor,ts:String((U==null?void 0:U.ended_at)||(U==null?void 0:U.started_at)||""),text:oe,provider:typeof(Q==null?void 0:Q.provider)=="string"?String(Q.provider):void 0,model:typeof(Q==null?void 0:Q.model)=="string"?String(Q.model):void 0,generated_at:typeof(Q==null?void 0:Q.generated_at)=="string"?String(Q.generated_at):void 0,source:Q==null?void 0:Q.source})}return b.scanned=hn.length,b.found},[hn]);p.useEffect(()=>{xr.current=Ir.trim()},[Ir]),p.useEffect(()=>{const b=l.trim(),T=la.trim();if(!(Ht&&Ws==="subworkflow"&&!!T&&T!==b)){Eo.current="",Ir.trim()&&Ai("");return}Eo.current!==T&&(Eo.current=T,xr.current=T,Ai(T))},[Ht,l,Ws,la,Ir]),p.useEffect(()=>{Ru({})},[N]);const Bc=p.useMemo(()=>((Array.isArray(O==null?void 0:O.entrypoints)?O==null?void 0:O.entrypoints:[])||[]).map(T=>String((T==null?void 0:T.flow_id)||"").trim()).filter(Boolean),[O]),Li=p.useMemo(()=>{const b=String((ve==null?void 0:ve.workflow_id)||"").trim();return Ht&&Jn?b:""},[Ht,Jn,ve==null?void 0:ve.workflow_id]),A_=p.useMemo(()=>{var Q;if(!Ht||!l.trim()||!Li.trim())return Lr;const b=String((ve==null?void 0:ve.status)||"").trim().toLowerCase(),T=String((ve==null?void 0:ve.current_node)||"").trim();if(b!=="waiting"&&b!=="running"||!T)return Lr;const F=lr(l.trim(),T);if(!F)return Lr;const U=String(Ws||((Q=ve==null?void 0:ve.waiting)==null?void 0:Q.reason)||"").trim().toLowerCase(),Z=typeof(ar==null?void 0:ar.node_id)=="string"?String(ar.node_id).trim():"",X=typeof(ar==null?void 0:ar.status)=="string"?String(ar.status).trim().toLowerCase():"";return b==="waiting"&&U==="until"||!Lr.trim()||(X==="waiting"||X==="running")&&!Z?F:Lr},[Ht,l,Li,ve==null?void 0:ve.status,ve==null?void 0:ve.current_node,(_a=ve==null?void 0:ve.waiting)==null?void 0:_a.reason,Ws,Lr,ar]),T_=p.useMemo(()=>{const b={},T=l.trim(),F=(U,Z)=>{if(!Z)return;const X=typeof(Z==null?void 0:Z.node_id)=="string"?String(Z.node_id).trim():"";if(!X)return;const Q=lr(U,X);if(!Q)return;const oe=String((Z==null?void 0:Z.ended_at)||(Z==null?void 0:Z.started_at)||"").trim(),Ge=Vt(oe);Ge!==null&&(b[Q]=Math.max(b[Q]||0,Ge))};for(const U of hn)U&&U.record&&F(T,U.record);for(const U of sn)U&&U.record&&F(String(U.run_id||"").trim(),U.record);return b},[hn,sn,l,Co]);p.useEffect(()=>{var F;if(!Ht||!l.trim()||!Li.trim())return;const b=String((ve==null?void 0:ve.current_node)||"").trim();!b||String(((F=ve==null?void 0:ve.waiting)==null?void 0:F.reason)||"").trim()==="subworkflow"||Lc(lr(l.trim(),b))},[Ht,l,Li,ve==null?void 0:ve.current_node,(fh=ve==null?void 0:ve.waiting)==null?void 0:fh.reason]),p.useEffect(()=>{const b=String((_s==null?void 0:_s.flow_id)||"").trim();b&&(vl.trim()||wr(b))},[_s,vl]),p.useEffect(()=>{const b=Li.trim(),T=N.trim(),F=vl.trim();if(b){let Z=!1;return Ra(!0),wc(""),Ke.get_workflow_flow(b).then(X=>{if(Z)return;const Q=X==null?void 0:X.flow;xl(Q&&typeof Q=="object"?Q:null)}).catch(X=>{Z||(xl(null),wc(String((X==null?void 0:X.message)||X||"Failed to load workflow flow")))}).finally(()=>{Z||Ra(!1)}),()=>{Z=!0}}if(!T||!F){xl(null),wc(""),Ra(!1);return}let U=!1;return Ra(!0),wc(""),Ke.get_bundle_flow(T,F).then(Z=>{if(U)return;const X=Z==null?void 0:Z.flow,Q=X&&typeof X=="object"?X:null;xl(Q),Q&&Ru(oe=>({...oe,[F]:Q}))}).catch(Z=>{U||(xl(null),wc(String((Z==null?void 0:Z.message)||Z||"Failed to load flow")))}).finally(()=>{U||Ra(!1)}),()=>{U=!0}},[Li,N,vl,Ke]),p.useEffect(()=>{const b=N.trim();if(!Ji||!b||!Ki)return;let T=!1;const F=3,U=ke=>{const ye=Array.isArray(ke==null?void 0:ke.nodes)?ke.nodes:[],Fe=[];for(const Pe of ye){const rt=Pe!=null&&Pe.data&&typeof Pe.data=="object"?Pe.data:{};if(String((rt==null?void 0:rt.nodeType)||(Pe==null?void 0:Pe.type)||"").trim()!=="subflow")continue;const dt=(rt==null?void 0:rt.subflowId)||(rt==null?void 0:rt.flowId),xn=typeof dt=="string"?dt.trim():"";xn&&Fe.push(xn.includes(":")?xn.split(":",2)[1]:xn)}return Fe},Z=new Set,X=new Set,Q=(ke,ye)=>{if(!(!ke||ye>=F))for(const Fe of U(ke)){const Pe=String(Fe||"").trim();if(!Pe||Z.has(Pe))continue;Z.add(Pe),X.add(Pe);const rt=yc[Pe];rt&&Q(rt,ye+1)}};Q(Ki,0);const oe=Array.from(X).filter(ke=>!yc[ke]).slice(0,20);return oe.length?((async()=>{for(const ke of oe){if(T)return;try{const ye=await Ke.get_bundle_flow(b,ke),Fe=ye==null?void 0:ye.flow,Pe=Fe&&typeof Fe=="object"?Fe:null;if(!Pe)continue;Ru(rt=>rt[ke]?rt:{...rt,[ke]:Pe})}catch{}}})(),()=>{T=!0}):void 0},[Ji,N,Ki,yc,Ke]);const oh=p.useMemo(()=>{const T=(Array.isArray(O==null?void 0:O.flows)?O==null?void 0:O.flows:[]).map(F=>String(F||"").trim()).filter(Boolean);return T.length?Array.from(new Set(T)).sort():Array.from(new Set(Bc)).sort()},[O,Bc]);p.useEffect(()=>{pi&&Lr.trim()&&(ea(""),$o.current="")},[pi,l,Lr]),p.useEffect(()=>{const b=Ir.trim(),T=l.trim();if(!(Ht&&!!b&&b!==T)){vr.current&&vr.current.abort(),vr.current=null,Bn.current=0,Pu&&jl("");return}if(Pu===b)return;vr.current&&vr.current.abort();const U=new AbortController;vr.current=U,Bn.current=0,jl(b),kn({ts:an(),kind:"info",title:`Following run ${b} (status/events)`});let Z=250;return(async()=>{for(;!U.signal.aborted;){try{await Ke.stream_ledger(b,{after:Bn.current,on_step:Q=>m_(b,Q),signal:U.signal});return}catch(Q){if(U.signal.aborted)break;const oe=String((Q==null?void 0:Q.message)||Q||"stream error");kn({ts:an(),kind:"error",title:"Child ledger stream error (will retry)",preview:tn(oe),data:{child_run_id:b,error:oe}})}if(U.signal.aborted)break;await new Promise(Q=>setTimeout(Q,Z)),Z=Math.min(5e3,Math.floor(Z*1.6))}})(),()=>{U.abort()}},[Ht,Ir,l,Ke,Pu]),p.useEffect(()=>{if(!Ht||!l.trim())return;let b=!1;const T=async()=>{if(!b&&!Da.current&&Co.length&&!(ut.current>Date.now())){Da.current=!0;try{const U=Co.map(oe=>String(oe||"").trim()).filter(Boolean);if(!U.length)return;const Z=U.map(oe=>({run_id:oe,after:Number(ta.current[oe]||0)})),X=await Ke.get_ledger_batch({runs:Z,limit:200}),Q=X&&typeof X=="object"?X.runs:{};for(const oe of U){if(b)return;const Ge=Q&&typeof Q=="object"?Q[oe]:null,ke=Array.isArray(Ge==null?void 0:Ge.items)?Ge.items:[],ye=typeof(Ge==null?void 0:Ge.next_after)=="number"?Ge.next_after:Number(ta.current[oe]||0),Fe=Number(ta.current[oe]||0);for(let Pe=0;Pe<ke.length;Pe++){const rt=ke[Pe];__(oe,{cursor:Fe+Pe+1,record:rt})}ta.current[oe]=ye}}catch(U){if(b||String((U==null?void 0:U.name)||"")==="Superseded")return;kn({ts:an(),kind:"error",title:"Subrun digest poll failed",preview:tn(String((U==null?void 0:U.message)||U||""))}),zm("Subrun digest poll failed",tn(String((U==null?void 0:U.message)||U||"")))}finally{Da.current=!1}}};T();const F=window.setInterval(()=>void T(),2e3);return()=>{b=!0,window.clearInterval(F),Da.current=!1}},[Ht,l,Co,Ke]);const Ii=p.useMemo(()=>{const b=l.trim(),T=[];for(const F of hn)!F||!F.record||T.push({run_id:b,cursor:F.cursor,record:F.record});for(const F of sn)!F||!F.record||T.push({run_id:String(F.run_id||"").trim(),cursor:F.cursor,record:F.record});return T},[hn,sn,l]),Uc=p.useMemo(()=>{var T,F,U,Z;const b={};for(const X of Ii){const Q=String(X.run_id||((T=X.record)==null?void 0:T.run_id)||"").trim();!Q||String(((U=(F=X.record)==null?void 0:F.effect)==null?void 0:U.type)||"").trim()!=="llm_call"||String(((Z=X.record)==null?void 0:Z.status)||"")!=="started"&&(b[Q]=(b[Q]||0)+1)}return b},[Ii]),Ys=p.useMemo(()=>{const b=Ir.trim();if(b)return b;let T="",F=-1;for(const[U,Z]of Object.entries(Uc))Z>F&&(T=U,F=Z);return T||l.trim()},[Uc,Ir,l]),Oi=(Qg.trim()||Ys).trim(),ca=p.useMemo(()=>{var Z;const b=new Set,T=l.trim(),F=Ir.trim();T&&b.add(T),F&&b.add(F);for(const X of Co){const Q=String(X||"").trim();Q&&b.add(Q)}for(const X of Ii){const Q=String(X.run_id||((Z=X.record)==null?void 0:Z.run_id)||"").trim();Q&&b.add(Q)}const U=Array.from(b);return U.sort((X,Q)=>T&&X===T&&Q!==T?-1:T&&Q===T&&X!==T?1:F&&X===F&&Q!==F?-1:F&&Q===F&&X!==F?1:X<Q?-1:X>Q?1:0),U},[l,Ir,Co,Ii]),ah=p.useMemo(()=>{var b;for(let T=hn.length-1;T>=0;T--){const F=I1((b=hn[T])==null?void 0:b.record);if(F)return F}return""},[hn]);function M_(b){jf(b);const T=l.trim();if(!(!T||typeof window>"u"))try{window.history.replaceState(null,"",jO(nO(T),b))}catch{}}const Cn=p.useMemo(()=>{const b=l.trim();return b&&(On.find(T=>String(T.run_id||"").trim()===b)||nn.find(T=>String(T.run_id||"").trim()===b))||null},[On,nn,l]),gs=p.useMemo(()=>Cn||(ve&&String((ve==null?void 0:ve.run_id)||"").trim()?op(ve):null),[Cn,ve]),us=gs?`${String(gs.run_id||"")}|${String(gs.workflow_id||"")}|${String(gs.automation_id||"")}|${String(gs.session_id||"")}`:"",R_=String((gs==null?void 0:gs.session_id)||"").trim(),L_=String((gs==null?void 0:gs.updated_at)||""),I_=Math.floor(Date.now()/6e4);p.useEffect(()=>{if(e!=="observe"||Ns!=="agent"||!R_||!L||Kn.key!==us||Kn.loading)return;const b=me.current;Ke.list_runs({session_id:R_,include_metrics:!0,limit:200}).then(T=>{if(b!==me.current)return;const F=Array.isArray(T==null?void 0:T.items)?T.items.map(op):[];Y(U=>U.key===us?{...U,runs:F,runs_error:""}:U)}).catch(T=>{b===me.current&&Y(F=>F.key===us?{...F,runs_error:String((T==null?void 0:T.message)||T||"failed")}:F)})},[L_,I_,Kn.key,Kn.loading]),p.useEffect(()=>{if(e!=="observe"||Ns!=="agent"||!us||!L||Kn.key===us)return;const b=gs,T=String(b.run_id||"").trim(),F=++me.current;Y({...Vj,key:us,loading:!0});const U=String(b.workflow_id||"").trim(),Z=()=>{const oe=U.indexOf("@"),Ge=oe>=0?U.indexOf(":",oe):-1;return oe>=0&&Ge>oe?Ke.get_bundle_flow(U.slice(0,Ge),U.slice(Ge+1)):Ke.get_workflow_flow(U)},X=String(b.automation_id||"").trim(),Q=String(b.session_id||"").trim();Promise.allSettled([Ke.get_run_input_data(T),U?Z():Promise.reject(new Error("the run names no workflow")),X?Ke.automations_client().getAutomation(X):Promise.resolve(null),Q?Ke.list_runs({session_id:Q,include_metrics:!0,limit:200}):Promise.resolve({items:[]})]).then(([oe,Ge,ke,ye])=>{var gt;if(F!==me.current)return;const Fe=dt=>{var xn;return dt.status==="rejected"?String(((xn=dt.reason)==null?void 0:xn.message)||dt.reason||"failed"):""},Pe=ke.status==="fulfilled"?ke.value:null,rt=ye.status==="fulfilled"&&Array.isArray((gt=ye.value)==null?void 0:gt.items)?ye.value.items.map(op):[];Y({key:us,loading:!1,input_data:oe.status==="fulfilled"?oe.value:null,input_error:Fe(oe),flow:Ge.status==="fulfilled"?Ge.value:null,flow_error:Fe(Ge),automation_body:Pe,automation:Pe?Rm(Pe):null,automation_error:Fe(ke),runs:rt,runs_error:Fe(ye)})})},[e,Ns,us,L,Kn.key]);const fd=p.useMemo(()=>{const b=new Map;for(const T of Kn.runs)String(T.run_id||"").trim()&&b.set(String(T.run_id).trim(),T);for(const T of On){const F=String(T.run_id||"").trim();if(!F)continue;const U=b.get(F);b.set(F,U?{...U,...T,tokens_total:T.tokens_total??U.tokens_total,llm_calls:T.llm_calls??U.llm_calls,tool_calls:T.tool_calls??U.tool_calls}:T)}return gs&&!b.has(String(gs.run_id||"").trim())&&b.set(String(gs.run_id).trim(),gs),Array.from(b.values())},[Kn.runs,On,gs]),O_=p.useMemo(()=>gD(Ii,l.trim(),lr),[Ii,l,Co]),ly=p.useMemo(()=>{if(!gs)return null;const b=QC(gs,ve),T=new Map;return ve&&T.set(String(b.run_id||"").trim(),ve),ef(b,Sx(fd,{now_ms:Lu,details:T}))},[gs,ve,fd,Lu]),co=String((ve==null?void 0:ve.status)||(Cn==null?void 0:Cn.status)||"").trim(),lh=String(Ws||((hh=ve==null?void 0:ve.waiting)==null?void 0:hh.reason)||(Cn==null?void 0:Cn.waiting_reason)||"").trim().toLowerCase(),Qr=!!(ve!=null&&ve.is_scheduled||Cn!=null&&Cn.is_scheduled),Tn=!!(ve!=null&&ve.paused||Cn!=null&&Cn.paused),Is=Qr&&co.toLowerCase()==="waiting",Es=Is&&lh==="until",Vs=Vt(ao),Nr=Es&&Vs!==null?sm(Vs-Date.now()):"",uo=tg(ve),ys=Qr&&Tn?"Suspended":Is?"Scheduled":rm({status:co,paused:Tn,stop_reason:uo});async function Wl(){if(L){Bu(!0),Mf("");try{const b=To,T=b==="session"?String(Sl||oa||D||"").trim():"",F=b==="run"?String(Pn||l||"").trim():"",U=T4(sa),Z=Nl.length?Nl.join(","):"",X=M4(Ro),Q=Math.max(0,Zi)*$p,oe=await Ke.search_artifacts({scope:b,session_id:T||void 0,run_id:F||void 0,query:Yi||void 0,artifact_kind:Z||void 0,created_after:U||void 0,include_stats:!0,limit:$p,offset:Q,order_by:X.order_by,order:X.order}),Ge=[],ke=new Set;for(const gt of Array.isArray(oe==null?void 0:oe.items)?oe.items:[]){const dt=C4(gt,"search");!dt||ke.has(dt.artifact_id)||(ke.add(dt.artifact_id),Ge.push(dt))}const ye=oe!=null&&oe.stats&&typeof oe.stats=="object"?oe.stats:{},Fe=Number((ye==null?void 0:ye.total)??(oe==null?void 0:oe.total)??Ge.length),Pe=G0(oe);let rt=Pe;if(Nl.length)try{const gt=await Ke.search_artifacts({scope:b,session_id:T||void 0,run_id:F||void 0,query:Yi||void 0,created_after:U||void 0,include_stats:!0,limit:1,offset:0,order_by:X.order_by,order:X.order});rt=G0(gt)}catch{rt=Pe}Fu(Number.isFinite(Fe)?Math.max(0,Fe):Ge.length),zu(Number((ye==null?void 0:ye.total_bytes)??(ye==null?void 0:ye.byte_total)??0)||0),Xm(Pe),Qm(rt),kc(Ge),Lo(gt=>{var dt;return gt&&Ge.some(xn=>xn.artifact_id===gt)?gt:((dt=Ge[0])==null?void 0:dt.artifact_id)||""})}catch(b){Mf(String((b==null?void 0:b.message)||b||"Failed to load artifacts")),kc([]),Fu(0),zu(0),Xm({}),Qm({}),Lo("")}finally{Bu(!1)}}}async function ua(){if(L){Ku(!0),Or("");try{const b=await Ke.audit_log_tail({max_bytes:16e4}),T=typeof(b==null?void 0:b.bytes)=="number"?Number(b.bytes):0,F=!!(b!=null&&b.truncated);no(String((b==null?void 0:b.content)||"")),Lf(`${T.toLocaleString()} bytes${F?" (tail)":""}`)}catch(b){Or(String((b==null?void 0:b.message)||b||"Failed to load audit log")),no(""),Lf("")}finally{Ku(!1)}}}async function Wc(b){if(!L)return;const T=String(b||ci||Pn||l||"").trim();if(!T){Sc([]),Ml(""),Pf("Select a run in Activity or Artifacts to load its runtime ledger.");return}Ba(!0),Pf("");try{const F=await Ke.get_ledger(T,{after:0,limit:2e3}),U=Array.isArray(F.items)?F.items:[];Sc(U.map((X,Q)=>({cursor:Q+1,record:X})));const Z=typeof F.next_after=="number"?Number(F.next_after):U.length;Ml(`${U.length.toLocaleString()} record${U.length===1?"":"s"}${Z>=2e3?" (first 2,000)":""}`)}catch(F){Pf(String((F==null?void 0:F.message)||F||"Failed to load run ledger")),Sc([]),Ml("")}finally{Ba(!1)}}p.useEffect(()=>{L&&e==="runtime"&&Wl()},[L,e,To,Sl,Pn,Yi,Nl,sa,Ro,Zi]),p.useEffect(()=>{L&&(Gu||to||e==="runtime"&&ua())},[L,e,Ns]),p.useEffect(()=>{if(!L||e!=="runtime"||bc!=="logs"||Zn!=="run_ledger"&&Zn!=="provider_calls")return;const b=String(ci||Pn||l||"").trim();b&&Wc(b)},[L,e,bc,Zn,ci,Pn,l]);const fo=p.useMemo(()=>{const b=new Map;for(const T of[...nn,...On]){const F=String(T.run_id||"").trim();F&&b.set(F,T)}for(const T of Co){const F=String(T||"").trim();!F||b.has(F)||b.set(F,{run_id:F,workflow_id:null,status:"",created_at:null,updated_at:null,ledger_len:null,parent_run_id:Kr.current[F]||null,session_id:oa||null})}return l.trim()&&!b.has(l.trim())&&b.set(l.trim(),{run_id:l.trim(),workflow_id:typeof(ve==null?void 0:ve.workflow_id)=="string"?String(ve.workflow_id):null,status:typeof(ve==null?void 0:ve.status)=="string"?String(ve.status):"",created_at:typeof(ve==null?void 0:ve.created_at)=="string"?String(ve.created_at):null,updated_at:typeof(ve==null?void 0:ve.updated_at)=="string"?String(ve.updated_at):null,ledger_len:hn.length||null,parent_run_id:typeof(ve==null?void 0:ve.parent_run_id)=="string"?String(ve.parent_run_id):null,session_id:typeof(ve==null?void 0:ve.session_id)=="string"?String(ve.session_id):oa||null}),Array.from(b.values()).sort((T,F)=>{const U=Vt(T.updated_at||T.created_at)??0;return(Vt(F.updated_at||F.created_at)??0)-U})},[On,nn,l,ve,hn.length,Co,oa]),qc=p.useMemo(()=>dD(fo,{query:Tu,filter:Mu,group_by:yf,workflow_label_by_id:hi,parent_hint:b=>Kr.current[b]||""}),[fo,Tu,Mu,yf,hi]),Ms=p.useMemo(()=>{const b={};for(const T of fo){const F=String(T.run_id||"").trim();F&&(b[F]=T)}return b},[fo]),Vc=String(ci||Pn||l||"").trim(),da=Vc&&Ms[Vc]||null,ho=String(Sl||(da==null?void 0:da.session_id)||oa||D||"").trim(),Hc=p.useMemo(()=>Du.map(b=>ag(b,Ms,hi)),[Du,Ms,hi]);p.useEffect(()=>{ir(0)},[Yi,Nl,sa,Pn,Ro,Mo,To,Sl]);const ch=Math.max(1,Math.ceil(jc/$p)),gi=Math.min(Math.max(0,Zi),ch-1);p.useEffect(()=>{Zi!==gi&&ir(gi)},[Zi,gi]);const mo=p.useMemo(()=>Hc,[Hc,gi]),fa=p.useMemo(()=>{const b={};for(const T of mo){const F=Mo==="type"?uv(T,Ms,hi):E4(T,Mo);b[F]||(b[F]=[]),b[F].push(T)}return Object.entries(b).map(([T,F])=>({key:T,items:F})).sort((T,F)=>{var U,Z;if(Mo==="time"){const X=Vt((U=T.items[0])==null?void 0:U.created_at)??0,Q=Vt((Z=F.items[0])==null?void 0:Z.created_at)??0;if(X!==Q)return Q-X}return T.key.localeCompare(F.key)})},[mo,Mo,Ms,hi]),ha=p.useMemo(()=>{const b=br.trim();return b?mo.find(T=>T.artifact_id===b)||mo[0]||null:mo[0]||null},[mo,br]);p.useEffect(()=>{e!=="runtime"||bc!=="artifacts"||h_(ha)},[e,bc,ha==null?void 0:ha.artifact_id]),p.useEffect(()=>()=>{Io.url&&URL.revokeObjectURL(Io.url)},[Io.url]);const Gc=p.useMemo(()=>fo.filter(b=>Yd(b.status)),[fo]);p.useEffect(()=>{if(e!=="settings"&&e!=="launch"||!L||se)return;let b=!1;return(async()=>{const[T,F]=await Promise.all([Ke.list_skills(),Ke.list_mcp_servers()]);b||(te(T),Me(F),de(!0))})(),()=>{b=!0}},[e,L,se]);function ql(){gc&&window.setTimeout(()=>{var b;return(b=kf.current)==null?void 0:b.scrollIntoView({block:"start"})},60)}function Uo(b){No(b),ql()}const hd=[{id:"board",label:"Board",icon:s.jsx(qe,{name:"board",size:16})},{id:"observe",label:"Observe",icon:s.jsx(qe,{name:"history",size:16})},{id:"runtime",label:"System",icon:s.jsx(qe,{name:"server",size:16})},{id:"automations",label:"Automations",icon:s.jsx(qe,{name:"refresh",size:16})}],$r={board:"Board",observe:"Observe",runtime:"System",launch:"Launch",automations:"Automations",settings:"Settings"},Wo=s.jsx(aD,{connected:L,request:Yu,value:ro,onChange:b=>Qn("workspace",b===null?void 0:b),disabled:Be||Ot}),yi=s.jsx(s.Fragment,{children:jr?s.jsxs("details",{className:"launch_capabilities",style:{marginTop:"10px"},children:[s.jsxs("summary",{className:"help_text muted",style:{cursor:"pointer"},children:["Capabilities",fi.length?` · ${fi.length} skill${fi.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."}),B===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."}):B.length?s.jsx("div",{className:"launch_skill_list",children:B.map(b=>{var Z;const T=fi.includes(b.name),F=b.blocked===!0,U=b.requires_review===!0&&!F;return s.jsxs("label",{className:`launch_skill_row ${F?"is_blocked":""} ${T?"is_on":""}`,title:[b.description||"",b.tree_hash?`tree ${b.tree_hash.slice(0,16)}…`:"",F&&((Z=b.reasons)!=null&&Z.length)?`blocked: ${b.reasons.join("; ")}`:""].filter(Boolean).join(`
175
+ `),children:[s.jsx("input",{type:"checkbox",checked:T,disabled:F||Be||Ot||He,onChange:X=>{const Q=X.target.checked?Array.from(new Set([...fi,b.name])):fi.filter(oe=>oe!==b.name);Qn("skills",Q.length?Q:void 0)}}),s.jsx("span",{className:"launch_skill_name",children:b.name}),b.trust_level?s.jsx("span",{className:`chip ${F?"danger":U?"warn":"muted"}`,children:F?"blocked":U?"review":b.trust_level}):null,b.description?s.jsx("span",{className:"launch_skill_desc",children:b.description}):null]},b.name)})}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"The gateway's skills shelf is empty."}),fi.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}),Dr=s.jsxs("section",{className:"launch_workspaces","data-section":"workspaces",style:{marginTop:"10px"},children:[s.jsx("div",{className:"launch_label launch_section_title",children:"Workspaces"}),Wo,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:$c,onChange:b=>Qn("workspace_root",b.target.value||void 0),placeholder:"/path/to/workspace",disabled:Be||Ot}),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."})]})})]}),P_=s.jsxs("details",{className:"launch_bundles",style:{marginTop:"10px"},children:[s.jsx("summary",{className:"help_text muted",style:{cursor:"pointer"},children:"Flow files"}),s.jsxs("div",{className:"launch_workflow_bar",style:{marginTop:"8px"},children:[s.jsx("input",{ref:bo,type:"file",accept:".flow",style:{display:"none"},onChange:b=>{const T=b.target.files&&b.target.files.length?b.target.files[0]:null;T&&Gf(T)}}),s.jsx("button",{type:"button",className:"btn launch_btn_upload",onClick:()=>{var b;return(b=bo.current)==null?void 0:b.click()},disabled:!L||V||$i||Be||Ot,title:"Upload a .flow bundle",children:$i?"…":"Upload .flow"}),s.jsxs("button",{type:"button",className:"btn launch_btn_reload",onClick:()=>void Hf(),disabled:!L||V||bt||Be||Ot,title:"Reload picks up server-side edits",children:[s.jsx(qe,{name:"refresh",size:14}),bt?"…":"Reload bundles"]})]})]});function md(b){t("observe"),No("ledger"),Ri(b)}const uh={on_select:b=>void Un.select(b),on_row_action:(b,T)=>{if(T==="discuss"||T==="edit")throw new Error(`${T} is routed by AutomationsPage (route_row_action), not the app handlers.`);if(T==="archive"){Un.ask_archive(b.automation_id);return}Un.row_action(b,T)},on_legacy_action:(b,T)=>{if(T==="open_run"){md(b.automation_id);return}if(T==="recreate"){Zf(b.automation_id).catch(F=>Un.report_error(F));return}Un.legacy_action(b,T)},on_confirm_archive:b=>void Un.row_action(b,"archive"),on_cancel_archive:()=>Un.ask_archive(""),on_status_filter:b=>void Un.set_status_filter(b),on_refresh:()=>void Un.refresh(),on_new:()=>Qe("automate"),on_show_archived:b=>Un.set_show_archived(b)};return s.jsxs("div",{className:`app-shell shell${vf?" nav_open":""}`,children:[wf&&vf?s.jsx("div",{className:"shell_nav_backdrop","aria-hidden":"true",onClick:()=>Qo(!1)}):null,s.jsxs("aside",{className:"shell_sidebar",id:"shell_nav",ref:bf,...Gi.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:()=>Qo(!1),children:s.jsx(qe,{name:"x",size:16})})]}),s.jsxs("nav",{className:"shell_nav",children:[hd.map(b=>s.jsxs("button",{className:`shell_nav_item ${e===b.id?"active":""}`,onClick:()=>{t(b.id),Qo(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:b.icon}),s.jsx("span",{className:"shell_nav_label",children:b.label})]},b.id)),s.jsxs("a",{className:"shell_nav_item",href:o,target:"_blank",rel:"noreferrer",title:"Open the entity app (memory graph + visits)",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(qe,{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"),Qo(!1)},type:"button",children:[s.jsx("span",{className:"shell_nav_icon",children:s.jsx(qe,{name:"settings",size:16})}),s.jsx("span",{className:"shell_nav_label",children:"Settings"})]})]}),s.jsx("div",{className:"shell_sidebar_footer",children:s.jsxs("div",{className:"shell_connection shell_connection_passive",title:L?"Gateway connected":V?"Gateway: connecting…":"Gateway: signed out",children:[s.jsx("span",{className:`gateway_led ${L?"ok":V?"warn":"err"}`,"aria-hidden":"true"}),s.jsx("span",{className:`shell_connection_label ${L&&((Kc=(gd=z==null?void 0:z.gateway)==null?void 0:gd.principal)!=null&&Kc.user_id)?"mono":""}`,children:L?((z_=(F_=z==null?void 0:z.gateway)==null?void 0:F_.principal)==null?void 0:z_.user_id)||(n.gateway_auth_mode==="direct"?"direct dev":"connected"):V?"connecting…":"signed out"}),L&&gf?s.jsxs("span",{className:"shell_connection_notice",role:"status",title:gf,children:[gl[gl.length-1].title,gl.reduce((b,T)=>b+T.count,0)>1?` ×${gl.reduce((b,T)=>b+T.count,0)}`:""]}):null]})})]}),s.jsxs("div",{className:"shell_main",...Gi.attrs.main,children:[s.jsxs("header",{className:"shell_header",children:[s.jsx("button",{ref:xf,type:"button",className:"shell_nav_toggle","data-nav-toggle":!0,"aria-label":"Open navigation","aria-controls":"shell_nav","aria-expanded":vf,title:"Navigation",onClick:()=>Qo(!0),children:s.jsx(qe,{name:"list",size:18})}),s.jsx("div",{className:"shell_header_title",children:$r[e]||"Observer"}),s.jsxs("div",{className:"shell_header_actions",children:[i?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(W2,{docs:{open:jt,onToggle:()=>ct(b=>!b),label:"Docs assistant"},appearance:{onOpen:()=>pt(!0)},about:{identity:Bf,versions:Uf,onOpen:di},connection:{phase:H.phase,signingOut:H.signingOut,onConnect:()=>H.openModal(),onDisconnect:()=>mi()}})]})]}),s.jsx(r2,{...H.modalProps}),s.jsx(oS,{open:kt,onClose:()=>pt(!1),value:ze,onChange:st}),s.jsx(qI,{open:jt,onClose:()=>ct(!1),connected:L,topOffset:44,gateway:Ke}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?L?s.jsx(mq,{gateway_connected:L,runs:nn,all_runs:On,runs_refreshed_at:Le,runs_stale:Yg,notice:gf,entities:re,entities_total:Ee,entities_error:We,on_open_run:b=>{t("observe"),No("agent"),Ri(b)},on_resume_wait:Kf,on_open_automation:b=>{Te(!1),t("automations"),Un.refresh().then(()=>Un.select(b))},entity_app_href:o,on_read_diary:(b,T)=>Ke.read_entity_diary_entry(b,T),phase_graph:Tc,client:Ke,on_rename_automation:(b,T,F)=>Un.revise(b,{title:T},F??null),on_revise_automation:(b,T,F)=>Un.revise(b,T,F),on_automation_command:(b,T)=>Un.command(b,T),on_resume_run:b=>Ic(b,"resume"),on_cancel_run:b=>Ic(b,"cancel"),on_cancel_runs:sy,code_app:Ve,done_loaded:(()=>{const b=IU(Ke);return b!==null&&b.epoch===io.current&&b.sweep_at!==null})()}):s.jsx("div",{className:"page page_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card mc_hero",children:[s.jsx("div",{className:"title",children:s.jsx("h1",{children:"Connect to your gateway"})}),s.jsxs("p",{className:"muted",children:["Mission Control shows every run and entity on one board — but nothing is connected yet.",M?` Last attempt: ${M}`:""]}),s.jsxs("div",{className:"row",style:{gap:"8px",alignItems:"center"},children:[s.jsx("button",{className:"btn primary",onClick:()=>H.openModal(),disabled:V,children:V?"Connecting…":"Sign in"}),s.jsx("button",{className:"btn",onClick:()=>void Fo({open_modal_if_needed:!0}),disabled:V,title:"Retry with an existing browser session or a direct dev token",children:"Retry connection"})]})]})})}):null,e==="settings"?s.jsx("div",{className:"page page_scroll",children:s.jsxs("div",{className:"page_inner settings_col",children:[s.jsxs("section",{className:"pane",children:[s.jsxs("div",{className:"pane_header",children:[s.jsx("span",{className:"pane_title",children:"Gateway"}),s.jsx("span",{className:"pane_spacer"}),s.jsx("span",{className:`chip ${L?"ok":"warn"}`,children:nS(z).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:()=>H.openModal(),children:"Manage connection…"}),L?s.jsx("button",{className:"btn",onClick:()=>mi(),title:"Sign this browser out of the gateway (this app's session only)",children:"Sign out"}):null]})]}),M?s.jsx("div",{className:"warn_callout",children:M}):null,s.jsx("div",{className:"settings_row",children:s.jsx(HP,{checked:n.auto_connect_gateway,onChange:b=>r(T=>({...T,auto_connect_gateway:b}))})}),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:b=>r(T=>({...T,gateway_url:b.target.value})),placeholder:kg})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Dev bearer token"}),s.jsx("input",{type:"password",value:n.auth_token,onChange:b=>r(T=>({...T,auth_token:b.target.value,gateway_auth_mode:"direct"})),placeholder:"development only — prefer the sign-in dialog"})]}),s.jsx("button",{className:"btn",onClick:()=>void Fo({prefer_direct:!0}),disabled:V,children:V?"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(Yj,{className:"field",providerLabel:"Provider",modelLabel:"Model",providerPlaceholder:"(gateway default)",modelPlaceholder:"(gateway default)",provider:n.maintenance_ai_provider,model:n.maintenance_ai_model,providers:Zu,models:Qu.models,loadingProviders:V,loadingModels:qf,modelError:Pl?Qu.error:"",allowCustomProvider:!0,allowCustomModel:!0,allowGatewayDefault:!0,gatewayDefaultLabel:"(gateway default)",onChange:b=>r(T=>({...T,maintenance_ai_provider:b.provider,maintenance_ai_model:b.model}))}),s.jsx("div",{className:"settings_subhead",children:"Skills"}),B===null?s.jsx("div",{className:"settings_row_help",children:L?se?"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)."}):B.length?s.jsx("div",{className:"settings_choice_list",children:B.map(b=>{const T=n.assistant_skill_names.includes(b.name);return s.jsx(GP,{name:b.name,version:b.version,description:b.description,checked:T,onChange:F=>r(U=>({...U,assistant_skill_names:F?Array.from(new Set([...U.assistant_skill_names,b.name])):U.assistant_skill_names.filter(Z=>Z!==b.name)}))},b.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:b=>r(T=>({...T,worker_url:b.target.value})),placeholder:"https://your-mcp-worker-endpoint"}),s.jsx("input",{className:"mono",type:"password",value:n.worker_token,onChange:b=>r(T=>({...T,worker_token:b.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(sP,{gateway:L?Ke:null,connected:L,defaults:Jf,value:Rc,onChange:c_})})]})]})}):null,s.jsx(tc,{open:je,title:Ne==="automate"?"New automation":"Run once",variant:"fullscreen",onClose:()=>Te(!1),children:s.jsx("div",{className:"launch_modal_scroll",children:s.jsx("div",{className:"page_inner constrained",children:s.jsxs("div",{className:"card",children:[s.jsx(E3,{mode:Ne,automate_available:pe.available,automate_reason:pe.reason,on_change:ae}),Ne==="automate"&&!pe.available&&L?s.jsx("div",{className:"warn_callout",role:"note",children:pe.reason}):null,Ne==="automate"&&we.length?s.jsx("div",{className:"help_text",role:"note",children:we.map(b=>s.jsx("div",{children:b},b))}):null,L?null:s.jsxs("div",{className:"warn_callout",children:["Not connected."," ",s.jsx("button",{className:"btn primary",onClick:()=>H.openModal(),children:"Sign in"})," ","to run flows on this gateway."]}),Ne==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(iN,{id:"launch-workflow-picker",className:"launch_workflow_picker",interfaceId:null,defaultInterface:Ud,ariaLabel:"Flow",workflows:Ol,entryDetail:Ff,value:A0(jr,((mh=Ol.data)==null?void 0:mh.entries)??[]),currentLabel:jr&&!A0(jr,((_h=Ol.data)==null?void 0:_h.entries)??[])?{name:hi[Xu]||Xu}:null,unavailableReason:L?V?"Loading flows…":null:"Sign in to load flows.",onChange:(b,T)=>{const F=KO(b,T);F&&Xf(F)}})}),s.jsxs("div",{className:"field",children:[_s!=null&&_s.description?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:String(_s.description)}):null,P?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading flow…"}):null,J?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:J}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),jr?on===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:an()})]}),s.jsx("div",{className:"body mono",children:"Invalid input JSON — reselect the workflow to reset its inputs."})]}):Cc?s.jsx("div",{className:"launch_inputs",children:(()=>{const b=Be||Ot,T=[],F=[];for(const X of Xr){if(!X||typeof X!="object")continue;const Q=String(X.id||"").trim();if(!Q||Ne==="automate"&&r1.includes(Q)||Ne==="automate"&&i1.includes(Q))continue;const oe=String(X.type||"").trim().toLowerCase();oe==="tools"||oe==="skills"||oe==="mcp"||oe==="mcp_servers"||Q==="skills"||Q==="mcp"||Q==="mcp_servers"||oe==="array"||Wa(oe)||Q==="prompt"||Q==="system"?T.push(X):F.push(X)}const U=X=>String(X||"").trim().replace(/_/g," ").replace(/\b\w/g,Q=>Q.toUpperCase()),Z=(X,Q)=>{const oe=String(X.id||"").trim();if(!oe)return null;const Ge=String(X.label||oe).trim()||oe,ke=Ge===oe?U(oe):Ge,ye=String(X.type||"").trim().toLowerCase(),Fe=Object.prototype.hasOwnProperty.call(X,"default"),Pe=Fe?X.default:void 0,rt=Fe?typeof Pe=="string"?Pe:Br(Pe,80):"",gt=on==null?void 0:on[oe],dt=Fe?`${rt}`:"";if(ye==="tools"){if(Ne==="automate"&&oe==="tools")return null;const ft=Array.isArray(gt)?gt.map(ds=>String(ds||"").trim()).filter(Boolean):[],en=Array.isArray(Pe)?Pe.map(ds=>String(ds||"").trim()).filter(Boolean):[],Yn=Array.from(new Set([...Ec,...ft,...en])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx(Hw,{options:Yn,value:ft,disabled:b,placeholder:"(no tools selected)",onChange:ds=>Qn(oe,ds)})]},oe)}if(ye==="skills"||oe==="skills")return null;if(ye==="mcp"||ye==="mcp_servers"||oe==="mcp"||oe==="mcp_servers"){const ft=Array.isArray(gt)?gt.map(ds=>String(ds||"").trim()).filter(Boolean):[];if(be===null&&!ft.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),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."})]},oe);const en=(be||[]).map(ds=>ds.name),Yn=Array.from(new Set([...en,...ft])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx(Hw,{options:Yn,value:ft,disabled:b,placeholder:"(no MCP servers selected)",onChange:ds=>Qn(oe,ds)})]},oe)}if(ye==="provider"||ye==="provider_text"){const ft=typeof gt=="string"?String(gt):"";return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsxs("select",{value:ft,onChange:en=>Qn(oe,en.target.value),disabled:b,children:[s.jsx("option",{value:"",children:dt||"(select)"}),ps.map(en=>s.jsx("option",{value:en,children:en},en))]})]},oe)}if(ye==="model"||ye==="model_text"){const ft=typeof gt=="string"?String(gt):"",en=String((on==null?void 0:on.provider)||"").trim(),Yn=en?mn[en]:void 0,ds=Yn&&Array.isArray(Yn.models)?Yn.models.map(dr=>String(dr||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),ds.length?s.jsxs("select",{value:ft,onChange:dr=>Qn(oe,dr.target.value),disabled:b,children:[s.jsx("option",{value:"",children:dt||"(select)"}),ds.map(dr=>s.jsx("option",{value:dr,children:dr},dr))]}):s.jsx("input",{value:ft,onChange:dr=>Qn(oe,dr.target.value),placeholder:dt||"model id",disabled:b})]},oe)}if(ye==="boolean"){const ft=typeof gt=="boolean"?gt?"true":"false":"";return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsxs("select",{value:ft,onChange:en=>{const Yn=String(en.target.value||"").trim();Yn?Qn(oe,Yn==="true"):Qn(oe,void 0)},disabled:b,children:[s.jsx("option",{value:"",children:dt||"(default)"}),s.jsx("option",{value:"true",children:"Yes"}),s.jsx("option",{value:"false",children:"No"})]})]},oe)}if(ye==="number"){const ft=typeof gt=="number"&&Number.isFinite(gt)?String(gt):"";return s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("input",{type:"number",value:ft,onChange:en=>{const Yn=String(en.target.value||"").trim();if(!Yn){Qn(oe,void 0);return}const ds=Number(Yn);Number.isFinite(ds)&&Qn(oe,ds)},placeholder:dt,disabled:b})]},oe)}if(ye==="array"){const ft=Array.isArray(gt)?gt.map(en=>String(en||"").trim()).filter(Boolean).join(`
176
+ `):"";return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("textarea",{className:"mono",value:ft,onChange:en=>{const Yn=String(en.target.value||"").split(/\r?\n/g).map(ds=>String(ds||"").trim()).filter(Boolean);Qn(oe,Yn.length?Yn:void 0)},placeholder:dt||"(one item per line)",rows:2,disabled:b})]},oe)}if(Wa(ye)){const ft=typeof dc[oe]=="string"?dc[oe]:"",en=String(js[oe]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[ke," ",s.jsx("span",{className:"launch_label_type",children:ye})]}),s.jsx("textarea",{className:"mono",value:ft,onChange:Yn=>{const ds=String(Yn.target.value??"");ul(wi=>({...wi,[oe]:ds}));const dr=ds.trim();if(!dr){pr(wi=>{const vi={...wi};return delete vi[oe],vi}),Qn(oe,void 0);return}try{const wi=JSON.parse(dr);pr(vi=>{const Vl={...vi};return delete Vl[oe],Vl}),Qn(oe,wi)}catch(wi){pr(vi=>({...vi,[oe]:String((wi==null?void 0:wi.message)||wi||"Invalid JSON")}))}},placeholder:dt||"{...}",rows:3,disabled:b}),en?s.jsx("div",{className:"launch_field_error",children:en}):null]},oe)}const xn=typeof gt=="string"?String(gt):"";return oe==="prompt"||oe==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("textarea",{value:xn,onChange:ft=>Qn(oe,ft.target.value),placeholder:dt||(oe==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:b})]},oe):s.jsxs("div",{className:Q||"launch_field",children:[s.jsx("label",{className:"launch_label",children:ke}),s.jsx("input",{value:xn,onChange:ft=>Qn(oe,ft.target.value),placeholder:dt,disabled:b})]},oe)};return T.sort((X,Q)=>{const oe={system:0,prompt:1,tools:2};return(oe[String(X.id||"")]??10)-(oe[String(Q.id||"")]??10)}),s.jsxs(s.Fragment,{children:[T.map(X=>Z(X)),F.length>0?s.jsx("div",{className:"launch_grid",children:F.map(X=>Z(X,"launch_grid_cell"))}):null]})})()}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field",style:{marginTop:"10px"},children:[s.jsx("label",{children:"Prompt (common)"}),s.jsx("textarea",{value:o_,onChange:b=>Qn("prompt",b.target.value),placeholder:"What do you want the workflow/agent to do?",rows:3,disabled:Be||Ot})]}),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:Il,onChange:b=>Qn("provider",b.target.value),placeholder:"lmstudio / ollama / openai / ...",disabled:Be||Ot})]})}),s.jsx("div",{className:"col",children:s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Model (common)"}),s.jsx("input",{value:a_,onChange:b=>Qn("model",b.target.value),placeholder:"qwen/qwen3-next-80b / gpt-4.1 / ...",disabled:Be||Ot})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Choose a flow above to set its inputs."}),Ne==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(A3,{form:ot,email_status:ui.email_status,on_open_my_email:Po,served:Ll,on_open_preferences:Po,defaults:Do,connections:ui.trigger_connections,mailboxes:ui.mailboxes,tools:xS(on||{})??void 0,available_tools:Ec,on_tools_change:b=>S(JSON.stringify(bS(on||{},b),null,2)),disabled:He,on_change:b=>mt(T=>({...T,...b})),workspaces:Wo}),s.jsx(T3,{form:ot,disabled:He,on_change:b=>mt(T=>({...T,...b}))}),yi]}):s.jsxs(s.Fragment,{children:[yi,Dr,P_]}),s.jsx("div",{className:"section_divider"}),zn?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:zn})]}):null,Ne==="automate"&&et.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:et.map(b=>s.jsx("li",{children:b},b))}):null,Ne==="automate"&&ce?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":ce.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:ce.code}),s.jsxs("span",{children:[s.jsx("strong",{children:Gp(ce).title})," ",Gp(ce).detail,ce.field?s.jsxs("span",{className:"mono",children:[" (",ce.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const b=Ne==="automate",T=L?jr?on===null?"Inputs contain invalid JSON":b&&!pe.available?"Automations unavailable on this gateway":Be||Ot?"Attaching to a run…":V||P?"Loading…":He?"Submitting…":"":"Choose a flow":"Sign in first";return s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"launch_submit_btn",onClick:()=>void ny(),disabled:!!T,title:T,children:b?He?"Creating…":"Create automation":Be?"Launching…":"Launch now"}),T&&!He&&!Be?s.jsx("span",{className:"mono muted launch_disabled_reason",children:T}):null]})})()})]})})})}),e==="automations"?s.jsx(VP,{workflowPickerOptions:{interfaceId:null,defaultInterface:Ud,workflows:Ol,entryDetail:Ff,request:(b,T)=>Ke.get_gateway_json(b,T.signal)},availableTools:Ec,ctl:Un,gateway:Ke,active:e==="automations"&&L,available:pe,h:uh,voice_session_id:D,workspace_request:Yu,host:{on_open_run:b=>md(b),...Po?{on_open_my_email:Po}:{},on_open_session:(b,T)=>{kn({ts:an(),kind:"info",title:"Discussion started",preview:tn(T),data:b})}}}):null,e==="runtime"?s.jsx(eD,{runs_loading:rs,gateway_connected:L,tab:bc,runs:fo,active_runs:Gc,all_artifacts:Du,artifacts:mo,artifact_total_count:jc,artifact_total_bytes:Af,artifact_facets:Tf,artifact_type_facets:Zm,artifact_page:gi,artifact_page_size:$p,artifact_groups:fa,selected_artifact:ha,embedded_preview:Io,loading:ey,error:na,query:Yi,scope:To,type_filters:Nl,date_filter:sa,group_by:Mo,sort_by:Ro,artifact_run_filter:Pn,audit_log_text:to,audit_log_meta:za,audit_log_loading:Gu,audit_log_error:Yr,workflow_label_by_id:hi,run_by_id:Ms,selected_run_id:Vc,session_id:ho,runtime_log_source:Zn,runtime_log_query:n_,runtime_ledger_log_items:If,runtime_ledger_log_meta:r_,runtime_ledger_log_loading:i_,runtime_ledger_log_error:Of,on_tab_change:Ym,on_query_change:Xi,on_scope_change:Ti,on_session_filter_change:e_,on_type_filters_change:Fa,on_date_filter_change:$l,on_group_by_change:Rf,on_sort_by_change:ra,on_artifact_page_change:ir,on_artifact_run_filter_change:b=>{const T=String(b||"").trim();Xn(T),T&&Ts(T),T&&To!=="run"&&Ti("run")},on_refresh_artifacts:()=>void Wl(),on_refresh_audit:()=>void ua(),on_refresh_runtime_ledger:b=>void Wc(b),on_runtime_log_source_change:Mi,on_runtime_log_query_change:s_,on_select_run:b=>{const T=String(b||"").trim();Ts(T);const F=T&&Ms[T]||null,U=String((F==null?void 0:F.session_id)||"").trim();U&&e_(U)},on_select_artifact:Lo,on_preview_artifact:b=>void ed(b),on_download_artifact:b=>void f_(b),on_open_run:b=>{Ts(String(b||"").trim()),t("observe"),No("ledger"),Ri(b)},on_open_ledger:b=>{Ts(String(b||"").trim()),t("observe"),No("ledger"),Ri(b)},on_refresh_runs:()=>void Dn(Ke,{force:!0}),on_reconnect:()=>void Fo({open_modal_if_needed:!0}),on_open_settings:()=>t("settings"),memory_panel:L?s.jsx(A9,{gateway:Ke,selected_run_id:ci,selected_session_id:ho}):null}):null,e==="observe"?s.jsx("div",{className:"page observe_page",children:s.jsxs("div",{className:`observatory_layout${Um?"":" list_collapsed"}`,children:[s.jsx(nD,{sections:qc,selected_run_id:l,root_run_id:h,search:Tu,filter:Mu,group_by:yf,loading:rs,connected:L,on_sign_in:()=>H.openModal(),total_runs:fo.length,workflow_label_by_id:hi,automation_titles:zf,on_search:Bm,on_filter:wl,on_group_by:Zg,on_refresh:()=>void Dn(),on_select:(b,T)=>{Ri(b,{root_run_id:T||b}),ql()},list:{open:Um,on_toggle:Wm}}),s.jsxs("div",{className:"observatory_main",children:[s.jsxs("div",{className:"observe_toolbar",children:[s.jsxs("div",{className:"observe_toolbar_row",children:[l.trim()?s.jsxs("div",{className:"observe_run_identity",title:l.trim(),children:[s.jsx("span",{className:"observe_run_name",children:hi[String((Cn==null?void 0:Cn.workflow_id)||"")]||String((Cn==null?void 0:Cn.workflow_id)||"").trim()||Ln(l.trim(),22)}),s.jsx("span",{className:"chip mono muted",children:Ln(l.trim(),14)}),s.jsx("span",{className:`chip ${Sa(ys||co,uo)}`,title:String((uo==null?void 0:uo.headline)||""),children:ys||co||"unknown"})]}):y?s.jsx("span",{className:"observe_run_identity_empty observe_run_link_missing",role:"alert",children:sO(y)}):s.jsx("span",{className:"observe_run_identity_empty",children:"No run selected"}),s.jsx("span",{className:"observe_toolbar_spacer"}),l.trim()?s.jsxs(s.Fragment,{children:[Jn?s.jsx(JP,{active:!xs,unavailableReason:ay,busy:Be||Ot,onChange:b=>{if(!b){Vr("pause"),Hr(""),Ci(""),qr(!0);return}Qf("resume")}}):s.jsx("button",{className:"btn",onClick:()=>{if(zc==="pause"){Vr("pause"),Hr(""),Ci(""),qr(!0);return}Qf("resume")},disabled:ur,children:C_}),Nt?s.jsx("button",{className:"btn primary",onClick:()=>void eh(),disabled:Be||Ot||pi||xs,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{Vr("cancel"),Hr(""),Ci(""),qr(!0)},disabled:Be||Ot||pi,children:"Cancel"}),s.jsx("button",{className:"btn btn_icon",onClick:Fl,title:"Clear the run view",children:s.jsx(qe,{name:"x",size:14})})]}):null]}),l.trim()&&!pi?s.jsx("div",{className:"observe_steer_row",children:s.jsx(u2,{runId:l.trim(),parked:Dc,submit:(b,T)=>Ke.submit_command({command_id:`steer-${Zs()}`,run_id:b,type:"inject_guidance",payload:{guidance:T},client_id:"web_pwa"}).then(F=>({accepted:!!(F!=null&&F.accepted),duplicate:!!(F!=null&&F.duplicate),seq:Number((F==null?void 0:F.seq)??0)})),onSent:()=>kn({ts:an(),kind:"info",title:"Steer queued",preview:"inject_guidance submitted — delivery shows as abstract.steer_seen in the ledger"})})}):null,Dc||Jn||Au?s.jsxs("div",{className:"observe_toolbar_context",children:[Dc?s.jsxs("div",{className:"observe_context_card info",children:[s.jsxs("div",{className:"observe_context_label",children:[(()=>{const b=Jn?xs?"suspended":"scheduled":"waiting";return s.jsx("span",{className:`chip ${Sa(b)}`,children:b})})(),s.jsx("span",{className:"muted",children:Ws||"unknown"})]}),s.jsxs("div",{className:"observe_context_body",children:[cr?s.jsxs("span",{className:"mono",title:cr,children:[s.jsx("span",{className:"muted",children:"wait_key"}),": ",Ln(cr,46)]}):null,Ws==="event"&&od?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"event"}),": ",od]}):null,Ws==="subworkflow"&&la?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"child"}),": ",Ln(la,18)]}):null,Ws==="until"&&ao?s.jsxs("span",{className:"mono",title:ao,children:[s.jsx("span",{className:"muted",children:"until"}),": ",Ln(ao,46)]}):null,Ws==="until"&&ao?s.jsx("span",{className:"mono muted",children:(()=>{const b=Vt(ao),T=b!==null?new Date(b).toLocaleString():ao,F=b!==null?sm(b-Date.now()):"";return`Next at ${T}${F?` (in ${F})`:""}`})()}):null]}),Ws==="subworkflow"&&la?s.jsxs("div",{className:"observe_context_actions",children:[s.jsx("button",{className:"btn primary",onClick:async()=>{d(la),await rd(la)},disabled:Be,children:"Attach to child"}),h.trim()&&h.trim()!==l.trim()?s.jsx("button",{className:"btn",onClick:async()=>{d(h.trim()),await rd(h.trim())},disabled:Be,children:"Back to root"}):null]}):null]}):null,Jn?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:rh?`every ${Ha}`:"once"})]}),s.jsxs("div",{className:"observe_context_body",children:[Ha?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"interval"}),": ",Ha]}):null,s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"share ctx"}),": ",$_?"yes":"no"]}),typeof Ul=="number"?s.jsxs("span",{className:"mono",children:[s.jsx("span",{className:"muted",children:"repeats"}),": ",Ul]}):null]}),Ga!==null?s.jsxs("div",{className:"observe_context_budget",children:[s.jsxs("span",{className:"mono muted",children:[typeof ih=="number"&&typeof E_=="number"?`${ih.toLocaleString()} / ${E_.toLocaleString()}`:"",` • ${Math.round(Math.max(0,Math.min(1,Ga))*100)}%`]}),s.jsx("div",{className:"observe_budget_bar",children:s.jsx("div",{className:`observe_budget_fill ${Ga>=.9?"danger":Ga>=.75?"warn":"ok"}`,style:{width:`${Math.round(Math.max(0,Math.min(1,Ga))*100)}%`}})})]}):null,s.jsxs("div",{className:"observe_context_actions",children:[rh?s.jsx("button",{className:"btn",onClick:()=>{vs(Ha||""),Ls(!0),Ss(""),Bi(!0)},disabled:Be||oi,children:"Edit schedule"}):null,rh?s.jsx("button",{className:"btn",onClick:()=>{Fs(""),$a(!0)},disabled:Be||zs,children:"Compact context"}):null,s.jsx("button",{className:"btn",onClick:()=>void Zf(l.trim()).catch(b=>An(String((b==null?void 0:b.message)||b))),disabled:Be||!l.trim(),title:"Open Launch → Automate prefilled from this schedule (this schedule is not changed)",children:"Recreate as automation"})]})]}):null,Au?s.jsxs("div",{className:"observe_context_card error",children:[s.jsx("span",{className:"chip danger",children:"error"}),s.jsx("span",{className:"mono",children:Au})]}):null]}):null]}),s.jsxs("div",{className:"card panel_card card_scroll observe_viewer observe_viewer_full",ref:kf,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":Ns==="agent",className:`tab ${Ns==="agent"?"active":""}`,onClick:()=>Uo("agent"),children:"Agent"}),s.jsx("button",{role:"tab","aria-selected":Ns==="ledger",className:`tab ${Ns==="ledger"?"active":""}`,onClick:()=>Uo("ledger"),children:"Ledger"}),s.jsx("button",{role:"tab","aria-selected":Ns==="graph",className:`tab ${Ns==="graph"?"active":""}`,onClick:()=>Uo("graph"),children:"Flow"}),s.jsx("button",{role:"tab","aria-selected":Ns==="chat",className:`tab ${Ns==="chat"?"active":""}`,onClick:()=>Uo("chat"),children:"Ask"})]}),Ns==="ledger"&&(hn.length>0||sn.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!hn.length&&!sn.length,title:"Copy full ledger as JSONL",onClick:()=>{const F=[...hn.map(X=>({run_id:l.trim()||X.record.run_id||"",cursor:X.cursor,record:X.record})),...sn.map(X=>({run_id:X.run_id,cursor:X.cursor,record:X.record}))].map(X=>{var Ge,ke;const Q=String(((Ge=X.record)==null?void 0:Ge.ended_at)||((ke=X.record)==null?void 0:ke.started_at)||"").trim(),oe=Vt(Q);return{...X,_ms:oe??0}});F.sort((X,Q)=>(X._ms||0)-(Q._ms||0));const Z=(F.length>5e3?F.slice(F.length-5e3):F).map(({_ms:X,...Q})=>JSON.stringify(Q)).join(`
177
+ `);Pr(Z)},children:"Copy JSONL"})}):null,Ns==="graph"?s.jsxs("div",{className:"tab_bar_controls",children:[s.jsx("button",{className:`seg_action ${Ji?"active":""}`,"aria-pressed":Ji,onClick:()=>$f(b=>!b),children:"Subflows"}),s.jsx("button",{className:`seg_action ${La?"active":""}`,"aria-pressed":La,onClick:()=>Cf(b=>!b),children:"Path"}),oh.length?s.jsx("select",{className:"mono seg_select",value:vl,onChange:b=>wr(String(b.target.value||"")),disabled:!!Li.trim()||!N.trim()||Nf,children:oh.map(b=>s.jsx("option",{value:b,children:b},b))}):null]}):null]}),Ns==="agent"?l.trim()&&gs?s.jsx(Bq,{run:gs,detail:ve,input_data:Kn.key===us?Kn.input_data:null,flow:Kn.key===us?Kn.flow:null,automation:Kn.key===us?Kn.automation:null,automation_body:Kn.key===us?Kn.automation_body:null,runs:fd,records:Ii,stall_after_ms:MC(typeof localStorage>"u"?null:localStorage),loading:{detail:Be&&!ve,input_data:Kn.key!==us||Kn.loading,flow:Kn.key!==us||Kn.loading},errors:Kn.key===us?{input_data:Kn.input_error||void 0,flow:Kn.flow_error||void 0}:{},on_open_run:b=>void Ri(b),on_ask:()=>Uo("chat"),on_action:(b,T)=>{if(b==="resume"){Ic(T,"resume");return}if(b==="open_subrun"){Ri(T);return}li(""),Uo("ledger")},on_reveal_workspace:()=>void Dl(),on_copy:b=>void Pr(b)}):s.jsx("div",{className:"rs_page",children:s.jsx("p",{className:"rs_notice",children:l.trim()?"Loading the run…":"Pick a run to see what its agent can do, what it was given, and where it stands."})}):null,Ns==="ledger"?l.trim()?s.jsxs("div",{className:"rs_page",children:[s.jsx(BO,{status:ys||co||"unknown",duration:Cn?yu(Cn):"",facts:EO(CO(Ii)),error:im(Cn)||String((ve==null?void 0:ve.error)||"").trim(),answer:ah||String((lo==null?void 0:lo.text)||"").trim(),waiting_for_user:!!(dn!=null&&dn.wait_key)&&String((dn==null?void 0:dn.reason)||"")==="user",on_answer_wait:()=>li(""),workspace_root:Hm,on_reveal_workspace:()=>void Dl(),speak:L?s.jsx(cP,{voice:oo,speak_key:`outcome:${l.trim()}`,text:im(Cn)||String((ve==null?void 0:ve.error)||"").trim()||ah||String((lo==null?void 0:lo.text)||"").trim(),error:Wt}):null,on_open_artifacts:()=>{const b=String(l||"").trim();b&&(Ts(b),Xn(b),Ti("run")),Ym("artifacts"),t("runtime")}}),s.jsx(zO,{items:Ii,run_id:Oi,run_options:ca,run_llm_counts:Uc,on_select_run:b=>Vm(b),state:qm,on_state:M_,node_label:(b,T)=>{const F=T?(Zr==null?void 0:Zr[lr(b,T)])||(Zr==null?void 0:Zr[T]):null;return String((F==null?void 0:F.label)||T||"").trim()},on_copy:b=>void Pr(b),on_open_run:b=>void Ri(b,{root_run_id:h||l||b})})]}):s.jsx("div",{className:"empty_state_inline",children:"Select a run on the left to inspect it — or start one from Launch."}):null,Ns==="graph"?s.jsxs(s.Fragment,{children:[Gm?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:an()})]}),s.jsx("div",{className:"body mono",children:Gm})]}):null,Nf?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:Li.trim()?Li.trim():vl})]}),s.jsx("div",{className:"body mono",children:"Loading graph…"})]}):null,s.jsx("div",{className:"graph_panel",children:s.jsx(i5,{flow:Ki,flow_by_id:yc,expand_subflows:Ji,simplify:!0,prefer_vertical:!0,vertical_compact:.78,schedule_next_in:Nr,schedule_interval:Ha,node_last_ms:T_,active_node_id:A_,recent_nodes:Km,visited_nodes:Jm,highlight_path:La,now_ms:Lu,run_id:l.trim(),run_line:ly,run_status:ys||co,node_facts:O_,on_open_run:b=>void Ri(b)})})]}):null,Ns==="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(Wr,{value:mf,options:_f,placeholder:pc?"Loading…":_f.length?"Select a saved discussion…":"(none saved)",disabled:!l.trim()||!L||!_f.length,loading:pc,searchable:!0,clearable:!0,onChange:b=>{Nu(b),Ma("")}})}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:0},children:[s.jsx("button",{className:"btn",type:"button",disabled:!mf.trim()||!L||$u,onClick:()=>void ry(),children:$u?"Loading…":"Load"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length||Bt||yr||$u,onClick:()=>{bn([]),Hn(null),De(""),ht(""),Hi(""),mc(""),Ta("")},children:"Clear"}),s.jsx("button",{className:"btn",type:"button",onClick:()=>void Oc(),disabled:!l.trim()||!L||pc,children:pc?"Refreshing…":"Refresh"})]})]}),s.jsxs("div",{className:"actions",style:{justifyContent:"flex-end",marginTop:"8px",flexWrap:"wrap"},children:[s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length||!l.trim()||!L||yr||!Cu,onClick:()=>void nh(),title:Cu?"":"No changes since last save",children:yr?"Saving…":!Cu&&df?"Saved":"Save discussion"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length,onClick:()=>Va("download"),children:"Export Markdown"}),s.jsx("button",{className:"btn",type:"button",disabled:!Ft.length,onClick:()=>Va("copy"),children:En==="copied"?"Copied":En==="failed"?"Copy failed":"Copy Markdown"})]}),df?s.jsxs("div",{className:"chat_hint",children:["Last saved: ",cu(df)]}):null,_l?s.jsx("div",{className:"chat_hint chat_hint_danger",children:_l}):null,Pm?s.jsx("div",{className:"chat_hint chat_hint_danger",children:Pm}):null,hf?s.jsx("div",{className:"chat_hint chat_hint_danger",children:hf}):null]})]}),Ye?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:an()})]}),s.jsx("div",{className:"body mono",children:Ye})]}):null,Wt?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:an()})]}),s.jsx("div",{className:"body mono",children:Wt})]}):null,s.jsx("div",{className:"chat_messages",style:{marginTop:"10px"},children:s.jsx(fx,{messages:Ft,className:"log_scroll",after:s.jsx(QI,{history:ls}),afterKey:ls?`${ls.replayed_messages}:${ls.dropped_messages}`:null,messageProps:oo.tts_supported&&L?{onSpeakToggle:w_,getSpeakState:th,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(hx,{ref:Rr,value:Oe,onChange:De,onSubmit:()=>void y_(),placeholder:"Ask about this run…",disabled:!l.trim()||!L||Bt,busy:Bt||oo.voice_ptt_busy,busyLabel:oo.voice_ptt_busy?"Transcribing…":"Thinking…",rows:3,sendButtonClassName:"btn primary",actions:s.jsx(w1,{voice:oo,defaults:Jf.value,prefs:Rc,blocked:L?Bt?"Wait for the answer.":null:"Connect to the gateway first."})}),h1()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:d1})]})]}):null,l.trim()?s.jsxs("div",{className:`status_bar ${Ea?"pulse":""}`,children:[s.jsx("strong",{children:"Run"}),":"," ",s.jsx("span",{className:"mono",children:ys||co||"unknown"}),Es&&Nr?s.jsxs("span",{className:"mono muted",children:[" • next in ",Nr]}):null,Zo?s.jsxs("span",{className:"mono muted",children:[" • ",Zo]}):null]}):null]})]})]})}):null,s.jsxs(tc,{open:t_,title:Wu||"Artifact",onClose:()=>{Cl(!1),ia(""),eo(""),kr(!1),Tl(null),or&&(URL.revokeObjectURL(or),Vu(""))},actions:s.jsx("button",{className:"btn",onClick:()=>{Cl(!1),ia(""),eo(""),kr(!1),Tl(null),or&&(URL.revokeObjectURL(or),Vu(""))},children:"Close"}),children:[Hu?s.jsx("div",{className:"mono muted",style:{fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:"Loading…"}):null,Jr?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)",marginBottom:"8px"},children:Jr}):null,Qi==="image"&&or?s.jsx("img",{className:"runtime_preview_media",src:or,alt:Wu||"Artifact preview"}):Qi==="audio"&&or?s.jsx(Rg,{className:"runtime_preview_media",src:or,name:Wu||void 0}):Qi==="video"&&or?s.jsx("video",{className:"runtime_preview_media",controls:!0,src:or}):s.jsx(P1,{artifact:Al,text:qu||"(empty)",className:"runtime_preview_text"})]}),Rs?s.jsxs(tc,{open:Rs,title:"Edit schedule",onClose:()=>{Bi(!1),vs(""),Ls(!0),Ss(""),Ui(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{Bi(!1),vs(""),Ls(!0),Ss(""),Ui(!1)},disabled:Be||oi,children:"Back"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await id({interval:dl,apply_immediately:ri})||(Bi(!1),Ss(""),Ui(!1))},disabled:Be||oi||!dl.trim(),children:"Save"})]}),children:[ii?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:an()})]}),s.jsx("div",{className:"body mono",children:ii})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Interval"}),s.jsx("input",{className:"mono",value:dl,onChange:b=>vs(String(b.target.value||"")),placeholder:"20m / 1h / 0.5s / 250ms",disabled:Be||oi}),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(b=>s.jsx("button",{className:"btn",onClick:()=>vs(b),disabled:Be||oi,children:b},b))})]}),s.jsx("div",{className:"field",children:s.jsx(XP,{checked:ri,busy:Be||oi,onChange:Ls})})]}):null,In?s.jsxs(tc,{open:In,title:"Compact scheduled context",onClose:()=>{$a(!1),Fs(""),gr(!1)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{$a(!1),Fs(""),gr(!1)},disabled:Be||zs,children:"Cancel"}),s.jsx("button",{className:"btn primary",onClick:async()=>{await g_({preserve_recent:fl,compression_mode:Tr,focus:Wi})||($a(!1),Fs(""),gr(!1))},disabled:Be||zs,children:zs?"Compacting…":"Compact"})]}),children:[ko?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:an()})]}),s.jsx("div",{className:"body mono",children:ko})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Preserve recent turns"}),s.jsx("input",{type:"number",min:1,value:String(fl),onChange:b=>hl(Math.max(1,parseInt(b.target.value||"6",10)||6)),disabled:Be||zs})]}),s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Mode"}),s.jsxs("select",{value:Tr,onChange:b=>fc(b.target.value),disabled:Be||zs,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:Wi,onChange:b=>Ca(String(b.target.value||"")),placeholder:"e.g. important decisions, next steps…",disabled:Be||zs})]})]}):null,jo?s.jsxs(tc,{open:jo,title:Mr==="cancel"?"Cancel run":Jn?"Suspend schedule":"Pause run",onClose:()=>{qr(!1),Hr(""),Ci("")},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{qr(!1),Hr(""),Ci("")},disabled:Be||Ot,children:"Back"}),s.jsx("button",{className:`btn ${Mr==="cancel"?"danger":"primary"}`,onClick:async()=>{Ci("");const b=await Qf(Mr,{reason:hc});if(b){Ci(b);return}qr(!1),Hr(""),Ci("")},disabled:Be||Ot,children:Mr==="pause"?Jn?"Suspend":"Pause":"Cancel"})]}),children:[ku?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:an()})]}),s.jsx("div",{className:"body mono",children:ku})]}):null,s.jsxs("div",{className:"field",children:[s.jsx("label",{children:"Reason (optional)"}),s.jsx("input",{className:"mono",value:hc,onChange:b=>Hr(b.target.value),placeholder:"reason…"})]})]}):null,ad?s.jsxs(tc,{open:ad,title:cd,onClose:()=>{cr&&li(cr)},actions:s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn",onClick:()=>{No("ledger"),t("observe"),ql(),cr&&li(cr)},disabled:!l.trim(),children:"Open ledger"}),s.jsx("button",{className:"btn",onClick:()=>cr&&li(cr),disabled:Ot,children:"Dismiss"}),aa.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Ot,onClick:()=>Pc({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Ot,onClick:()=>Pc({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!so||Ot,onClick:()=>v_(aa),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:cd}),s.jsx("p",{children:j_})]}),s.jsx(wu,{status:Cs||"waiting"})]}),zo?s.jsxs("div",{className:`wait_request_card ${Bl?"":"inferred"}`,children:[s.jsx("span",{children:Bo}),s.jsx(Gj,{metadata:iy}),s.jsx(Ni,{text:zo}),Bl?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."}),dd.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:dd.map((b,T)=>s.jsxs("div",{className:`wait_turn_row role_${b.role.replace(/[^a-z0-9_-]+/g,"_")}`,children:[s.jsxs("div",{className:"wait_turn_meta",children:[s.jsx("strong",{children:b.role==="assistant"?"Assistant":b.role==="user"||b.role==="human"?"User":b.role}),b.ts?s.jsx("span",{className:"mono muted",children:cu(b.ts)}):null]}),s.jsx(Gj,{metadata:b.runtime_metadata}),s.jsx(Ni,{text:tn(b.text,{max_chars:1200,max_lines:10})})]},`${b.role}:${T}`))})]}):null,s.jsxs("div",{className:"artifact_detail_grid",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workflow"}),s.jsx("strong",{children:Ko(zl,hi)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Run"}),s.jsx("strong",{className:"mono",children:Ln(l.trim(),24)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Node"}),s.jsx("strong",{className:"mono",children:zl.current_node||String((ar==null?void 0:ar.node_id)||"—")})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Elapsed"}),s.jsx("strong",{children:yu(zl)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Session"}),s.jsx("strong",{className:"mono",children:zl.session_id?Ln(String(zl.session_id),18):"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Wait key"}),s.jsx("strong",{className:"mono",children:Ln(cr,28)})]})]}),N_?s.jsxs("details",{className:"runtime_raw_details wait_full_input_details",open:!zo,children:[s.jsx("summary",{className:"mono muted",children:"Full run input JSON"}),s.jsx("div",{className:"wait_shared_json",children:s.jsx(hr,{value:oy,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:[ld.map(b=>s.jsxs("div",{className:"wait_event_row",children:[s.jsxs("span",{className:"mono",children:["#",b.cursor]}),s.jsx("strong",{children:b.summary||b.effect_type||b.status||"event"}),s.jsx("span",{className:"mono muted",children:[b.node_id,b.status,cu(b.ts)].filter(Boolean).join(" · ")})]},`${b.cursor}:${b.node_id}:${b.status}`)),ld.length?null:s.jsx("div",{className:"empty_state_inline",children:"No ledger context is loaded. Open the ledger before deciding."})]})]})]}),aa.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:aa.map((b,T)=>s.jsxs("div",{className:"wait_tool_card",children:[s.jsxs("div",{className:"wait_tool_header",children:[s.jsx("strong",{children:String((b==null?void 0:b.name)||"tool")}),s.jsxs("div",{className:"wait_tool_badges",children:[s.jsx("span",{className:"chip mono warn",children:"approval"}),E1(b).map(F=>s.jsxs("span",{className:"chip mono muted",title:C1,children:[F,"~"]},F))]})]}),s.jsx("div",{className:"wait_tool_args",children:s.jsx(hr,{value:(b==null?void 0:b.arguments)||{},collapseAfterDepth:3,showCopy:!0})})]},`${String((b==null?void 0:b.name)||"tool")}:${T}`))}),so?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 _i(l.trim(),"Cancelled from wait prompt"),disabled:!l.trim()||Ot,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(hr,{value:dn||{},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:zo||"No explicit prompt was provided. Open the ledger for context before responding."}),s.jsx(tD,{wait:dn,disabled:Ot,on_submit:b=>Pc({response:b})}),s.jsx("div",{className:"actions",children:s.jsx("button",{className:"btn danger",onClick:()=>void _i(l.trim(),"Cancelled from wait prompt"),disabled:!l.trim()||Ot,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(hr,{value:dn||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(tO).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}SE();wE.createRoot(document.getElementById("root")).render(s.jsx(Ae.StrictMode,{children:s.jsx(Jq,{})}));
178
+ //# sourceMappingURL=index-aA7H5BZb.js.map