@abstractframework/observer 0.10.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/index-C-WrY7Nk.css +1 -0
- package/dist/assets/index-DRRbcUk2.js +178 -0
- package/dist/assets/index-DRRbcUk2.js.map +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -4
- package/dist/assets/index-Ch6SmizF.js +0 -178
- package/dist/assets/index-Ch6SmizF.js.map +0 -1
- package/dist/assets/index-DwiX-y0a.css +0 -1
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
var aE=Object.defineProperty;var lE=(e,t,n)=>t in e?aE(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var jn=(e,t,n)=>lE(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 cE(){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,ne,se){this.props=B,this.context=ne,this.refs=k,this.updater=se||y}v.prototype.isReactComponent={},v.prototype.setState=function(B,ne){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,ne,"setState")},v.prototype.forceUpdate=function(B){this.updater.enqueueForceUpdate(this,B,"forceUpdate")};function N(){}N.prototype=v.prototype;function $(B,ne,se){this.props=B,this.context=ne,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,P={current:null},R={key:!0,ref:!0,__self:!0,__source:!0};function I(B,ne,se){var ue,ve={},Te=null,ke=null;if(ne!=null)for(ue in ne.ref!==void 0&&(ke=ne.ref),ne.key!==void 0&&(Te=""+ne.key),ne)D.call(ne,ue)&&!R.hasOwnProperty(ue)&&(ve[ue]=ne[ue]);var le=arguments.length-2;if(le===1)ve.children=se;else if(1<le){for(var xe=Array(le),Ee=0;Ee<le;Ee++)xe[Ee]=arguments[Ee+2];ve.children=xe}if(B&&B.defaultProps)for(ue in le=B.defaultProps,le)ve[ue]===void 0&&(ve[ue]=le[ue]);return{$$typeof:e,type:B,key:Te,ref:ke,props:ve,_owner:P.current}}function W(B,ne){return{$$typeof:e,type:B.type,key:ne,ref:B.ref,props:B.props,_owner:B._owner}}function G(B){return typeof B=="object"&&B!==null&&B.$$typeof===e}function K(B){var ne={"=":"=0",":":"=2"};return"$"+B.replace(/[=:]/g,function(se){return ne[se]})}var V=/\/+/g;function M(B,ne){return typeof B=="object"&&B!==null&&B.key!=null?K(""+B.key):ne.toString(36)}function A(B,ne,se,ue,ve){var Te=typeof B;(Te==="undefined"||Te==="boolean")&&(B=null);var ke=!1;if(B===null)ke=!0;else switch(Te){case"string":case"number":ke=!0;break;case"object":switch(B.$$typeof){case e:case t:ke=!0}}if(ke)return ke=B,ve=ve(ke),B=ue===""?"."+M(ke,0):ue,S(ve)?(se="",B!=null&&(se=B.replace(V,"$&/")+"/"),A(ve,ne,se,"",function(Ee){return Ee})):ve!=null&&(G(ve)&&(ve=W(ve,se+(!ve.key||ke&&ke.key===ve.key?"":(""+ve.key).replace(V,"$&/")+"/")+B)),ne.push(ve)),1;if(ke=0,ue=ue===""?".":ue+":",S(B))for(var le=0;le<B.length;le++){Te=B[le];var xe=ue+M(Te,le);ke+=A(Te,ne,se,xe,ve)}else if(xe=g(B),typeof xe=="function")for(B=xe.call(B),le=0;!(Te=B.next()).done;)Te=Te.value,xe=ue+M(Te,le++),ke+=A(Te,ne,se,xe,ve);else if(Te==="object")throw ne=String(B),Error("Objects are not valid as a React child (found: "+(ne==="[object Object]"?"object with keys {"+Object.keys(B).join(", ")+"}":ne)+"). If you meant to render a collection of children, use an array instead.");return ke}function O(B,ne,se){if(B==null)return B;var ue=[],ve=0;return A(B,ue,"","",function(Te){return ne.call(se,Te,ve++)}),ue}function L(B){if(B._status===-1){var ne=B._result;ne=ne(),ne.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=ne)}if(B._status===1)return B._result.default;throw B._result}var J={current:null},H={transition:null},z={ReactCurrentDispatcher:J,ReactCurrentBatchConfig:H,ReactCurrentOwner:P};function te(){throw Error("act(...) is not supported in production builds of React.")}return Sn.Children={map:O,forEach:function(B,ne,se){O(B,function(){ne.apply(this,arguments)},se)},count:function(B){var ne=0;return O(B,function(){ne++}),ne},toArray:function(B){return O(B,function(ne){return ne})||[]},only:function(B){if(!G(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=te,Sn.cloneElement=function(B,ne,se){if(B==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+B+".");var ue=x({},B.props),ve=B.key,Te=B.ref,ke=B._owner;if(ne!=null){if(ne.ref!==void 0&&(Te=ne.ref,ke=P.current),ne.key!==void 0&&(ve=""+ne.key),B.type&&B.type.defaultProps)var le=B.type.defaultProps;for(xe in ne)D.call(ne,xe)&&!R.hasOwnProperty(xe)&&(ue[xe]=ne[xe]===void 0&&le!==void 0?le[xe]:ne[xe])}var xe=arguments.length-2;if(xe===1)ue.children=se;else if(1<xe){le=Array(xe);for(var Ee=0;Ee<xe;Ee++)le[Ee]=arguments[Ee+2];ue.children=le}return{$$typeof:e,type:B.type,key:ve,ref:Te,props:ue,_owner:ke}},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=I,Sn.createFactory=function(B){var ne=I.bind(null,B);return ne.type=B,ne},Sn.createRef=function(){return{current:null}},Sn.forwardRef=function(B){return{$$typeof:l,render:B}},Sn.isValidElement=G,Sn.lazy=function(B){return{$$typeof:m,_payload:{_status:-1,_result:B},_init:L}},Sn.memo=function(B,ne){return{$$typeof:h,type:B,compare:ne===void 0?null:ne}},Sn.startTransition=function(B){var ne=H.transition;H.transition={};try{B()}finally{H.transition=ne}},Sn.unstable_act=te,Sn.useCallback=function(B,ne){return J.current.useCallback(B,ne)},Sn.useContext=function(B){return J.current.useContext(B)},Sn.useDebugValue=function(){},Sn.useDeferredValue=function(B){return J.current.useDeferredValue(B)},Sn.useEffect=function(B,ne){return J.current.useEffect(B,ne)},Sn.useId=function(){return J.current.useId()},Sn.useImperativeHandle=function(B,ne,se){return J.current.useImperativeHandle(B,ne,se)},Sn.useInsertionEffect=function(B,ne){return J.current.useInsertionEffect(B,ne)},Sn.useLayoutEffect=function(B,ne){return J.current.useLayoutEffect(B,ne)},Sn.useMemo=function(B,ne){return J.current.useMemo(B,ne)},Sn.useReducer=function(B,ne,se){return J.current.useReducer(B,ne,se)},Sn.useRef=function(B){return J.current.useRef(B)},Sn.useState=function(B){return J.current.useState(B)},Sn.useSyncExternalStore=function(B,ne,se){return J.current.useSyncExternalStore(B,ne,se)},Sn.useTransition=function(){return J.current.useTransition()},Sn.version="18.3.1",Sn}var rb;function vm(){return rb||(rb=1,hy.exports=cE()),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 uE(){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 dE(){return ob||(ob=1,fy.exports=uE()),fy.exports}var s=dE(),p=vm();const Ce=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 fE(){return ab||(ab=1,(function(e){function t(H,z){var te=H.length;H.push(z);e:for(;0<te;){var B=te-1>>>1,ne=H[B];if(0<i(ne,z))H[B]=z,H[te]=ne,te=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],te=H.pop();if(te!==z){H[0]=te;e:for(var B=0,ne=H.length,se=ne>>>1;B<se;){var ue=2*(B+1)-1,ve=H[ue],Te=ue+1,ke=H[Te];if(0>i(ve,te))Te<ne&&0>i(ke,ve)?(H[B]=ke,H[Te]=te,B=Te):(H[B]=ve,H[ue]=te,B=ue);else if(Te<ne&&0>i(ke,te))H[B]=ke,H[Te]=te,B=Te;else break e}}return z}function i(H,z){var te=H.sortIndex-z.sortIndex;return te!==0?te: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&&J(S,z.startTime-H)}}function D(H,z){x=!1,k&&(k=!1,N(I),I=-1),y=!0;var te=g;try{for(C(z),_=n(d);_!==null&&(!(_.expirationTime>z)||H&&!K());){var B=_.callback;if(typeof B=="function"){_.callback=null,g=_.priorityLevel;var ne=B(_.expirationTime<=z);z=e.unstable_now(),typeof ne=="function"?_.callback=ne:_===n(d)&&r(d),C(z)}else r(d);_=n(d)}if(_!==null)var se=!0;else{var ue=n(h);ue!==null&&J(S,ue.startTime-z),se=!1}return se}finally{_=null,g=te,y=!1}}var P=!1,R=null,I=-1,W=5,G=-1;function K(){return!(e.unstable_now()-G<W)}function V(){if(R!==null){var H=e.unstable_now();G=H;var z=!0;try{z=R(!0,H)}finally{z?M():(P=!1,R=null)}}else P=!1}var M;if(typeof $=="function")M=function(){$(V)};else if(typeof MessageChannel<"u"){var A=new MessageChannel,O=A.port2;A.port1.onmessage=V,M=function(){O.postMessage(null)}}else M=function(){v(V,0)};function L(H){R=H,P||(P=!0,M())}function J(H,z){I=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 te=g;g=z;try{return H()}finally{g=te}},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 te=g;g=H;try{return z()}finally{g=te}},e.unstable_scheduleCallback=function(H,z,te){var B=e.unstable_now();switch(typeof te=="object"&&te!==null?(te=te.delay,te=typeof te=="number"&&0<te?B+te:B):te=B,H){case 1:var ne=-1;break;case 2:ne=250;break;case 5:ne=1073741823;break;case 4:ne=1e4;break;default:ne=5e3}return ne=te+ne,H={id:m++,callback:z,priorityLevel:H,startTime:te,expirationTime:ne,sortIndex:-1},te>B?(H.sortIndex=te,t(h,H),n(d)===null&&H===n(h)&&(k?(N(I),I=-1):k=!0,J(S,te-B))):(H.sortIndex=ne,t(d,H),x||y||(x=!0,L(D))),H},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(H){var z=g;return function(){var te=g;g=z;try{return H.apply(this,arguments)}finally{g=te}}}})(py)),py}var lb;function hE(){return lb||(lb=1,_y.exports=fE()),_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 mE(){if(cb)return xi;cb=1;var e=vm(),t=hE();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"),P=Symbol.for("react.portal"),R=Symbol.for("react.fragment"),I=Symbol.for("react.strict_mode"),W=Symbol.for("react.profiler"),G=Symbol.for("react.provider"),K=Symbol.for("react.context"),V=Symbol.for("react.forward_ref"),M=Symbol.for("react.suspense"),A=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),J=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 te=Object.assign,B;function ne(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 ue(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(Ae){var w=Ae}Reflect.construct(a,[],u)}else{try{u.call()}catch(Ae){w=Ae}a.call(u.prototype)}else{try{throw Error()}catch(Ae){w=Ae}a()}}catch(Ae){if(Ae&&w&&typeof Ae.stack=="string"){for(var j=Ae.stack.split(`
|
|
35
|
+
`),E=w.stack.split(`
|
|
36
|
+
`),q=j.length-1,oe=E.length-1;1<=q&&0<=oe&&j[q]!==E[oe];)oe--;for(;1<=q&&0<=oe;q--,oe--)if(j[q]!==E[oe]){if(q!==1||oe!==1)do if(q--,oe--,0>oe||j[q]!==E[oe]){var ce=`
|
|
37
|
+
`+j[q].replace(" at new "," at ");return a.displayName&&ce.includes("<anonymous>")&&(ce=ce.replace("<anonymous>",a.displayName)),ce}while(1<=q&&0<=oe);break}}}finally{se=!1,Error.prepareStackTrace=f}return(a=a?a.displayName||a.name:"")?ne(a):""}function ve(a){switch(a.tag){case 5:return ne(a.type);case 16:return ne("Lazy");case 13:return ne("Suspense");case 19:return ne("SuspenseList");case 0:case 2:case 15:return a=ue(a.type,!1),a;case 11:return a=ue(a.type.render,!1),a;case 1:return a=ue(a.type,!0),a;default:return""}}function Te(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 R:return"Fragment";case P:return"Portal";case W:return"Profiler";case I:return"StrictMode";case M:return"Suspense";case A:return"SuspenseList"}if(typeof a=="object")switch(a.$$typeof){case K:return(a.displayName||"Context")+".Consumer";case G: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 O:return u=a.displayName||null,u!==null?u:Te(a.type)||"Memo";case L:u=a._payload,a=a._init;try{return Te(a(u))}catch{}}return null}function ke(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 Te(u);case 8:return u===I?"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 le(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":return a;case"object":return a;default:return""}}function xe(a){var u=a.type;return(a=a.nodeName)&&a.toLowerCase()==="input"&&(u==="checkbox"||u==="radio")}function Ee(a){var u=xe(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=Ee(a))}function _t(a){if(!a)return!1;var u=a._valueTracker;if(!u)return!0;var f=u.getValue(),w="";return a&&(w=xe(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 ot(a,u){var f=u.checked;return te({},u,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:f??a._wrapperState.initialChecked})}function ze(a,u){var f=u.defaultValue==null?"":u.defaultValue,w=u.checked!=null?u.checked:u.defaultChecked;f=le(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 He(a,u){u=u.checked,u!=null&&C(a,"checked",u,!1)}function ft(a,u){He(a,u);var f=le(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")?Ot(a,u.type,f):u.hasOwnProperty("defaultValue")&&Ot(a,u.type,le(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 Ot(a,u,f){(u!=="number"||Qe(a.ownerDocument)!==a)&&(f==null?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+f&&(a.defaultValue=""+f))}var Ne=Array.isArray;function Re(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=""+le(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 tt(a,u){if(u.dangerouslySetInnerHTML!=null)throw Error(n(91));return te({},u,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function re(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(Ne(f)){if(1<f.length)throw Error(n(93));f=f[0]}u=f}u==null&&(u=""),f=u}a._wrapperState={initialValue:le(f)}}function ge(a,u){var f=le(u.value),w=le(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 de(a){var u=a.textContent;u===a._wrapperState.initialValue&&u!==""&&u!==null&&(a.value=u)}function je(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 X(a,u){return a==null||a==="http://www.w3.org/1999/xhtml"?je(u):a==="http://www.w3.org/2000/svg"&&u==="foreignObject"?"http://www.w3.org/1999/xhtml":a}var Oe,pt=(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(Oe=Oe||document.createElement("div"),Oe.innerHTML="<svg>"+u.valueOf().toString()+"</svg>",u=Oe.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;u.firstChild;)a.appendChild(u.firstChild)}});function at(a,u){if(u){var f=a.firstChild;if(f&&f===a.lastChild&&f.nodeType===3){f.nodeValue=u;return}}a.textContent=u}var Et={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},yt=["Webkit","ms","Moz","O"];Object.keys(Et).forEach(function(a){yt.forEach(function(u){u=u+a.charAt(0).toUpperCase()+a.substring(1),Et[u]=Et[a]})});function jt(a,u,f){return u==null||typeof u=="boolean"||u===""?"":f||typeof u!="number"||u===0||Et.hasOwnProperty(a)&&Et[a]?(""+u).trim():u+"px"}function st(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 Pt=te({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 Lt(a,u){if(u){if(Pt[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 mn(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,_e=null;function Me(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 wt(a){rs?_e?_e.push(a):_e=[a]:rs=a}function ie(){if(rs){var a=rs,u=_e;if(_e=rs=null,Me(a),u)for(a=0;a<u.length;a++)Me(u[a])}}function fe(a,u){return a(u)}function $e(){}var Le=!1;function We(a,u,f){if(Le)return a(u,f);Le=!0;try{return fe(a,u,f)}finally{Le=!1,(rs!==null||_e!==null)&&($e(),ie())}}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 nt=!1;if(l)try{var ut={};Object.defineProperty(ut,"passive",{get:function(){nt=!0}}),window.addEventListener("test",ut,ut),window.removeEventListener("test",ut,ut)}catch{nt=!1}function xt(a,u,f,w,j,E,q,oe,ce){var Ae=Array.prototype.slice.call(arguments,3);try{u.apply(f,Ae)}catch(Ze){this.onError(Ze)}}var bt=!1,Tt=null,zt=!1,ct=null,Yt={onError:function(a){bt=!0,Tt=a}};function vn(a,u,f,w,j,E,q,oe,ce){bt=!1,Tt=null,xt.apply(Yt,arguments)}function hn(a,u,f,w,j,E,q,oe,ce){if(vn.apply(this,arguments),bt){if(bt){var Ae=Tt;bt=!1,Tt=null}else throw Error(n(198));zt||(zt=!0,ct=Ae)}}function sn(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(sn(a)!==a)throw Error(n(188))}function Be(a){var u=a.alternate;if(!u){if(u=sn(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,oe=j.child;oe;){if(oe===f){q=!0,f=j,w=E;break}if(oe===w){q=!0,w=j,f=E;break}oe=oe.sibling}if(!q){for(oe=E.child;oe;){if(oe===f){q=!0,f=E,w=j;break}if(oe===w){q=!0,w=E,f=j;break}oe=oe.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?Rt(a):null}function Rt(a){if(a.tag===5||a.tag===6)return a;for(a=a.child;a!==null;){var u=Rt(a);if(u!==null)return u;a=a.sibling}return null}var Fn=t.unstable_scheduleCallback,fn=t.unstable_cancelCallback,Xe=t.unstable_shouldYield,nn=t.unstable_requestPaint,cn=t.unstable_now,Ar=t.unstable_getCurrentPriorityLevel,As=t.unstable_ImmediatePriority,ws=t.unstable_UserBlockingPriority,_r=t.unstable_NormalPriority,ye=t.unstable_LowPriority,Nt=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 oe=q&~j;oe!==0?w=Rs(oe):(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),oe=1<<q,ce=j[q];ce===-1?((oe&f)===0||(oe&w)!==0)&&(j[q]=dl(oe,u)):ce<=u&&(a.expiredLanes|=oe),E&=~oe}}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=sn(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=he(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=he(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=he(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 he(a,u,f,w){if(Y=null,a=On(w),a=Fa(a),a!==null)if(u=sn(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 Ie(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 ye:return 16;case Nt:return 536870912;default:return 16}default:return 16}}var De=null,Ye=null,mt=null;function Wt(){if(mt)return mt;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 mt=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 oe in a)a.hasOwnProperty(oe)&&(f=a[oe],this[oe]=f?f(E):E[oe]);return this.isDefaultPrevented=(E.defaultPrevented!=null?E.defaultPrevented:E.returnValue===!1)?Bt:pn,this.isPropagationStopped=pn,this}return te(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=te({},Js,{view:0,detail:0}),ls=En(bn),Hn,Rr,yr,Vi=te({},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=te({},Vi,{dataTransfer:0}),df=En(Hi),mc=te({},bn,{relatedTarget:0}),Aa=En(mc),Ta=te({},Js,{animationName:0,elapsedTime:0,pseudoElement:0}),ff=En(Ta),_c=te({},Js,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),pc=En(_c),ju=te({},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=te({},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=te({},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=te({},bn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:pl}),pf=En(_f),gl=te({},Js,{propertyName:0,elapsedTime:0,pseudoElement:0}),Fm=En(gl),zm=te({},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(),mt=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){wt(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,hn(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 oe=w[q],ce=oe.instance,Ae=oe.currentTarget;if(oe=oe.listener,ce!==E&&j.isPropagationStopped())break e;Ao(j,oe,Ae),E=ce}else for(q=0;q<w.length;q++){if(oe=w[q],ce=oe.instance,Ae=oe.currentTarget,oe=oe.listener,ce!==E&&j.isPropagationStopped())break e;Ao(j,oe,Ae),E=ce}}}if(zt)throw a=ct,zt=!1,ct=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(Ie(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,!nt||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 oe=w.stateNode.containerInfo;if(oe===j||oe.nodeType===8&&oe.parentNode===j)break;if(q===4)for(q=w.return;q!==null;){var ce=q.tag;if((ce===3||ce===4)&&(ce=q.stateNode.containerInfo,ce===j||ce.nodeType===8&&ce.parentNode===j))return;q=q.return}for(;oe!==null;){if(q=Fa(oe),q===null)return;if(ce=q.tag,ce===5||ce===6){w=E=q;continue e}oe=oe.parentNode}}w=w.return}We(function(){var Ae=E,Ze=On(f),rt=[];e:{var Je=$o.get(a);if(Je!==void 0){var kt=Ft,Ct=a;switch(a){case"keypress":if(Dt(f)===0)break e;case"keydown":case"keyup":kt=Ma;break;case"focusin":Ct="focus",kt=Aa;break;case"focusout":Ct="blur",kt=Aa;break;case"beforeblur":case"afterblur":kt=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":kt=_l;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":kt=df;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":kt=pf;break;case Jm:case Iu:case bl:kt=ff;break;case Gr:kt=Fm;break;case"scroll":kt=ls;break;case"wheel":kt=gf;break;case"copy":case"cut":case"paste":kt=pc;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":kt=Cu}var Mt=(u&4)!==0,Os=!Mt&&a==="scroll",we=Mt?Je!==null?Je+"Capture":null:Je;Mt=[];for(var me=Ae,Se;me!==null;){Se=me;var lt=Se.stateNode;if(Se.tag===5&<!==null&&(Se=lt,we!==null&&(lt=Ue(me,we),lt!=null&&Mt.push(Ir(me,lt,Se)))),Os)break;me=me.return}0<Mt.length&&(Je=new kt(Je,Ct,null,f,Ze),rt.push({event:Je,listeners:Mt}))}}if((u&7)===0){e:{if(Je=a==="mouseover"||a==="pointerover",kt=a==="mouseout"||a==="pointerout",Je&&f!==wn&&(Ct=f.relatedTarget||f.fromElement)&&(Fa(Ct)||Ct[Ti]))break e;if((kt||Je)&&(Je=Ze.window===Ze?Ze:(Je=Ze.ownerDocument)?Je.defaultView||Je.parentWindow:window,kt?(Ct=f.relatedTarget||f.toElement,kt=Ae,Ct=Ct?Fa(Ct):null,Ct!==null&&(Os=sn(Ct),Ct!==Os||Ct.tag!==5&&Ct.tag!==6)&&(Ct=null)):(kt=null,Ct=Ae),kt!==Ct)){if(Mt=_l,lt="onMouseLeave",we="onMouseEnter",me="mouse",(a==="pointerout"||a==="pointerover")&&(Mt=Cu,lt="onPointerLeave",we="onPointerEnter",me="pointer"),Os=kt==null?Je:$l(kt),Se=Ct==null?Je:$l(Ct),Je=new Mt(lt,me+"leave",kt,f,Ze),Je.target=Os,Je.relatedTarget=Se,lt=null,Fa(Ze)===Ae&&(Mt=new Mt(we,me+"enter",Ct,f,Ze),Mt.target=Se,Mt.relatedTarget=Os,lt=Mt),Os=lt,kt&&Ct)t:{for(Mt=kt,we=Ct,me=0,Se=Mt;Se;Se=xr(Se))me++;for(Se=0,lt=we;lt;lt=xr(lt))Se++;for(;0<me-Se;)Mt=xr(Mt),me--;for(;0<Se-me;)we=xr(we),Se--;for(;me--;){if(Mt===we||we!==null&&Mt===we.alternate)break t;Mt=xr(Mt),we=xr(we)}Mt=null}else Mt=null;kt!==null&&Ef(rt,Je,kt,Mt,!1),Ct!==null&&Os!==null&&Ef(rt,Os,Ct,Mt,!0)}}e:{if(Je=Ae?$l(Ae):window,kt=Je.nodeName&&Je.nodeName.toLowerCase(),kt==="select"||kt==="input"&&Je.type==="file")var It=Um;else if(No(Je))if(Wm)It=Sf;else{It=Vm;var Gt=Qg}else(kt=Je.nodeName)&&kt.toLowerCase()==="input"&&(Je.type==="checkbox"||Je.type==="radio")&&(It=Hm);if(It&&(It=It(a,Ae))){wf(rt,It,f,Ze);break e}Gt&&Gt(a,Je,Ae),a==="focusout"&&(Gt=Je._wrapperState)&&Gt.controlled&&Je.type==="number"&&Ot(Je,"number",Je.value)}switch(Gt=Ae?$l(Ae):window,a){case"focusin":(No(Gt)||Gt.contentEditable==="true")&&(Ji=Gt,$f=Ae,La=null);break;case"focusout":La=$f=Ji=null;break;case"mousedown":Cf=!0;break;case"contextmenu":case"mouseup":case"dragend":Cf=!1,Lu(rt,f,Ze);break;case"selectionchange":if(wc)break;case"keydown":case"keyup":Lu(rt,f,Ze)}var Kt;if(Eu)e:{switch(a){case"compositionstart":var dn="onCompositionStart";break e;case"compositionend":dn="onCompositionEnd";break e;case"compositionupdate":dn="onCompositionUpdate";break e}dn=void 0}else wl?Bm(a,f)&&(dn="onCompositionEnd"):a==="keydown"&&f.keyCode===229&&(dn="onCompositionStart");dn&&(Au&&f.locale!=="ko"&&(wl||dn!=="onCompositionStart"?dn==="onCompositionEnd"&&wl&&(Kt=Wt()):(De=Ze,Ye="value"in De?De.value:De.textContent,wl=!0)),Gt=Ai(Ae,dn),0<Gt.length&&(dn=new hf(dn,a,null,f,Ze),rt.push({event:dn,listeners:Gt}),Kt?dn.data=Kt:(Kt=Mu(f),Kt!==null&&(dn.data=Kt)))),(Kt=Xg?yf(a,f):Zg(a,f))&&(Ae=Ai(Ae,"onBeforeInput"),0<Ae.length&&(Ze=new hf("onBeforeInput","beforeinput",null,f,Ze),rt.push({event:Ze,listeners:Ae}),Ze.data=Kt))}vr(rt,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 oe=f,ce=oe.alternate,Ae=oe.stateNode;if(ce!==null&&ce===w)break;oe.tag===5&&Ae!==null&&(oe=Ae,j?(ce=Ue(f,E),ce!=null&&q.unshift(Ir(f,ce,oe))):j||(ce=Ue(f,E),ce!=null&&q.push(Ir(f,ce,oe)))),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,ke(a)||"Unknown",j));return te({},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 oe=j.refs;q===null?delete oe[E]:oe[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(we,me){if(a){var Se=we.deletions;Se===null?(we.deletions=[me],we.flags|=16):Se.push(me)}}function f(we,me){if(!a)return null;for(;me!==null;)u(we,me),me=me.sibling;return null}function w(we,me){for(we=new Map;me!==null;)me.key!==null?we.set(me.key,me):we.set(me.index,me),me=me.sibling;return we}function j(we,me){return we=dt(we,me),we.index=0,we.sibling=null,we}function E(we,me,Se){return we.index=Se,a?(Se=we.alternate,Se!==null?(Se=Se.index,Se<me?(we.flags|=2,me):Se):(we.flags|=2,me)):(we.flags|=1048576,me)}function q(we){return a&&we.alternate===null&&(we.flags|=2),we}function oe(we,me,Se,lt){return me===null||me.tag!==6?(me=en(Se,we.mode,lt),me.return=we,me):(me=j(me,Se),me.return=we,me)}function ce(we,me,Se,lt){var It=Se.type;return It===R?Ze(we,me,Se.props.children,lt,Se.key):me!==null&&(me.elementType===It||typeof It=="object"&&It!==null&&It.$$typeof===L&&ui(It)===me.type)?(lt=j(me,Se.props),lt.ref=Ke(we,me,Se),lt.return=we,lt):(lt=xn(Se.type,Se.key,Se.props,null,we.mode,lt),lt.ref=Ke(we,me,Se),lt.return=we,lt)}function Ae(we,me,Se,lt){return me===null||me.tag!==4||me.stateNode.containerInfo!==Se.containerInfo||me.stateNode.implementation!==Se.implementation?(me=Yn(Se,we.mode,lt),me.return=we,me):(me=j(me,Se.children||[]),me.return=we,me)}function Ze(we,me,Se,lt,It){return me===null||me.tag!==7?(me=qt(Se,we.mode,lt,It),me.return=we,me):(me=j(me,Se),me.return=we,me)}function rt(we,me,Se){if(typeof me=="string"&&me!==""||typeof me=="number")return me=en(""+me,we.mode,Se),me.return=we,me;if(typeof me=="object"&&me!==null){switch(me.$$typeof){case D:return Se=xn(me.type,me.key,me.props,null,we.mode,Se),Se.ref=Ke(we,null,me),Se.return=we,Se;case P:return me=Yn(me,we.mode,Se),me.return=we,me;case L:var lt=me._init;return rt(we,lt(me._payload),Se)}if(Ne(me)||z(me))return me=qt(me,we.mode,Se,null),me.return=we,me;Un(we,me)}return null}function Je(we,me,Se,lt){var It=me!==null?me.key:null;if(typeof Se=="string"&&Se!==""||typeof Se=="number")return It!==null?null:oe(we,me,""+Se,lt);if(typeof Se=="object"&&Se!==null){switch(Se.$$typeof){case D:return Se.key===It?ce(we,me,Se,lt):null;case P:return Se.key===It?Ae(we,me,Se,lt):null;case L:return It=Se._init,Je(we,me,It(Se._payload),lt)}if(Ne(Se)||z(Se))return It!==null?null:Ze(we,me,Se,lt,null);Un(we,Se)}return null}function kt(we,me,Se,lt,It){if(typeof lt=="string"&<!==""||typeof lt=="number")return we=we.get(Se)||null,oe(me,we,""+lt,It);if(typeof lt=="object"&<!==null){switch(lt.$$typeof){case D:return we=we.get(lt.key===null?Se:lt.key)||null,ce(me,we,lt,It);case P:return we=we.get(lt.key===null?Se:lt.key)||null,Ae(me,we,lt,It);case L:var Gt=lt._init;return kt(we,me,Se,Gt(lt._payload),It)}if(Ne(lt)||z(lt))return we=we.get(Se)||null,Ze(me,we,lt,It,null);Un(me,lt)}return null}function Ct(we,me,Se,lt){for(var It=null,Gt=null,Kt=me,dn=me=0,fr=null;Kt!==null&&dn<Se.length;dn++){Kt.index>dn?(fr=Kt,Kt=null):fr=Kt.sibling;var Wn=Je(we,Kt,Se[dn],lt);if(Wn===null){Kt===null&&(Kt=fr);break}a&&Kt&&Wn.alternate===null&&u(we,Kt),me=E(Wn,me,dn),Gt===null?It=Wn:Gt.sibling=Wn,Gt=Wn,Kt=fr}if(dn===Se.length)return f(we,Kt),Zn&&za(we,dn),It;if(Kt===null){for(;dn<Se.length;dn++)Kt=rt(we,Se[dn],lt),Kt!==null&&(me=E(Kt,me,dn),Gt===null?It=Kt:Gt.sibling=Kt,Gt=Kt);return Zn&&za(we,dn),It}for(Kt=w(we,Kt);dn<Se.length;dn++)fr=kt(Kt,we,dn,Se[dn],lt),fr!==null&&(a&&fr.alternate!==null&&Kt.delete(fr.key===null?dn:fr.key),me=E(fr,me,dn),Gt===null?It=fr:Gt.sibling=fr,Gt=fr);return a&&Kt.forEach(function(Hl){return u(we,Hl)}),Zn&&za(we,dn),It}function Mt(we,me,Se,lt){var It=z(Se);if(typeof It!="function")throw Error(n(150));if(Se=It.call(Se),Se==null)throw Error(n(151));for(var Gt=It=null,Kt=me,dn=me=0,fr=null,Wn=Se.next();Kt!==null&&!Wn.done;dn++,Wn=Se.next()){Kt.index>dn?(fr=Kt,Kt=null):fr=Kt.sibling;var Hl=Je(we,Kt,Wn.value,lt);if(Hl===null){Kt===null&&(Kt=fr);break}a&&Kt&&Hl.alternate===null&&u(we,Kt),me=E(Hl,me,dn),Gt===null?It=Hl:Gt.sibling=Hl,Gt=Hl,Kt=fr}if(Wn.done)return f(we,Kt),Zn&&za(we,dn),It;if(Kt===null){for(;!Wn.done;dn++,Wn=Se.next())Wn=rt(we,Wn.value,lt),Wn!==null&&(me=E(Wn,me,dn),Gt===null?It=Wn:Gt.sibling=Wn,Gt=Wn);return Zn&&za(we,dn),It}for(Kt=w(we,Kt);!Wn.done;dn++,Wn=Se.next())Wn=kt(Kt,we,dn,Wn.value,lt),Wn!==null&&(a&&Wn.alternate!==null&&Kt.delete(Wn.key===null?dn:Wn.key),me=E(Wn,me,dn),Gt===null?It=Wn:Gt.sibling=Wn,Gt=Wn);return a&&Kt.forEach(function(oE){return u(we,oE)}),Zn&&za(we,dn),It}function Os(we,me,Se,lt){if(typeof Se=="object"&&Se!==null&&Se.type===R&&Se.key===null&&(Se=Se.props.children),typeof Se=="object"&&Se!==null){switch(Se.$$typeof){case D:e:{for(var It=Se.key,Gt=me;Gt!==null;){if(Gt.key===It){if(It=Se.type,It===R){if(Gt.tag===7){f(we,Gt.sibling),me=j(Gt,Se.props.children),me.return=we,we=me;break e}}else if(Gt.elementType===It||typeof It=="object"&&It!==null&&It.$$typeof===L&&ui(It)===Gt.type){f(we,Gt.sibling),me=j(Gt,Se.props),me.ref=Ke(we,Gt,Se),me.return=we,we=me;break e}f(we,Gt);break}else u(we,Gt);Gt=Gt.sibling}Se.type===R?(me=qt(Se.props.children,we.mode,lt,Se.key),me.return=we,we=me):(lt=xn(Se.type,Se.key,Se.props,null,we.mode,lt),lt.ref=Ke(we,me,Se),lt.return=we,we=lt)}return q(we);case P:e:{for(Gt=Se.key;me!==null;){if(me.key===Gt)if(me.tag===4&&me.stateNode.containerInfo===Se.containerInfo&&me.stateNode.implementation===Se.implementation){f(we,me.sibling),me=j(me,Se.children||[]),me.return=we,we=me;break e}else{f(we,me);break}else u(we,me);me=me.sibling}me=Yn(Se,we.mode,lt),me.return=we,we=me}return q(we);case L:return Gt=Se._init,Os(we,me,Gt(Se._payload),lt)}if(Ne(Se))return Ct(we,me,Se,lt);if(z(Se))return Mt(we,me,Se,lt);Un(we,Se)}return typeof Se=="string"&&Se!==""||typeof Se=="number"?(Se=""+Se,me!==null&&me.tag===6?(f(we,me.sibling),me=j(me,Se),me.return=we,we=me):(f(we,me),me=en(Se,we.mode,lt),me.return=we,we=me),q(we)):f(we,me)}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,un(a,w)}function un(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,un(a,f)}return j=w.interleaved,j===null?(u.next=u,Yu(w)):(u.next=j.next,j.next=u),w.interleaved=u,un(a,f)}function rn(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,oe=j.shared.pending;if(oe!==null){j.shared.pending=null;var ce=oe,Ae=ce.next;ce.next=null,q===null?E=Ae:q.next=Ae,q=ce;var Ze=a.alternate;Ze!==null&&(Ze=Ze.updateQueue,oe=Ze.lastBaseUpdate,oe!==q&&(oe===null?Ze.firstBaseUpdate=Ae:oe.next=Ae,Ze.lastBaseUpdate=ce))}if(E!==null){var rt=j.baseState;q=0,Ze=Ae=ce=null,oe=E;do{var Je=oe.lane,kt=oe.eventTime;if((w&Je)===Je){Ze!==null&&(Ze=Ze.next={eventTime:kt,lane:0,tag:oe.tag,payload:oe.payload,callback:oe.callback,next:null});e:{var Ct=a,Mt=oe;switch(Je=u,kt=f,Mt.tag){case 1:if(Ct=Mt.payload,typeof Ct=="function"){rt=Ct.call(kt,rt,Je);break e}rt=Ct;break e;case 3:Ct.flags=Ct.flags&-65537|128;case 0:if(Ct=Mt.payload,Je=typeof Ct=="function"?Ct.call(kt,rt,Je):Ct,Je==null)break e;rt=te({},rt,Je);break e;case 2:_s=!0}}oe.callback!==null&&oe.lane!==0&&(a.flags|=64,Je=j.effects,Je===null?j.effects=[oe]:Je.push(oe))}else kt={eventTime:kt,lane:Je,tag:oe.tag,payload:oe.payload,callback:oe.callback,next:null},Ze===null?(Ae=Ze=kt,ce=rt):Ze=Ze.next=kt,q|=Je;if(oe=oe.next,oe===null){if(oe=j.shared.pending,oe===null)break;Je=oe,oe=Je.next,Je.next=null,j.lastBaseUpdate=Je,j.shared.pending=null}}while(!0);if(Ze===null&&(ce=rt),j.baseState=ce,j.firstBaseUpdate=Ae,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=rt}}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:X(null,"");break;default:a=a===8?u.parentNode:u,u=a.namespaceURI||null,a=a.tagName,u=X(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=X(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 oe=q=null,ce=null,Ae=E;do{var Ze=Ae.lane;if((Qn&Ze)===Ze)ce!==null&&(ce=ce.next={lane:0,action:Ae.action,hasEagerState:Ae.hasEagerState,eagerState:Ae.eagerState,next:null}),w=Ae.hasEagerState?Ae.eagerState:a(w,Ae.action);else{var rt={lane:Ze,action:Ae.action,hasEagerState:Ae.hasEagerState,eagerState:Ae.eagerState,next:null};ce===null?(oe=ce=rt,q=w):ce=ce.next=rt,cs.lanes|=Ze,ua|=Ze}Ae=Ae.next}while(Ae!==null&&Ae!==E);ce===null?q=w:ce.next=oe,wr(w,u.memoizedState)||(Cs=!0),u.memoizedState=w,u.baseState=q,u.baseQueue=ce,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=un(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,oe=E(q,f);if(j.hasEagerState=!0,j.eagerState=oe,wr(oe,q)){var ce=u.interleaved;ce===null?(j.next=j,Yu(u)):(j.next=ce.next,ce.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=te({},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:te({},u,f),a.memoizedState=f,a.lanes===0&&(a.updateQueue.baseState=f)}var id={isMounted:function(a){return(a=a._reactInternals)?sn(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),rn(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),rn(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),rn(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+=ve(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=Z.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"&&!it(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,oe=u.memoizedProps;q.props=oe;var ce=q.context,Ae=f.contextType;typeof Ae=="object"&&Ae!==null?Ae=di(Ae):(Ae=ir(f)?Lo:Ts.current,Ae=Zi(u,Ae));var Ze=f.getDerivedStateFromProps,rt=typeof Ze=="function"||typeof q.getSnapshotBeforeUpdate=="function";rt||typeof q.UNSAFE_componentWillReceiveProps!="function"&&typeof q.componentWillReceiveProps!="function"||(oe!==w||ce!==Ae)&&w_(u,q,w,Ae),_s=!1;var Je=u.memoizedState;q.state=Je,Il(u,w,q,j),ce=u.memoizedState,oe!==w||Je!==ce||br.current||_s?(typeof Ze=="function"&&(eh(u,f,Ze,w),ce=u.memoizedState),(oe=_s||g_(u,f,oe,w,Je,ce,Ae))?(rt||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=ce),q.props=w,q.state=ce,q.context=Ae,w=oe):(typeof q.componentDidMount=="function"&&(u.flags|=4194308),w=!1)}else{q=u.stateNode,Wf(a,u),oe=u.memoizedProps,Ae=u.type===u.elementType?oe:_i(u.type,oe),q.props=Ae,rt=u.pendingProps,Je=q.context,ce=f.contextType,typeof ce=="object"&&ce!==null?ce=di(ce):(ce=ir(f)?Lo:Ts.current,ce=Zi(u,ce));var kt=f.getDerivedStateFromProps;(Ze=typeof kt=="function"||typeof q.getSnapshotBeforeUpdate=="function")||typeof q.UNSAFE_componentWillReceiveProps!="function"&&typeof q.componentWillReceiveProps!="function"||(oe!==rt||Je!==ce)&&w_(u,q,w,ce),_s=!1,Je=u.memoizedState,q.state=Je,Il(u,w,q,j);var Ct=u.memoizedState;oe!==rt||Je!==Ct||br.current||_s?(typeof kt=="function"&&(eh(u,f,kt,w),Ct=u.memoizedState),(Ae=_s||g_(u,f,Ae,w,Je,Ct,ce)||!1)?(Ze||typeof q.UNSAFE_componentWillUpdate!="function"&&typeof q.componentWillUpdate!="function"||(typeof q.componentWillUpdate=="function"&&q.componentWillUpdate(w,Ct,ce),typeof q.UNSAFE_componentWillUpdate=="function"&&q.UNSAFE_componentWillUpdate(w,Ct,ce)),typeof q.componentDidUpdate=="function"&&(u.flags|=4),typeof q.getSnapshotBeforeUpdate=="function"&&(u.flags|=1024)):(typeof q.componentDidUpdate!="function"||oe===a.memoizedProps&&Je===a.memoizedState||(u.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||oe===a.memoizedProps&&Je===a.memoizedState||(u.flags|=1024),u.memoizedProps=w,u.memoizedState=Ct),q.props=w,q.state=Ct,q.context=ce,w=Ae):(typeof q.componentDidUpdate!="function"||oe===a.memoizedProps&&Je===a.memoizedState||(u.flags|=4),typeof q.getSnapshotBeforeUpdate!="function"||oe===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 oe=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,oe,E)):xs(a,u,oe,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,oe;if((oe=q)||(oe=a!==null&&a.memoizedState===null?!1:(j&2)!==0),oe?(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=ht(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&&(oe=j.dehydrated,oe!==null))return iy(a,u,q,w,oe,j,f);if(E){E=w.fallback,q=u.mode,j=a.child,oe=j.sibling;var ce={mode:"hidden",children:w.children};return(q&1)===0&&u.child!==j?(w=u.child,w.childLanes=0,w.pendingProps=ce,u.deletions=null):(w=dt(j,ce),w.subtreeFlags=j.subtreeFlags&14680064),oe!==null?E=dt(oe,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=ht({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=ht({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 oe=w.dgst;return w=oe,E=Error(n(419)),w=Oc(E,w,void 0),zo(a,u,q,w)}if(oe=(q&a.childLanes)!==0,Cs||oe){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,un(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=ae.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=ot(a,j),w=ot(a,w),E=[];break;case"select":j=te({},j,{value:void 0}),w=te({},w,{value:void 0}),E=[];break;case"textarea":j=tt(a,j),w=tt(a,w),E=[];break;default:typeof j.onClick!="function"&&typeof w.onClick=="function"&&(a.onclick=jc)}Lt(f,w);var q;f=null;for(Ae in j)if(!w.hasOwnProperty(Ae)&&j.hasOwnProperty(Ae)&&j[Ae]!=null)if(Ae==="style"){var oe=j[Ae];for(q in oe)oe.hasOwnProperty(q)&&(f||(f={}),f[q]="")}else Ae!=="dangerouslySetInnerHTML"&&Ae!=="children"&&Ae!=="suppressContentEditableWarning"&&Ae!=="suppressHydrationWarning"&&Ae!=="autoFocus"&&(i.hasOwnProperty(Ae)?E||(E=[]):(E=E||[]).push(Ae,null));for(Ae in w){var ce=w[Ae];if(oe=j!=null?j[Ae]:void 0,w.hasOwnProperty(Ae)&&ce!==oe&&(ce!=null||oe!=null))if(Ae==="style")if(oe){for(q in oe)!oe.hasOwnProperty(q)||ce&&ce.hasOwnProperty(q)||(f||(f={}),f[q]="");for(q in ce)ce.hasOwnProperty(q)&&oe[q]!==ce[q]&&(f||(f={}),f[q]=ce[q])}else f||(E||(E=[]),E.push(Ae,f)),f=ce;else Ae==="dangerouslySetInnerHTML"?(ce=ce?ce.__html:void 0,oe=oe?oe.__html:void 0,ce!=null&&oe!==ce&&(E=E||[]).push(Ae,ce)):Ae==="children"?typeof ce!="string"&&typeof ce!="number"||(E=E||[]).push(Ae,""+ce):Ae!=="suppressContentEditableWarning"&&Ae!=="suppressHydrationWarning"&&(i.hasOwnProperty(Ae)?(ce!=null&&Ae==="onScroll"&&Bn("scroll",a),E||oe===ce||(E=[])):(E=E||[]).push(Ae,ce))}f&&(E=E||[]).push("style",f);var Ae=E;(u.updateQueue=Ae)&&(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":ze(w,E),Bn("invalid",w);break;case"select":w._wrapperState={wasMultiple:!!E.multiple},Bn("invalid",w);break;case"textarea":re(w,E),Bn("invalid",w)}Lt(f,E),j=null;for(var q in E)if(E.hasOwnProperty(q)){var oe=E[q];q==="children"?typeof oe=="string"?w.textContent!==oe&&(E.suppressHydrationWarning!==!0&&kc(w.textContent,oe,a),j=["children",oe]):typeof oe=="number"&&w.textContent!==""+oe&&(E.suppressHydrationWarning!==!0&&kc(w.textContent,oe,a),j=["children",""+oe]):i.hasOwnProperty(q)&&oe!=null&&q==="onScroll"&&Bn("scroll",w)}switch(f){case"input":Ve(w),et(w,E,!0);break;case"textarea":Ve(w),de(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=je(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=mn(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":ze(a,w),j=ot(a,w),Bn("invalid",a);break;case"option":j=w;break;case"select":a._wrapperState={wasMultiple:!!w.multiple},j=te({},w,{value:void 0}),Bn("invalid",a);break;case"textarea":re(a,w),j=tt(a,w),Bn("invalid",a);break;default:j=w}Lt(f,j),oe=j;for(E in oe)if(oe.hasOwnProperty(E)){var ce=oe[E];E==="style"?st(a,ce):E==="dangerouslySetInnerHTML"?(ce=ce?ce.__html:void 0,ce!=null&&pt(a,ce)):E==="children"?typeof ce=="string"?(f!=="textarea"||ce!=="")&&at(a,ce):typeof ce=="number"&&at(a,""+ce):E!=="suppressContentEditableWarning"&&E!=="suppressHydrationWarning"&&E!=="autoFocus"&&(i.hasOwnProperty(E)?ce!=null&&E==="onScroll"&&Bn("scroll",a):ce!=null&&C(a,E,ce,q))}switch(f){case"input":Ve(a),et(a,w,!1);break;case"textarea":Ve(a),de(a);break;case"option":w.value!=null&&a.setAttribute("value",""+le(w.value));break;case"select":a.multiple=!!w.multiple,E=w.value,E!=null?Re(a,!!w.multiple,E,!1):w.defaultValue!=null&&Re(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&&cn()>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*cn()-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=cn(),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,St=null;function qs(a,u){var f=a.ref;if(f!==null)if(typeof f=="function")try{f(null)}catch(w){Q(a,u,w)}else f.current=null}function Ga(a,u,f){try{f()}catch(w){Q(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,oe=-1,ce=-1,Ae=0,Ze=0,rt=a,Je=null;t:for(;;){for(var kt;rt!==f||j!==0&&rt.nodeType!==3||(oe=q+j),rt!==E||w!==0&&rt.nodeType!==3||(ce=q+w),rt.nodeType===3&&(q+=rt.nodeValue.length),(kt=rt.firstChild)!==null;)Je=rt,rt=kt;for(;;){if(rt===a)break t;if(Je===f&&++Ae===j&&(oe=q),Je===E&&++Ze===w&&(ce=q),(kt=rt.nextSibling)!==null)break;rt=Je,Je=rt.parentNode}rt=kt}f=oe===-1||ce===-1?null:{start:oe,end:ce}}else f=null}f=f||{start:0,end:0}}else f=null;for(Af={focusedElem:a,selectionRange:f},rr=!1,St=u;St!==null;)if(u=St,a=u.child,(u.subtreeFlags&1028)!==0&&a!==null)a.return=u,St=a;else for(;St!==null;){u=St;try{var Ct=u.alternate;if((u.flags&1024)!==0)switch(u.tag){case 0:case 11:case 15:break;case 1:if(Ct!==null){var Mt=Ct.memoizedProps,Os=Ct.memoizedState,we=u.stateNode,me=we.getSnapshotBeforeUpdate(u.elementType===u.type?Mt:_i(u.type,Mt),Os);we.__reactInternalSnapshotBeforeUpdate=me}break;case 3:var Se=u.stateNode.containerInfo;Se.nodeType===1?Se.textContent="":Se.nodeType===9&&Se.documentElement&&Se.removeChild(Se.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(lt){Q(u,u.return,lt)}if(a=u.sibling,a!==null){a.return=u.return,St=a;break}St=u.return}return Ct=ih,ih=!1,Ct}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(oe){Q(f,u,oe)}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,oe=q;e:for(;oe!==null;){switch(oe.tag){case 5:Ys=oe.stateNode,Oi=!1;break e;case 3:Ys=oe.stateNode.containerInfo,Oi=!0;break e;case 4:Ys=oe.stateNode.containerInfo,Oi=!0;break e}oe=oe.return}if(Ys===null)throw Error(n(160));ah(E,q,j),Ys=null,Oi=!1;var ce=j.alternate;ce!==null&&(ce.return=null),j.return=null}catch(Ae){Q(j,u,Ae)}}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(Mt){Q(a,a.return,Mt)}try{lo(5,a,a.return)}catch(Mt){Q(a,a.return,Mt)}}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{at(j,"")}catch(Mt){Q(a,a.return,Mt)}}if(w&4&&(j=a.stateNode,j!=null)){var E=a.memoizedProps,q=f!==null?f.memoizedProps:E,oe=a.type,ce=a.updateQueue;if(a.updateQueue=null,ce!==null)try{oe==="input"&&E.type==="radio"&&E.name!=null&&He(j,E),mn(oe,q);var Ae=mn(oe,E);for(q=0;q<ce.length;q+=2){var Ze=ce[q],rt=ce[q+1];Ze==="style"?st(j,rt):Ze==="dangerouslySetInnerHTML"?pt(j,rt):Ze==="children"?at(j,rt):C(j,Ze,rt,Ae)}switch(oe){case"input":ft(j,E);break;case"textarea":ge(j,E);break;case"select":var Je=j._wrapperState.wasMultiple;j._wrapperState.wasMultiple=!!E.multiple;var kt=E.value;kt!=null?Re(j,!!E.multiple,kt,!1):Je!==!!E.multiple&&(E.defaultValue!=null?Re(j,!!E.multiple,E.defaultValue,!0):Re(j,!!E.multiple,E.multiple?[]:"",!1))}j[To]=E}catch(Mt){Q(a,a.return,Mt)}}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(Mt){Q(a,a.return,Mt)}}break;case 3:if(Cn(u,a),us(a),w&4&&f!==null&&f.memoizedState.isDehydrated)try{Ea(u.containerInfo)}catch(Mt){Q(a,a.return,Mt)}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=cn())),w&4&&M_(a);break;case 22:if(Ze=f!==null&&f.memoizedState!==null,a.mode&1?(ur=(Ae=ur)||Ze,Cn(u,a),ur=Ae):Cn(u,a),us(a),w&8192){if(Ae=a.memoizedState!==null,(a.stateNode.isHidden=Ae)&&!Ze&&(a.mode&1)!==0)for(St=a,Ze=a.child;Ze!==null;){for(rt=St=Ze;St!==null;){switch(Je=St,kt=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 Ct=Je.stateNode;if(typeof Ct.componentWillUnmount=="function"){w=Je,f=Je.return;try{u=w,Ct.props=u.memoizedProps,Ct.state=u.memoizedState,Ct.componentWillUnmount()}catch(Mt){Q(w,f,Mt)}}break;case 5:qs(Je,Je.return);break;case 22:if(Je.memoizedState!==null){fd(rt);continue}}kt!==null?(kt.return=Je,St=kt):fd(rt)}Ze=Ze.sibling}e:for(Ze=null,rt=a;;){if(rt.tag===5){if(Ze===null){Ze=rt;try{j=rt.stateNode,Ae?(E=j.style,typeof E.setProperty=="function"?E.setProperty("display","none","important"):E.display="none"):(oe=rt.stateNode,ce=rt.memoizedProps.style,q=ce!=null&&ce.hasOwnProperty("display")?ce.display:null,oe.style.display=jt("display",q))}catch(Mt){Q(a,a.return,Mt)}}}else if(rt.tag===6){if(Ze===null)try{rt.stateNode.nodeValue=Ae?"":rt.memoizedProps}catch(Mt){Q(a,a.return,Mt)}}else if((rt.tag!==22&&rt.tag!==23||rt.memoizedState===null||rt===a)&&rt.child!==null){rt.child.return=rt,rt=rt.child;continue}if(rt===a)break e;for(;rt.sibling===null;){if(rt.return===null||rt.return===a)break e;Ze===rt&&(Ze=null),rt=rt.return}Ze===rt&&(Ze=null),rt.sibling.return=rt.return,rt=rt.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&&(at(j,""),w.flags&=-33);var E=oh(a);Uc(a,E,j);break;case 3:case 4:var q=w.stateNode.containerInfo,oe=oh(a);Ii(a,oe,q);break;default:throw Error(n(161))}}catch(ce){Q(a,a.return,ce)}a.flags&=-3}u&4096&&(a.flags&=-4097)}function R_(a,u,f){St=a,L_(a)}function L_(a,u,f){for(var w=(a.mode&1)!==0;St!==null;){var j=St,E=j.child;if(j.tag===22&&w){var q=j.memoizedState!==null||zc;if(!q){var oe=j.alternate,ce=oe!==null&&oe.memoizedState!==null||ur;oe=zc;var Ae=ur;if(zc=q,(ur=ce)&&!Ae)for(St=j;St!==null;)q=St,ce=q.child,q.tag===22&&q.memoizedState!==null?O_(j):ce!==null?(ce.return=q,St=ce):O_(j);for(;E!==null;)St=E,L_(E),E=E.sibling;St=j,zc=oe,ur=Ae}I_(a)}else(j.subtreeFlags&8772)!==0&&E!==null?(E.return=j,St=E):I_(a)}}function I_(a){for(;St!==null;){var u=St;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 oe=u.stateNode;if(f===null&&u.flags&4){f=oe;var ce=u.memoizedProps;switch(u.type){case"button":case"input":case"select":case"textarea":ce.autoFocus&&f.focus();break;case"img":ce.src&&(f.src=ce.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(u.memoizedState===null){var Ae=u.alternate;if(Ae!==null){var Ze=Ae.memoizedState;if(Ze!==null){var rt=Ze.dehydrated;rt!==null&&Ea(rt)}}}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){Q(u,u.return,Je)}}if(u===a){St=null;break}if(f=u.sibling,f!==null){f.return=u.return,St=f;break}St=u.return}}function fd(a){for(;St!==null;){var u=St;if(u===a){St=null;break}var f=u.sibling;if(f!==null){f.return=u.return,St=f;break}St=u.return}}function O_(a){for(;St!==null;){var u=St;try{switch(u.tag){case 0:case 11:case 15:var f=u.return;try{Bc(4,u)}catch(ce){Q(u,f,ce)}break;case 1:var w=u.stateNode;if(typeof w.componentDidMount=="function"){var j=u.return;try{w.componentDidMount()}catch(ce){Q(u,j,ce)}}var E=u.return;try{Li(u)}catch(ce){Q(u,E,ce)}break;case 5:var q=u.return;try{Li(u)}catch(ce){Q(u,q,ce)}}}catch(ce){Q(u,u.return,ce)}if(u===a){St=null;break}var oe=u.sibling;if(oe!==null){oe.return=u.return,St=oe;break}St=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?cn():Uo!==-1?Uo:Uo=cn()}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:Ie(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=cn()+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&&fn(f),a.callbackNode=null,a.callbackPriority=0;else if(u=w&-w,a.callbackPriority!==u){if(f!=null&&fn(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=Nt;break;default:f=_r}f=pe(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=cn()+500,_a(a,u));do try{z_();break}catch(oe){fh(a,oe)}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,cn()),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,cn()),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-cn(),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=cn()-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,cn()),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,cn()),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,cn()),f;if(f===6)throw Error(n(345));return a.finishedWork=a.current.alternate,a.finishedLanes=u,b(a,Ms,ho),Dr(a,cn()),null}function _d(a,u){var f=Tn;Tn|=1;try{return a(u)}finally{Tn=f,Tn===0&&(da=cn()+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,oe=f,ce=u;if(u=Vs,oe.flags|=32768,ce!==null&&typeof ce=="object"&&typeof ce.then=="function"){var Ae=ce,Ze=oe,rt=Ze.tag;if((Ze.mode&1)===0&&(rt===0||rt===11||rt===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 kt=cr(q);if(kt!==null){kt.flags&=-257,Ws(kt,q,oe,E,u),kt.mode&1&&aa(E,Ae,u),u=kt,ce=Ae;var Ct=u.updateQueue;if(Ct===null){var Mt=new Set;Mt.add(ce),u.updateQueue=Mt}else Ct.add(ce);break e}else{if((u&1)===0){aa(E,Ae,u),gd();break e}ce=Error(n(426))}}else if(Zn&&oe.mode&1){var Os=cr(q);if(Os!==null){(Os.flags&65536)===0&&(Os.flags|=256),Ws(Os,q,oe,E,u),Of(Va(ce,oe));break e}}E=ce=Va(ce,oe),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 we=Pc(E,ce,u);o_(E,we);break e;case 1:oe=ce;var me=E.type,Se=E.stateNode;if((E.flags&128)===0&&(typeof me.getDerivedStateFromError=="function"||Se!==null&&typeof Se.componentDidCatch=="function"&&(gi===null||!gi.has(Se)))){E.flags|=65536,u&=-u,E.lanes|=u;var lt=v_(E,oe,u);o_(E,lt);break e}}E=E.return}while(E!==null)}_h(f)}catch(It){u=It,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=be(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,pe(_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 oe=Tn;Tn|=4,lh.current=null,E_(a,f),gs(f,a),Gm(Af),rr=!!Fu,Af=Fu=null,a.current=f,R_(f),nn(),Tn=oe,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,cn()),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,St=a.current;St!==null;){var E=St,q=E.child;if((St.flags&16)!==0){var oe=E.deletions;if(oe!==null){for(var ce=0;ce<oe.length;ce++){var Ae=oe[ce];for(St=Ae;St!==null;){var Ze=St;switch(Ze.tag){case 0:case 11:case 15:lo(8,Ze,E)}var rt=Ze.child;if(rt!==null)rt.return=Ze,St=rt;else for(;St!==null;){Ze=St;var Je=Ze.sibling,kt=Ze.return;if(A_(Ze),Ze===Ae){St=null;break}if(Je!==null){Je.return=kt,St=Je;break}St=kt}}}var Ct=E.alternate;if(Ct!==null){var Mt=Ct.child;if(Mt!==null){Ct.child=null;do{var Os=Mt.sibling;Mt.sibling=null,Mt=Os}while(Mt!==null)}}St=E}}if((E.subtreeFlags&2064)!==0&&q!==null)q.return=E,St=q;else e:for(;St!==null;){if(E=St,(E.flags&2048)!==0)switch(E.tag){case 0:case 11:case 15:lo(9,E,E.return)}var we=E.sibling;if(we!==null){we.return=E.return,St=we;break e}St=E.return}}var me=a.current;for(St=me;St!==null;){q=St;var Se=q.child;if((q.subtreeFlags&2064)!==0&&Se!==null)Se.return=q,St=Se;else e:for(q=me;St!==null;){if(oe=St,(oe.flags&2048)!==0)try{switch(oe.tag){case 0:case 11:case 15:Bc(9,oe)}}catch(It){Q(oe,oe.return,It)}if(oe===q){St=null;break e}var lt=oe.sibling;if(lt!==null){lt.return=oe.return,St=lt;break e}St=oe.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 Q(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 Z(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>cn()-Vc?_a(a,0):fo|=f),Dr(a,u)}function ee(a,u){u===0&&((a.mode&1)===0?u=1:(u=pr,pr<<=1,(pr&130023424)===0&&(pr=4194304)));var f=$r();a=un(a,u),a!==null&&(Ss(a,u,f),Dr(a,f))}function ae(a){var u=a.memoizedState,f=0;u!==null&&(f=u.retryLane),ee(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),ee(a,f)}var be;be=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 oe=E.dependencies;if(oe!==null){q=E.child;for(var ce=oe.firstContext;ce!==null;){if(ce.context===w){if(E.tag===1){ce=Xr(-1,f&-f),ce.tag=2;var Ae=E.updateQueue;if(Ae!==null){Ae=Ae.shared;var Ze=Ae.pending;Ze===null?ce.next=ce:(ce.next=Ze.next,Ze.next=ce),Ae.pending=ce}}E.lanes|=f,ce=E.alternate,ce!==null&&(ce.lanes|=f),Ju(E.return,f,u),oe.lanes|=f;break}ce=ce.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,oe=q.alternate,oe!==null&&(oe.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 pe(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 it(a){return a=a.prototype,!(!a||!a.isReactComponent)}function gt(a){if(typeof a=="function")return it(a)?1:0;if(a!=null){if(a=a.$$typeof,a===V)return 11;if(a===O)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")it(a)&&(q=1);else if(typeof a=="string")q=5;else e:switch(a){case R:return qt(f.children,j,E,u);case I:q=8,j|=8;break;case W:return a=Pe(12,f,u,j|2),a.elementType=W,a.lanes=E,a;case M:return a=Pe(13,f,u,j),a.elementType=M,a.lanes=E,a;case A:return a=Pe(19,f,u,j),a.elementType=A,a.lanes=E,a;case J:return ht(f,j,E,u);default:if(typeof a=="object"&&a!==null)switch(a.$$typeof){case G:q=10;break e;case K:q=9;break e;case V:q=11;break e;case O: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 ht(a,u,f,w){return a=Pe(22,a,w,u),a.elementType=J,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,oe,ce){return a=new ds(a,u,f,oe,ce),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:P,key:w==null?null:""+w,children:a,containerInfo:u,implementation:f}}function vi(a){if(!a)return ci;a=a._reactInternals;e:{if(sn(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,oe,ce){return a=dr(f,w,!0,a,j,E,q,oe,ce),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),rn(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 nE(){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 sE(a,u,f,w,j){if(j){if(typeof w=="function"){var E=w;w=function(){var Ae=U_(q);E.call(Ae)}}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 oe=w;w=function(){var Ae=U_(ce);oe.call(Ae)}}var ce=dr(a,0,!1,null,null,!1,!1,"",nb);return a._reactRootContainer=ce,a[Ti]=ce.current,Ei(a.nodeType===8?a.parentNode:a),ma(function(){B_(u,ce,f,w)}),ce}function V_(a,u,f,w,j){var E=f._reactRootContainer;if(E){var q=E;if(typeof j=="function"){var oe=j;j=function(){var ce=U_(q);oe.call(ce)}}B_(u,q,a,j)}else q=sE(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,cn()),(Tn&6)===0&&(da=cn()+500,Qi()))}break;case 13:ma(function(){var w=un(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=un(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=un(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(ft(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),ft(w,j)}}}break;case"textarea":ge(a,f);break;case"select":u=f.value,u!=null&&Re(a,!!f.multiple,u,!1)}},fe=_d,$e=ma;var rE={usingClientEntryPoint:!1,Events:[sa,$l,Mo,wt,ie,_d]},ph={findFiberByHostInstance:Fa,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},iE={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||nE,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(iE),nr=H_}catch{}}return xi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=rE,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=mE(),my.exports}var db;function _E(){if(db)return G_;db=1;var e=Kj();return G_.createRoot=e.createRoot,G_.hydrateRoot=e.hydrateRoot,G_}var pE=_E();const gE=Yv(pE),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 yE(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(yE(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 wE(e){const t=String(e).trim();return Lw.find(n=>n.id===t)||Lw[1]}function vE(e){const t=String(e).trim();return Iw.find(n=>n.id===t)||Iw[1]}function hb(e){try{const t=document.documentElement,n=wE(e.font_scale||"md"),r=vE(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 xE(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(()=>xE(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 bE(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 kE(){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}=bE(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 P=p.useRef(null),R=p.useRef(null),I=p.useRef(null),W=p.useRef(v),G=p.useId(),K=x||`af-select-${G.replace(/[^a-zA-Z0-9_-]/g,"")}`,V=`${K}-listbox`,[M,A]=p.useState(!1),[O,L]=p.useState(""),[J,H]=p.useState(0),[z,te]=p.useState("bottom"),[B,ne]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{W.current=v},[v]);const se=p.useMemo(()=>{if(!k)return t;const Ne=String(e??"").trim();return!Ne||t.some(Re=>Re.value===Ne)?t:[...t,{value:Ne,label:Ne}]},[k,t,e]),ue=p.useMemo(()=>{const Ne=String(e??"");return se.find(Re=>Re.value===Ne)||null},[se,e]),ve=p.useMemo(()=>(ue==null?void 0:ue.label)||String(e||"").trim()||"",[ue,e]),Te=p.useMemo(()=>{const Ne=O.trim().toLowerCase();return Ne?se.filter(Re=>Re.label.toLowerCase().includes(Ne)||Re.value.toLowerCase().includes(Ne)):se},[se,O]),ke=p.useMemo(()=>{if(!l)return null;const Ne=O.trim();if(!Ne||se.some(re=>re.value===Ne))return null;const tt=($==null?void 0:$(Ne,{options:se}))||"";return{value:Ne,label:N?N(Ne):`Use "${Ne}"`,disabled:!!tt,reason:tt}},[l,N,se,O,$]),le=p.useMemo(()=>{const Ne=ke?[ke,...Te]:Te;if(Ne.length>0)return Ne;const Re=String(e??"").trim();return i&&Re?[{value:Re,label:ve||Re}]:Ne},[ke,Te,i,ve,e]),xe=p.useCallback(()=>{const Ne=P.current;if(!Ne)return;const Re=Ne.getBoundingClientRect(),tt=Math.max(Re.width,h),re=Math.max(8,Math.min(Re.left,window.innerWidth-tt-8)),ge=window.innerHeight-Re.bottom,de=Re.top,je=ge>=220||ge>=de?"bottom":"top";te(je);const X=je==="bottom"?Re.bottom+6:Re.top-6;ne({left:re,top:X,width:tt})},[h]),Ee=p.useCallback(()=>{A(!1),L("")},[]);p.useEffect(()=>{var Ne;M&&((Ne=W.current)==null||Ne.call(W))},[M]),p.useEffect(()=>{if(!M)return;xe();const Ne=()=>xe();return window.addEventListener("resize",Ne),window.addEventListener("scroll",Ne,!0),()=>{window.removeEventListener("resize",Ne),window.removeEventListener("scroll",Ne,!0)}},[M,xe]),p.useEffect(()=>{if(!M)return;const Ne=Re=>{var re,ge;const tt=Re.target;tt&&((re=P.current)!=null&&re.contains(tt)||(ge=R.current)!=null&&ge.contains(tt)||Ee())};return document.addEventListener("mousedown",Ne,!0),()=>document.removeEventListener("mousedown",Ne,!0)},[M,Ee]),p.useEffect(()=>{if(!M)return;const Ne=Math.max(0,le.findIndex(Re=>Re.value===e));H(Ne===-1?0:Ne),o&&setTimeout(()=>{var Re;return(Re=I.current)==null?void 0:Re.focus()},0)},[M,o,e,le]);const Ve=Ne=>{var tt;const Re=le.find(re=>re.value===Ne);Re!=null&&Re.disabled||(C(Ne),Ee(),(tt=P.current)==null||tt.focus())},_t=Ne=>{var Re,tt;if(Ne.key==="Escape")return Ne.preventDefault(),Ee(),(Re=P.current)==null||Re.focus(),!0;if(Ne.key==="Tab")return Ee(),(tt=P.current)==null||tt.focus(),!1;if(Ne.key==="ArrowDown")return Ne.preventDefault(),H(re=>Math.min(re+1,Math.max(0,le.length-1))),!0;if(Ne.key==="ArrowUp")return Ne.preventDefault(),H(re=>Math.max(re-1,0)),!0;if(Ne.key==="Home")return Ne.preventDefault(),H(0),!0;if(Ne.key==="End")return Ne.preventDefault(),H(Math.max(0,le.length-1)),!0;if(Ne.key==="Enter"){Ne.preventDefault();const re=le[J];return re&&Ve(re.value),!0}return!1},Qe=Ne=>{if(!r){if(M){if(_t(Ne))return;if(Ne.key===" "&&!o){Ne.preventDefault();const Re=le[J];Re&&Ve(Re.value)}return}(Ne.key==="Enter"||Ne.key===" "||Ne.key==="ArrowDown"||Ne.key==="ArrowUp")&&(Ne.preventDefault(),A(!0))}},ot=!!String(e||"").trim(),ze=ot?ve:n,He=ke!=null&&ke.disabled?ke.reason||"Unavailable":"",ft=M&&le.length>0?`${K}-opt-${J}`:void 0,et=s.jsx("span",{className:yd("af-select-value",!ot&&"af-select-value--placeholder"),children:i&&!ot?"Loading…":ze}),Ot=D?D(ue,String(e||"")):et;return s.jsxs("span",{className:yd("af-select",m==="pin"?"af-select--pin":"af-select--panel",_),children:[s.jsxs("button",{ref:P,id:K,type:"button",className:yd("af-select-trigger",d&&ot&&"af-select-trigger--clearable",g),disabled:r,onMouseDown:Ne=>Ne.stopPropagation(),onClick:Ne=>{Ne.stopPropagation(),!r&&A(Re=>!Re)},onKeyDown:Qe,role:o?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":M,"aria-controls":M?V:void 0,"aria-activedescendant":o?void 0:ft,"aria-label":y,children:[Ot,s.jsx("span",{className:yd("af-select-caret",M&&"af-select-caret--open"),children:"▾"})]}),d&&ot?s.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:Ne=>{Ne.preventDefault(),Ne.stopPropagation()},onClick:Ne=>{var Re;Ne.preventDefault(),Ne.stopPropagation(),C(""),Ee(),(Re=P.current)==null||Re.focus()},title:"Clear",children:"×"}):null,M?jg.createPortal(s.jsxs("div",{ref:R,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:Ne=>Ne.stopPropagation(),onClick:Ne=>Ne.stopPropagation(),onWheel:Ne=>Ne.stopPropagation(),onKeyDown:_t,tabIndex:-1,children:[o?s.jsxs("div",{className:"af-select-search",children:[s.jsx("input",{ref:I,className:"af-select-search-input",value:O,onChange:Ne=>L(Ne.target.value),placeholder:c,onKeyDown:_t,role:"combobox","aria-expanded":!0,"aria-controls":V,"aria-activedescendant":ft,"aria-invalid":!!He,"aria-describedby":He?`${K}-custom-error`:void 0}),He?s.jsx("div",{id:`${K}-custom-error`,className:"af-select-custom-error",role:"alert",children:He}):null]}):null,s.jsx("div",{className:"af-select-options",role:"listbox",id:V,"aria-label":y,children:i&&le.length===0?s.jsx("div",{className:"af-select-empty",children:"Loading…"}):le.length===0?s.jsx("div",{className:"af-select-empty",children:"No results"}):le.map((Ne,Re)=>{var X;const tt=Ne.value===e,re=Re===J,ge=String(Ne.group||"").trim(),de=Re>0?String(((X=le[Re-1])==null?void 0:X.group)||"").trim():"",je=!!ge&&ge!==de;return s.jsxs(Ce.Fragment,{children:[je?s.jsx("div",{className:"af-select-group",role:"presentation",children:ge}):null,s.jsx("div",{id:`${K}-opt-${Re}`,role:"option","aria-selected":tt,className:yd("af-select-option",tt&&"af-select-option--selected",re&&"af-select-option--highlighted",Ne.disabled&&"af-select-option--disabled"),title:Ne.disabled?Ne.reason||"Unavailable":void 0,onMouseEnter:()=>H(Re),onMouseDown:Oe=>{Oe.preventDefault(),Oe.stopPropagation()},onClick:()=>Ve(Ne.value),"aria-disabled":Ne.disabled?!0:void 0,children:S?S(Ne,{selected:tt,highlighted:re}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"af-select-option-label",children:[s.jsx("span",{children:Ne.label}),Ne.reason?s.jsx("small",{className:"af-select-option-reason",children:Ne.reason}):null]}),tt?s.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},Ne.value)})})]}),document.body):null]})}function jE(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 SE(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(),_=jE(e.providers),g=SE(e.models),y=typeof e.markSaved=="object"?e.markSaved:null,x=(S,D,P,R)=>e.markSaved&&!P&&!R&&(!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 NE(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 $E(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=NE(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function CE(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 EE(e){const t=$E(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(CE(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 vt(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 AE(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 TE(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 ME(e,t="Gateway default"){const n=TE(e);return n?`${t} · ${n}`:t}const RE="The gateway does not say which reasoning levels this model supports.",LE="Set anyway",IE="Reasoning and MTP choices appear when the gateway can describe the selected model.",OE="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({}),[P,R]=p.useState(!1),[I,W]=p.useState(""),G=p.useRef(e);G.current=e;const[K,V]=p.useState({status:"idle",value:null,message:""}),M=e.fetchGatewayDefault;p.useEffect(()=>{if(!M||t)return;let Re=!0;const tt=re=>V(ge=>JSON.stringify(ge)===JSON.stringify(re)?ge:re);return V(re=>re.status==="idle"?{...re,status:"loading"}:re),M().then(re=>{var ge;Re&&(re?(ge=re.warnings)!=null&&ge.length?tt({status:"unusable",value:re,message:re.warnings.join(" ")}):tt({status:"resolved",value:re,message:""}):tt({status:"none",value:null,message:""}))}).catch(re=>{Re&&tt({status:"error",value:null,message:String((re==null?void 0:re.message)||re)})}),()=>{Re=!1}},[M,t]);const A=K.status==="resolved"?K.value:null,O=p.useRef({provider:String(n.provider||"").trim(),model:String(n.model||"").trim()});p.useEffect(()=>{if(!h||o.provider||t)return;let Re=!0;return k(!0),(async()=>{try{const tt=await G.current.fetchProviders();if(!Re)return;y(Array.isArray(tt)?tt:[]),N("")}catch(tt){if(!Re)return;y([]),N(`#FALLBACK provider discovery failed: ${String((tt==null?void 0:tt.message)||tt)}`)}finally{Re&&k(!1)}})(),()=>{Re=!1}},[h,o.provider,t]);const L=String(n.provider||"").trim();p.useEffect(()=>{if(!L||t||o.model){C([]),W(""),R(!1);return}let Re=!0;return C([]),R(!0),W(""),(async()=>{try{const tt=await G.current.fetchModels(L);if(!Re)return;const re=[],ge={};for(const de of Array.isArray(tt)?tt:[]){const je=typeof de=="string"?de:String((de==null?void 0:de.id)||"");je&&(re.push(je),typeof de!="string"&&(de!=null&&de.label)&&de.label!==je&&(ge[je]=String(de.label)))}C(re),D(ge)}catch(tt){if(!Re)return;C([]),W(`#FALLBACK model discovery failed: ${String((tt==null?void 0:tt.message)||tt)}`)}finally{Re&&R(!1)}})(),()=>{Re=!1}},[L,t,o.model]);const J=String(n.model||"").trim(),H=e.defaultModeLabel||"Gateway default",z=K.status==="none"?`${H} · none configured`:ME(A,H),te=e.customModeLabel||"Custom",B=e.effectiveDefault||(K.value?{provider:K.value.provider,model:K.value.model}:void 0),ne=L||(B==null?void 0:B.provider)||"",se=J||(L?"":B==null?void 0:B.model)||"",[ue,ve]=p.useState({levels:[],error:"",loading:!1}),[Te,ke]=p.useState(!1),le=!!e.fetchModelCapabilities,[xe,Ee]=p.useState();p.useEffect(()=>{let Re=!0;if(Ee(void 0),ve({levels:[],error:"",loading:le&&!!se}),!(!le||!se||t))return G.current.fetchModelCapabilities(se,ne).then(tt=>{var X;if(!Re)return;if(tt!=null&&tt.error)throw new Error(String(tt.error));Ee(tt);const re=(tt==null?void 0:tt.capabilities)||tt||{},ge=re.reasoning_levels||re.thinking_levels,de=Array.isArray(ge)?[...new Set(ge.filter(Oe=>typeof Oe=="string"&&!!Oe.trim()))]:[];!de.length&&re.thinking_support===!0&&((X=re.thinking_control)!=null&&X.prompt_disable_token)&&de.push("off","auto");const je=typeof re.thinking_support=="boolean"?re.thinking_support:void 0;ve({levels:de,support:je,error:"",loading:!1})}).catch(tt=>{Re&&ve({levels:[],error:String((tt==null?void 0:tt.message)||tt),loading:!1})}),()=>{Re=!1}},[ne,se,le,t]),p.useEffect(()=>ke(!1),[ne,se]);const Ve=e.inheritLabel||"Workflow / Gateway default",_t=m&&(A!=null&&A.reasoning)?`${Ve} (${A.reasoning})`:Ve,Qe=!m||e.optionsInDefaultMode!==!1,ot=e.reasoningLadder?[...new Set(e.reasoningLadder.filter(Re=>typeof Re=="string"&&Re.trim()))]:null,ze=ue.loading?"loading":ue.levels.length||ue.support===!0?"supported":ue.support===!1?"unsupported":"unknown",He=e.unknownReasoning==="allow-override"&&!!(ot!=null&&ot.length),ft=String(n.reasoning||"").trim();let et=[],Ot=!1;if(!ot)et=ue.levels.map(Re=>({value:Re,label:Re}));else if(ze==="supported"||ze==="loading"){const Re=ue.levels;et=[...ot,...Re.filter(re=>!ot.includes(re))].map(re=>!Re.length||Re.includes(re)?{value:re,label:re}:{value:re,label:re,disabled:!0,reason:"This model does not advertise it"})}else ze==="unknown"&&He&&(Ot=!Te,et=ot.map(Re=>({value:Re,label:Re})));ft&&!et.some(Re=>Re.value===ft)&&et.push({value:ft,label:`${ft} (saved)`});const Ne=(le||He)&&(et.length>0||ze==="unknown"&&He);return s.jsxs("div",{className:`af-pmp${i?" af-pmp--compact":""}${e.className?` ${e.className}`:""}`,"data-gateway-default":M?K.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:"",...le?{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:te})]}),K.status==="error"||K.status==="unusable"?s.jsx("div",{role:"status",className:"af-pmp__hint","data-gateway-default-problem":K.status,children:K.status==="error"?`The gateway's default could not be read: ${K.message}`:`Gateway warning: ${K.message}`}):null,h?s.jsx(Yj,{provider:L,model:J,providers:g,models:$,modelDisplayNames:S,markSaved:O.current,providerPinned:o.provider,modelPinned:o.model,disabled:t,loadingProviders:x,loadingModels:P,providerError:v||void 0,modelError:I||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:i,gatewayDefaultLabel:i?z:void 0,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:Re=>e.onChange({...n,provider:Re.provider,model:Re.model,...le?{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&&Ne?s.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":ze,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||ue.loading||Ot,onChange:Re=>e.onChange({...n,reasoning:Re})}),ze==="unknown"&&He?s.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[RE," ",s.jsxs("label",{className:"af-pmp__override",children:[s.jsx("input",{type:"checkbox",checked:Te,disabled:t,onChange:Re=>{ke(Re.target.checked),!Re.target.checked&&n.reasoning&&e.onChange({...n,reasoning:""})}})," ",LE]})]}):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(EE,{value:n.speculation,inheritLabel:Ve,onChange:Re=>e.onChange({...n,speculation:Re}),capabilities:xe,disabled:t,loading:ue.loading,hideNote:!!ue.error}):null,Qe&&ue.error?s.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?IE:OE,s.jsxs("details",{className:"af-pmp__details",children:[s.jsx("summary",{children:"Technical details"}),s.jsx("span",{children:ue.error})]})]}):null]})}function pb(...e){return e.filter(Boolean).join(" ")}function PE({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:P=!1,submitLabel:R="Sign in",submittingLabel:I="Signing in...",closeLabel:W="Close",signOutLabel:G="Sign out",showClose:K=!1,showSignOut:V=!1,error:M,message:A,className:O,onSubmit:L,onClose:J,onSignOut:H}){const z=S||D,te=z||P||!String(h||"").trim()||!String(g||"").trim(),B=ne=>{ne.preventDefault(),!te&&L()};return s.jsxs("form",{className:pb("af-gateway-signin",O),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:ne=>d==null?void 0:d(ne.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:ne=>_(ne.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:ne=>k(ne.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:ne=>C==null?void 0:C(ne.target.checked),disabled:z}),$]})]}),M?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:M}):null,!M&&A?s.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:A}):null,s.jsxs("div",{className:"af-gateway-signin__actions",children:[K?s.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:J,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:G}):null,s.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:te,children:D?I:R})]})]})}function DE(e){return e==="light"?"Light":"Dark"}function FE(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:DE(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 zE(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 BE(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 UE=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function WE(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=UE.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,WE(e)]})}function qE(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function VE(e){return qE(e)?!e.checked:null}let HE=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-${++HE}`: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=VE({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 GE(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 KE=150,Zv="data-af-tip";function JE(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 YE(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:KE;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 O=l.getBoundingClientRect(),L=o.getBoundingClientRect(),J=JE(O,{width:L.width,height:L.height},{width:r.innerWidth,height:r.innerHeight});o.style.top=`${J.top}px`,o.style.left=`${J.left}px`,o.setAttribute("data-side",J.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=O=>{y(),x(),l&&l!==O&&v();const L=Zj(O);if(!L||O.isConnected===!1)return;if(l=O,o.textContent=L,o.hidden=!1,String(O.getAttribute("aria-label")||"").trim()!==L){const H=O.getAttribute("aria-describedby");g=H&&H!==c?H:null,O.setAttribute("aria-describedby",g?`${g} ${c}`:c)}k()},$=O=>{x(),l!==O&&d!==O&&(y(),d=O,h=setTimeout(()=>{const L=d;h=null,d=null,L&&N(L)},i))},C=()=>{y(),l&&(x(),m=setTimeout(v,100))},S=O=>{try{if(typeof O.matches=="function")return O.matches(":focus-visible")}catch{}return _},D=O=>{if(O.pointerType==="touch")return;if(o.contains(O.target)){x();return}const J=yy(O.target,e);J&&$(J)},P=O=>{const J=O.relatedTarget||null;if(!(J&&(o.contains(J)||l&&l.contains(J)||d&&d.contains(J)))){if(d&&!l){y();return}l&&C()}},R=O=>{const L=O.relatedTarget||null;L&&(o.contains(L)||l&&l.contains(L))||C()},I=O=>{const L=yy(O.target,e);L&&S(L)&&$(L)},W=O=>{const L=yy(O.target,e);L&&(L===l||L===d)&&v()},G=()=>{_=!1,v()},K=O=>{if(O.key==="Escape"||O.key==="Esc"){l?(O.preventDefault(),v()):y();return}!O.metaKey&&!O.ctrlKey&&!O.altKey&&(_=!0)},V=()=>v(),M=e;M.addEventListener("pointerover",D),M.addEventListener("pointerout",P),M.addEventListener("focusin",I),M.addEventListener("focusout",W),o.addEventListener("pointerover",D),o.addEventListener("pointerout",R),n.addEventListener("pointerdown",G,!0),r.addEventListener("keydown",K,!0),r.addEventListener("scroll",V,!0),r.addEventListener("resize",V);let A=!1;return()=>{A||(A=!0,v(),M.removeEventListener("pointerover",D),M.removeEventListener("pointerout",P),M.removeEventListener("focusin",I),M.removeEventListener("focusout",W),o.removeEventListener("pointerover",D),o.removeEventListener("pointerout",R),n.removeEventListener("pointerdown",G,!0),r.removeEventListener("keydown",K,!0),r.removeEventListener("scroll",V,!0),r.removeEventListener("resize",V),o.parentNode&&o.parentNode.removeChild(o))}}const K_=new WeakMap;function XE(e){let t=K_.get(e);t||(t={count:0,release:YE(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 XE(document)},[])}function yb(e){rf();const t=Ce.Children.only(e.children),n=String(e.content||"").trim();return n?Ce.cloneElement(t,{[Zv]:n}):t}function Qj(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function ZE(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(A=>{var L;$.current+=1,d(A),(L=i.current)==null||L.call(i,A);const O=Qj(A);if(O)m("connected"),k.current="connected",y.current=!1,v.current="none",x.current||g(!1);else if(A!==null){const J=k.current;m("disconnected"),k.current="disconnected",J!=="disconnected"&&(v.current=N.current?"signout":J==="connected"?"mid":"boot");const H=o.current==="blocking"||v.current!=="mid"||c.current;!y.current&&H&&g(!0)}A!==null&&(x.current=O)},[]),S=p.useCallback(async()=>{const A=$.current;try{const O=await Pw(n);if($.current!==A)return;C(O)}catch{if($.current!==A)return;C(null)}},[n,C]),[D,P]=p.useState(!1),[R,I]=p.useState(null),W=p.useCallback(async()=>{P(!0),I(null),$.current+=1;let A=null;try{await tS(n)}catch(O){A=String((O==null?void 0:O.message)||O||"Sign-out request failed")}N.current=!0;try{await S()}finally{N.current=!1}return I(A),P(!1),A===null&&k.current!=="connected"},[n,S]),G=p.useRef(!1);p.useEffect(()=>{G.current||(G.current=!0,S())},[S]);const K=p.useCallback(()=>{g(!0)},[]),V=p.useCallback(()=>{const A=k.current;r==="blocking"&&A==="disconnected"||(A==="disconnected"&&(y.current=!0),g(!1))},[r]),M=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:R,openModal:K,refresh:S,signOut:W,modalProps:M}}const QE="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 e2(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!==QE?`${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 t2(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 n2(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(""),[P,R]=p.useState(""),I=p.useMemo(()=>nS(c),[c]),W=M=>{var A;l(M),(A=e.onStatusChange)==null||A.call(e,M)},G=p.useRef(!1);if(p.useEffect(()=>{var A;if(!e.isOpen)return;const M=!G.current;if(G.current=!0,M&&e.initialStatus!==void 0&&e.initialStatus!==null){const O=e.initialStatus;W(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&_(wy(O.gateway_url));const L=(A=O.gateway)==null?void 0:A.principal;L!=null&&L.user_id&&y(L.user_id);return}r(!0),D(""),Pw(t).then(O=>{var J;W(O),typeof O.gateway_url=="string"&&O.gateway_url.trim()&&_(wy(O.gateway_url));const L=(J=O.gateway)==null?void 0:J.principal;L!=null&&L.user_id&&y(L.user_id)}).catch(O=>D(`Failed to load connection status: ${String((O==null?void 0:O.message)||O)}`)).finally(()=>r(!1))},[e.isOpen]),p.useEffect(()=>{if(!e.isOpen)return;const M=A=>{A.key==="Escape"&&!A.defaultPrevented&&!e.blocking&&(A.preventDefault(),e.onClose())};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||d)return null;const K=async()=>{o(!0),D(""),R("");try{const M=wy(m);_(M);const A=await t2({gateway_url:M,gateway_user_id:g,gateway_token:x,persist:$},t);W(A),k(""),h(!0),e.onClose()}catch(M){D(String((M==null?void 0:M.message)||M))}finally{o(!1)}},V=async()=>{o(!0),D(""),R("");try{await tS(t),k("");const M=await Pw(t).catch(()=>null);W(M),R("Signed out. This browser no longer holds a gateway session.")}catch(M){D(String((M==null?void 0:M.message)||M))}finally{o(!1)}};return s.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:M=>{!e.blocking&&M.target===M.currentTarget&&e.onClose()},children:s.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:s.jsx(PE,{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:I.label,statusTone:I.tone,showGatewayUrl:!0,gatewayUrl:m,onGatewayUrlChange:M=>_(M),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:P,onSubmit:K})})})}function s2(){return globalThis.crypto}function r2(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=s2();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return r2(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 i2(){return nl()}function o2(){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 a2(e){const t=e.commandsPath||vt("commands"),n=i2(),r=JSON.stringify({command_id:n,run_id:e.runId,type:"inject_guidance",payload:{guidance:e.guidance}}),i=e.csrfToken!==void 0?[e.csrfToken]:o2();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 l2(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 a2({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)"},c2=/^var\(--[a-z0-9-]+\)$/i;function u2(e,t){const n=e||"neutral";if(n==="custom"){const r=String(t||"").trim();return c2.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":u2(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 d2(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 f2='button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function h2(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(f2)||e)}function m2(){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 _2(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 _;(_=h2(c,m2()))==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 p2(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 g2(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=p2(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 P=r.activeElement,R=!P||P===r.body||t.contains(P);m(R)};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 y2(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 g2(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 w2={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"},v2={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"}},x2={framework:w2,apps:v2},Vp=x2;function iS(){return{...Vp.framework}}function b2(){return Object.keys(Vp.apps).sort()}function k2(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: ${b2().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 j2(e,t){try{const n=await e(vt("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 S2={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 N2(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 $2(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 C2='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function E2(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(C2));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 A2(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:$2(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:N2(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 T2(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}E2(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(A2,{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 M2(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 R2(e){return`af_appearance_${e}_v1`}function L2(e,t){const n=R2(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=M2({...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(FE,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),s.jsx("label",{className:"af-appearance__label",children:"Font size"}),s.jsx(zE,{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(BE,{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 I2(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 O2(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function P2(e,t){return O2(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 D2(e,t){const n=Qv(t);return`Signed in as ${eS(e)}${n?` · gateway ${n}`:""}`}const xy="--af-topbar-h";function F2(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 z2(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function B2(e){var S,D;const t=P2(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(),F2(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 P=k.current;if(!i||!P)return;const R=typeof AbortController<"u"?new AbortController:null;let I=!0;return h(S2),j2(P,R==null?void 0:R.signal).then(W=>{I&&h(W)}),()=>{I=!1,R==null||R.abort()}},[i]);const v=I2(n,r),N=e.identity&&n==="connected"?e2(t.status):null,$=()=>void t.disconnect();let C=null;if(N&&e.identity){const P=eS(N),R=D2(N,(S=t.status)==null?void 0:S.gateway_url),I=s.jsxs(s.Fragment,{children:[s.jsx(qe,{name:"user",size:14}),s.jsx("span",{className:"af-topbar__identity-label",children:P})]});if(e.identity==="badge")C=s.jsx("span",{className:"af-topbar__identity af-topbar__identity--badge","data-af-identity":"badge","data-af-tip":R,"aria-label":R,children:I});else{const W=z2(N.userId),G=Qv((D=t.status)==null?void 0:D.gateway_url);C=s.jsx(y2,{label:`Account: ${R}`,tip:R,className:"af-topbar__account",buttonClassName:"af-topbar__identity af-topbar__identity--menu",buttonContent:I,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 ",P]}),G?s.jsxs("span",{className:"af-topbar__account-host",children:["Gateway ",G]}):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 P;o(!0),(P=_.onOpen)==null||P.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(T2,{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 U2(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 W2(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 q2(){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 V2(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*H2(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 G2=350;function K2(){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 J2(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function Y2(){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 X2(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 Z2(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 Q2(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 eA(e){const t=p.useRef(e);t.current=e;const n=de=>{var je,X;return(X=(je=t.current).on_error)==null?void 0:X.call(je,de)},r=p.useMemo(()=>J2()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),i=p.useMemo(()=>K2()&&typeof e.transcribe=="function",[e.transcribe]),[o,c]=p.useState({key:"",status:"idle"}),l=p.useRef(o),d=p.useCallback(de=>{l.current=de,c(je=>je.key===de.key&&je.status===de.status?je:de)},[]),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),P=p.useRef(!1),R=()=>{try{const de=globalThis,je=(de==null?void 0:de.AudioContext)||(de==null?void 0:de.webkitAudioContext);if(!je)return null;if(!_.current){const pt=new je,at=pt.createGain();at.gain.value=1,at.connect(pt.destination),_.current=pt,g.current=at}const X=_.current,Oe=g.current;if(!X||!Oe)return null;Q2(X,t.current.output_device_id||""),Oe.gain.value=Kd(t.current.volume)*(t.current.muted?0:1);try{X.state==="suspended"&&X.resume()}catch{}return{ctx:X,gain:Oe}}catch{return null}};p.useEffect(()=>{const de=g.current;de&&(de.gain.value=Kd(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const I=p.useCallback(()=>{const de=y.current;if(y.current=null,!!de){try{de.onended=null}catch{}try{de.stop()}catch{}try{de.disconnect()}catch{}}},[]),W=p.useCallback(()=>{var de;I(),N.current+=1,(de=$.current)==null||de.abort(),$.current=null,C.current=[],S.current=0,D.current=!0,P.current=!1,m.current="",h.current="",x.current=null,k.current=0,v.current=0,d({key:"",status:"idle"})},[I,d]);p.useEffect(()=>()=>{var de,je;W();try{(de=g.current)==null||de.disconnect()}catch{}try{(je=_.current)==null||je.close()}catch{}_.current=null,g.current=null,x.current=null},[]);const G=async(de,je,X)=>{const Oe=N.current,pt=R();if(!pt)throw new Error("TTS playback is not supported in this browser");const{ctx:at,gain:Et}=pt;try{at.state==="suspended"&&await at.resume()}catch{}if(Oe!==N.current)return;I();const yt=at.createBufferSource();yt.buffer=je,yt.connect(Et);const jt=Number.isFinite(Number(je.duration))?Number(je.duration):0,st=Math.max(0,Math.min(Number(X||0),jt>0?Math.max(0,jt-.01):0));v.current=at.currentTime-st,k.current=st,y.current=yt,h.current=de,yt.onended=()=>{y.current===yt&&(y.current=null,k.current=0,v.current=0,h.current="",d({key:"",status:"idle"}))},yt.start(0,st),d({key:de,status:"playing"})},K=(de,je)=>{if(je!==N.current)return;const X=R();if(!X)return;const Oe=C.current,pt=S.current;if(pt>=Oe.length){D.current&&(h.current="",k.current=0,v.current=0,d({key:"",status:"idle"}));return}const at=Oe[pt],{ctx:Et,gain:yt}=X;I();const jt=Et.createBufferSource();jt.buffer=at,jt.connect(yt);const st=Number.isFinite(Number(at.duration))?Number(at.duration):0,Pt=Math.max(0,Math.min(Number(k.current||0),st>0?Math.max(0,st-.01):0));v.current=Et.currentTime-Pt,y.current=jt,h.current=de,jt.onended=()=>{je===N.current&&y.current===jt&&(y.current=null,S.current=pt+1,k.current=0,K(de,je))};try{Et.state==="suspended"&&Et.resume()}catch{}jt.start(0,Pt),d({key:de,status:"playing"})},V=async(de,je,X)=>{var yt;const Oe=R();if(!Oe){n==null||n("This browser cannot play spoken replies.");return}I();const pt=++N.current;(yt=$.current)==null||yt.abort();const at=new AbortController;$.current=at,C.current=[],S.current=0,D.current=!1,P.current=!1,x.current=null,k.current=0,v.current=0,h.current=de,m.current=de,d({key:de,status:"loading"}),n==null||n("");let Et=null;try{for await(const jt of X(je,at.signal)){if(pt!==N.current)return;let st;try{st=await by(Oe.ctx,jt),Et||(Et=X2(jt))}catch{if(!Et)continue;try{st=await by(Oe.ctx,Z2(Et,jt))}catch{continue}}if(pt!==N.current)return;C.current.push(st),!y.current&&!P.current&&(m.current="",K(de,pt))}if(pt!==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&&!P.current&&K(de,pt)}catch(jt){if(pt!==N.current)return;n==null||n(wh("Reading aloud failed",jt)),W()}finally{$.current===at&&($.current=null)}},M=p.useCallback(async(de,je)=>{var Pt;const X=String(de||"").trim(),Oe=String(je||"").trim();if(!X||!Oe)return;const pt=t.current.tts,at=t.current.tts_stream;if(typeof pt!="function"&&typeof at!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Et=R();if(!Et){n==null||n("This browser cannot play spoken replies.");return}const yt=l.current,jt=yt.key===X;if(jt&&yt.status==="playing"){if(y.current){const Lt=Math.max(0,Et.ctx.currentTime-Number(v.current||0));k.current=Lt}else k.current=0;P.current=!0,I(),d({key:X,status:"paused"});return}if(jt&&yt.status==="paused"){if(C.current.length>0){n==null||n(""),P.current=!1,d({key:X,status:"playing"}),K(X,N.current);return}const Lt=x.current;if(Lt){n==null||n(""),P.current=!1;try{await G(X,Lt,k.current)}catch(mn){n==null||n(wh("Reading aloud failed",mn)),d({key:"",status:"idle"})}return}}if(jt&&yt.status==="loading")return;if(typeof at=="function"){await V(X,Oe,at);return}I(),N.current+=1,(Pt=$.current)==null||Pt.abort(),$.current=null;const st=N.current;C.current=[],S.current=0,D.current=!0,P.current=!1,x.current=null,k.current=0,v.current=0,h.current=X,m.current=X,d({key:X,status:"loading"}),n==null||n("");try{const Lt=await pt(Oe);if(m.current!==X||N.current!==st)return;const mn=await by(Et.ctx,Lt);if(m.current!==X||N.current!==st)return;x.current=mn,k.current=0,await G(X,mn,0)}catch(Lt){if(N.current!==st)return;m.current===X&&(m.current="",h.current="",d({key:"",status:"idle"})),n==null||n(wh("Reading aloud failed",Lt))}},[]),[A,O]=p.useState(!1),[L,J]=p.useState(!1),H=p.useRef(!1),z=p.useRef(i);z.current=i;const te=p.useCallback(de=>{H.current=de,O(je=>je===de?je:de)},[]),B=p.useRef(!1),ne=p.useRef(null),se=p.useRef(null),ue=p.useRef([]),ve=p.useRef(""),Te=p.useRef(0),ke=p.useRef(!1),le=p.useRef(!1),[xe,Ee]=p.useState(0),Ve=p.useRef(0),_t=p.useRef(null),Qe=p.useRef(0),ot=p.useRef(new Set),ze=p.useRef(null),He=p.useCallback(de=>{const je=Math.round(Math.min(1,Math.max(0,Number(de)||0))*20)/20;if(je!==Qe.current){Qe.current=je;for(const X of Array.from(ot.current))X(je)}},[]),ft=p.useCallback(de=>(ot.current.add(de),de(Qe.current),()=>{ot.current.delete(de)}),[]),et=p.useRef(new Set),Ot=p.useCallback(de=>(et.current.add(de),()=>{et.current.delete(de)}),[]);function Ne(){var X,Oe;const de=ze.current;ze.current=null;try{de==null||de()}catch{}He(0);try{(Oe=(X=ne.current)==null?void 0:X.getTracks)==null||Oe.call(X).forEach(pt=>{try{pt.stop()}catch{}})}catch{}ne.current=null;const je=_t.current;_t.current=null;try{je==null||je.close()}catch{}}const Re=p.useCallback(()=>{Te.current+=1,ke.current=!1;const de=se.current;if(de){de.onstop=null,de.ondataavailable=null,de.onerror=null;try{de.stop()}catch{}}se.current=null,Ne(),te(!1),B.current=!1,J(!1),Ee(0),ue.current=[]},[te]);p.useEffect(()=>()=>Re(),[Re]);async function tt(de,je){var at,Et;if(n==null||n(""),B.current)return;const X=Ve.current?Date.now()-Ve.current:1/0;if(!de||!de.size||X<G2){Ee(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 Oe=t.current.transcribe;if(typeof Oe!="function"){n==null||n("Speech to text is not available on this gateway.");return}B.current=!0;const pt=Te.current;J(!0),Ee(Date.now());try{const yt=await Oe(de,je),jt=typeof yt=="string"||!yt?{text:String(yt||"")}:yt,st=String(jt.text||"").trim();if(pt!==Te.current)return;if(st){(Et=(at=t.current).on_transcript)==null||Et.call(at,st,{...jt,text:st});for(const Pt of Array.from(et.current))Pt(st,{...jt,text:st})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(yt){if(pt===Te.current){const jt=String((yt==null?void 0:yt.message)||yt||"").trim().replace(/\.$/,"");n==null||n(jt?`Transcription failed: ${jt}.`:"Transcription failed.")}}finally{pt===Te.current&&(B.current=!1,J(!1),Ee(0))}}const re=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||ke.current||H.current||se.current)return;ue.current=[];const de=Te.current;ke.current=!0,le.current=!1;try{const je=await cS(t.current.input_device_id||"");if(de!==Te.current){je.getTracks().forEach(yt=>yt.stop());return}if(le.current){le.current=!1,je.getTracks().forEach(yt=>yt.stop()),Ee(0);return}ne.current=je;const X=Number(t.current.input_gain??1);try{ze.current=dS(je,He,Number.isFinite(X)&&X>0?X:1)}catch{}const Oe=Y2();ve.current=Oe;let pt=je;const at=Number(t.current.input_gain??1);if(Number.isFinite(at)&&at>0&&at!==1&&uS()){const yt=globalThis.AudioContext||globalThis.webkitAudioContext,jt=new yt,st=jt.createGain();st.gain.value=at;const Pt=jt.createMediaStreamDestination();jt.createMediaStreamSource(je).connect(st),st.connect(Pt),_t.current=jt,pt=Pt.stream}const Et=Oe?new MediaRecorder(pt,{mimeType:Oe}):new MediaRecorder(pt);se.current=Et,Et.ondataavailable=yt=>{if(de===Te.current)try{yt!=null&&yt.data&&ue.current.push(yt.data)}catch{}},Et.onerror=()=>{de===Te.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Et.onstop=()=>{if(de===Te.current){te(!1),Ne(),se.current=null;try{const yt=new Blob(ue.current,{type:ve.current||""});tt(yt,ve.current)}catch(yt){n==null||n(wh("The recording could not be prepared",yt))}}},Et.start(),Ve.current=Date.now(),Ee(Ve.current),te(!0)}catch(je){if(de!==Te.current)return;Ne(),se.current=null,te(!1),Ee(0),n==null||n(Hp(je))}finally{de===Te.current&&(ke.current=!1)}},[]),ge=p.useCallback(()=>{const de=se.current;if(ke.current&&!de){le.current=!0;return}if(!(!H.current||!de)){te(!1);try{de.stop()}catch(je){n==null||n(wh("The recording could not stop",je))}}},[]);return p.useEffect(()=>{if(!A||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&Fw(t.current.capture_mode)==="toggle")return;const de=()=>ge();return window.addEventListener("pointerup",de),window.addEventListener("pointercancel",de),()=>{window.removeEventListener("pointerup",de),window.removeEventListener("pointercancel",de)}},[A]),{tts_supported:r,tts_playback:o,toggle_tts:M,stop_tts:W,voice_ptt_supported:i,voice_ptt_recording:A,voice_ptt_busy:L,start_voice_ptt_recording:re,stop_voice_ptt_recording:ge,cancel_voice_ptt_recording:Re,voice_ptt_since:xe,subscribe_level:ft,voice_capture_mode:Fw(e.capture_mode),add_transcript_listener:Ot}}const tA={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&&tA[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 nA(e){return Array.from(new Set(e.map(Cg).filter(Boolean))).sort()}function sA(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):[],rA=200;function iA({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 tt,re,ge,de,je;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),P=p.useRef(n);P.current=n;const[R,I]=p.useState({}),[W,G]=p.useState(""),[K,V]=p.useState(!1),[M,A]=p.useState(""),[O,L]=p.useState(0),J=p.useRef(e);J.current=e;const H=p.useRef(!0),z=()=>{var X,Oe;N.current+=1,D.current!==null&&clearTimeout(D.current),D.current=null,(X=$.current)==null||X.abort(),$.current=null,(Oe=C.current)==null||Oe.abort(),C.current=null};p.useEffect(()=>(H.current=!0,()=>{H.current=!1,z()}),[]);const te=X=>JSON.stringify([X.provider||"",X.model||"",X.voice||"",X.profile||""]),B=X=>`The sample did not play: ${String((X==null?void 0:X.message)||X).replace(/\.$/,"")}.`,ne=(X,Oe)=>{const pt=new AbortController;C.current=pt,v({state:"playing",error:""}),mS(X,{deviceId:(g==null?void 0:g.deviceId)||"",volume:g==null?void 0:g.volume,signal:pt.signal}).then(()=>H.current&&N.current===Oe&&v({state:"idle",error:""})).catch(at=>H.current&&N.current===Oe&&v({state:"idle",error:B(at)}))},se=X=>{if(!_)return;z();const Oe=N.current,pt=new AbortController;$.current=pt,v({state:"loading",error:""}),_(X,void 0,{signal:pt.signal}).then(at=>{!H.current||N.current!==Oe||($.current=null,S.current={key:te(X),bytes:at},ne(at,Oe))}).catch(at=>{!H.current||N.current!==Oe||($.current=null,v({state:"idle",error:B(at)}))})},ue=X=>{if(!_)return;z();const Oe=N.current;if(S.current&&S.current.key===te(X)){ne(S.current.bytes,Oe);return}v({state:"loading",error:""}),D.current=setTimeout(()=>{D.current=null,H.current&&N.current===Oe&&se(X)},rA)},ve=()=>{if(k.state!=="idle"){z(),v({state:"idle",error:""});return}const X=J.current;if(S.current&&S.current.key===te(X)){z(),ne(S.current.bytes,N.current);return}se(X)};p.useEffect(()=>{A("")},[e.provider]),p.useEffect(()=>{let X=!0;return V(!0),I({}),G(""),P.current(e.provider,e.model).then(Oe=>{X&&(I(Oe),G(Oe.error?String(Oe.error):""))}).catch(Oe=>{X&&G(String((Oe==null?void 0:Oe.message)||Oe))}).finally(()=>{X&&V(!1)}),()=>{X=!1}},[e.provider,e.model,O]);const Te=Array.isArray(R.items)?R.items:[...Array.isArray(R.profiles)?R.profiles.map(X=>({...X,voice_kind:"profile"})):[],...Array.isArray(R.voices)?R.voices.map(X=>({...X,voice_kind:"voice"})):[]],ke=X=>JSON.stringify([X.provider||"",X.model||"",X.voice_kind==="profile"?"profile":"voice",X.id]),le=X=>(!e.provider||!X.provider||X.provider===e.provider)&&(!e.model||!X.model||X.model===e.model),xe=X=>JSON.stringify([X.provider||"",X.voice_kind==="profile"?"profile":"voice",X.id]),Ee=new Map;for(const X of Te){if(!(X!=null&&X.id))continue;const Oe=xe(X);Ee.has(Oe)||Ee.set(Oe,new Set),Ee.get(Oe).add(String(X.model||""))}const Ve=X=>{var Oe;return(((Oe=Ee.get(xe(X)))==null?void 0:Oe.size)||0)>1},_t=X=>Ve(X)&&!e.model?JSON.stringify([X.provider||"","",X.voice_kind==="profile"?"profile":"voice",X.id]):ke(X),Qe=Te.find(X=>X.id===(e.profile||e.voice)&&X.voice_kind==="profile"==!!e.profile&&le(X))||(!e.profile&&e.voice?Te.find(X=>X.id===e.voice&&X.voice_kind==="profile"&&le(X)):void 0),ot=Qe?_t(Qe):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",ze=nA(Te),He=ze.length>1;p.useEffect(()=>{!He&&!K&&A("")},[He,K]);const ft=He?M:"",et=new Set,Ot=Te.filter(X=>(X==null?void 0:X.id)&&(!e.provider||!X.provider||X.provider===e.provider)&&(!Ve(X)||!e.model||X.model===e.model||!Ee.get(xe(X)).has(e.model))&&(sA(X,ft)||_t(X)===ot)).filter(X=>{const Oe=_t(X);return et.has(Oe)?!1:(et.add(Oe),!0)}).map(X=>{const Oe=Cg(X);return{value:_t(X),group:pS(X),label:`${X.label||X.name||X.id}${Oe?` · ${_u(Oe)}`:""}${!e.provider&&X.provider?` · ${X.provider}`:""}`}}).sort((X,Oe)=>Nb.indexOf(X.group)-Nb.indexOf(Oe.group)),Ne=String(((tt=Qe==null?void 0:Qe.tags)==null?void 0:tt.description)||"").trim();ot&&!Ot.some(X=>X.value===ot)&&Ot.unshift({value:ot,group:"",label:`${e.profile||e.voice} (saved)`});const Re=X=>t({...e,...X});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:X=>{z(),v({state:"idle",error:""}),t({...e,...X,voice:"",profile:""})},fetchProviders:async()=>{const X=await P.current();if(X.error&&!Y_(X.tts_providers||X.providers).length)throw new Error(X.error);return Y_(X.tts_providers||X.providers).map(Oe=>({name:Oe}))},fetchModels:async X=>{var yt,jt;const Oe=await P.current(X),pt=Y_(((yt=Oe.tts_models_by_provider)==null?void 0:yt[X])||Oe.tts_models||Oe.models),at=Array.isArray((jt=Oe.tts_model_details_by_provider)==null?void 0:jt[X])?Oe.tts_model_details_by_provider[X]:[],Et=new Map(at.filter(st=>st&&st.id).map(st=>[String(st.id),String(st.label||(st.role==="cloning"?`${st.id} (clones)`:st.id))]));return pt.map(st=>({id:st,label:Et.get(st)||st}))},providerLabel:"Speech provider",modelLabel:"Speech model"}),He?s.jsxs("label",{children:["Voices that speak",s.jsx(Wr,{ariaLabel:"Voice language",placeholder:"Any language",value:M,searchable:!1,options:[{value:"",label:"Any language"},...ze.map(X=>({value:X,label:_u(X)}))],onChange:A})]}):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:ot,disabled:K,options:[{value:"",label:d||"Gateway / provider default"},...Ot],onChange:X=>{let Oe;if(!X)Oe={voice:"",profile:""};else{const[pt,at,Et,yt]=JSON.parse(X);Oe={provider:pt||e.provider||"",model:at||(pt&&pt!==e.provider?"":e.model)||"",voice:Et==="voice"?yt:"",profile:Et==="profile"?yt:""}}Re(Oe),ue({...e,...Oe})}}),_?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:K&&k.state==="idle",onClick:ve,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,Ne?s.jsx("p",{className:"af-voice-settings__description",children:Ne}):null,K?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,!K&&!W&&e.provider&&Te.length===0&&String(R.unavailable_reason||"").trim()?s.jsx("p",{className:"af-voice-note",role:"status","data-voice-note":"unavailable",children:String(R.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:X=>Re({speed:X.target.value?Number(X.target.value):void 0}),children:[s.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(X=>s.jsxs("option",{value:X,children:[X,"×"]},X))]})]}),o&&((ge=(re=R.controls)==null?void 0:re.quality_preset)!=null&&ge.supported)?s.jsxs("label",{children:["Quality",s.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:X=>Re({quality_preset:X.target.value}),children:[s.jsx("option",{value:"",children:"Gateway default"}),Y_(R.controls.quality_preset.values).map(X=>s.jsx("option",{value:X,children:X},X))]})]}):null,(je=(de=R.controls)==null?void 0:de.instructions)!=null&&je.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:X=>Re({instructions:X.target.value})})]}):null]}):null,x&&(x.design||x.clone)?s.jsx(lA,{creation:x,defaultLanguage:ft,recordFrom:y,onCreated:(X,Oe)=>{const pt=J.current;t({...pt,provider:Oe||pt.provider||"",model:"",voice:X,profile:""}),L(at=>at+1)}}):null,m!=null&&m.list?s.jsx(uA,{library:m,refreshKey:O,onChanged:()=>L(X=>X+1),onRemoved:X=>{const Oe=J.current;Oe.voice===X&&t({...Oe,voice:""})}}):null,c?s.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const oA={value:"",label:"Detect from the recording"},aA=3e4;function lA({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,P]=p.useState(!1),[R,I]=p.useState(0),[W,G]=p.useState({text:"",tone:"info"}),K=p.useRef(!1),V=p.useRef(!0),M=p.useRef(null);p.useEffect(()=>(V.current=!0,()=>{var z;V.current=!1,(z=M.current)==null||z.abort()}),[]);const A=Object.keys(yS).map(z=>({value:z,label:_u(z)})),O=o==="design"?_:y,L=()=>{if(M.current){M.current.abort();return}const z=new AbortController;M.current=z;const te=Date.now();P(!0),G({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:aA,signal:z.signal,onLevel:B=>V.current&&I(B)}).then(({blob:B,peak:ne})=>{if(V.current){if(ne<fS){G({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}v(B),G({text:`Recording ready (${Math.max(1,Math.round((Date.now()-te)/1e3))} s).`,tone:"ok"})}}).catch(B=>{V.current&&((B==null?void 0:B.name)==="AbortError"?G({text:"Recording cancelled.",tone:"info"}):G({text:Hp(B),tone:"error"}))}).finally(()=>{M.current===z&&(M.current=null),V.current&&(P(!1),I(0))})},J=async()=>{if(!(K.current||M.current)){K.current=!0,S(!0),G({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;G({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;G({text:`The voice was not created: ${String((z==null?void 0:z.message)||z).replace(/\.$/,"")}.`,tone:"error"})}finally{K.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 te=z.target.files&&z.target.files[0]||null;v(te),te&&G({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(R*100),children:s.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(R*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:O,searchable:!1,options:o==="design"?A:[oA,...A],onChange:o==="design"?g:x})]}),s.jsx("button",{type:"button","data-action":"create-voice",disabled:C||!H,onClick:J,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 cA=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 uA({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 R=$.current.list;if(!R)return;let I=!0;return l(W=>({loading:!0,error:W.error})),R().then(W=>{I&&(o(cA(W).filter(G=>{var K;return jy(G)&&!((K=G==null?void 0:G.tags)!=null&&K.builtin)})),l({loading:!1,error:""}))}).catch(W=>I&&l({loading:!1,error:`The voices could not be listed: ${$b(W)}.`})),()=>{I=!1}},[t,v]);const D=(R,I,W,G)=>{C.current||(C.current=!0,y(R),k({text:"",tone:"info"}),I().then(()=>{S.current&&(k({text:W,tone:"ok"}),h(null),_(""),G==null||G(),N(K=>K+1),n==null||n())}).catch(K=>S.current&&k({text:`${$b(K)||"The gateway refused"}.`,tone:"error"})).finally(()=>{C.current=!1,S.current&&y("")}))},P=R=>String(R.name||R.label||jy(R));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(R=>{const I=jy(R),W=pS(R)==="Shared voices",G=Cg(R),K=String(R.engine||R.provider||""),V=g===I;return s.jsxs("li",{className:"af-voice-library__item","data-voice-id":I,children:[(d==null?void 0:d.id)===I?s.jsxs("span",{className:"af-voice-library__edit",children:[s.jsx("input",{"aria-label":`New name for ${P(R)}`,value:d.name,onChange:M=>h({id:I,name:M.target.value})}),s.jsx("button",{type:"button","data-action":"save-voice-name",disabled:V||!d.name.trim(),onClick:()=>D(I,()=>$.current.rename(I,{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:[P(R),s.jsx("span",{className:"af-voice-library__meta",children:[W?"Shared":"Yours",G?_u(G):"",K].filter(Boolean).join(" · ")})]}),m===I?s.jsxs("span",{className:"af-voice-library__confirm",role:"group","aria-label":`Delete ${P(R)}?`,children:["Delete ",P(R),"?",s.jsx("button",{type:"button","data-action":"confirm-delete-voice",disabled:V,onClick:()=>D(I,()=>$.current.remove(I),`${P(R)} was deleted.`,()=>r==null?void 0:r(I)),children:"Delete"}),s.jsx("button",{type:"button","data-action":"keep-voice",disabled:V,onClick:()=>_(""),children:"Keep"})]}):(d==null?void 0:d.id)!==I?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:I,name:P(R)}),children:"Rename"}):null,e.remove?s.jsx("button",{type:"button","data-action":"delete-voice",disabled:!!g,onClick:()=>_(I),children:"Delete"}):null,e.share&&!W?s.jsx("button",{type:"button","data-action":"share-voice",disabled:!!g,onClick:()=>D(I,()=>$.current.share(I),`${P(R)} is shared with everyone.`),children:"Share"}):null]}):null]},I)})}):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=vt("automations"),dA=vt("trigger-sources"),fA=vt("me/email"),hA=vt("me/email/accounts"),mA=vt("triggers/connections"),_A=vt("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 pA(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 gA(){return nl()}function yA(e){const t=e.newId??gA,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(pA(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",dA),getMyEmail:()=>r("GET",fA),listTriggerConnections:()=>r("GET",mA),listMailboxes:()=>r("GET",hA),previewSchedule:i=>r("POST",_A,{trigger:i})}}function wS(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 vS(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 wA(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 vA={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},xA={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.`},bA="Next scheduled run: {time}.",kA="Growing context: later runs see this run in their history.",jA={run_now:{name:"playCircle"}},SA={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."},NA={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:vA,hints:xA,run_now_next_run_line:bA,run_now_growing_line:kA,icons:jA,email:SA,schedule:NA},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 xS(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 bS(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=bS(e);return n?(t??[]).find(r=>r.connection_id===n)??null:null}function $A(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(bS(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 xS(m,o)}return Ep.something}const CA=["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)} ${CA[Number(o)-1]??o}`;return{day:r,clock:i,label:l}}function EA(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=EA(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 AA(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)||$A(N?$:t.trigger??$,t.connections,t.mailboxes);const D=P=>{var R;return!!P&&typeof P=="object"&&((R=P.data)==null?void 0:R.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 TA=/^([1-9][0-9]*)([smhd])$/,MA={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function jm(e){if(typeof e!="string")return null;const t=TA.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function RA(e){const t=jm(e);if(!t)return`every ${e}`;const[n,r]=MA[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 kS(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const LA={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},$n=ex.email,jS="email.received",SS=1,IA="1h",OA="60s",NS=60,sx=100,Uw=1e3,Eb=200,Ab=200,Tb=50;function Ag(e){return!!e&&e.source_id===jS&&e.source_version===SS}function Tg(e){return!!e&&e.effective_enabled===!0}function $S(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 PA=/[\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("@")&&!PA.test(t)}function DA(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const CS={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function rx(e){return e?IA:OA}function ES(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=$S(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 FA(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&&(ES(n.every)??0)<NS&&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,DA,"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 AS(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 ${RA(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=$S(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 zA(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function BA(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function TS(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function MS(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function UA(e){return MS(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"},WA=new Set(["running","waiting","backoff"]);function qA(e,t=[]){return e.current_occurrence!=null}function RS(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 LS(e,t){var n;return e.next_run_at&&e.next_run_local?`${US(e.next_run_local,e.time_zone)} (${VA(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 VA(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=qA(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 HA(e){return e.status==="active"?yo.pause:yo.resume}function GA(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 KA(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=GA(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:!WA.has(t.status)}})}function JA(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function IS(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 YA={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:YA[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 OS(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:QA(n)?sT(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:wS(t==null?void 0:t.target.input_data),notifyEmail:t?MS(t.notify):null,emailRecipients:t?zA((l=t.notify)==null?void 0:l.recipients):null}}function XA(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=OS(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&&(ES(t.every)??0)<NS)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(DS(l)||r.push(PS),(t.context!==e.context_mode||l!==c.growingMaxTokens)&&(i.context=FS(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:vS(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=TS(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:wA(h)}}return Object.keys(i).length?i:null}const tm=5e4,ZA="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.",PS="Max growing context must be a positive whole number of tokens.";function DS(e){return Number.isSafeInteger(e)&&e>0}function FS(e,t){return{mode:e,...t!==tm?{growing:{max_tokens:t}}:{}}}const fs=ex.schedule,Kp=["mon","tue","wed","thu","fri","sat","sun"],zS=["daily","weekly","monthly"],BS=2;function QA(e){return e.source_id==="schedule"&&e.source_version===BS}const eT=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function US(e,t){if(!e)return"";const n=eT.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function tT(e,t="account"){return(t==="account"?fs.time_zone_line:fs.time_zone_line_automation).replace("{time_zone}",e)}const nT=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function WS(e){return zS.includes(e.kind)}function ox(e){const t=[];if(nT.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 sT(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 rT=[{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 qS(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 iT(e){const t=e.trim().split(`
|
|
56
|
+
`)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const oT=/^\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=qS(e.until);r?n.until=r:t.push("Stop at must be a date and time (UTC).")}return n}function aT(e){const t=[],n=e.when;if(n.kind==="once"){const l=(n.at||"").trim().slice(0,16);return oT.test(l)?{config:{kind:"once",at:l},errors:t}:{config:null,errors:[fs.error_once]}}if(WS(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=qS(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 VS(e){const t=aT(e);return t.config?{trigger:{source_id:"schedule",source_version:BS,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function lT(e){return e.kind==="every"||e.kind==="once"||WS(e)}function HS(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()||iT(r);i.length>120&&n.push("Title is at most 120 characters.");const o=e.trigger==="email",c=o?FA(e.email??CS):null,l=o?null:VS(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"&&!DS(h)&&n.push(PS),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:jS,source_version:SS,config:c.config}:l.trigger,context:FS(e.context,e.context==="growing"?h:tm),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(_.notify=TS(!0,d==null?void 0:d.recipients)),{ok:!0,body:_}}const cT="Tools run without asking (you approve them now by creating this automation)";function uT(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 dT(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 GS={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class fT{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||hT(n.error))&&this.open.delete(t)}}function hT(e){return ix(e)&&e.status>0&&e.code!=="invalid_response"}function mT(){return nl()}class _T{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 pT="08:00",gT=["mon"],KS={at:pT,days:[...gT],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(KS,e)}const yT=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function JS(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(d2,{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:yT.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 wT(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:tT(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 vT(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function YS(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:vT(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(wT,{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 XS(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 ZS="@default",QS="No workflows available for this app — ask your admin.",eN={shared:"Shared",mine:"Mine"};class Gl extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function xT(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 bT(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function kT(e,t={}){return e===null?bT(t):xT(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 jT(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 ST(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=AT((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?jT(r,c):{status:"unavailable",reason:"no interface named for the gateway default"}}}function NT(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:eN[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const $T={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function CT(e){return $T[e]??e}function ET(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(CT))].join(", "),n].filter(Boolean).join(" · "):n}function AT(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 TT(e){return e.value}function MT(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function RT(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 LT(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:ZS,name:"Gateway default",detail:MT((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const i of NT(n))for(const o of i.entries)r.push({key:o.value,value:o.value,name:o.name,detail:ET(o,n),title:TT(o),group:i.id,entry:o});return r}async function IT(e,t,n){var o;const r=await fetch(Xv(e,vt(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 OT(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 tN(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=kT(t,{allVersions:r});return(l.current?l.current(x,{signal:y.signal}):IT(o,x,y.signal)).then(v=>{y.signal.aborted||_({status:"ready",data:ST(v,t,{defaultInterface:n}),error:""})}).catch(v=>{y.signal.aborted||_({status:"error",data:null,error:OT(v)})}),()=>y.abort()},[t,n,r,i,o,c,d]);const g=p.useCallback(()=>h(y=>y+1),[]);return{...m,reload:g}}function PT(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 nN(...e){return e.filter(Boolean).join(" ")}function sN(e){const t=tN({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(()=>LT(n.data,r).map(I=>{const W=I.entry&&x?x(I.entry):null;return W?{...I,detail:W}:I}),[n.data,r,x]),v=k.find(I=>I.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===ZS?"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(PT(_.current)),l(!0);const I=k.findIndex(W=>W.value===e.value);h(I>=0?I:0)},[C,k,e.value]),P=p.useCallback(I=>{var W;S(),I.value!==e.value&&e.onChange(I.value,I.entry),(W=_.current)==null||W.focus()},[S,e]);p.useEffect(()=>{if(!c)return;const I=G=>{m.current&&!m.current.contains(G.target)&&S()},W=()=>S();return document.addEventListener("mousedown",I),document.addEventListener("touchstart",I),window.addEventListener("resize",W),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("touchstart",I),window.removeEventListener("resize",W)}},[c,S]),p.useEffect(()=>{var W;if(!c||d<0)return;const I=typeof document<"u"?document.getElementById(`${i}-opt-${d}`):null;(W=I==null?void 0:I.scrollIntoView)==null||W.call(I,{block:"nearest"})},[c,d,i]);const R=I=>{if(!c){["Enter"," ","ArrowDown","ArrowUp"].includes(I.key)&&(I.preventDefault(),D());return}if(I.key==="Escape"){I.preventDefault(),S();return}if(I.key==="Tab"){S();return}if(I.key==="Enter"||I.key===" "){I.preventDefault(),d>=0&&k[d]&&P(k[d]);return}const W=RT(I.key,d,k.length);W!==null&&(I.preventDefault(),h(W))};return s.jsxs("div",{ref:m,className:nN("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:R,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(DT,{id:o,idBase:i,rows:k,value:e.value,highlight:d,ariaLabel:e.ariaLabel||"Workflow",style:g,onHighlight:h,onChoose:P}):null,n.status==="error"?s.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&k.every(I=>!I.entry)&&!r?s.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:QS}):null]})}function DT(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:nN("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:eN[o]}),c.map(l=>t(l.row,l.index))]},o)),i.length===0?s.jsx("p",{className:"af-workflow-picker__empty",children:QS}):null]})}function FT(e){const t=zw(e.target);return s.jsxs("div",{className:"af-auto__field",children:[s.jsx("span",{children:"Flow"}),s.jsx(sN,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:zT(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 zT(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 BT(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 rN(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 UT(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 WT(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 qT={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function iN(e){const t=String(e.status),n=qT[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:LA[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 VT(e){return ix(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function HT(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return s.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>s.jsxs(Ce.Fragment,{children:[n,r<t.length-1?s.jsx("wbr",{}):null]},r))})}function GT(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 KT(e){const t=e.summary,n=RS(t),r=GT(t,e.triggerSources),i=LS(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(iN,{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:kS(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:IS(t)})]})]})}function JT(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:AS(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:[kS(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:UA(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:BA(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(HT,{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,YT=Sm.run_now_next_run_line,XT=Sm.run_now_growing_line;function Jp(e,t){const n=[Gw[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(YT.replace("{time}",US(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(XT)),n.join(`
|
|
58
|
+
`)}function ZT(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 QT(e){const t=em(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",i=ZT(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(HA(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 eM(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 tM(e){var P;const t=OS(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(((P=t.calendar)==null?void 0:P.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 R=ox(x);if(!R.config)return null;const I=e.summary.trigger.config.time_zone;return{source_id:e.summary.trigger.source_id,source_version:e.summary.trigger.source_version,config:{...R.config,...typeof I=="string"?{time_zone:I}:{}}}})(),v=YS(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:R=>{R.preventDefault(),e.onSubmit({...eM(R.currentTarget,t),...x?{calendar:x}:{},...n?{target:n}:{},...e.availableTools!==void 0?{tools:i}:{}})},onKeyDown:R=>{R.key==="Escape"&&e.onCancel&&(R.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(FT,{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(([R,I])=>s.jsx("option",{value:R,children:I},R))})]}),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:zS.map(R=>s.jsxs("label",{children:[s.jsx("input",{type:"radio",name:`${C}-calendar-kind`,value:R,checked:x.kind===R,disabled:e.busy,onChange:()=>_(R)})," ",fs[`kind_${R}`]]},R))}),s.jsx(JS,{value:x,onChange:R=>y(I=>lx(I??Ib(R),R)),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:ZA})]})})]}),t.toolApproval?s.jsxs("fieldset",{className:"af-auto__field",children:[s.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?s.jsx(XS,{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(rN,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),s.jsx(GE,{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(R=>s.jsx("li",{children:R},R))}):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 nM(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 sM(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 rM="What the agent received";function Kw(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function iM(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:GS[t.kind]??"Waiting"}),t.prompt?i(t.prompt):s.jsxs("span",{children:[" ",c]})]});if(t.kind==="tool_approval"){const c=uT(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=dT(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 oM(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=nM(t.user_turn,_)!==null,y=sM(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:rM}),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(iM,{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 aM=5e3,lM={[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 cM(e){var Te,ke;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=le=>{var xe;d||l(le),(xe=y.current)==null||xe.call(y,le)},[k,v]=p.useState([]),[N,$]=p.useState(!1),[C,S]=p.useState(null),[D,P]=p.useState(null),[R,I]=p.useState(null);p.useEffect(()=>{if(!R)return;const le=setTimeout(()=>I(null),aM);return()=>clearTimeout(le)},[R]),p.useEffect(()=>{var xe;if(!m)return;v([]);const le=Lb(o.current,['.af-auto__revise [name="title"]']);le==null||le.focus(),(xe=le==null?void 0:le.scrollIntoView)==null||xe.call(le,{block:"nearest"})},[m,t.automation_id]);const[W,G]=p.useState(null);p.useEffect(()=>{var le;W&&((le=Lb(o.current,[...W,".af-auto__notice",".af-auto__title"]))==null||le.focus(),G(null))},[W]);const K=p.useRef(null);K.current||(K.current=new fT(e.newId??mT));const V=K.current,M=le=>P(VT(le)),A=(le,xe,Ee)=>{P(null),I(null),xe(V.idFor(le)).then(Ve=>{V.settle(le,{ok:!0}),Ee(Ve)},Ve=>{V.settle(le,{ok:!1,error:Ve}),M(Ve)})},O=JA(t),L=p.useRef(e.onSeen);L.current=e.onSeen;const J=p.useRef(null);J.current||(J.current=new _T),p.useEffect(()=>{const le=J.current,xe=O?`${t.automation_id}|${O}`:null;if(!O||!le.next(xe,t))return;const Ee=t;L.current(O).then(()=>le.succeeded(xe),Ve=>{le.failed(xe,Ee),M(Ve)})});const H=em(t,e.occurrences,n),z=KA(e.occurrences),te=(ke=(Te=e.definition)==null?void 0:Te.target.input_data)==null?void 0:ke.prompt,B=le=>e.occurrenceEvents&&le in e.occurrenceEvents?AA(e.occurrenceEvents[le],{trigger:t.trigger,connections:e.triggerConnections,mailboxes:e.mailboxes,timeZone:t.time_zone,nowMs:e.nowMs}):null,ne=t.occurrence_count-e.occurrences.length,se=D??e.error??null,ue=se?Gp(se):null,ve=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(KT,{summary:t,workflowLabel:e.workflowName,triggerSources:e.triggerSources,titleId:i,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}),s.jsx(QT,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:m,notice:R,onDismissNotice:()=>I(null),idBase:`${i}-ctl`,onCommand:le=>A(`command:${le}`,xe=>e.onCommand(le,void 0,{command_id:xe}),()=>{le===yo.archive?($(!1),I("Archive requested."),G(['[data-action="archive"]'])):I(lM[le]??"Command sent.")}),onToggleRevise:()=>{v([]),x(!m)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),G(['[data-action="archive"]'])}})]}),m&&g?s.jsx(tM,{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),G(['[data-action="edit"]'])},onSubmit:le=>{const xe=g.summary,Ee=XA(xe,le,g.definition);if(Ee===null){v(["Nothing changed."]);return}if("errors"in Ee){v(Ee.errors);return}v([]),A(`revise:${xe.revision}:${JSON.stringify(Ee)}`,async Ve=>{const _t=le.target&&Ee.target?{...Ee,target:await(e.prepareTarget?e.prepareTarget(Ee.target):BT(Ee.target,e.workflowPickerOptions))}:Ee;return e.onRevise(_t,xe.revision,{command_id:Ve})},()=>{I("Saved; applies from the next run."),x(!1),G(['[data-action="edit"]'])})}}):e.definition?s.jsx(JT,{definition:e.definition,renderText:r,served:t,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}):null,ue?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:ue.title})," ",s.jsx("span",{children:ue.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:()=>P(null),children:s.jsx(qe,{name:"x",size:12})}):null]}):null,ve.items.length||ve.waits.length?s.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:s.jsxs("ul",{children:[ve.items.map(le=>s.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${le.kind}`,"data-cursor":le.cursor,children:[s.jsx("span",{className:`af-auto-badge af-auto-badge--${le.kind==="failure"?"failed":"notified"}`,children:le.kind==="failure"?"Failed":"Notified"})," ",s.jsx("strong",{children:le.title})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",le.index," · ",Bw(le.at)]}),le.body?s.jsx("div",{className:"af-auto__attention-body",children:r(le.body)}):null]},le.cursor)),ve.waits.map(le=>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":le.kind,children:GS[le.kind]??"Waiting for you"})," ",s.jsxs("span",{className:"af-auto-turn__muted",children:["#",le.index]}),le.prompt?s.jsx("div",{className:"af-auto__attention-body",children:r(le.prompt)}):null]},`${le.run_id}:${le.wait_key}`))]})}):null,ne>0?s.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:s.jsx(Ur,{icon:"history",label:`Load earlier runs (${ne} more)`})}):null,z.length?s.jsx("ol",{className:"af-auto__timeline","aria-label":"Runs",children:z.map(le=>{const xe=`[data-index="${le.row.index}"]`;return s.jsx(oM,{view:le,busy:n,eventCard:B(le.row.run_id),task:typeof te=="string"?te:void 0,timeZone:t.time_zone,nowMs:e.nowMs,discuss:H.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?Ee=>{var Ve;P(null);try{Promise.resolve((Ve=e.onOpenResource)==null?void 0:Ve.call(e,Ee)).catch(M)}catch(_t){M(_t)}}:void 0,discussOpen:C===le.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(Ee,Ve,_t)=>{P(null),e.onAnswerWait(Ee,Ve,_t).then(()=>I("Answer sent."),M)},onWaitError:Ee=>P({status:0,code:"invalid_payload",message:Ee}),onDiscussOpen:S,onDiscussCancel:()=>{S(null),G([`${xe} [data-action="discuss"]`])},onDiscussSubmit:(Ee,Ve)=>A(`discuss:${Ee}:${Ve}`,_t=>e.onDiscuss(Ee,Ve,{request_id:_t}),()=>{S(null),I("Discussion started in a new conversation."),G([`${xe} [data-action="discuss"]`])})},le.row.run_id)})}):s.jsx("p",{className:"af-auto__empty",children:"No runs yet."})]})}const oN=72;function uM(e,t=oN){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 dM(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function fM(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:uM(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}=fM(e.src,e.peaks),y=_??new Array(oN).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 P;const D=(P=n.current)==null?void 0:P.getBoundingClientRect();!D||!l||N(dM(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,P;(P=(D=S.currentTarget).setPointerCapture)==null||P.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 P=Math.max(1.5,S*30),R=(D+.5)/y.length<=x;return s.jsx("rect",{className:R?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:D*2+.3,y:16-P/2,width:1.4,height:P,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)),hM=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"),mM=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"),_M=pu("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),pM=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"),gM={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:hM},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:mM},shell:{line:["#"],strings:['"',"'"],keywords:_M},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:pM},data:{line:["#"],strings:['"',"'"],keywords:Fb},json:{line:[],strings:['"'],keywords:Fb},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:pu("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:pu("")}},yM={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 yM[i]||""}const wM=e=>e>="0"&&e<="9",vM=e=>/[A-Za-z_$]/.test(e),zb=e=>/[A-Za-z0-9_$]/.test(e);function aN(e,t){const n=String(e??""),r=gM[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(wM(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(vM(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=aN(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?xM(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(Ce.Fragment,{children:e.text},t):s.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function xM(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 lN=["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`${lN[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`${lN[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 bM=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),kM=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),jM=new Set("mp4 m4v webm mov ogv mkv".split(" ")),SM=new Set("mts cts".split(" ")),NM=new Set(["video/mp2t"]),$M=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function CM(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=CM(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":bM.has(n)?"image":kM.has(n)?"audio":jM.has(n)?"video":cx(e)||SM.has(n)?"code":$M.has(n)?"text":r.startsWith("image/")&&r!=="image/svg+xml"?"image":r.startsWith("audio/")?"audio":r.startsWith("video/")&&!NM.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 EM(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(AM,{kind:t,p:e})]})})]})}function AM({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 TM(e){return e==="any_except_denied"?ni.postureAnyExceptDenied:ni.postureAllowedOnly}function MM(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 RM(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 LM(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 IM(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}=LM(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 OM(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 PM(e,t,n,r){return $m(e,{...t,folders:t.folders.map(i=>i.path===n?{path:n,mode:r}:i)})}function DM(e,t,n){return $m(e,{...t,posture:n})}function FM(e,t,n){return $m(e,{...t,default_mode:n})}function zM(e,t,n,r){const i=String(n).trim();return $m(e,{...t,folders:[...t.folders,{path:i,mode:OM(e,t.posture)}]})}function BM(e,t,n){return $m(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function UM(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 WM(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function qM(e="me",t=Zh){return`${WM(t)}/workspace/effective/${encodeURIComponent(e)}`}const Gb=e=>e==="ro"||e==="rw"||e==="deny",VM=e=>e==="ro"||e==="rw",HM=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 GM(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(Kb);if(!(HM(t.posture)&&(VM(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=qM(t,n);return async(i,o)=>GM(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 KM=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function JM(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 cN(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"?JM(e.value,e.effective):e.state,k=e.level==="run"?e.effective:e.state,v=m&&m.base===k?m.value:x,N=v?IM(y,v):null,$=O=>{if(e.level==="run"){const L=e,J=O.configured===!1?null:{posture:O.posture,default_mode:O.default_mode,folders:O.folders};return Promise.resolve(L.onChange(J))}return e.save(O)};async function C(O,L){if(n!==null||g)return!1;r(O),l(null),o(J=>{const H={...J};return delete H[O],H});try{const J=await $(L);return KM(J)&&_({base:k,value:J}),l(O),!0}catch(J){return o(H=>({...H,[O]:Jb(J)})),!1}finally{r(null)}}const S=O=>i[O]?s.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:i[O]}):c===O?s.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:qn.saved}):null,D=(O,L)=>s.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":O,"data-af-tip":L,tabIndex:L?0:void 0,children:Vb(O)}),P=(O,L,J,H,z)=>s.jsx("span",{className:"af-workspace__access",role:"group","aria-label":O,"data-workspace":z,"data-access":L,children:J.map(te=>{const B=!!te.reason||!!g;return s.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":L===te.value?"true":"false","aria-disabled":B?"true":void 0,"data-af-tip":te.reason||void 0,"data-action":`${z}-${te.value}`,onClick:()=>B||n!==null||te.value===L?void 0:H(te.value),children:te.text},te.value)})}),R=O=>{if(O.builtin)return D("deny",qn.builtinRefused);if(!O.editable||!v)return D(O.mode);const L=v.policy;return s.jsxs(s.Fragment,{children:[P(`${qn.accessLabel} ${O.path}`,O.mode,["rw","ro","deny"].map(J=>({value:J,text:Vb(J),reason:O.reasons[J]})),J=>void C(O.path,PM(y,L,O.path,J)),"workspace-mode"),s.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${qn.remove} ${O.path}`,"data-af-tip":`${qn.remove} ${O.path}`,"aria-disabled":g||n!==null?"true":void 0,onClick:()=>g||n!==null?void 0:void C(O.path,BM(y,L,O.path)),children:s.jsx(qe,{name:"x",size:16})})]})};async function I(O){if(!v||!N||!N.canAdd)return;const L=O.trim();L&&await C("add",zM(y,v.policy,L))&&h("")}async function W(){if(!e.choose||n!==null||g)return;let O;try{O=await e.choose()}catch(L){o(J=>({...J,add:Jb(L)}));return}O&&await I(O)}const G=N?N.rows.filter(O=>O.mode!=="deny"):[],K=N?N.rows.filter(O=>O.mode==="deny"):[],V=O=>s.jsxs("li",{className:"af-workspace__row","data-workspace":O.builtin?"builtin":"row","data-path":O.path,"data-mode":O.mode,"data-cap":O.cap??void 0,children:[s.jsx("code",{className:"af-workspace__path",children:O.path}),s.jsx("span",{className:"af-workspace__controls",children:R(O)}),S(O.path)]},`${O.builtin?"builtin:":""}${O.path}`),M=y==="account"?qn.followGateway:qn.useDefault,A=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:RM(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:M,description:A,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:O=>void C("follow",UM(v,O))}),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:TM(N.posture)}):P(qn.postureLabel,N.posture,[{value:"allowed_only",text:qn.postureAllowedOnly},{value:"any_except_denied",text:qn.postureAnyExceptDenied}],O=>void C("posture",DM(y,v.policy,O)),"workspace-posture"),s.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:MM(N.posture)}),S("posture")]}),s.jsxs("ul",{className:"af-workspace__list","aria-label":qn.title,"data-workspace":"list",children:[G.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:qn.allowedTitle}):null,G.map(V),K.length?s.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:qn.deniedTitle}):null,K.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?P(`${qn.accessLabel} ${qn.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:qn.accessReadWrite},{value:"ro",text:qn.accessRead}],O=>void C("everything-else",FM(y,v.policy,O)),"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:O=>h(O.target.value),onKeyDown:O=>{O.key==="Enter"?(O.preventDefault(),I(d)):O.key==="Escape"&&(O.preventDefault(),h(""),o(L=>{const J={...L};return delete J.add,J}))}}),s.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!g||!d.trim()||n!==null,onClick:()=>void I(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"&&!G.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)} %`,YM="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function XM(e){var P,R,I;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"}),V2({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=((P=e.labels)==null?void 0:P.device)||"Output device",D=((R=e.labels)==null?void 0:R.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:YM,trailing:s.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:t,onClick:N,children:((I=e.labels)==null?void 0:I.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 ZM(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 QM(e){const t=ZM(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 uN(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function eR(e){var K,V,M;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=A=>e.onChange({...y,...A}),k=uN(y.input_gain),v=e.listDevices||lS,N=p.useRef(v);N.current=v;const $=()=>{N.current("audioinput").then(A=>_.current&&i(A)).catch(()=>_.current&&i({devices:[],labelled:!1}))};p.useEffect(()=>{t||$()},[t]);const C=()=>{c(""),q2().then(()=>{var A;$(),(A=e.onDevicesChanged)==null||A.call(e)}).catch(A=>_.current&&c(Hp(A)))},S=()=>{d({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),hS({deviceId:y.input_device||"",ms:3e3,gain:k,onLevel:A=>_.current&&m(A)}).then(async({blob:A,peak:O})=>{var L,J,H;if(_.current){if(O<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(A,{deviceId:((L=e.playOn)==null?void 0:L.deviceId)||"",volume:(J=e.playOn)==null?void 0:J.volume}),_.current&&(d({phase:"idle",message:`The microphone works (peak level ${Ty(O)}).`,tone:"ok"}),$(),(H=e.onDevicesChanged)==null||H.call(e))}}).catch(A=>_.current&&d({phase:"idle",message:Hp(A),tone:"error"}))},D=y.input_device||"",P=[{value:"",label:"System default"},...r.devices.map(A=>({value:A.id,label:A.label})),...D&&!r.devices.some(A=>A.id===D)?[{value:D,label:"Saved microphone (not connected)"}]:[]],R=l.phase!=="idle",I=l.phase==="recording",W=((K=e.labels)==null?void 0:K.device)||"Input device",G=((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||R,onClick:S,children:l.phase==="recording"?"Recording…":l.phase==="playing"?"Playing…":((M=e.labels)==null?void 0:M.test)||"Test"}),children:s.jsx(Wr,{ariaLabel:W,placeholder:"System default",value:D,options:P,disabled:t,searchable:!1,onOpen:$,onChange:A=>x({input_device:A})})}),s.jsx(QM,{source:I?null:e.levelSource,level:I?h:e.level,origin:I?"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:G,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:A=>x({input_gain:Number(A.currentTarget.value)/100})}),s.jsx("span",{className:"af-voice-range__value",children:Ty(k)})]}):null]})}const tR=["provider","model","voice","profile","speed","quality_preset","instructions"];function nR(e){const t={};for(const n of tR){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function sR(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 rR=[{value:"",label:"Detect automatically"},...Object.keys(gS).map(e=>({value:e,label:_u(e)}))],iR=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function oR(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function aR(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const lR=[{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 cR(e){var ve,Te,ke,le,xe,Ee,Ve,_t,Qe,ot;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",P=ze=>e.onChange({...S,...ze}),R=Kd(S.reply_volume),I=uN(S.input_gain),W=r.tts!==!1&&!e.ttsSlot,G=r.stt!==!1,K=W||G||!!e.ttsSlot,V=e.voiceLibrary||e.createVoice;p.useEffect(()=>{if(n)return;let ze=!0;return i.current().then(He=>ze&&d(He||{})).catch(()=>ze&&d({})),g||o.current().then(He=>ze&&m({value:He||{},failed:!1})).catch(()=>ze&&m({value:null,failed:!0})),()=>{ze=!1}},[n,g]);const M=S.stt_provider||((Te=(ve=_.value)==null?void 0:ve.stt)!=null&&Te.configured?String(_.value.stt.provider||""):""),A=!!e.fetchLanguages;p.useEffect(()=>{const ze=c.current;if(n||!ze||r.microphone===!1)return;let He=!0;return ze("stt",M||void 0).then(ft=>He&&$(Array.isArray(ft)?ft.map(et=>String(et).toLowerCase()).filter(Boolean):[])).catch(()=>He&&$(null)),()=>{He=!1}},[n,A,M,r.microphone]);const O=kb(_.value,"tts",_.failed),L=kb(_.value,"stt",_.failed),J=[(ke=_.value)==null?void 0:ke.tts,(le=_.value)==null?void 0:le.stt].map(ze=>ze&&!ze.configured?ze.note:"").filter(Boolean),H=[(xe=_.value)==null?void 0:xe.tts,(Ee=_.value)==null?void 0:Ee.stt].map(ze=>{var He;return ze&&ze.configured?String(((He=ze.hint)==null?void 0:He.sentence)||"").trim():""}).filter(Boolean),z=!!((_t=(Ve=l.controls)==null?void 0:Ve.quality_preset)!=null&&_t.supported),te={deviceId:C&&S.output_device||"",volume:R},B=N&&N.length?[{value:"",label:"Detect automatically"},...N.map(ze=>({value:ze,label:_u(ze)}))]:[...rR],ne=S.stt_language||"";ne&&!B.some(ze=>ze.value===ne)&&B.push({value:ne,label:`${_u(ne)} (saved)`});const se=Fw(S.capture_mode??((Qe=e.captureDefaults)==null?void 0:Qe.capture_mode)),ue=S.auto_send??((ot=e.captureDefaults)==null?void 0:ot.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,K?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:O,overrideSummary:oR(S),overrideOwner:t,open:y==="tts",onToggle:()=>x(y==="tts"?"":"tts"),onReset:()=>P({provider:"",model:"",voice:"",profile:""}),disabled:n,children:s.jsx(iA,{value:S,onChange:ze=>e.onChange({...S,...ze}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:V,previewVoice:e.previewVoice?(ze,He,ft)=>e.previewVoice({...S,...ze},He,ft):void 0,previewOn:te,recordFrom:{deviceId:S.input_device||"",gain:I}})}):null,G?s.jsx(qb,{label:"Speech → text",setting:"stt",defaultSummary:L,overrideSummary:aR(S),overrideOwner:t,open:y==="stt",onToggle:()=>x(y==="stt"?"":"stt"),onReset:()=>P({stt_provider:"",stt_model:""}),disabled:n,children:s.jsx(Xj,{value:{provider:S.stt_provider||"",model:S.stt_model||""},onChange:ze=>P({stt_provider:ze.provider,stt_model:ze.model}),fetchProviders:async()=>{const ze=await i.current();return Yb(ze.stt_providers).map(He=>({name:He}))},fetchModels:async ze=>{var ft;const He=await i.current(ze);return Yb(((ft=He.stt_models_by_provider)==null?void 0:ft[ze])||He.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,J.map(ze=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:ze},ze)),H.map(ze=>s.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:ze},ze))]}):null,r.output!==!1?s.jsx(zh,{variant:D,title:"Output",children:s.jsx(XM,{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(eR,{value:S,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:te,onDevicesChanged:()=>v(ze=>ze+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:B,disabled:n,searchable:!1,onChange:ze=>P({stt_language:ze})})}),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:se,options:iR,disabled:n,searchable:!1,onChange:ze=>P({capture_mode:ze==="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:ue,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ze=>P({auto_send:ze})})})]}):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:ze=>P({read_aloud:ze})})}),s.jsx(oc,{label:"Voice latency",setting:"latency",help:z?"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:z&&S.quality_preset||"",options:lR,disabled:n||!z,searchable:!1,onChange:ze=>P({quality_preset:ze})})})]}):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 uR(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function dR(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 fR(e){return e.endsWith(`
|
|
68
|
+
`)?e:`${e}
|
|
69
|
+
`}function hR(e){return String(e||"").trimStart().startsWith("```")}function dN(e,t){const r=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const i of e){const o=dR(i);r.push(`## ${o}`,"");const c=String(i.content||""),l=Og(c);l!==null&&!hR(c)?r.push("```json",uR(l).trimEnd(),"```",""):r.push(fR(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 fN(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 mR=3,_R=Number.MAX_SAFE_INTEGER;function hN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mN(e){return Array.isArray(e)}function pR(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 gR(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 yR(e,t,n){return e===null?s.jsx(Id,{kind:"null",children:"null"}):typeof e=="string"?s.jsx(gR,{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 wR(e){return mN(e)?e.length===1?"1 item":`${e.length} items`:hN(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function _N(e){const{label:t,value:n,depth:r,collapseAfterDepth:i,expansionMode:o,expansionVersion:c,trailingComma:l}=e,d=r*14,h=hN(n),m=mN(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,yR(n,o,c),l?",":""]});const v=m?"[":"{",N=m?"]":"}",$=wR(n),C=y?`${v}`:`${v}…${N}${$?` (${$})`:""}`,S=m?n.map((D,P)=>({key:String(P),label:void 0,value:D})):Object.entries(n).map(([D,P])=>({key:D,label:D,value:P}));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,P)=>{const R=P===S.length-1;return s.jsx(_N,{label:D.label,value:D.value,depth:r+1,collapseAfterDepth:i,expansionMode:o,expansionVersion:c,trailingComma:!R},`${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 vR(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):mR,h=i.mode==="unfolded"?_R:d,m=p.useMemo(()=>typeof t=="string"?vR(t):t,[t]),_=p.useMemo(()=>pR(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(_N,{value:m,depth:0,collapseAfterDepth:h,expansionMode:i.mode,expansionVersion:i.version,trailingComma:!1})})]})}function xR({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=aN(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(Ce.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 pN(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Yw="http://same-origin.invalid/";function bR(e){try{const t=new URL(e,Yw);return t.protocol==="http:"&&t.origin===new URL(Yw).origin}catch{return!1}}function gN(e){const t=String(e||"").trim();return pN(t)??(t&&bR(t)?t:void 0)}let au=null;function kR(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 yN(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),_=gN(r.slice(d+2,h));if(_&&au&&!au(_)){c(),n.push(yN(`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),_=pN(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 jR(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 SR(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 wN(e,t,n){const r=e.items.map((i,o)=>s.jsxs("li",{children:[Qa(i.content,t),i.children.map((c,l)=>wN(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 NR(e,t,n){return SR(e).map((r,i)=>wN(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||kR:null;try{return $R(e)}finally{au=t}}function $R({text:e,className:t,highlight:n,highlights:r,highlightClassName:i,highlightId:o}){const c=jR(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 $=gN(k[2]||"");if($&&au&&!au($)){l.push(s.jsx("p",{className:"pc-md_p",children:yN(`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(xR,{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(Ce.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 P=Zb(D),R=[];for(let I=0;I<C;I++)R.push(P[I]??"");S.push(R),_+=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,P)=>s.jsx("th",{children:Qa(D,m)},`th:${_}:${P}`))})}),s.jsx("tbody",{children:S.map((D,P)=>s.jsx("tr",{children:D.map((R,I)=>s.jsx("td",{children:Qa(R,m)},`td:${_}:${P}:${I}`))},`tr:${_}:${P}`))})]})},`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(Ce.Fragment,{children:NR($,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(Ce.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 vN(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 CR=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),ER=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 xN(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 AR(e,t){const n=String(t||"").split("/").pop()||"",r=n.lastIndexOf(".");if(r>0&&CR.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:ER.has(i)}function TR(e){const t=n=>!!n&&(!xN(n)||AR(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}const s0=1024*1024,MR="1 MiB",RR=25*1024*1024,bN=(e,t)=>`${vt(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function LR(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 IR(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=LR(e)??n,d=l!==void 0?l>o:o>=t;return{text:i,received:o,total:l,partial:d}}function OR(e){return`Showing the first ${MR} of ${e!==void 0?Lg(e):"a file of unknown size"}; download for the rest.`}function PR(e){try{return decodeURIComponent(e)}catch{return e}}function DR(e,t,n){const r=`${vt(`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(PR(m));return h.length?bN(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?``:`[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 FR(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>RR){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(bN(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 IR(_,s0,n.size_bytes);if(c.signal.aborted)return;o({status:"ready",kind:y,contentType:g,text:y==="markdown"?DR(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 kN(e){const{markdownImages:t,inlineImage:n,renderMarkdown:r,...i}=e;return s.jsx(EM,{...i,nowMs:e.nowMs??Date.now(),renderMarkdown:r||(o=>s.jsx(Ni,{text:o,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}function zR(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:OR(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 BR(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=BR(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 jN({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 UR(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`},SN=e=>e===void 0?Cr:`${Math.round(e).toLocaleString()} tok/s`,WR=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",lu=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,qR=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function VR(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(qR),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 HR(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?` (${WR(o,o+c)})`:""}`},{label:"Newly processed",value:ei(e.fedTokens)},{label:"Outcome",value:VR(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 ${SN(n)}`:""}`),i.join(" · ")}function GR(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 ${SN(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)} · ${NN(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 NN(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${lu(e.calls,"call")} (${e.tools.join(", ")})`}function KR(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)} · ${NN(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"?HR(t):e==="time"?GR(t):KR(t)}function JR(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(Ce.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 YR(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,P=window.innerHeight,R=$.top-Ja-S,I=$.bottom+Ja,W=R>=Ja?R:I+S<=P-Ja?I:Math.max(Ja,P-Ja-S),G=Math.min(Math.max(Ja,$.left),Math.max(Ja,D-Ja-C));i({top:W,left:G})};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(JR,{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 $N(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function XR(e){const t=$N(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 CN({tool:e,showCopy:t=!0}){const[n,r]=p.useState(!1),i=$N(e.arguments),o=XR(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(jN,{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(Ce.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 EN({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(CN,{tool:r,showCopy:t},r.id))]})}function ZR(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 QR(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 eL=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 eL.has(new URL(t,n).protocol)?t:void 0}catch{return}}function AN(e,t){return xN(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function tL({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=TR({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",...AN(l,String(e.name||"").trim()||g),children:"Raw file"}):null]}),r&&!t?s.jsx(kN,{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 nL({item:e,onOpenFile:t,markdown:n}){const[r,i]=p.useState(!1);if(e.kind==="file")return s.jsx(tL,{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",...AN(c,String(e.name||"").trim()||h),children:h})}):null]})}function dx(e){var P,R;const t=e.message,n=p.useMemo(()=>QR(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),i=p.useMemo(()=>{if(!r)return"";const I=new Date(r);return Number.isFinite(I.getTime())?I.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&&((P=e.getSpeakState)==null?void 0:P.call(e,t))||"idle",_=m==="loading"?"loader":m==="playing"?"pause":"speaker",g=m==="loading"?"Generating audio…":m==="playing"?"Pause":m==="paused"?"Resume":"Speak (TTS)",y=e.showCopy!==!1,x=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],k=t.statistics,v=t.stats,N=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(v)?v:k?ZR(k):[],[e.stats,v,k]),$=Array.isArray(t.media)?t.media:[],C=String(d?d.reasoning||"":t.reasoning||""),S=!!String(t.content||"").trim();if(t.toolActivity)return s.jsx(CN,{tool:t.toolActivity,showCopy:e.showCopy});const D=e.renderFooter?e.renderFooter(t):null;if(((R=e.variant)==null?void 0:R.call(e,t))==="hint"||t.kind==="tool_policy_decision"){const I=String(t.level||"").trim().toLowerCase();return s.jsxs("div",{className:["pc-chat-hint",I==="warn"||I==="error"?`pc-chat-hint--${I}`:"",e.className].filter(Boolean).join(" "),role:"note","data-variant":"hint",children:[s.jsx("span",{className:"pc-chat-hint__text",children:String(t.content||"")}),D!=null&&D!==!1?s.jsx("div",{className:"pc-chat-footer",children:D}):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":g,title:g,onClick:()=>{var I;return(I=e.onSpeakToggle)==null?void 0:I.call(e,t)},children:s.jsx(qe,{name:_,size:22,className:m==="loading"?"pc-chat-speak-spinner":void 0})}):null,y?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 I=await il(String(t.content||""));c(I?"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]})]}),C.trim()?s.jsxs("details",{className:"pc-chat-thinking",children:[s.jsx("summary",{children:"Thinking"}),s.jsx("div",{className:"pc-chat-thinking-body",children:C})]}):null,S||!d&&!$.length?s.jsx("div",{className:"pc-chat-body",children:s.jsx(vN,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,$.length?s.jsx("div",{className:"pc-chat-media",children:$.slice(0,24).map((I,W)=>s.jsx(nL,{item:I,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},I.id||`${I.kind}:${I.src}:${W}`))}):null,x.length?s.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:x.slice(0,24).map((I,W)=>{const G=String(I.label||"").trim()||"attachment",K=String(I.target||"").trim(),V=String(I.title||"").trim(),M=!!I.disabled||typeof I.onClick!="function";return s.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:V||G,onClick:M?void 0:I.onClick,disabled:M,children:[s.jsx(qe,{name:"paperclip",size:14}),K?s.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${K}`,children:K}):null,s.jsx("span",{className:"pc-chat-attachment-name",children:G})]},I.id||`${G}:${W}`)})}):null,N.length?s.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:N.slice(0,12).map((I,W)=>{const G=String(I.label||"").trim();if(!G)return null;if(I.detail)return s.jsx(YR,{label:G,detail:I.detail,icon:I.icon,onClick:I.onClick},I.id||`${G}:${W}`);const K=String(I.title||"").trim(),V=typeof I.onClick=="function",M=V?"button":"span";return s.jsxs(M,{...V?{type:"button"}:{},className:["pc-chat-stat",V?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:K||void 0,onClick:V?()=>{var A;return(A=I.onClick)==null?void 0:A.call(I)}:void 0,children:[I.icon?s.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:I.icon}):null,s.jsx("span",{className:"pc-chat-stat-label",children:G})]},I.id||`${G}:${W}`)})}):null,D!=null&&D!==!1?s.jsx("div",{className:"pc-chat-footer",children:D}):null]})}function sL(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(sL(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(EN,{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=Ce.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 TN(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 rL={"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 iL(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=rL[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 MN(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=iL(i.name,i.type,t);return o===i.name?i:new File([i],o,{type:i.type,lastModified:i.lastModified})})}class oL{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 aL(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jc(e){return typeof e=="string"&&e.trim()!==""}function lL(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function RN(e){return"reason"in e}function LN(e,t){const n=aL(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"),lL(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 cL(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 LN(n,e)}const uL={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 dL(e){return`This reply is not streamed: ${e?uL[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const _x=e=>vt(`runs/${encodeURIComponent(e)}/workspace`);function fL(e){return _x(e)}function hL(e,t){return`${_x(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function mL(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 _L(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 pL(e,t,n){const r=await e(fL(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 gL(e,t,n,r){const i=await e(hL(t,n),{signal:r});if(!i.ok)throw await of(i,"The folder could not be listed");return _L(await i.json(),n)}async function yL(e,t,n,r){const i=await e(mL(t,n),{signal:r});if(!i.ok)throw await of(i,"The file could not be read");return await i.blob()}async function wL(e,t,n,r){const i=await pL(e,t,r);return{where:i,listing:i.exists?await gL(e,t,n,r):null}}function vL(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 IN(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 xL(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function bL(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 kL=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function jL(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return kL.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 ON(e,t,n){const r=n==="open"?jL(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 SL(e,t,n){const r=await e(AE(t),{signal:n.signal});if(!r.ok)throw await of(r,`${n.name} could not be read`);ON(await r.blob(),n.name,n.mode??"open")}function NL(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function $L(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 CL(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function PN(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),P=S&&S.runId===n&&!e.onSelectFile?S.entry:null,R=FR(t,n,P,`${e.refreshKey??""}:${$}`);p.useEffect(()=>{if(!n)return;const M=new AbortController;return y(!0),h(""),(async()=>{try{const A=await wL(t,n,o,M.signal);M.signal.aborted||l({runId:n,...A})}catch(A){M.signal.aborted||h(String((A==null?void 0:A.message)||A))}finally{M.signal.aborted||y(!1)}})(),()=>M.abort()},[t,n,o,$,e.refreshKey]),p.useEffect(()=>_(""),[n]);const I=c&&c.runId===n?c:null,W=p.useCallback(async M=>{k(M.path),h("");try{ON(await yL(t,n,M.path),M.name,"download")}catch(A){h(String((A==null?void 0:A.message)||A))}finally{k("")}},[t,n]),G=(I==null?void 0:I.where.workspace_root)||"",K=e.nowMs??Date.now();return s.jsx(EL,{title:e.title,note:e.note,where:(I==null?void 0:I.where)??null,path:o,listing:(I==null?void 0:I.listing)??null,error:d,notice:m,loading:g,fileBusy:x,selectedPath:e.onSelectFile?e.selectedPath:P==null?void 0:P.path,className:e.className,nowMs:K,openingFolder:v,onNavigate:M=>{D(null),i({runId:n,path:M})},onRefresh:()=>C(M=>M+1),onFile:M=>void W(M),onSelectFile:e.onSelectFile??(M=>D({runId:n,entry:M})),onClose:e.onClose,onCopyPath:G?()=>{(e.copyText||CL)(G).then(M=>_(M?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&$L(I==null?void 0:I.where)?()=>{N(!0),_(""),e.onOpenFolder().then(()=>_("Folder opened on this machine.")).catch(M=>_(`Open folder failed: ${String((M==null?void 0:M.message)||M)}`)).finally(()=>N(!1))}:void 0,preview:P?s.jsx(kN,{name:P.name,path:P.path,sizeBytes:P.size_bytes,modified:P.mtime,nowMs:K,...zR(R),actions:(V=e.fileActions)==null?void 0:V.call(e,P),onDownload:()=>void W(P),onClose:()=>D(null)}):null})}function EL(e){var o,c,l,d;const t=e.listing?bL(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:NL(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:vL(e.path).map((h,m,_)=>m===_.length-1?s.jsx("span",{"aria-current":"page",children:h.label},h.path):s.jsxs(Ce.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:xL(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:IN(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 AL={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},DN="docs";function TL(e){return vt(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Ly(e){return`${String(e||"app")}-docs-assistant:${nl()}`}function ML(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}),{...AL,session_id:e.sessionId,kind:DN,input_data:t}}function FN(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 RL(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*LL(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 IL(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 OL(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(TL(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(vt("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(vt("runs/start"),{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(ML({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(vt(`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 LL(v.body,g.signal)){const S=cL(C.event,C.data);!S||RN(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 IL(t,o.signal);const v=await rc(await c(vt(`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 $=FN(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 PL(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:DN,limit:"500",include_ledger_len:"false"}),i=await rc(await e(vt(`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(vt(`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 DL(e,t,n,r){var o;const i=[];for(const c of t.runIds){const[l,d]=await Promise.all([rc(await e(vt(`runs/${encodeURIComponent(c)}/input_data`),{signal:r}),"A past question could not be read"),rc(await e(vt(`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=FN(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 FL(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 zL=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function BL(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,TN(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=MN(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 UL(e){rf();const{source:t}=e,n=p.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=p.useMemo(()=>e.ask||OL({fetchGateway:(M,A)=>n.current(M,A),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 M;return(M=v.current)==null?void 0:M.abort()},[]);const D=p.useCallback(async()=>{S(M=>({...M,state:"loading"}));try{const M=await PL((A,O)=>n.current(A,O),t.app);S({state:"ready",items:M})}catch(M){S({state:"error",items:[],error:String((M==null?void 0:M.message)||M)})}},[t.app]),P=p.useCallback(async M=>{var A;(A=v.current)==null||A.abort(),S(O=>({...O,state:"loading"}));try{const O=await DL((L,J)=>n.current(L,J),M,t.name);i.current=M.sessionId,c(O),k(""),$(!1),S(L=>({...L,state:"ready"}))}catch(O){S(L=>({...L,state:"error",error:String((O==null?void 0:O.message)||O)}))}},[t.name]),R=p.useCallback(async M=>{try{const A=await n.current(vt(`sessions/${encodeURIComponent(M.sessionId)}/archive`),{method:"POST"});if(!A.ok)throw await of(A,"The conversation could not be archived");i.current===M.sessionId&&(i.current=Ly(t.app),c([])),S(O=>({...O,items:O.items.filter(L=>L.sessionId!==M.sessionId)}))}catch(A){S(O=>({...O,state:"error",error:String((A==null?void 0:A.message)||A)}))}},[t.app]);p.useEffect(()=>{var M;e.connected||(M=v.current)==null||M.abort()},[e.connected]),p.useEffect(()=>()=>{for(const M of m)M.preview&&URL.revokeObjectURL(M.preview)},[]);const I=p.useCallback(M=>{k(""),_(A=>[...A,...M.map(O=>({id:nl(),file:O,preview:zL.test(O.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(O):void 0}))])},[]),W=p.useCallback(async M=>{const A=String(M||"").trim();if(!A||g||!e.connected)return;const O=m;h(""),_([]),k("");const L=O.filter(ue=>ue.preview).map(ue=>({kind:"image",src:ue.preview,label:ue.file.name})),J=O.map(ue=>({id:ue.id,label:ue.file.name,title:ue.file.name,disabled:!0})),H={id:`u-${nl()}`,role:"user",content:A,ts:rp(),...L.length?{media:L}:{},...J.length?{attachments:J}:{}},z=`a-${nl()}`,te=[...l.current,H],B={id:z,role:"assistant",title:t.name,content:"",ts:rp(),live:{callId:z,reasoning:"",label:"answering"}};c([...te,B]),y(!0);const ne=new AbortController;v.current=ne;const se=ue=>c([...te,ue]);try{const ue=await r(A,{signal:ne.signal,sessionId:i.current,files:O.map(ve=>ve.file),onText:ve=>{ne.signal.aborted||se({...B,content:ve,live:{callId:z,reasoning:"",label:"streaming"}})},onHistory:ve=>k(RL(ve))});ne.signal.aborted||se({id:z,role:"assistant",title:t.name,content:ue,ts:rp()})}catch(ue){const ve=ne.signal.aborted;se({id:z,role:"assistant",title:t.name,level:ve?"warn":"error",content:ve?"Stopped. Nothing more will be shown for this question.":String((ue==null?void 0:ue.message)||ue||"The docs assistant failed."),ts:rp()})}finally{v.current===ne&&(v.current=null),y(!1)}},[r,g,m,e.connected,t.name]),G=()=>{var M;(M=v.current)==null||M.abort(),i.current=Ly(t.app),c([]),_([]),h(""),k("")},K=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 M=!N;$(M),M&&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:()=>{G(),$(!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(FL,{items:C.items,state:C.state,error:C.error,nowMs:Date.now(),activeSessionId:i.current,onOpen:M=>void P(M),onArchive:M=>void R(M)})}):null,s.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:s.jsx(BL,{source:t,messages:o,draft:d,onDraftChange:h,onSend:()=>void W(d),onStop:()=>{var M;return(M=v.current)==null?void 0:M.abort()},busy:g,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:m.map(M=>({id:M.id,name:M.file.name})),onAddFiles:I,onNotice:k,onRemoveFile:M=>_(A=>{const O=A.find(L=>L.id===M);return O!=null&&O.preview&&URL.revokeObjectURL(O.preview),A.filter(L=>L.id!==M)}),notice:x,suggestions:e.suggestions,onSuggestion:M=>void W(M),placeholder:e.placeholder})})]});return{headerActions:K,body:V}}function WL(e){const{headerActions:t,body:n}=UL(e);return s.jsx(_2,{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",qL=["version","root_run_id","workflow","session_id","status","display_status","cursor","interaction","open_waits","usage","warnings"],l0=["runs","messages","activities","artifacts"],zN=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function BN(e){return e==null?"None":e===!0?"True":e===!1?"False":String(e)}function VL(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 BN(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 BN(e==="runs"?t.run_id:t.id)}function Qw(e,t){return[(Array.isArray(t.order)&&t.order.length?t.order:[]).map(VL),Zw(e,t)]}function UN(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 HL(e,t){return UN(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=>zN(t,i)&&ev(e[i],t[i]))}return!1}function GL(e,t){const n=e&&Object.keys(e).length?{...e}:Object.fromEntries(l0.map(r=>[r,[]]));for(const r of qL)zN(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,_)=>UN(m.key,_.key)),n[r]=h.map(m=>m.it)}else n[r]=c}return n}let KL=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 JL{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=YL(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=GL(this.view,n),this.lastEventId=r,"delta")}}function YL(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 XL 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 XL(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 ZL(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 KL,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"]),QL=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 WN(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 eI(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 tI(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 nI(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 sI(e){return(Array.isArray(e.tool_calls)?e.tool_calls:[]).map((n,r)=>{var d;const i=eI(n,e),o=yn(n.status||e.status).toLowerCase(),c=tI(n),l=i==="failed"?nI(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 qN(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 rI(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 iI(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"||!QL.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 oI(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=iI(e),r=e.interaction?WN(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:oI(y,y.id===c?n:void 0)});const d=[],h=[],m=[];for(const y of e.activities||[])if(y.kind==="tool"){const x=sI(y);d.push(...x),x.forEach((k,v)=>l.push({order:[...y.order||[],v],id:`${y.id}:${v}`,message:qN(k)}))}else if(y.kind==="tool_policy"){const x=rI(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)=>HL(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 aI(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 VN(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(P=>kh(P)===kh(m)):[];!g.length&&Ya(m)&&c.filter(P=>Ya(P)===Ya(m)).length===1&&(g=l.filter(P=>Ya(P)===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||aI(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 HN(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 lI(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 cI(e){const t=ss(typeof e=="string"&&e.trim().startsWith("{")?HN(e):e);return Mn(t.error_class)}function uI(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 _=uI(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 le of[S.started_at,S.ended_at]){const xe=Date.parse(Mn(le));Number.isFinite(xe)&&(o=Math.min(o,xe),c=Math.max(c,xe))}for(const le of VN(t,C))le.status==="waiting"&&y.add(le.id);if(ss(S.effect).type!=="llm_call"||S.status!=="completed")continue;i.llmCalls+=1;const P=ss(S.result),R=ss(P.output),I=ss(P.usage||P.token_usage||P.tokens||R.usage||R.token_usage||R.tokens),W=ya(I,["input_tokens","prompt_tokens","prompt","input","in"]),G=ya(I,["output_tokens","completion_tokens","completion","output","out"]),K=ya(I,["total_tokens","total"])??(W!==void 0||G!==void 0?(W||0)+(G||0):void 0);K!==void 0&&(W===void 0||G===void 0||W+G!==K)&&(l=!0),W!==void 0&&(i.inputTokens=(i.inputTokens||0)+W),G!==void 0&&(i.outputTokens=(i.outputTokens||0)+G),K!==void 0&&(i.totalTokens=(i.totalTokens||0)+K);const V=Ad(P.gen_time??R.gen_time);V!==void 0&&(i.genTimeMs=(i.genTimeMs||0)+V,i.timedCalls=(i.timedCalls||0)+1);const M=ss(P.metadata||R.metadata),A=ss(M.performance),O=Ad(A.prompt_tokens_per_second),L=Ad(A.generation_tokens_per_second),J=ss(M.prompt_cache),H=Ad(J.cached_tokens),z=Ad(J.fed_tokens);if(O!==void 0||L!==void 0){if(i.measuredSpeedCalls=(i.measuredSpeedCalls||0)+1,O!==void 0&&O>0&&(i.promptTokensPerSecond=(i.promptTokensPerSecond||0)+O,W!==void 0)){const le=W/O*1e3;i.prefillMs=(i.prefillMs||0)+le,z!==void 0&&(d+=z,h+=le)}L!==void 0&&L>0&&(i.generationTokensPerSecond=(i.generationTokensPerSecond||0)+L,G!==void 0&&(i.decodeMs=(i.decodeMs||0)+G/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 le=Mn(J.outcome);if(le){const xe=i.cacheOutcomes||[];xe.includes(le)||xe.push(le),i.cacheOutcomes=xe}}const te=Mn(S.step_id)||void 0,B=te&&_.get(`${C.runId}:${te}`)||{},ne=ss(P.route),se={runId:C.runId};te&&(se.stepId=te),Mn(S.started_at)&&(se.startedAt=Mn(S.started_at));const ue=Mn(P.model||R.model)||Mn(ne.model)||B.model,ve=Mn(ne.provider)||Mn(ss(M._provider_request).provider)||B.provider||Mn(P.provider);ue&&(se.model=ue),ve&&(se.provider=ve),ue&&(i.models=wd(i.models,ue)),ve&&(i.providers=wd(i.providers,ve)),(K===void 0||W!==void 0&&G!==void 0&&W+G===K)&&(W!==void 0&&(se.inputTokens=W),G!==void 0&&(se.outputTokens=G)),K!==void 0&&(se.totalTokens=K);const Te=lI(I);Te!==void 0&&(se.reasoningTokens=Te,i.reasoningTokens=(i.reasoningTokens||0)+Te),H!==void 0&&(se.cachedTokens=H),z!==void 0&&(se.fedTokens=z),Mn(J.outcome)&&(se.cacheOutcome=Mn(J.outcome)),Mn(J.backend)&&(se.cacheBackend=Mn(J.backend),i.cacheBackends=wd(i.cacheBackends,se.cacheBackend)),V!==void 0&&(se.genTimeMs=V),O!==void 0&&O>0&&(se.promptTokensPerSecond=O),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&&G!==void 0&&(se.generationMs=G/se.generationTokensPerSecond*1e3),se.generationMs!==void 0&&G!==void 0&&(i.generationPhaseMs=(i.generationPhaseMs||0)+se.generationMs,i.generationPhaseTokens=(i.generationPhaseTokens||0)+G);const ke=ss(M.speculation);if(Object.keys(ke).length){const le={};Mn(ke.mode)&&(le.mode=Mn(ke.mode)),typeof ke.used=="boolean"&&(le.used=ke.used),Mn(ke.draft_kind)&&(le.draftKind=Mn(ke.draft_kind));const xe=ya(ke,["accepted_tokens"]),Ee=ya(ke,["drafted_tokens"]),Ve=ya(ke,["rounds"]),_t=ya(ke,["num_draft_tokens"]);xe!==void 0&&(le.acceptedTokens=xe),Ee!==void 0&&(le.draftedTokens=Ee),xe!==void 0&&Ee&&(le.acceptanceRate=xe/Ee),Ve!==void 0&&(le.rounds=Ve),_t!==void 0&&(le.draftLength=_t),se.speculation=le;const Qe=i.speculation||(i.speculation={calls:0,used:0});Qe.calls+=1,le.used&&(Qe.used+=1),le.mode&&(Qe.modes=wd(Qe.modes,le.mode)),le.draftKind&&(Qe.draftKinds=wd(Qe.draftKinds,le.draftKind)),xe!==void 0&&Ee!==void 0&&(Qe.acceptedTokens=(Qe.acceptedTokens||0)+xe,Qe.draftedTokens=(Qe.draftedTokens||0)+Ee),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={}),P=D[C.name]||(D[C.name]={calls:0,failed:0});if(P.calls+=1,S){P.failed+=1;const K=cI(C.output);K&&((P.errors||(P.errors={}))[K]=(((v=P.errors)==null?void 0:v[K])||0)+1)}const R=Date.parse(Mn(C.startedAt)),I=Date.parse(Mn(C.endedAt));if(Number.isFinite(R)&&Number.isFinite(I)&&I>=R){const K=`${C.runId}|${C.startedAt}|${C.endedAt}`,V=x.get(K)||{ms:I-R,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(K,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=HN(C.arguments),G=Mn(W.destination||W.destination_path||W.file_path||W.path||W.filename);G&&r.add(G)}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 P of S){const R=($=i.toolBreakdown)==null?void 0:$[P];R&&(R.sharedBatches=(R.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 dI(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 fI(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 hI=new Set(["blob:","data:","http:","https:"]);function mI(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return hI.has(new URL(t,n).protocol)?t:void 0}catch{return}}function _I(e){const t=typeof e.size=="number"?IN(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 pI(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}=_I(n),c=mI(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 gI(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 yI(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 wI(e){var V,M,A;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,P=async(O,L)=>{var z;if(e.disabled||N.current||$.current)return;const J=k,H=++S.current;N.current=!0,x(null),g(""),d(O);try{const te=await L();if(!C.current||v.current!==J||S.current!==H)return;$.current=!0,m(!0);const B=te&&typeof te=="object"&&typeof te.outcomeNote=="string"?String(te.outcomeNote):"";g(`Response sent. Waiting for the workflow to continue.${B?` ${B}`:""}`)}catch(te){if(!C.current||v.current!==J||S.current!==H)return;x({submission:O,message:_0(te)}),g("The action failed. You can try again."),(z=e.onError)==null||z.call(e,te)}finally{if(!C.current||v.current!==J||S.current!==H)return;N.current=!1,d(null)}},R=async O=>{var J;if(e.disabled||N.current||$.current)return;const L=k;try{if(await O(),!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)}`),(J=e.onError)==null||J.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 I=()=>{y&&P(y.submission,()=>gI(t,y.submission))},W=t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required"),G=(O,L)=>O?s.jsx("button",{type:"button",className:"pc-workflow-interaction__defer","data-decision":"defer",disabled:D,onClick:()=>void R(O),children:L}):null;let K;if(t.kind==="ask-user")K=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(O=>s.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice","data-decision":"choice",disabled:D||O.disabled,onClick:()=>void P({kind:"choice",answer:O.id},()=>t.onSubmit(O.id)),children:[s.jsx("span",{children:O.label}),O.description?s.jsx("small",{children:O.description}):null]},O.id))}):null,t.allowFreeText!==!1?s.jsxs("div",{className:"pc-workflow-interaction__entry",children:[s.jsx("textarea",{"aria-label":"Response",value:r,onChange:O=>i(O.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:n?1:2,disabled:D,onKeyDown:O=>{O.key!=="Enter"||O.shiftKey||O.nativeEvent.isComposing||O.keyCode===229||(O.preventDefault(),r.trim()&&P({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 P({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:[G(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 P({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 O=String(t.disabledReason||"").trim(),L=D||!!O,J=[!O&&t.onApproveForSession&&t.approveForSessionDescription?t.approveForSessionDescription:"",!O&&t.onApproveAll&&t.approveAllDescription?t.approveAllDescription:""].filter(Boolean),H=J.length?String(t.broadScopeSummary||"").trim():"";K=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:[G(t.onDefer,t.deferLabel||Vo.decideLater),s.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:D,onClick:()=>void P({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 P({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:O||t.approveForSessionDescription||void 0,onClick:()=>void P({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:O||t.approveForSessionDescription||void 0,onClick:()=>void P({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:O||t.approveAllDescription||void 0,onClick:()=>void P({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,(M=t.denyOptions)!=null&&M.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 P({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,O&&(t.onApproveAll||t.onApproveForSession||(A=t.approveKinds)!=null&&A.length)?s.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note",children:O}):null,H&&J.length?s.jsxs("details",{className:"pc-workflow-interaction__scope-details","data-scope-details":"",children:[s.jsx("summary",{children:"What the broader choices allow"}),J.map(z=>s.jsx("p",{className:"pc-workflow-interaction__scope",children:z},z))]}):J.map(z=>s.jsx("p",{className:"pc-workflow-interaction__scope",children:z},z))]})}else K=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:O=>c(O.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 P({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]})]}),K,y?s.jsx(yI,{message:y.message,onRetry:I,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 vI(e){var re;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 ge,de;return((de=(ge=e.steer)==null?void 0:ge.modes)==null?void 0:de[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),P=p.useRef(0);p.useEffect(()=>(v.current=!0,()=>{var ge;v.current=!1,S.current+=1,D.current+=1,P.current+=1,N.current=!1,$.current=!1,C.current=!1,(ge=k.current)==null||ge.abort(),k.current=null}),[]);const R=!!e.blockedNotice,I=!!e.disabled||R,W=!!e.busy||t,G=t||!!e.busy&&!e.sendWhileBusy,K=e.stopState||null,V=(K==null?void 0:K.phase)==="stopping",M=e.steer&&typeof e.steer.onSteer=="function"?e.steer:null,A=M?(re=M.modes)!=null&&re.length?M.modes:["guide"]:[],O=A.includes(h)?h:A[0]||"guide",L=!!M&&!!e.busy,J=Array.isArray(e.attachmentItems)?e.attachmentItems:[];p.useEffect(()=>{g(null)},[!!e.busy]);const H=typeof e.onFiles=="function",z=p.useRef(null),[te,B]=p.useState(null),[ne,se]=p.useState(""),ue=p.useRef(e.onFiles);ue.current=e.onFiles;const ve=p.useRef(I);ve.current=I;const Te=async(ge,de)=>{const je=ue.current;if(je){if(ve.current){d({action:"attach",message:"attachments are unavailable right now."});return}if(de.length)d({action:"attach",message:TN(de)});else if(ge.length)d(null);else{d({action:"attach",message:"the drop contained no files."});return}if(ge.length){se(`Attaching ${ge.length} ${ge.length===1?"file":"files"}…`);try{await je(ge)}catch(X){v.current&&d({action:"attach",message:vd(X)})}}}},ke=p.useRef(Te);ke.current=Te,p.useEffect(()=>{if(!H||typeof window>"u")return;const ge=new oL;let de=0;const je=st=>!!(z.current&&st instanceof Node&&z.current.contains(st)),X=()=>{ge.reset(),de&&window.clearInterval(de),de=0,B(null)},Oe=()=>{de||(de=window.setInterval(()=>{ge.active(Date.now())||X()},250))},pt=st=>{var mn;if(!Uh((mn=st.dataTransfer)==null?void 0:mn.types))return;ge.enter(Date.now());const Pt=je(st.target),Lt=i0(st.dataTransfer);B(wn=>wn&&wn.over===Pt&&wn.count===(Lt??wn.count)?wn:{count:Lt??(wn==null?void 0:wn.count)??null,over:Pt}),Oe()},at=st=>{var Lt;if(!Uh((Lt=st.dataTransfer)==null?void 0:Lt.types))return;st.preventDefault(),ge.over(Date.now());const Pt=je(st.target);st.dataTransfer&&(st.dataTransfer.dropEffect=Pt&&!ve.current?"copy":"none"),B(mn=>mn&&mn.over===Pt?mn:{count:(mn==null?void 0:mn.count)??i0(st.dataTransfer),over:Pt}),Oe()},Et=st=>{var Pt;Uh((Pt=st.dataTransfer)==null?void 0:Pt.types)&&(ge.leave(Date.now())||X())},yt=st=>{var On;if(!Uh((On=st.dataTransfer)==null?void 0:On.types))return;const Pt=je(st.target),Lt=st.defaultPrevented&&!Pt;if(st.preventDefault(),X(),Lt)return;if(!Pt){d({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:mn,folders:wn}=mx(st.dataTransfer);ke.current(mn,wn)},jt=st=>{st.key==="Escape"&&ge.depth>0&&X()};return window.addEventListener("dragenter",pt),window.addEventListener("dragover",at),window.addEventListener("dragleave",Et),window.addEventListener("drop",yt),window.addEventListener("dragend",X),window.addEventListener("blur",X),window.addEventListener("keydown",jt),()=>{window.removeEventListener("dragenter",pt),window.removeEventListener("dragover",at),window.removeEventListener("dragleave",Et),window.removeEventListener("drop",yt),window.removeEventListener("dragend",X),window.removeEventListener("blur",X),window.removeEventListener("keydown",jt),de&&window.clearInterval(de)}},[H]);const le=ge=>{if(!H||I)return;const de=MN(ge.clipboardData);de.length&&(ge.preventDefault(),Te(de,[]))},xe=te?s.jsxs("div",{className:["pc-workflow-chat__dropzone",te.over?"is-over":"",I?"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:I?"Attachments are unavailable right now":o0(te.count)}),I?null:s.jsx("span",{children:te.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,Ee=te?I?"Attachments are unavailable right now":o0(te.count):ne,Ve=async ge=>{if(!M)return;const de=O,je=++S.current;N.current=!0,d(null),g(null),n(!0);try{const X=await M.onSteer(ge,de);if(!v.current||S.current!==je)return;if(!(X!=null&&X.accepted)&&!(X!=null&&X.duplicate)){d({action:"steer",message:"the gateway did not accept this message (accepted=false)."});return}g({mode:de,...typeof X.seq=="number"?{seq:X.seq}:{},duplicate:!!X.duplicate}),e.onDraftChange("")}catch(X){v.current&&S.current===je&&d({action:"steer",message:vd(X)})}finally{v.current&&S.current===je&&(N.current=!1,n(!1))}},_t=async()=>{const ge=String(e.draft||"");if(I||N.current||!ge.trim())return;if(L)return void Ve(ge);if(!e.sendWhileBusy&&e.busy)return;const de=J.length?fI(J):null;if(de){d({action:"send",message:de});return}const je=++S.current,X=new AbortController;k.current=X,N.current=!0,d(null),g(null),n(!0);try{await e.onSend(ge,{signal:X.signal})}catch(Oe){v.current&&S.current===je&&!X.signal.aborted&&d({action:"send",message:vd(Oe)})}finally{k.current===X&&(k.current=null),v.current&&S.current===je&&(N.current=!1,n(!1))}},Qe=async()=>{if(I||$.current||!e.onCancel)return;const ge=++D.current;$.current=!0,d(null),i(!0);const je=k.current||new AbortController;je.abort(new DOMException("Stopped by the user","AbortError"));try{await e.onCancel(je.signal)}catch(X){v.current&&D.current===ge&&d({action:"cancel",message:vd(X)})}finally{v.current&&D.current===ge&&($.current=!1,i(!1))}},ot=async()=>{if(I||C.current||!e.onAttach)return;const ge=++P.current;C.current=!0,d(null),c(!0);try{await e.onAttach()}catch(de){v.current&&P.current===ge&&d({action:"attach",message:vd(de)})}finally{v.current&&P.current===ge&&(C.current=!1,c(!1))}},ze=()=>{l&&((l.action==="send"||l.action==="steer")&&_t(),l.action==="cancel"&&Qe(),l.action==="attach"&&ot())},He=e.toolbar||null,ft=ge=>dN((Array.isArray(e.messages)?e.messages:[]).filter(de=>!de.toolActivity&&!de.live&&String(de.content||"").trim()),ge?{heading:ge}:void 0),et=async ge=>{if(!I){d(null);try{await ge()}catch(de){v.current&&d({action:"toolbar",message:vd(de)})}}},Ot=async()=>{const ge=await il(ft());v.current&&(x(ge?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>v.current&&x("idle"),1200))},Ne=He?s.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[He.onNewSession?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:I,onClick:()=>void et(He.onNewSession),children:[s.jsx(qe,{name:"plus",size:14}),s.jsx("span",{children:"New chat"})]}):null,He.onClear?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:I,onClick:()=>void et(He.onClear),children:[s.jsx(qe,{name:"trash",size:14}),s.jsx("span",{children:"Clear"})]}):null,He.copyTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"copy",onClick:()=>void Ot(),children:[s.jsx(qe,{name:y==="copied"?"check":"copy",size:14}),s.jsx("span",{children:y==="copied"?"Copied":y==="failed"?"Copy failed":"Copy"})]}):null,He.exportTranscript?s.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const ge=He.exportTranscript;fN({filename:ge.filename,text:ft(ge.heading),mime:"text/markdown;charset=utf-8"})},children:[s.jsx(qe,{name:"download",size:14}),s.jsx("span",{children:"Export"})]}):null]}):null,Re=O==="queue"?"Queue":"Steer",tt=_?_.mode==="queue"?`Queued for the next turn${typeof _.seq=="number"?` (seq ${_.seq})`:""}.`:`${_.duplicate?"Already queued":"Queued"}${typeof _.seq=="number"?` (seq ${_.seq})`:""}. ${M!=null&&M.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",te?"pc-workflow-chat--dragging":"",te!=null&&te.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||Ne?s.jsxs("header",{className:["pc-workflow-chat__header",Ne?"pc-workflow-chat__header--toolbar":""].filter(Boolean).join(" "),children:[e.header?s.jsx("div",{className:"pc-workflow-chat__header-main",children:e.header}):null,Ne]}):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(wI,{interaction:e.interaction,disabled:I}):null,R?s.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${R?"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"?O==="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:ze,disabled:I,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:I,busy:L?t:G,sendLabel:L?Re:e.sendLabel,busyLabel:L?O==="queue"?"Queueing…":"Steering…":e.busyLabel,rows:2,leading:e.attachments||J.length?s.jsxs("div",{className:"pc-workflow-chat__attachments",children:[J.length?s.jsx(pI,{items:J,onRemove:e.onRemoveAttachment,onRetry:e.onRetryAttachment,disabled:I}):null,e.attachments]}):null,overlay:xe,onPaste:H?le: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:I||o,onClick:()=>void ot(),children:[s.jsx(qe,{name:"paperclip",size:16}),s.jsx("span",{children:o?"Attaching…":"Attach"})]}):null,e.composerExtras,L&&A.length>1?s.jsx("span",{className:"pc-workflow-chat__steer-modes",role:"group","aria-label":"While the run is busy",children:A.map(ge=>s.jsx("button",{type:"button",className:"pc-workflow-chat__steer-mode","data-steer-mode":ge,"aria-pressed":O===ge,disabled:I||t,onClick:()=>m(ge),children:ge==="queue"?"Queue next turn":"Guide this run"},ge))}):null,W&&e.onCancel?s.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:I||r||V,onClick:()=>void Qe(),children:[s.jsx(qe,{name:"x",size:14}),s.jsx("span",{children:r||V?"Stopping…":"Stop"})]}):K?s.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${K.phase}`,role:"status","aria-live":"polite",children:K.label}):null]})}),M?s.jsx("div",{className:"pc-workflow-chat__steer-status",role:"status","aria-live":"polite",children:tt}):null,H?s.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:Ee}):null]}),e.footer?s.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function xI(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 bI(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 $t(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 kI(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 $t(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 jI(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=$t(e[r]);if(i)return i}const t=Jt(e.context);for(const r of["task","message"]){const i=$t(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($t(i==null?void 0:i.role).toLowerCase()!=="user")continue;const o=$t(i==null?void 0:i.content);if(o)return o}return""}function GN(e){const t=Jt(e.result);return Jt(t==null?void 0:t.wait)}function Fy(e){return e?$t(e.reason)==="subworkflow"||$t(e.wait_key).startsWith("subworkflow:"):!1}function g0(e,t){return!!(e&&e.runId===t.runId&&$t(e.wait.wait_key)===$t(t.wait.wait_key))}function nv(e){return Jt(e.effect)||{}}function SI(e,t){return $t(e.run_id)||t}function y0(e){return $t(e.ended_at)||$t(e.started_at)||void 0}function w0(e){const t=new Set,n=h=>{const m=$t(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);$t(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=GN(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=$t(c==null?void 0:c.wait_key);return d.startsWith("subworkflow:")&&n(d.slice(12)),[...t]}const zy=new WeakMap,NI=/^(live|live-end|stream-unavailable):/;function $I(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 CI{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=$t(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?"":$t(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=$t((r=this.snapshot.run)==null?void 0:r.session_id)||$t((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(kI(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||$t(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=>$t(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=$t(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=$t(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($t(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||$t(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:$t(r.wait.wait_key),payload:{response:t}})}answerEvent(t,n){const r=this.requireInteraction();if(n&&(r.runId!==n.runId||$t(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:$t(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||$t(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:$t(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}:${$t(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}:${$t(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:!!$t(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=$t((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:$t(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(!$t(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(!$I(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 JL;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,$t(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(P=>l.turns.get(P)||C.get(P)).filter(P=>!!P);this.viewEarlier={messages:[...S,...D.flatMap(P=>P.messages)],tools:D.flatMap(P=>P.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 $=$t((N=this.viewRun)==null?void 0:N.created_at),C=$?l.order.filter(P=>l.turns.has(P)&&l.created.has(P)&&l.created.get(P)<$):[];C.length&&(d(C),this.adoptView());let S;try{S=await o.listSessionTurns(t,{signal:i})}catch(P){if(!this.live(r))return;if(_o(P))throw this.viewTurnCache=jh(),P;d(C,new Map,[c(`history:${n}:unlisted`,`Earlier turns of this conversation could not be listed: ${P instanceof Error?P.message:String(P)}`)]),this.adoptView();return}if(!this.live(r))return;_=S.length>Tp,_&&(S=S.slice(S.length-Tp));for(const P of S)P.created_at&&l.created.set(P.run_id,P.created_at);l.order=S.map(P=>P.run_id);const D=l.order.indexOf(t);m=D>=0?l.order.slice(0,D):l.order.filter(P=>P!==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=>NI.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&&$t(l.wait.wait_key)===$t(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=$t(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=$t(t.run_id)||n,o=Jt(t.input_data)||Jt(t.input)||{},c=$t(t.prompt)||p0(o);c&&this.addMessage({id:`turn:${i}:user`,role:"user",content:c,ts:$t(t.created_at)||void 0});const l=this.historicalRunFailures.get(i);if(l){const _=$t(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?$t(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:$t(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const i=[...new Set(t.map(d=>$t(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(dI(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=jI(g)===404;this.historicalRuns.set(_,null),this.historicalRunFailures.set(_,{missing:y,detail:g instanceof Error?g.message:$t((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=SI(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=$t(i.type).toLowerCase(),c=Jt(n.result),l=$t(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=$t(y.name)||$t(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 $=$t((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=UR(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=GN(n);if(l==="waiting"&&h&&!os(this.snapshot.status)&&!os(bi(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${$t(h.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:h,...$t(n.step_id)?{stepId:$t(n.step_id)}:{}})})),o==="tool_calls")for(const y of VN(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=$t((_=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=$t(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=$t(c.name)||$t(l==null?void 0:l.name),h=Jt(c.payload!==void 0?c.payload:l==null?void 0:l.payload);d==="abstract.status"&&$t(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:$t(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=$t(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 qN(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=LN(n)}catch(d){this.fail(d,!1);return}const i=`${r.run_id}:${r.call_id}`;if(RN(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:dL(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:$t((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 EI(e){const t=p.useMemo(()=>new CI(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 AI(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 KN(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function TI(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?KN(t,n,i):null}function MI(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=AI(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 $=KN(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=>TI(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 JN(e){return s.jsx(vN,{text:e,images:"link"})}const RI={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:RI[e.kind],runId:e.runId},images:"link"})}function LI(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function II(e,t,n={}){var h;if(!e)return null;const r=LI(e)?WN(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(P=>String((P==null?void 0:P.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 P;await t.approveWithPolicyChange(_,()=>{P=x()}),P&&await P.catch(R=>{throw new Error(`This batch was allowed, but "Allow for this chat" could not be turned on: ${R instanceof Error?R.message:String(R)}`)})}}:{};let C=$,S=[];const D=n.sessionPolicy;if(D){const P=t.approveAllForSession,R=t.approveKindForSession,I=t.denyToolForSession,W=t.denyKindForSession,G=t.sessionPolicyStatus;if(typeof P!="function"||typeof R!="function"||typeof I!="function"||typeof W!="function"||typeof G!="function")throw new Error("presentInteraction: sessionPolicy needs a WorkflowSessionController (approveAllForSession, approveKindForSession, denyToolForSession, denyKindForSession, sessionPolicyStatus).");const K=G.call(t),V=D.ask?[...D.ask]:void 0,M=(J,H)=>{var te;const z=String(((te=J==null?void 0:J.scope)==null?void 0:te[H])||"").trim();return z?`Applies: ${z}`:N.noScopeNote},A=J=>({outcomeNote:[r0(J==null?void 0:J.clamped),M(J,"approve")].filter(Boolean).join(" ")}),O=J=>({outcomeNote:`${N.denyForChatNote} ${M(J,"deny")}`}),L=r0(K.clamped);if(K.mode==="unavailable")C={scopeNote:N.unavailablePolicyNote(K.reason||"")};else if(K.mode==="gateway"){const J=[...new Set(m.map(B=>{var ne;return String((B==null?void 0:B.toolset)||"").trim()||String(((ne=D.toolsetOf)==null?void 0:ne.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.",te=K.policy;S=te?g.filter(B=>Object.prototype.hasOwnProperty.call(te.deny||{},B)):[],C={approveForSessionLabel:N.allowForChat,approveForSessionDescription:J.length?`Each of ${(()=>{const B=[`“${N.allowForChat}” (every tool)`,...J.map(ne=>`“${N.allowKindForChat(ne)}” (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()=>A(await P.call(t,_,{...D.maxRiskRank!==void 0?{maxRiskRank:D.maxRiskRank}:{},...V?{ask:V}:{}})),approveKinds:J.map(B=>({kind:B,label:N.allowKindForChat(B),onApprove:async()=>A(await R.call(t,_,B,V?{ask:V}:{}))})),denyOptions:[...g.map(B=>({key:`tool:${B}`,label:N.denyToolForChat(B),onDeny:async()=>O(await I.call(t,_,B,V?{ask:V}:{}))})),...J.map(B=>({key:`kind:${B}`,label:N.denyKindForChat(B),onDeny:async()=>O(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.`}:{},...te?{policySummary:`This chat's policy: ${Object.keys(te.approve||{}).length} tools allowed without asking, ${Object.keys(te.deny||{}).length} denied. ${M(te,"approve")}`}:{},...L?{notCovered:L}:{}}}else C=x?{...$,scopeNote:N.localChatPolicyNote}:{approveForSessionLabel:N.allowForRun,onApproveForSession:async()=>{await P.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(EN,{tools:m.map((P,R)=>({id:String((P==null?void 0:P.call_id)||(P==null?void 0:P.id)||R),runId:r.runId,name:(P==null?void 0:P.name)||"Tool",arguments:P==null?void 0:P.arguments,status:"waiting"}))}),s.jsxs("details",{children:[s.jsx("summary",{children:"Review full tool arguments (JSON)"}),s.jsx(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 _=MI(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 OI={app:"observer",name:"AbstractObserver"},PI=["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 DI(e){const t=p.useRef(e.gateway);t.current=e.gateway;const n=(r,i)=>t.current.fetch_gateway(r,i);return s.jsx(WL,{open:e.open,onClose:e.onClose,source:OI,fetchGateway:n,connected:e.connected,topOffset:e.topOffset,placeholder:"Ask about the observer…",suggestions:PI})}function FI(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 zI(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 BI(e,t,n){return e<=0?-1:t<0?n?e-1:0:(t+(n?e-1:1))%e}const UI='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function WI(e){return typeof document>"u"?!1:Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"]')).some(t=>t!==e)}function qI(e){const[t,n]=p.useReducer(FI,!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:WI(i.current)});return}if(m.key!=="Tab"||!i.current)return;const _=Array.from(i.current.querySelectorAll(UI)).filter(y=>y.offsetParent!==null||y===document.activeElement),g=BI(_.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:zI(e.is_drawer,t)}}function VI(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 HI(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 GI(e){const t=HI(e.history);return t?s.jsx(dx,{message:{role:"system",level:"info",title:"History",content:t}}):null}const KI="api/local/reveal",JI="sw.js",sv="#run/";function YI(e){return`${sv}${encodeURIComponent(String(e||"").trim())}`}function YN(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 XI(e){return`Run ${e} cannot be opened: it does not exist on this gateway, or your account cannot see it.`}function ZI(e){const t=YN(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 QI={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"},eO=new Set(["wait","resume","memory","model","node"]),tO=new Set(["abstract.status","abstract.progress","abstract.steer_seen","abstract.summary"]),nO={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 sO(e){const t=String(e||"").trim();return t?QI[t]||"other":"node"}function rO(e,t,n){return n?!1:e==="event"?tO.has(String(t||"").trim()):eO.has(e)}const iO=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 oO(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+iO[N]+l[N]>>>0,D=(h>>>2|h<<30)^(h>>>13|h<<19)^(h>>>22|h<<10),P=h&m^h&_^m&_,R=D+P>>>0;v=k,k=x,x=y,y=g+S>>>0,g=_,_=m,m=h,h=S+R>>>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 aO(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e[rv]&&typeof e[rv]=="object")}function lO(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 cO(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 uO(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)?cO(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 oO(JSON.stringify(i))!==String(n.sha256||"")?{state:"unverified",value:i,reason:"checksum differs from the record"}:{state:"resolved",value:i}}function dO(e,t){const n=[],r=[],i=(o,c,l)=>{if(l>14)return o;if(aO(o)){const d=uO(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 XN(e){const t=e==null?void 0:e.result;return t&&typeof t=="object"&&Array.isArray(t.results)?t.results:[]}function fO(e,t){return e?String(e.status||"")==="failed"||e.error?!0:t==="tool"&&XN(e).some(n=>n&&n.success===!1):!1}function hO(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=lO(r.map(k=>k.record)),o=new Map,c=[];for(const k of r){const v=k.record,$=hO(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=dO(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=sO(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 P=fO($,S),R=String(((x=v.started)==null?void 0:x.started_at)||($==null?void 0:$.started_at)||""),I=String(($==null?void 0:$.ended_at)||""),W=k0(R),G=k0(I);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:R,ended_at:I,duration_ms:W!==null&&G!==null?Math.max(0,G-W):null,started:v.started,record:$,failed:P,housekeeping:rO(S,D,P),cycle:l,unresolved:N.unresolved,unverified:N.unverified})}return d}function mO(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 _O={view:"cycles",only:"all",all_steps:!1,q:""};function pO(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 gO=["all","llm","tools","failed"];function j0(e){const t=String(e||""),n=t.indexOf("?");if(n<0)return{..._O};const r=new URLSearchParams(t.slice(n+1)),i=String(r.get("only")||"");return{view:r.get("view")==="steps"?"steps":"cycles",only:gO.includes(i)?i:"all",all_steps:r.get("all")==="1",q:String(r.get("q")||"")}}function yO(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 ZN(e){if(typeof e!="string")return e??{};try{return JSON.parse(e)}catch{return e}}function QN(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:ZN(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=QN(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 wO={"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 P=wO[D.path];P&&o.push(`${P}: ${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 P=D.function&&typeof D.function=="object"?D.function:D;return{name:String(P.name||"?"),description:String(P.description||""),schema:P.parameters??P.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:QN(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:ZN((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=XN(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 vO(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 e1(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}(${vO(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 t1(e){return e.kind==="llm_call"?Cm(e).model:""}function xO(e,t){var r,i;const n=[e.kind,e.effect_type,e.event_name,e.node_id,t,e.status,e1(e),t1(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 bO(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 kO(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 on(){return new Date().toISOString()}function jO(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 SO(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?"—":SO(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 NO(...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 $O(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($O(e));return Math.max(0,(r!==null?r:t)-n)}function yu(e,t=Date.now()){return bu(Tm(e,t))}function CO(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 EO={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 AO(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 TO(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(jN,{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 MO(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 RO(e){const t=e.step,n=e1(t),r=t1(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:nO[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(AO,{step:t,on_copy:e.on_copy}):t.kind==="tool"?s.jsx(TO,{step:t,on_copy:e.on_copy}):s.jsx(MO,{step:t,on_copy:e.on_copy,on_open_run:e.on_open_run})}):null]})}function LO(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=pO(n,t,x=>{let k=c.get(x.id);return k===void 0&&(k=xO(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(RO,{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:EO[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?mO(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 IO(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 OO=new Set;function PO(e){if(!(e.connections===Rp.connections&&e.mailboxes===Rp.mailboxes)){Rp={connections:e.connections,mailboxes:e.mailboxes};for(const t of OO)t()}}function DO(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 FO(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&&FO(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 zO(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 BO="@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 UO(e,t){return e==="@default"?{kind:"default",interface:Ud}:t?{kind:"bundle",bundle_id:t.bundleId,flow_id:t.flowId}:null}function WO(e){return e?e.kind==="default"?`${BO}${e.interface}`:`${e.bundle_id}:${e.flow_id}`:""}function qO(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 VO(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 HO={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 GO(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 KO="#launch/automate";function JO(e){const t=YN(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:KS,email:CS,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."},n1=["use_context"],YO="This choice also tells the flow whether to read the earlier runs.",s1=["event"];function XO(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 r1(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 ZO(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function QO(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||{}))ZO(_)&&(c[m]=_);return{form:o,input_data:c}}function e3(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 i1(e){return[...e||[]].filter(t=>t.configured!==!1&&t.can_read!==!1).sort((t,n)=>Number(n.primary)-Number(t.primary))}function t3(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 n3(e,t){const n=[];for(const r of i1(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=xS(r.label||"a connection",r.source_id),o=t3(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 s3(e,t){if(e.when==="defaults")return t&&t.trigger.source_id==="schedule"?r1(t):null;if(e.when==="email"||e.when==="connection"||e.when==="manual")return null;const n=gx(e,"preview");return lT(n.when)?VS(n).trigger:null}function r3(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?i1(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=VO(t.input_data),c=typeof o.prompt=="string"?o.prompt:"";delete o.prompt;for(const g of n1)delete o[g];for(const g of s1)delete o[g];delete o.workspace_root;let l;try{l=qO(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=HS(h,{target:l,requestId:t.request_id});if(!m.ok)return m;const _=m.body;return e.when==="defaults"&&t.defaults?_.trigger=r1(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 i3(e,t=!1){if(e.when==="email"){if(!t)return"";const n=HS(gx(e,"preview",!0),{target:{flow_id:"@default",interface:Ud},requestId:"preview"});return n.ok?`Runs ${AS(n.body.trigger.config)}.`:""}return""}class o3{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 a3(e,t,n){const r=r3(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 l3(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 o1(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 c3(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 a1(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":LS(e,t),listening:l,current:RS(e),state:e.status,last:i?i.excerpt:"",last_status:i?`${d?`last: ${d} · `:""}#${i.index} ${i.status}${o}`:"no runs yet",attention:c?IS(e):null,legacy:r}}function l1(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 u3(e,t){const n=em(e,[],t),r=l1(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 d3(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 f3(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 h3=/^([1-9][0-9]*)([smhd])$/;function m3(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 _3(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=h3.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=m3(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 p3={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 g3(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 y3(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 w3=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 v3{constructor(t,n,r=[1500,4e3]){jn(this,"state",{...p3});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=zO(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;PO({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,y3(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"):`${x3[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=f3(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 x3={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 b3(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 k3(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:HO[e.mode]})]})}function j3(e){var h,m;const t=e.form,n=Tg(e.email_status),r=n3(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=i3(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:b3(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(UT,{value:t.email,onChange:_=>e.on_change({email:_}),disabled:e.disabled,idBase:"automate"}):o==="daily"||o==="weekly"||o==="monthly"?s.jsx(JS,{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:rT.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:YO})]}),s.jsxs("fieldset",{"data-section":"tools",children:[s.jsx("legend",{children:"Tools"}),e.available_tools&&e.on_tools_change?s.jsx(XS,{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"})})," ",cT,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(rN,{status:e.email_status,onOpenMyEmail:e.on_open_my_email}),s.jsx(WT,{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 S3(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 N3(e,t){const n=String(t||"").trim();return n||`Loading ${String(e||"").trim()||"data"}…`}function ol(e){const t=N3(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 $3={console:"Console",tray:"Tray",watch:"Watch",phone:"Phone",email:"Email",assistant:"Assistant",code:"Code"};function C3(e){switch(e){case"empty title":return"Nothing to notify: the title was empty.";case"no notify":return"Nothing to notify: this flow has no 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 E3(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 A3(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 T3(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 M3(e){const t=$3[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 R3=3e3,L3=5;function I3(e,t){return t>L3?!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 O3(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(P3,{after:t.after})]})}function P3(e){const t=e.after,n=E3(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:A3(i)}),s.jsxs("span",{className:"muted",children:[" ","· ",T3(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:[M3(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:C3(t.quiet_reason)})})]})}const D3=[1e3,3e3];async function F3(e,t=D3){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 z3(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 F3(()=>n(t));if(!h)return;i({status:"ready",after:g}),I3(g,m)&&(l.current=setTimeout(_,R3))}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(O3,{state:r})}function Zs(){return nl()}const c1=Sg("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).",u1="Copy failed — select and copy";function d1(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function B3(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 B3(t)}const U3=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 W3(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+$+U3[v]+o[v]>>>0,S=c(d,2)^c(d,13)^c(d,22),D=d&h^d&m^h&m,P=S+D>>>0;k=x,x=y,y=g,g=_+C>>>0,_=m,m=h,h=d,d=C+P>>>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 q3(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 W3(t)}const V3=/^[a-zA-Z0-9_-]+$/;function D0(e){return V3.test(String(e||"").trim())}async function H3(e){const t=String(e||"");return q3(t)}async function G3(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 H3(t)).slice(0,32)}`}const f1="abstractobserver_voice";function K3(){var e;try{const t=(e=globalThis.localStorage)==null?void 0:e.getItem(f1),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}const ov=new Set;function J3(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(f1,JSON.stringify(e||{}))}catch{}for(const n of ov)n(e||{})}function h1(){const[e,t]=p.useState(()=>K3());return p.useEffect(()=>(ov.add(t),()=>{ov.delete(t)}),[]),[e,J3]}function m1(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 Y3(e){if(e)return{design:t=>e.voice_design(t),clone:(t,n)=>e.voice_clone(t,n)}}function X3(e){const t=e.gateway;return s.jsx(cR,{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:Y3(t),unavailableReason:e.connected&&t?null:"Connect to a gateway to configure voice."})}const Z3=18e4;function Q3(e,t,n,r=()=>{}){return async function*(i,o){r(),yield*H2({path:e.gateway_url(vt(`runs/${encodeURIComponent(t)}/voice/tts/stream`)),headers:e.auth_headers(),signal:o,body:{text:i,request_id:Zs(),...nR(n())}})}}function eP(e,t,n,r,i=()=>{},o=Z3){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(),...sR(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 _1(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 G3(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=eA({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:_?Q3(t,i,()=>d.current,m):void 0,transcribe:_?eP(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 p1(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 tP(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 nP=350;function g1(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<nP){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=tP(!!l),h=U2(e.prefs,e.defaults),m=t.voice_ptt_recording?`Recording… ${l?aS(l,d):""}`.trim():t.voice_ptt_busy?W2(l||d,d,h):"",g=!d1()?c1: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 sP(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 rP="abstractobserver";function iP(e){return{replayView:ZL({fetch:(t,n)=>e.fetch_gateway(vt(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 oP(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 aP=new Set(["completed","failed","cancelled"]);function lP(e){var G;const{gateway:t,discussion:n}=e,r=p.useMemo(()=>iP(t),[t]),[i,o]=p.useState(((G=n.session)==null?void 0:G.run_id)||""),[c,l]=p.useState(""),[d,h]=p.useState(!1),[m,_]=p.useState(""),{controller:g,snapshot:y}=EI({transport:r,runId:i,enabled:e.connected,clientId:rP}),x=n.session,k=!!i&&!aP.has(y.status)&&y.status!=="idle",v=bI(y),[N]=h1(),$=m1(e.connected?t:null,e.connected),[C,S]=p.useState(""),D=_1({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:K=>l(V=>V.trim()?`${V.trimEnd()}
|
|
96
|
+
${K}`:K)}),P=p.useMemo(()=>{for(let K=y.messages.length-1;K>=0;K-=1){const V=y.messages[K];if(V.role==="assistant")return V.live?null:{key:String(V.id||""),text:String(V.content||"")}}return null},[y.messages]);p1(D,N.read_aloud===!0,P);const R=K=>D.tts_playback.key&&D.tts_playback.key===String(K.id||"")?D.tts_playback.status:"idle",I=async K=>{var M;const V=K.trim();if(V){h(!0);try{if(x){const A=String(((M=y.run)==null?void 0:M.workflow_id)||""),O=oP(A),L=await t.start_run(O.flow_id,{prompt:V},{bundle_id:O.bundle_id,session_id:x.session_id});o(L)}else{const A=await e.on_fork(n.automation_id,n.occurrence_index,V);o(A.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(PN,{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(vI,{header:W,messages:y.messages,draft:c,onDraftChange:l,onSend:I,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:II(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(g1,{voice:D,defaults:$.value,prefs:N,blocked:e.connected?null:"Connect to the gateway first.",error:C}),messageProps:D.tts_supported?{onSpeakToggle:K=>{S(""),D.toggle_tts(String(K.id||""),String(K.content||""))},getSpeakState:R}: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:xI(y)}):null]})})]})}const cP=qn.title;function F0(e){return`${cP}: ${e}`}const uP=["workspace_access_mode","workspace_allowed_paths"];function dP(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function fP(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 dP(t)?t:null}function y1(e,t){const n={...e||{}};for(const r of uP)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 hP(e,t){const n=e.target;return{target:{bundle_ref:n.bundle_ref,flow_id:n.flow_id,input_data:y1(n.input_data,t)}}}const mP=3e4,av=new WeakMap;function _P(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<mP)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 pP(e){av.delete(e)}function gP(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 _P(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 yP(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),pP(n)},[n,h]),_=t?e.disabled?"Saving…":null:"Connect to your gateway to choose workspaces.";return s.jsx(cN,{level:"run",idPrefix:e.id_prefix,value:r,effective:i,onChange:m,loadError:t?c:_,unavailableReason:_,footer:e.footer})}class wP{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:y1(n.target.input_data,r)}}}}async function vP(e,t,n,r,i){const o=t.expected(n.automation_id,n.summary.revision);await e.revise(n.automation_id,hP(n.definition,r),o,i),t.record(n.automation_id,o,r)}function w1(e){return`abstractobserver_list_open_${e}`}function v1(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function xP(e,t=v1()){try{return(t==null?void 0:t.getItem(w1(e)))!=="0"}catch{return!0}}function bP(e,t,n=v1()){try{n==null||n.setItem(w1(e),t?"1":"0")}catch{}}function ng(e){const[t,n]=p.useState(()=>xP(e)),r=p.useCallback(()=>{n(i=>{const o=!i;return bP(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 kP=5e3,jP=[["","All"],["active","Active"],["paused","Paused"],["completed","Completed"],["failed","Failed"],["archived","Archived"]],SP={pause:wa.pause,resume:wa.resume,run_now:wa.run_now,edit:wa.revise,archive:`${wa.archive}…`,discuss:wa.discuss},NP={pause:Go.pause,resume:Go.resume,run_now:Go.run_now,edit:Go.revise,archive:Go.archive,discuss:Go.discuss},$P={pause:"pause",resume:"resume",run_now:"run_now",edit:"revise",archive:"archive",discuss:"discuss"},CP={legacy_pause:Go.pause,legacy_resume:Go.resume,legacy_run_now:Go.run_now,open_run:"list",recreate:"refresh"};function EP(e){return s.jsx("span",{className:"auto_state","data-field":"state",children:s.jsx(iN,{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 AP={legacy_pause:"Suspend",legacy_resume:"Resume",legacy_run_now:"Run now",open_run:"Open run",recreate:"Recreate as automation"},TP="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 MP(e){const t=e.summary,n=a1(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=d3(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:TP,onChange:()=>e.h.on_legacy_action(t,h)},"active"),...m.map(_=>o(_,AP[_],d[_],()=>e.h.on_legacy_action(t,_),void 0,CP[_]))]}else{const d=u3(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(_,SP[_],d[_],()=>e.h.on_row_action(t,_),_==="archive"?"danger auto_action_end":void 0,NP[_],_==="archive",Jp($P[_],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(EP,{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:JN(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 RP(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:jP.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:KO,"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(MP,{summary:o,state:t,h:e.h},o.automation_id))})]})]})}function LP(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 IP(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 OP(e){const{fetchGateway:t,messageProps:n,readRunAfter:r,...i}=e,o=i.onOpenResource??(t?l=>SL(t,l.url,{name:l.name}):void 0),c=l=>l.kind==="answer"&&r?s.jsxs(s.Fragment,{children:[b0(l,n),s.jsx(z3,{run_id:l.runId,read:r})]}):b0(l,n);return s.jsx(cM,{...i,onOpenResource:o,renderText:JN,renderTurn:c})}function PP(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=a1(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=LP(e.ctl,e.host,e.edit,n==null?void 0:n.revisions),i=e.ctl,o=t.definition,c=fP(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(yP,{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=>vP(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(gP,{request:n.request,connected:n.connected,value:c,refresh_key:t.summary.revision??""})]})}):null,r?s.jsx(OP,{...r,readRunAfter:e.host.read_run_after,workflowName:IP(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 DP(e,t){if(t==="edit")return{kind:"edit"};if(t!=="discuss")return{kind:"forward"};const n=l1(e);return n===null?{kind:"none"}:{kind:"discuss",index:n}}function FP(e){const t=e.ctl,n=p.useRef(null);n.current||(n.current=new wP);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(),w3);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(),kP);return()=>window.clearTimeout(S)},[t,v]);const N=Ce.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,P)=>{e.host.on_open_session(S,D,P),k&&d({automation_id:k.automation_id,automation_title:k.summary.title,occurrence_index:P,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 P=DP(S,D);P.kind==="forward"?e.h.on_row_action(S,D):P.kind==="edit"?(l(null),m(""),g(S.automation_id),e.h.on_select(S.automation_id)):P.kind==="discuss"&&(e.h.on_select(S.automation_id),d({automation_id:S.automation_id,automation_title:S.title,occurrence_index:P.index}))}};return s.jsxs("div",{className:`page auto_page${i?"":" list_collapsed"}`,children:[s.jsx(RP,{state:t.state,available:e.available,h:C,list:{open:i,on_toggle:o},ws:r}),c?s.jsx(lP,{gateway:e.gateway,discussion:c,connected:e.active,voice_session_id:e.voice_session_id||"",on_fork:async(S,D,P)=>{const R=await t.discuss(S,D,P);return e.host.on_open_session(R,yx(D),D),l(I=>I&&{...I,session:R}),R},on_close:()=>l(null)},c.opened):s.jsx(PP,{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(PN,{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 zP(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 BP(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 UP="On: the schedule runs at its times. Off: suspended, scheduled runs are skipped until it is on again.";function WP(e){return s.jsx(Fi,{variant:"sm",action:"schedule-active",className:"observe_schedule_switch",label:"Active",hint:UP,checked:e.active,unavailableReason:e.unavailableReason,busy:e.busy,onChange:e.onChange})}function qP(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 VP(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 HP(){const e="0.10.1".trim();if(!e)throw new Error("AbstractObserver: __APP_VERSION__ is not defined; the vite/vitest config must inject it from package.json");return e}function GP(){return k2("abstractobserver",HP())}async function KP(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 JP(e){try{return new URL(String(e)),!0}catch{return!1}}function YP({baseUrl:e,endpoint:t}){const n=String(t||"api/gateway/host/metrics/gpu");return JP(n)?n:e&&String(e).trim()?new URL(n,String(e)).toString():n}async function XP({token:e,getToken:t}){if(typeof t=="function"){const n=await t();return n==null?"":String(n)}return e==null?"":String(e)}function ZP({token:e}){const t=String(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}function QP(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 e4({baseUrl:e,endpoint:t,token:n,getToken:r,signal:i,fetchImpl:o}={}){const c=YP({baseUrl:e,endpoint:t}),l=await XP({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",...ZP({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 t4(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 n4(){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 s4{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=n4();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:t4(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 e4({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=QP(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 r4(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 s4(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 i4(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 o4(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 a4(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 x1(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 b1(o)}function l4(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 c4(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 u4(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:b1(e)}function b1(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 d4(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 f4(e,t){var h;const n=String(t||""),r=i4(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||d4(n)||c4(i)||u4(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=o4(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")||x1(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")||a4(t)?"html":x1(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":f4(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 h4=/^\s*<runtime_metadata>\s*([\s\S]*?)\s*<\/runtime_metadata>\s*/i;function vx(e){const t=typeof e=="string"?e:String(e??""),n=h4.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 k1(...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 j1(e){const t=vx(lv(e));return{text:t.text,runtime_metadata:t.metadata}}function m4(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=j1((l==null?void 0:l.content)??(l==null?void 0:l.text)??l);if(h.text)return{text:h.text,runtime_metadata:k1(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 _4(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=j1((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=k1(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 S1(e){const t=String(e||"").trim().toLowerCase().replace(/\s+/g," ");return t==="please respond:"||t==="please respond"||t==="type response..."||t==="type response"}function p4(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 N1="inferred from the call's arguments (regex heuristic) — not a declared risk tier; declared tiers replace this when the grant API ships";function $1(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=p4(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 C1(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 E1(e,t){const n=String((e==null?void 0:e.prompt)||"").trim(),r=vx(n),i=m4(t);return r.text&&!S1(r.text)?{text:r.text,runtime_metadata:r.metadata}:i.text?i:{text:r.text||n,runtime_metadata:r.metadata}}function g4(e,t){return E1(e,t).text}function y4(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 w4(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 v4(e){const t=w4(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 A1(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=A1(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 x4(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 b4(e,t){if(!e||typeof e!="object")return null;const n=x4(e),r=A1(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 P=String(S||"").trim();P&&(d[P]=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:NO(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 k4(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=T1(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 j4(e){return e==="html"?"HTML":e==="json"?"JSON":e==="audio"?"Unclassified audio":e==="code"?"Code":e.slice(0,1).toUpperCase()+e.slice(1)}function S4(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 N4(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 $4(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 T1(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 C4(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 E4(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 M1(e){if(!e||typeof e!="object")return"Ledger record";const t=String(e.node_id||"").trim(),n=String(e.status||"").trim(),r=E4(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 R1(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 A4(e){return!!(e&&String(e.status||"")==="waiting")}function T4(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 M4=2,R4=Number.MAX_SAFE_INTEGER;function L4(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 I4(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(Ce.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 L1(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:[" ",L4(c.text)]}):null]}),i?s.jsxs("div",{className:"html-tree__children",children:[t.children.map((l,d)=>s.jsx(L1,{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 O4(e){const t=p.useMemo(()=>I4(e.text),[e.text]),[n,r]=p.useState({mode:"folded",version:0}),i=n.mode==="unfolded"?R4:M4;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(L1,{node:c,depth:0,collapseAfterDepth:i,expansionMode:n.mode,expansionVersion:n.version},`root:${l}`))})]})}function P4(e){var r;const t=l4(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 I1(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(P4,{text:t,className:e.className}):n==="html"?s.jsx(O4,{text:t,className:e.className}):s.jsx("pre",{className:`mono ${e.className}`,children:t})}function D4(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(I1,{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 O1(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 F4(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=O1(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 z4(e){const t=kx(e),n=af(t),r=jx(e);return r==="tool_approval"?`Tool approval: ${F4(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 B4(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 U4(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=z4(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,O1(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:B4(e),action_label:x,search_text:k,is_terminal:c,needs_user_action:y,is_stale:h,duration_ms:l,updated_ms:d}}function W4(e,t={}){const n=t.now_ms??Date.now(),r=t.workflow_label_by_id??{};return e.map(i=>U4(i,{now_ms:n,workflow_label:r[String(i.workflow_id||"")]||String(i.workflow_id||"")}))}function q4(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 V4(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 H4(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 G4(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 J of e.artifacts){const H=String(J.run_id||"").trim();H&&(L[H]=(L[H]||0)+1)}return L},[e.artifacts]),x=p.useMemo(()=>W4(e.runs,{workflow_label_by_id:e.workflow_label_by_id}),[e.runs,e.workflow_label_by_id]),k=p.useMemo(()=>q4(x),[x]),v=p.useMemo(()=>{const L=V4(x,{queue:t,query:l});return H4(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]),P=S?D.size:0,R=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]),I=$!=null&&$.waiting&&typeof $.waiting=="object"?$.waiting:null,W=I?af(I):[],G=(N==null?void 0:N.reason)||(I?xx(I,W):""),K=(N==null?void 0:N.expected_action)||(I?C1(I,W):""),V=I?g4(I,null):"",M=C&&y[C]||0,A=hs($==null?void 0:$.status),O=[{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:[O.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 J=L.run,H=String(J.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:te=>{(te.key==="Enter"||te.key===" ")&&(te.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(J,e.workflow_label_by_id)}),L.is_stale?s.jsx("span",{className:"chip warn",children:"stale"}):null,s.jsx(wu,{status:J.status})]}),s.jsxs("div",{className:"runtime_ops_row_sub",children:[s.jsx("span",{className:"mono",children:Ln(H,18)}),s.jsx("span",{children:cu(J.updated_at||J.created_at)}),s.jsx("span",{children:yu(J)}),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(J.llm_calls||0).toLocaleString()," llm"]}),s.jsxs("span",{children:[Number(J.tool_calls||0).toLocaleString()," tools"]}),s.jsxs("span",{children:[Number(J.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:te=>{te.stopPropagation(),e.on_open_run(H)},children:L.action_label}):s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_open_run(H)},children:"Open"}),s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_open_ledger(H)},children:"Ledger"}),s.jsx("button",{className:"btn",onClick:te=>{te.stopPropagation(),e.on_select_run(H),e.on_open_logs()},children:"Logs"}),s.jsx("button",{className:"btn",onClick:te=>{te.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)||v4($)}),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.":A?"This run is terminal. Open the ledger for the narrative and final error/output.":"This run is active or recently updated. Use ledger/provider logs to inspect live work.")})]}),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:M.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:[P.toLocaleString()," loaded run",P===1?"":"s"]}),s.jsxs("span",{children:[R.toLocaleString()," visible artifact",R===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,I?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:G})]}),s.jsx("p",{children:K}),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,J)=>s.jsxs(Ce.Fragment,{children:[s.jsx("span",{className:"chip mono warn",children:String((L==null?void 0:L.name)||"tool")}),$1(L).map(H=>s.jsxs("span",{className:"chip muted",title:N1,children:[H,"~"]},`${J}:${H}`))]},`${String((L==null?void 0:L.name)||"tool")}:${J}`))}):null,s.jsxs("details",{className:"runtime_raw_details",children:[s.jsx("summary",{className:"muted",children:"Raw wait payload"}),s.jsx(hr,{value:I,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 K4(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 M={},A=e.artifact_type_facets&&Object.keys(e.artifact_type_facets).length?e.artifact_type_facets:e.artifact_facets,O=(A==null?void 0:A.semantic_kind)||{},L=(A==null?void 0:A.render_kind)||{};for(const J of n)M[J]=Number(O[J]||L[J]||0);return M.audio=Number(O.audio||0),M.other=Number(O.other||0)+Number(O.artifact||0)+Number(O.binary||0)+Number(O["(none)"]||0),M},[e.artifact_facets,e.artifact_type_facets]),y=M=>{const A=new Set(i);A.has(M)?A.delete(M):A.add(M),e.on_type_filters_change(Array.from(A.values()))},x=p.useMemo(()=>{const M={waiting:[],running:[],failed:[],cancelled:[],completed:[],other:[]};for(const A of e.runs){const O=String(A.status||"").trim().toLowerCase();O==="waiting"?M.waiting.push(A):O==="running"?M.running.push(A):O==="failed"?M.failed.push(A):O==="cancelled"?M.cancelled.push(A):O==="completed"?M.completed.push(A):M.other.push(A)}return M},[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 O;const M=new Set,A=((O=e.artifact_facets)==null?void 0:O.run_id)||{};for(const L of Object.keys(A))L&&L!=="(none)"&&M.add(L);for(const L of e.artifacts)L.run_id&&M.add(L.run_id);for(const L of e.active_runs)L.run_id&&M.add(String(L.run_id));return Array.from(M).map(L=>e.run_by_id[L]||{run_id:L,workflow_id:null,status:"",created_at:null,updated_at:null}).sort((L,J)=>{const H=Yd(L.status)?0:1,z=Yd(J.status)?0:1;if(H!==z)return H-z;const te=Vt(L.updated_at||L.created_at)??0;return(Vt(J.updated_at||J.created_at)??0)-te}).slice(0,160)},[e.artifacts,e.active_runs,e.run_by_id,e.artifact_facets]),$=M=>{e.on_artifact_run_filter_change(M),e.on_session_filter_change(""),e.on_scope_change(M?"run":"all")},C=M=>e.gateway_connected?Math.max(0,Number(M||0)).toLocaleString():"—",S=e.selected_run_id&&e.run_by_id[e.selected_run_id]||null,D=p.useMemo(()=>{const M=e.runtime_log_query.trim().toLowerCase(),A=e.runtime_ledger_log_items||[];return M?A.filter(O=>{var H,z;const L=O.record||{};return[O.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(M)}):A},[e.runtime_ledger_log_items,e.runtime_log_query]),P=p.useMemo(()=>{const M=e.runtime_log_query.trim().toLowerCase(),A=T4(e.runtime_ledger_log_items);return M?A.filter(O=>[O.provider,O.model,O.run_id,O.node_id,O.status,O.error,O.prompt_preview,O.response_preview,O.tokens.prompt,O.tokens.completion,O.tokens.total].join(" ").toLowerCase().includes(M)):A},[e.runtime_ledger_log_items,e.runtime_log_query]),R=P.reduce((M,A)=>M+(Number(A.tokens.total)||0),0),I=P.filter(M=>M.missing_response||M.error).length,W=p.useMemo(()=>{const M=e.runtime_log_query.trim().toLowerCase(),A=String(e.audit_log_text||"").replace(/\r\n/g,`
|
|
130
|
+
`).replace(/\r/g,`
|
|
131
|
+
`).split(`
|
|
132
|
+
`).filter(Boolean);return M?A.filter(O=>O.toLowerCase().includes(M)):A},[e.audit_log_text,e.runtime_log_query]),G=e.runtime_log_source==="run_ledger"||e.runtime_log_source==="provider_calls",K=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(M=>s.jsxs("button",{role:"tab","aria-selected":e.tab===M,className:`runtime_mode_tab ${e.tab===M?"active":""}`,onClick:()=>e.on_tab_change(M),children:[s.jsx(qe,{name:M==="activity"?"history":M==="artifacts"?"download":M==="memory"?"agent":"terminal",size:14}),s.jsx("span",{children:M==="activity"?"Activity":M==="artifacts"?"Artifacts":M==="memory"?"Memory":"Logs"})]},M))}),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(G4,{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:M=>{$(M),e.on_select_run(M),e.on_tab_change("artifacts")},on_filter_session_artifacts:M=>{M&&(e.on_artifact_run_filter_change(""),e.on_session_filter_change(M),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:M=>e.on_query_change(M.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:M=>{const A=M.target.value;A!=="run"&&e.on_artifact_run_filter_change(""),A==="session"?e.on_session_filter_change(e.session_id):e.on_session_filter_change(""),e.on_scope_change(A)},children:[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:M=>e.on_group_by_change(M.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:M=>e.on_sort_by_change(M.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(M=>{const A=i.has(M),O=g[M]||0,L=j4(M);return s.jsxs("button",{type:"button","aria-pressed":A,"aria-label":`${L} artifact type filter. Type filters combine with OR.`,title:`${L}: ${A?"in the filter":"not in the filter"}. Type filters combine with OR.`,className:`artifact_filter_chip ${A?"active":""}`,onClick:()=>y(M),children:[s.jsx("span",{children:L}),s.jsx("span",{className:"artifact_chip_count",children:e.gateway_connected?O.toLocaleString():"—"})]},M)}),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(M=>s.jsx("button",{type:"button","aria-pressed":e.date_filter===M.value,className:`artifact_filter_chip ${e.date_filter===M.value?"active":""}`,onClick:()=>e.on_date_filter_change(M.value),children:M.label},M.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(M=>{const A=String(M.run_id||"").trim(),O=A===e.artifact_run_filter||A===(t==null?void 0:t.run_id);return s.jsxs("button",{className:`artifact_filter_run ${O?"selected":""}`,onClick:()=>$(A),title:A,children:[s.jsx("strong",{children:Ko(M,e.workflow_label_by_id)}),s.jsx("span",{className:"mono",children:Ln(A,15)}),s.jsx("span",{children:yu(M)})]},A)})]})]}),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(M=>s.jsxs("section",{className:"artifact_group",children:[s.jsxs("div",{className:"artifact_group_header",children:[s.jsx("span",{children:M.key}),s.jsx("span",{className:"artifact_group_count",children:M.items.length})]}),M.items.map(A=>{var z;const O=A.run_id&&e.run_by_id[A.run_id]||null,L=O?Ko(O,e.workflow_label_by_id):bx(A),J=Y0(A),H=Number(((z=A.access)==null?void 0:z.access_count)||0)||0;return s.jsxs("button",{className:`artifact_row ${(t==null?void 0:t.artifact_id)===A.artifact_id?"selected":""}`,onClick:()=>{e.on_select_artifact(A.artifact_id),A.run_id&&e.on_select_run(A.run_id)},title:A.artifact_id,children:[s.jsx(Z0,{artifact:A,size:18}),s.jsxs("div",{className:"artifact_row_main",children:[s.jsxs("div",{className:"artifact_row_title",children:[s.jsx("strong",{children:J0(ag(A,e.run_by_id,e.workflow_label_by_id))}),s.jsx("span",{className:"artifact_type_badge",children:qd(A)}),A.render_kind&&A.render_kind!==A.semantic_kind?s.jsx("span",{className:"artifact_type_badge muted",children:A.render_kind}):null,A.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"})," ",$4(A)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Size"})," ",ru(A.size_bytes)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Last seen"})," ",K0(A)]}),H?s.jsxs("span",{children:[s.jsx("b",{children:"Accesses"})," ",H.toLocaleString()]}):null,J?s.jsxs("span",{children:[s.jsx("b",{children:"Media"})," ",J]}):null,A.content_type?s.jsxs("span",{children:[s.jsx("b",{children:"MIME"})," ",A.content_type]}):null]}),s.jsxs("div",{className:"artifact_row_facts secondary",children:[L?s.jsxs("span",{children:[s.jsx("b",{children:"Workflow"})," ",L]}):null,A.run_id?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Run"})," ",Ln(A.run_id,13)]}):null,s.jsxs("span",{children:[s.jsx("b",{children:"Turn"})," ",cv(A)]}),Wd(A)?s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"Node"})," ",Wd(A)]}):null,om(A)?s.jsxs("span",{children:[s.jsx("b",{children:"Source"})," ",om(A)]}):null]}),s.jsxs("div",{className:"artifact_row_facts tertiary",children:[s.jsxs("span",{className:"mono",children:[s.jsx("b",{children:"ID"})," ",Ln(A.artifact_id,22)]}),s.jsxs("span",{children:[s.jsx("b",{children:"Provenance"})," ",H0(A)]})]}),X0(A)?s.jsx("div",{className:"artifact_row_path mono",children:X0(A)}):null]})]},A.artifact_id)})]},M.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,te,B,ne,se,ue,ve;const M=C4(t),A=T1(t),O=Y0(t),L=Number(((z=t.access)==null?void 0:z.access_count)||0)||0,J=Vn((te=t.links)==null?void 0:te.provider_trace,(B=t.links)==null?void 0:B.provider_trace_url,(ne=t.links)==null?void 0:ne.provider_trace_id),H=Vn((se=t.links)==null?void 0:se.audit,(ue=t.links)==null?void 0:ue.audit_tail,(ve=t.links)==null?void 0:ve.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(D4,{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:A||"—"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Media facts"}),s.jsx("strong",{children:O||"—"})]}),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]}),M?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:M})]}):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:()=>{J&&window.open(J,"_blank","noopener,noreferrer")},disabled:!J,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:K}),s.jsx("div",{className:"mono muted",children:V})]}),s.jsxs("div",{className:"actions",style:{marginTop:0},children:[G&&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:()=>{G?e.on_refresh_runtime_ledger(e.selected_run_id):e.on_refresh_audit()},disabled:G?e.runtime_ledger_log_loading:e.audit_log_loading,children:[s.jsx(qe,{name:"refresh",size:14}),G?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:M=>e.on_runtime_log_query_change(M.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(M=>{var se,ue;const A=M.record||{},O=String(((se=A==null?void 0:A.effect)==null?void 0:se.type)||"").trim(),L=String((A==null?void 0:A.status)||"").trim(),J=String((A==null?void 0:A.node_id)||"").trim(),H=Vn(A==null?void 0:A.ended_at,A==null?void 0:A.started_at,A==null?void 0:A.ts),z=Za(A),te=M1(A),B=O?tn(Br(((ue=A==null?void 0:A.effect)==null?void 0:ue.payload)??{},1200),{max_chars:1200,max_lines:6}):"",ne=R1(A)||(z?`Waiting for ${String(z.reason||"input")}`:"")||((A==null?void 0:A.result)!==void 0?Br(A.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:["#",M.cursor]}),s.jsx(wu,{status:L||"record"}),O?s.jsx("span",{className:"chip mono muted",children:O}):null,J?s.jsx("strong",{className:"mono",children:J}):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:[te||Lp(A),B&&B!=="{}"?B:""].filter(Boolean).join(`
|
|
133
|
+
`)})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Outcome"}),s.jsx("p",{children:tn(ne||"—",{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:A,collapseAfterDepth:3,showCopy:!0})]})]},`${e.selected_run_id}:${M.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:P.length.toLocaleString()}),s.jsx("em",{className:"mono",children:R?`${R.toLocaleString()} tokens`:"tokens not recorded"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Issues"}),s.jsx("strong",{children:I.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&&!P.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:P.map(M=>s.jsxs("article",{className:`provider_activity ${M.error||M.missing_response?"danger":""}`,children:[s.jsxs("div",{className:"provider_activity_header",children:[s.jsxs("div",{children:[s.jsx("h4",{children:[M.provider||"provider unknown",M.model||"model unknown"].join(" / ")}),s.jsxs("div",{className:"timeline_subtitle",children:[M.node_id?s.jsx("span",{className:"mono",children:M.node_id}):null,M.run_id?s.jsx("span",{className:"mono",children:Ln(M.run_id,16)}):null,s.jsx("span",{children:bu(M.duration_ms)}),M.status?s.jsx(wu,{status:M.status}):null]})]}),s.jsxs("div",{className:"provider_tokens mono",children:[M.tokens.total?M.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:M.prompt_preview||"No prompt payload captured"})]}),s.jsxs("div",{children:[s.jsx("span",{children:"Response / error"}),s.jsx("p",{children:M.response_preview||M.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:M.raw,collapseAfterDepth:3,showCopy:!0})]})]},M.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 J4(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:o1(e.run)}):null}function Y4(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 X4{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 P1.set(i,t),i}const P1=new WeakMap;class Z4 extends Error{constructor(n){super(n);jn(this,"name","GatewayTimeout")}}class Q4 extends Error{constructor(n){super(n);jn(this,"name","Superseded")}}async function an(e,t){try{return await globalThis.fetch(e,t)}catch(n){throw D1(n,e,t)}}async function Jy(e,t,n){try{return await e.json()}catch(r){throw D1(r,t,n)}}function D1(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&&P1.get(i)||3e4;return new Z4(`${l}: no answer within ${Math.round(d/1e3)} s — the gateway is busy`)}return new Q4(`${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 an(Xt(this._cfg.base_url,vt("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[vt("mcp/servers"),vt("mcp"),vt("discovery/mcp")])try{const n=await an(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[vt("skills"),vt("skills/registry")])try{const n=await an(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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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,vt(`runs/${encodeURIComponent(r)}/history_bundle?${i.toString()}`)),c=await an(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,vt(`runs?${l.toString()}`)),h=await an(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,vt(`audit/tail?max_bytes=${encodeURIComponent(String(n))}`)),i=await an(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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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,vt(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await an(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,vt(`sessions/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}&offset=${encodeURIComponent(String(o))}`)),l=await an(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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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,vt(`runs/${encodeURIComponent(i)}/artifacts/${encodeURIComponent(o)}/content${l}`)),h=await an(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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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,vt(`entities/${encodeURIComponent(r)}/diary/${encodeURIComponent(i)}?reason=${encodeURIComponent("observer board hint chip")}`)),c=await an(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,vt(`runs/${encodeURIComponent(t)}/ledger?after=${encodeURIComponent(String(r))}&limit=${encodeURIComponent(String(i))}`)),c=await an(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 an(Xt(this._cfg.base_url,vt("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,vt("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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt(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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt("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,vt(`bundles/${encodeURIComponent(r)}?${i.toString()}`)),l=await an(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 an(Xt(this._cfg.base_url,vt("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,vt(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),i=await an(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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt(`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 an(Xt(this._cfg.base_url,vt("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 yA({fetch:(n,r)=>fetch(n,r),baseUrl:this._cfg.base_url,headers:()=>Zt(t)})}async submit_command(t){const n=await an(Xt(this._cfg.base_url,vt("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 an(Xt(this._cfg.base_url,vt("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,vt(`runs/${encodeURIComponent(t)}/ledger/stream?after=${encodeURIComponent(String(r))}`)),l=await an(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 X4;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 eD(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 tD({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(cN,{level:"run",idPrefix:"observer-launch-workspace",value:n,effective:o,onChange:m,loadError:e?l:_,unavailableReason:_})}function nD(e){const t=(e||"").trim();return t?{Authorization:`Bearer ${t}`}:{}}class sD{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",...nD(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 rD(e,t){const n=Vt(e.updated_at||e.created_at)??0;return(Vt(t.updated_at||t.created_at)??0)-n}function iD(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(rD),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 oD(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 aD(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 lD(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 cD(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}cD(o[0],i[0])&&(i=o)}r.push(i.shift())}return r}function uD(e){return Pd(e.ended_at)??Pd(e.started_at)}function dD(e,t,n){var k,v,N,$,C,S,D,P,R,I;const r=String(t||"").trim();if(!r)return{};const i=[],o=new Set;for(const W of e||[]){const G=String((W==null?void 0:W.run_id)||((k=W==null?void 0:W.record)==null?void 0:k.run_id)||"").trim();G&&!o.has(G)&&(o.add(G),i.push(G))}i.sort((W,G)=>W===r?-1:G===r?1:0);const c=new Map;for(const W of i)c.set(W,Pg(e,W));const l=(W,G)=>{const K=String(n(W,G)||"").trim();return!K||W!==r&&K===G?"":K},d=new Map,h=(W,G=0)=>{if(d.has(W))return d.get(W)??null;d.set(W,null);const K=G<6?ok(c.get(W)||[]):null,V=K?ak(K,M=>h(M,G+1)):null;return d.set(W,V),V},m=new Map,_=(W,G)=>{let K=m.get(W);return K||(K={facts:{node_id:G,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,K)),K};let g=0;for(const W of i)for(const G of c.get(W)||[]){const K=String(G.node_id||"").trim();if(!K)continue;const V=l(W,K);if(!V)continue;const M=_(V,K);M.steps.push({step:G,rid:W,t:uD(G),seq:g++}),M.facts.run_ids.includes(W)||M.facts.run_ids.push(W)}const y=(e||[]).filter(W=>W&&W.record).map((W,G)=>({x:W,i:G})).sort((W,G)=>{const K=i.indexOf(String(W.x.run_id||W.x.record.run_id||"").trim()),V=i.indexOf(String(G.x.run_id||G.x.record.run_id||"").trim());return K!==V?K-V:(W.x.cursor||0)-(G.x.cursor||0)||W.i-G.i});g=0;for(const{x:W}of y){const G=String(W.run_id||W.record.run_id||"").trim(),K=String(W.record.node_id||"").trim();if(!G||!K)continue;const V=l(G,K),M=V?m.get(V):void 0;M&&M.records.push({rec:W.record,rid:G,t:Pd(W.record.ended_at)??Pd(W.record.started_at),seq:g++})}const x={};for(const[W,G]of m){const K=G.facts,V=lk(G.steps).map(se=>se.step),M=ok(V);K.visits=V.length,K.status=ak(M,se=>h(se)),K.last_effect=M.effect_type,K.last_status=M.status;let A=0,O=0,L=0,J=!1,H=0,z=null;const te=new Map;for(const se of V){const ue=Pd(se.started_at),ve=Pd(se.ended_at)??ue;if(ue!==null&&(K.first_ms=K.first_ms===null?ue:Math.min(K.first_ms,ue)),ve!==null&&(K.last_ms=K.last_ms===null?ve:Math.max(K.last_ms,ve)),typeof se.duration_ms=="number"&&(K.duration_ms+=se.duration_ms),se.kind==="llm_call"){H+=1,z=se;const ke=((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(ke&&typeof ke=="object"){const le=Number(ke.prompt_tokens??ke.input_tokens),xe=Number(ke.completion_tokens??ke.output_tokens),Ee=Number(ke.total_tokens);(Number.isFinite(le)||Number.isFinite(xe)||Number.isFinite(Ee))&&(J=!0,A+=Number.isFinite(le)?le:0,O+=Number.isFinite(xe)?xe:0,L+=Number.isFinite(Ee)?Ee:(Number.isFinite(le)?le:0)+(Number.isFinite(xe)?xe:0))}}else if(se.kind==="tool"){const ke=Em(se),le=ke.calls.length?ke.calls.map(xe=>xe.name):ke.results.map(xe=>xe.name);for(const xe of le){const Ee=te.get(xe)||{name:xe,calls:0,failed:0};Ee.calls+=1,te.set(xe,Ee)}for(const xe of ke.results){if(xe.success!==!1)continue;const Ee=te.get(xe.name)||{name:xe.name,calls:0,failed:0};Ee.failed+=1,te.set(xe.name,Ee)}}const Te=lD((S=se.record)==null?void 0:S.error);Te&&(K.last_error=Te),se.record&&Object.prototype.hasOwnProperty.call(se.record,"result")&&se.record.result!==void 0&&se.record.result!==null&&(K.last_result=se.record.result)}if(K.last_result_summary=aD(K.last_result),K.tools=Array.from(te.values()),H&&z){const se=Cm(z);if(K.llm={calls:H,model:se.model,provider:se.provider},J&&(K.llm.tokens={in:A,out:O,total:L}),se.messages.length||se.system){const ue=se.system?[{role:"system",content:se.system},...se.messages]:[...se.messages];K.context={provider:se.provider,model:se.model,messages_source:se.messages_source,messages:ue}}}K.records=lk(G.records).map(se=>se.rec);const B=K.status==="waiting"||K.status==="running"&&String(M.status)==="waiting"?String(((R=(P=(D=M.record)==null?void 0:D.result)==null?void 0:P.wait)==null?void 0:R.wait_key)||""):"",ne=new Set;for(const se of K.records){const ue=(I=se==null?void 0:se.result)==null?void 0:I.wait;if(String(se.status||"")==="waiting"&&ue&&typeof ue=="object"){const Te=String(ue.wait_key||""),ke=`${String(ue.reason||"")}|${Te}`;if(!ne.has(ke)){ne.add(ke);const le={reason:String(ue.reason||""),wait_key:Te,open:!1};typeof ue.prompt=="string"&&ue.prompt&&(le.prompt=ue.prompt),K.waits.push(le)}}const ve=Am(se);ve&&!K.subruns.includes(ve)&&K.subruns.push(ve)}if(B)for(const se of K.waits)se.open=se.wait_key===B;x[W]=K}return x}function fD(e){const t={};for(const[n,r]of Object.entries(e||{}))t[n]=r.status;return t}function hD(e){const{records:t,context:n,...r}=e;return JSON.stringify(r,null,2)}function mD(e){return e.records.map(t=>Zd(t)).join(`
|
|
138
|
+
`)}function _D(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 pD(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 gD={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"},yD=[{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 wD(){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:[yD.map(n=>s.jsxs("div",{className:"pin-legend-row",children:[s.jsx("span",{className:"pin-legend-shape",style:{color:gD[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 vD(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(hv,e)}function xD(e){return vD(e)?hv[e]:hv.any}function bD(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 kD=280,jD=6,SD=360,ND=1500;function F1(e,t=kD,n=jD){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 $D(e){return e===null||["string","number","boolean"].includes(typeof e)}function ck(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function CD(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($D))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 ED(e,t=SD){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(""),ND);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 z1(e){const t=e.size??12,n=t/2,r=e.filled?"currentColor":"none",i=bD(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:xD(e.type)},"aria-hidden":"true",children:o})}function AD(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=F1(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 TD(e){const[t,n]=p.useState(!1),r=ED(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 MD(e){const[t,n]=p.useState(!1),r=CD(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(TD,{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(AD,{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(MD,{value:t}):s.jsx("code",{className:"ap_pin_scalar",children:String(t)})}function RD(e){return e.state==="value"?al(e.value):e.state==="not_provided"&&e.flow_default?al(e.flow_default.value):null}function LD(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 ID(e){const{pin:t}=e,n=t.typed?t.type:"untyped",r=RD(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(z1,{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(LD,{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(ID,{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(z1,{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 OD(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}=OD(e);return{by_id:n,children_of:r,now_ms:Date.now(),...t||{}}}function B1(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 PD(e,t){return String((t==null?void 0:t.reason)||(e==null?void 0:e.waiting_reason)||"").trim().toLowerCase()}function DD(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 FD(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 zD=6e4;function BD(e,t){var c;const n=B1(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 UD(e){const t=String(e||"").trim(),n=si(t);return n&&n!==t?`${n} — ${t}`:t}function U1(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=WD(e,t,n);return{...r,brief:r.brief||r.text}}function WD(e,t,n=0){var N,$,C,S,D,P,R,I,W,G,K;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=B1(e,t),d=PD(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=FD(h,r),y=g?` · ${g}`:"";if(hs(c)){const V=rm(e),M=String((e==null?void 0:e.error)||"").trim(),A=(N=t.details)==null?void 0:N.get(o),O=Vt((e==null?void 0:e.created_at)||""),L=Vt((e==null?void 0:e.updated_at)||""),J=O!==null&&L!==null&&L>=O?er(L-O):"";let H=V;V==="failed"?H=M?`failed: ${Dd(M,120)}`:"failed":V==="completed"?H=J?`completed in ${J}`:"completed":V==="stopped"?H="stopped before the turn finished":V==="cancelled"&&(H="cancelled");const z=String((A==null?void 0:A.error)||"").trim();return V==="failed"&&!M&&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)),M=Vt((l==null?void 0:l.until)||""),A=(V==null?void 0:V.next_fire_ms)??M,O=[];V!=null&&V.current&&!hs(V.current.status)?O.push(`run #${V.current.index} in progress`):d==="subworkflow"&&O.push("a run is in progress"),(V==null?void 0:V.status)==="paused"?O.push("paused: scheduled runs are skipped"):A!==null?O.push(`next run in ${sm(Math.max(0,A-r))}`):(V==null?void 0:V.status)==="completed"||(V==null?void 0:V.status)==="failed"?O.push(`${V.status}: no next run`):V!=null&&V.event_driven?O.push("listening"):((C=V==null?void 0:V.trigger)==null?void 0:C.source_id)==="manual"?O.push("runs when someone presses Run now"):O.push("next run not scheduled"),V!=null&&V.last&&O.push(`last #${V.last.index} ${V.last.status}`),V&&O.push(`${V.occurrence_count} turn${V.occurrence_count===1?"":"s"}`);const L=O.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,M=V&&V.ended_ms===null&&V.started_ms!==null?V:null,A=Math.max(h??0,(V==null?void 0:V.ended_ms)??0,(V==null?void 0:V.started_ms)??0)||null,O=A?Math.max(0,r-A):null,L=O!==null&&O>i,J=M?`${M.effect||M.node_id||"step"} open ${er(r-M.started_ms)}`:"",H=String(((P=(D=t.details)==null?void 0:D.get(o))==null?void 0:P.current_node)||(e==null?void 0:e.current_node)||"").trim(),z=["running"];return H&&z.push(`step ${H}`),J?z.push(J):O!==null&&z.push(`last step ${er(O)} ago`),L&&z.push("no progress"),{..._,verb:"running",lane:"working",object:J||H||"",actor:"runtime",action:"open_run",stale_ms:O,stalled:L,open_step:J,text:z.join(" · ")}}if(c!=="waiting"){if((e==null?void 0:e.is_scheduled)===!0){const M=e!=null&&e.schedule_interval?`scheduled · every ${e.schedule_interval}`:"scheduled";return{..._,verb:"scheduled",lane:"scheduled",object:M,actor:"clock",action:"open_run",text:M}}const V=c?`${c}${y}`:"state unknown";return{..._,object:V,text:V,action:"inspect"}}if(DD(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(O=>String((O==null?void 0:O.name)||"tool").trim()).filter(Boolean),M=`${V.slice(0,3).join(", ")}${V.length>3?` +${V.length-3}`:""}`,A=`needs your approval: ${M||"tool call"}${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`approval: ${M}`,actor:"you",action:"approve",text:A}}if(d==="user"){if(dk(l)){const A=Dd(String((l==null?void 0:l.prompt)||""),80),O=A?`asks: ${A}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:A||"a question",actor:"you",action:"answer",text:O,brief:`asks a question${y}`}}if(((R=t.details)==null?void 0:R.has(o))===!0){const A=`waits for your answer${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:"your answer",actor:"you",action:"answer",text:A}}const M=`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:M}}if(d==="subworkflow"){const V=n<4?BD(e,t):null;if(!V){const L=String(((I=l==null?void 0:l.details)==null?void 0:I.sub_run_id)||"").trim(),J=L?(W=t.fates)==null?void 0:W.get(L):void 0,z=U1(e,t)||J&&Bg(J.workflow_id)||Qd(L);if(J&&J.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(J&&hs(J.status)){const B=Vt(J.updated_at),ne=B!==null?Math.max(0,t.now_ms-B):null;if(ne!==null&&ne<=zD){const Te=`its subrun ${z} ${J.status} ${er(ne)} ago · resuming${y}`;return{..._,verb:"running",lane:"working",object:`subrun ${z}`,actor:"runtime",action:"open_run",text:Te}}const se=ne!==null?` ${er(ne)} ago`:"",ue=J.status==="cancelled"?"was cancelled":J.status==="failed"?"failed":`ended ${J.status}`,ve=`stuck: subrun ${z} ${ue}${se}, this run was not resumed${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:`subrun ${z} (${J.status})`,actor:"you",action:"open_run",stuck:!0,stuck_facts:{subrun:z,status:J.status,ended_ms:ne},text:ve}}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 te=`waiting for a subrun to finish${y}`;return{..._,object:"a subrun",actor:"run",action:"open_run",text:te}}const M=ef(V,t,n+1),A=si(String(V.workflow_id||""))||Qd(String(V.run_id||""));if(M.verb==="running"){const L=[`running subrun ${A}`];return M.open_step?L.push(M.open_step):M.stale_ms!==null&&L.push(`last step ${er(M.stale_ms)} ago`),M.stalled&&L.push("no progress"),{..._,verb:"running",lane:"working",object:`subrun ${A}`,actor:"run",actor_run_id:String(V.run_id||""),action:"open_subrun",stale_ms:M.stale_ms,stalled:M.stalled,open_step:M.open_step,text:L.join(" · ")}}const O=`waiting for subrun ${A}: ${M.brief||M.text}`;return{..._,verb:"waiting",lane:"waiting_on",object:`subrun ${A}`,actor:"run",actor_run_id:String(V.run_id||""),action:"open_subrun",unresolved:M.unresolved,text:O}}if(d==="until"){const V=Vt((l==null?void 0:l.until)||""),M=V!==null?`sleeps until ${fk(V,r)}`:`sleeps until an unknown time${y}`,A=(e==null?void 0:e.is_scheduled)===!0;return{..._,...A?{verb:"scheduled",lane:"scheduled"}:{},object:"the clock",actor:"clock",action:"open_run",text:M}}if(d==="event"){if(dk(l)){const L=Dd(String((l==null?void 0:l.prompt)||""),80),J=L?`asks: ${L}${y}`:`asks a question${y}`;return{..._,verb:"needs_you",lane:"needs_you",object:L||"a question",actor:"you",action:"answer",text:J,brief:`asks a question${y}`}}const V=Vt((l==null?void 0:l.until)||""),M=String(((G=l==null?void 0:l.details)==null?void 0:G.event)||((K=l==null?void 0:l.details)==null?void 0:K.name)||"").trim(),A=M?`event ${M}`:"an event",O=V!==null?`waiting for ${A} until ${fk(V,r)}`:`waiting for ${A}${y}`;return{..._,object:A,actor:"external",action:"open_run",text:O}}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 W1(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 q1(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 V1(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?DO(e):""}function Rm(e){var k,v,N,$,C,S,D,P;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(R=>String(R)).filter(Boolean):[],d=Array.isArray((v=n==null?void 0:n.notify)==null?void 0:v.channels)?n.notify.channels.map(R=>String(R)):[],h=Array.isArray(t==null?void 0:t.capabilities)?t.capabilities.map(R=>String(R)):[],m=i!=null&&i._runtime&&typeof i._runtime=="object"?i._runtime:{},_=R=>Array.isArray(R)?R.map(I=>String(I)).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(((P=t==null?void 0:t.last_notification)==null?void 0:P.text)||"").trim()}}function qD(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 H1(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 G1(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 K1(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 VD(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(G1(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 HD(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(!H1(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(G1(g)!=="subflow")continue;const y=K1(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=VD(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($),R={x:C.x+d.x+240-S.x,y:C.y+d.y+0-S.y},I=Nh(k,v);r.push({id:`${k}=>${I}`,source:k,target:I,sourceHandle:"exec-out",targetHandle:"exec-in"}),o(x,k,R,h+1)}};return o(t,"",{x:0,y:0},0),{...t,id:Rn(t.id),nodes:n,edges:r}}function GD(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 KD(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 JD=new Set(["completed","failed","cancelled","stopped"]),J1={running:"here",waiting:"waiting here",failed:"failed here",done:"here",none:"here"},Y1={running:"running",waiting:"waiting",failed:"failed",done:"done",none:"not visited"},X1={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 Z1(e){const t=(e==null?void 0:e.waits.find(n=>n.open))||null;return t?X1[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 YD(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??u1:e.label})})}function gk(e){const[t,n]=p.useState(!1),{shown:r,clamped:i}=F1(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 XD(e){const[t,n]=p.useState(!1),r=oD(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 ZD(e){const{node:t,facts:n,status:r}=e,i=r==="waiting"?Z1(n):Y1[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:J1[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:X1[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(XD,{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?hD(n):""}),s.jsx(Ip,{label:"Copy records (JSONL)",disabled:!n||!n.records.length,get_text:()=>n?mD(n):""}),n!=null&&n.context?s.jsx(Ip,{label:"Copy context",get_text:()=>_D(n)}):null]})]})}function QD(e){var wt;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 ie=HD({root:n||{},flow_by_id:e.flow_by_id||{},expand_subflows:e.expand_subflows===!0,max_depth:3,max_nodes:700,max_edges:900}),fe=Array.isArray(ie.nodes)?ie.nodes:[],$e=Array.isArray(ie.edges)?ie.edges:[];let Le=[];for(const Be of fe){const Qt=Rn(Be==null?void 0:Be.id).trim();if(!Qt)continue;const Rt=Be!=null&&Be.position&&typeof Be.position=="object"?Be.position:{},Fn=typeof Rt.x=="number"?Rt.x:0,fn=typeof Rt.y=="number"?Rt.y:0,Xe=Be!=null&&Be.data&&typeof Be.data=="object"?Be.data:{},nn=Rn((Xe==null?void 0:Xe.label)||(Be==null?void 0:Be.label)||Qt)||Qt,cn=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,ye=cn==="subflow"?K1(Be):"",Nt=ws||_r!==void 0||ye?{schedule:ws||void 0,recurrent:_r,subflow_id:ye||void 0}:void 0;Le.push({id:Qt,x:Fn,y:fn,label:nn,type:cn,color:Ar,meta:Nt})}const We={};for(const Be of Le)We[Be.id]=Be;let Ue=[];for(const Be of $e){if(!H1(Be))continue;const Qt=Rn(Be==null?void 0:Be.source).trim(),Rt=Rn(Be==null?void 0:Be.target).trim();!Qt||!Rt||Ue.push({id:Rn((Be==null?void 0:Be.id)||`${Qt}->${Rt}`),source:Qt,target:Rt})}const nt=new Set(Le.map(Be=>Be.id));if(Ue=Ue.filter(Be=>nt.has(Be.source)&&nt.has(Be.target)),e.simplify===!0){const Qt=KD({nodes:Le,edges:Ue,keep_id:Rt=>{if(r&&Rt===r)return!0;const Fn=We[Rt];if(!Fn)return!1;const fn=Rn(Fn.type).trim().toLowerCase();return fn==="on_flow_start"||fn==="on_flow_end"||fn==="subflow"?!0:!GD(fn)},max_edges:900});Le=Qt.nodes,Ue=Qt.edges}if(e.prefer_vertical===!0&&Le.length>=2){const Be=Le.map(Xe=>Xe.x),Qt=Le.map(Xe=>Xe.y),Rt=Math.max(...Be)-Math.min(...Be),Fn=Math.max(...Qt)-Math.min(...Qt);Rt>=Fn&&(Le=Le.map(Xe=>({...Xe,x:Xe.y,y:Xe.x})));const fn=Math.min(...Le.map(Xe=>Xe.y));Le=Le.map(Xe=>({...Xe,y:fn+(Xe.y-fn)*l}))}const ut={};for(const Be of Le)ut[Be.id]=Be;const xt=160,bt=56,Tt=xt/2,zt=bt/2;let ct=0,Yt=0,vn=0,hn=0;Le.length&&(ct=Math.min(...Le.map(Be=>Be.x)),Yt=Math.min(...Le.map(Be=>Be.y)),vn=Math.max(...Le.map(Be=>Be.x+xt)),hn=Math.max(...Le.map(Be=>Be.y+bt)));let sn=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 Rt=ut[Qt.source],Fn=ut[Qt.target];if(!Rt||!Fn)continue;const fn=Rt.x+Tt,Xe=Rt.y+zt,nn=Fn.x+Tt,cn=Fn.y+zt,Ar=Math.max(1,Math.hypot(nn-fn,cn-Xe)),As=Math.max(28,Math.min(72,Ar*.14)),ws=Math.min(200,As*3.5);ws>sn&&(sn=ws)}}const Ht=60+sn,is={x:ct-Ht,y:Yt-Ht,w:vn-ct+Ht*2,h:hn-Yt+Ht*2,node_w:xt,node_h:bt};return{nodes:Le,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 ie=new Set;for(const fe of h)ie.add(`${fe.source}->${fe.target}`);return ie},[h]),[$,C]=p.useState(null),[S,D]=p.useState(null),P=p.useRef({}),R=p.useRef(null),I=p.useRef(null),W=p.useRef(null),G=p.useRef(!1),V=`flow_facts_${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,M=()=>{I.current!==null&&window.clearTimeout(I.current),I.current=null},A=ie=>{const fe=P.current[ie];if(!fe||typeof window>"u")return;const $e=fe.getBoundingClientRect(),Le=window.innerWidth,We=Math.min(400,Le-16);let Ue=$e.right+10,nt=$e.top;Ue+We>Le-8&&(Ue=$e.left-10-We),Ue<8&&(Ue=Math.min(Math.max(8,$e.left),Math.max(8,Le-We-8)),nt=$e.bottom+8),D(ut=>ut&&ut.top===nt&&ut.left===Ue&&ut.width===We?ut:{top:nt,left:Ue,width:We})},O=(ie,fe)=>{M(),A(ie),C({id:ie,mode:fe})},L=ie=>{M(),I.current=window.setTimeout(()=>C(fe=>fe&&fe.id===ie&&fe.mode!=="pinned"?null:fe),200)},J=(ie,fe)=>{if(M(),$&&$.id===ie&&$.mode==="pinned"){C(null);return}A(ie),C({id:ie,mode:"pinned"}),fe&&window.setTimeout(()=>{var $e;return($e=R.current)==null?void 0:$e.focus()},0)};p.useEffect(()=>()=>M(),[]),pk(()=>{$&&A($.id)},[$==null?void 0:$.id,g.x,g.y,g.w,g.h]);const H=()=>{const ie=R.current;if(!ie)return;const fe=ie.offsetHeight,$e=window.innerHeight;D(Le=>{if(!Le||Le.top+fe<=$e-8)return Le;const We=Math.max(8,$e-8-fe);return We===Le.top?Le:{...Le,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 ie=R.current;if(!$||!ie||typeof ResizeObserver>"u")return;const fe=new ResizeObserver(()=>H());return fe.observe(ie),()=>fe.disconnect()},[$==null?void 0:$.id,z]),p.useEffect(()=>{if(!$)return;const ie=Le=>{var We;Le.key==="Escape"&&(C(null),$.mode!=="hover"&&(G.current=!0,(We=P.current[$.id])==null||We.focus(),G.current=!1))},fe=Le=>{var Ue;const We=Le.target;We&&((Ue=R.current)!=null&&Ue.contains(We))||We&&typeof We.closest=="function"&&We.closest("[data-flow-node]")||C(null)},$e=()=>A($.id);return document.addEventListener("keydown",ie,!0),document.addEventListener("pointerdown",fe,!0),window.addEventListener("resize",$e),window.addEventListener("scroll",$e,!0),()=>{document.removeEventListener("keydown",ie,!0),document.removeEventListener("pointerdown",fe,!0),window.removeEventListener("resize",$e),window.removeEventListener("scroll",$e,!0)}},[$==null?void 0:$.id,$==null?void 0:$.mode]);const te=`${g.x} ${g.y} ${g.w} ${g.h}`,B={};for(const ie of d)B[ie.id]=ie;const ne=ie=>{let fe=Rn(ie).trim();if(!fe)return"";if(B[fe])return fe;for(;fe.includes("::");)if(fe=fe.slice(0,Math.max(0,fe.lastIndexOf("::"))),B[fe])return fe;return""},se=ne(r),ue={};for(const[ie,fe]of Object.entries(i)){if(typeof fe!="number")continue;const $e=ne(ie);$e&&(ue[$e]=Math.max(ue[$e]||0,fe))}const ve={};if(c)for(const[ie,fe]of Object.entries(o)){if(typeof fe!="number")continue;const $e=ne(ie);$e&&(ve[$e]=typeof ve[$e]=="number"?Math.min(ve[$e],fe):fe)}const Te=Rn(e.schedule_next_in).trim(),ke=Rn(e.schedule_interval).trim(),le=e.node_last_ms&&typeof e.node_last_ms=="object"?e.node_last_ms:{},xe=ie=>{try{const fe=new Date(ie),$e=String(fe.getHours()).padStart(2,"0"),Le=String(fe.getMinutes()).padStart(2,"0");return`${$e}:${Le}`}catch{return""}},Ee=(ie,fe)=>{var Ue,nt;const $e=Rn((Ue=ie.meta)==null?void 0:Ue.schedule).trim();if(!(((nt=ie.meta)==null?void 0:nt.recurrent)===!0))return fe&&Te?`next ${Te}`:$e&&$e.length<=12&&!$e.includes("T")?`in ${$e}`:"scheduled";const We=$e||ke;return We?fe&&Te?`${We} • next ${Te}`:`every ${We}`:fe&&Te?`next ${Te}`:"scheduled"},Ve=ie=>{var xt;const fe=Rn((xt=ie.meta)==null?void 0:xt.subflow_id).trim(),$e=fe&&e.flow_by_id?e.flow_by_id[fe]:null,We=Rn($e==null?void 0:$e.name).trim()||fe||ie.label||ie.id,Ue=typeof le[ie.id]=="number"?Number(le[ie.id]):null,nt=Ue!==null?xe(Ue):"",ut=nt?`last ${nt}`:"subflow";return{label:We,sub:ut}},_t=(ie,fe)=>{let $e=ie.label||ie.id,Le=ie.type;if(ie.type==="on_schedule")Le=Ee(ie,fe);else if(ie.type==="subflow"){const We=Ve(ie);$e=We.label,Le=We.sub}return{label:$e,type:Le}},Qe=Rn(e.run_status).trim().toLowerCase(),ot=e.run_line||null,ze=Rn(e.run_id).trim(),He=!!(Qe||ot||ze),ft=Qe?JD.has(Qe):ot?ot.verb==="done":!1,et=Qe==="failed"||Qe==="cancelled",Ot=e.node_facts||{},Ne=e.node_status||fD(Ot),Re={};for(const[ie,fe]of Object.entries(Ne)){const $e=ne(ie);if(!$e)continue;let Le=fe;ft&&(Le==="running"||Le==="waiting")&&(Le=et?"failed":"done");const We=((wt=Ot[ie])==null?void 0:wt.last_ms)??(typeof le[ie]=="number"?le[ie]:0),Ue=Re[$e];if(!Ue){Re[$e]={s:Le,t:We};continue}const nt=Qc(Le),ut=Qc(Ue.s);(nt!==ut?nt>ut:We!==Ue.t?We>Ue.t:Le==="failed"&&Ue.s!=="failed")&&(Re[$e]={s:Le,t:We})}const tt=ie=>{var fe;return((fe=Re[ie])==null?void 0:fe.s)||"none"};let re=se;if(!re&&He){let ie=null;for(const[fe,$e]of Object.entries(Re))(ft?et&&$e.s==="failed":Qc($e.s)>0)&&(!ie||Qc($e.s)>Qc(ie.s)||Qc($e.s)===Qc(ie.s)&&$e.t>ie.t)&&(ie={id:fe,...$e});re=ie?ie.id:""}const ge=ie=>ft&&Qe==="cancelled"&&ie==="failed"?"cancelled here":J1[ie],de=new Set;let je=null,X=null;for(const[ie,fe]of Object.entries(Ot)){if(!fe||fe.visits<=0)continue;const $e=ne(ie);$e&&de.add($e),fe.first_ms!==null&&(je=je===null?fe.first_ms:Math.min(je,fe.first_ms)),fe.last_ms!==null&&(X=X===null?fe.last_ms:Math.max(X,fe.last_ms))}for(const[ie,fe]of Object.entries(o)){if(typeof fe!="number")continue;const $e=ne(ie);$e&&de.add($e)}if(je===null||X===null){const ie=Object.values(le).filter(fe=>typeof fe=="number"&&Number.isFinite(fe));ie.length>=2&&(je=Math.min(...ie),X=Math.max(...ie))}const Oe=je!==null&&X!==null&&X>=je?X-je:null,pt=ie=>ie?ie==="waiting"?"waiting, reason not loaded":ie:"state not loaded",at=(ot==null?void 0:ot.text)||pt(Qe),yt=Sa(Qe||(ot?{running:"running",needs_you:"waiting",paused:"paused",waiting:"waiting",scheduled:"scheduled",done:""}[ot.verb]??"":"")),jt=re?B[re]:void 0,st=Rn(e.current_node_label).trim()||(jt?_t(jt,re===se).label:""),Pt=!!st&&(!ft||et),Lt=`${de.size.toLocaleString("en-US")} node${de.size===1?"":"s"} visited${Oe!==null?` in ${bu(Oe)}`:""}`,mn=He?s.jsxs("div",{className:"flow_banner","data-phase":ft?"finished":"ongoing",children:[s.jsx("span",{className:`chip ${yt}`,children:ft?"finished":"ongoing"}),s.jsx("span",{className:"flow_banner_text",children:at}),Pt?s.jsxs("span",{className:"flow_banner_at",children:["· at ",s.jsx("strong",{children:st})]}):null,ft&&n?s.jsxs("span",{className:"flow_banner_meta",children:["· ",Lt]}):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 He?s.jsxs("div",{className:"graph_wrap",children:[mn,s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"})]}):s.jsx("div",{className:"graph_empty mono",children:"(no graph loaded)"});const wn=(ie,fe,$e)=>{const Le=$e||x.current,We=_.current;if(!We)return{x:ie,y:fe};const Ue=We.getBoundingClientRect(),nt=Ue.width>0?(ie-Ue.left)/Ue.width:0,ut=Ue.height>0?(fe-Ue.top)/Ue.height:0;return{x:Le.x+nt*Le.w,y:Le.y+ut*Le.h}},On=(ie,fe,$e)=>{const Le=$e||x.current,We=Math.max(.12,Math.min(8,fe)),Ue=Le.w*We,nt=Le.h*We,ut=Le.w>0?(ie.x-Le.x)/Le.w:.5,xt=Le.h>0?(ie.y-Le.y)/Le.h:.5,bt=ie.x-ut*Ue,Tt=ie.y-xt*nt;y(mk({x:bt,y:Tt,w:Ue,h:nt},m))},Ks=(ie,fe,$e)=>{const Le=$e||x.current,We=_.current;if(!We)return;const Ue=We.getBoundingClientRect(),nt=.88,ut=Ue.width>0?ie/Ue.width*Le.w*nt:0,xt=Ue.height>0?fe/Ue.height*Le.h*nt:0;y(bt=>mk({x:($e||bt).x-ut,y:($e||bt).y-xt,w:($e||bt).w,h:($e||bt).h},m))},rs=(ie,fe,$e,Le)=>{const We=m.node_w,Ue=m.node_h,nt=Math.abs($e),ut=Math.abs(Le);if(nt<1e-6&&ut<1e-6)return{x:ie,y:fe};const xt=nt>1e-6?We/2/nt:Number.POSITIVE_INFINITY,bt=ut>1e-6?Ue/2/ut:Number.POSITIVE_INFINITY,Tt=Math.min(xt,bt);return{x:ie+$e*Tt,y:fe+Le*Tt}},_e=()=>JSON.stringify(pD({run_id:ze,status:Qe,state:at,finished:ft,now_ms:t,current_id:re,nodes:d.map(ie=>({id:ie.id,label:_t(ie,!1).label,type:ie.type})),edges:h,facts:Ot,status_of:tt}),null,2),Me=$?B[$.id]:void 0;return s.jsxs("div",{className:"graph_wrap",children:[mn,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 ie=_.current;if(!ie)return;const fe=ie.getBoundingClientRect(),$e=wn(fe.left+fe.width/2,fe.top+fe.height/2);On($e,.84)},title:"Zoom in",children:"+"}),s.jsx("button",{className:"btn graph_corner_btn",type:"button",onClick:()=>{const ie=_.current;if(!ie)return;const fe=ie.getBoundingClientRect(),$e=wn(fe.left+fe.width/2,fe.top+fe.height/2);On($e,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:_e})]}),s.jsx(wD,{})]}),s.jsxs("svg",{ref:_,className:"graph_svg",viewBox:te,role:"group","aria-label":"Workflow execution graph",onWheel:ie=>{ie.preventDefault();const fe=wn(ie.clientX,ie.clientY),$e=typeof ie.deltaY=="number"?ie.deltaY:0,Le=typeof ie.deltaMode=="number"?Number(ie.deltaMode):0,We=Le===1?$e*24:Le===2?$e*800:$e,Ue=45e-5*1.15*1.1;let nt=Math.exp(We*Ue);nt=Math.max(.86,Math.min(1.16,nt)),On(fe,nt)},onPointerDown:ie=>{var $e,Le;(Le=($e=ie.currentTarget).setPointerCapture)==null||Le.call($e,ie.pointerId),k.current.set(ie.pointerId,{x:ie.clientX,y:ie.clientY});const fe=Array.from(k.current.values());if(fe.length===1)v.current={mode:"pan",start_view:x.current,start_client:{x:ie.clientX,y:ie.clientY},start_dist:0,anchor_svg:{x:0,y:0}};else if(fe.length>=2){W.current=null;const We=fe[0],Ue=fe[1],nt=We.x-Ue.x,ut=We.y-Ue.y,xt=Math.max(1,Math.hypot(nt,ut)),bt={x:(We.x+Ue.x)/2,y:(We.y+Ue.y)/2},Tt=x.current;v.current={mode:"pinch",start_view:Tt,start_client:bt,start_dist:xt,anchor_svg:wn(bt.x,bt.y,Tt)}}},onPointerMove:ie=>{if(!k.current.has(ie.pointerId))return;k.current.set(ie.pointerId,{x:ie.clientX,y:ie.clientY});const fe=v.current;if(!fe)return;const $e=Array.from(k.current.values());if(fe.mode==="pan"&&$e.length===1){const Le=ie.clientX-fe.start_client.x,We=ie.clientY-fe.start_client.y;Ks(Le,We,fe.start_view)}else if(fe.mode==="pinch"&&$e.length>=2){const Le=$e[0],We=$e[1],Ue=Le.x-We.x,nt=Le.y-We.y,ut=Math.max(1,Math.hypot(Ue,nt)),xt=fe.start_dist/ut;On(fe.anchor_svg,xt,fe.start_view)}},onPointerUp:ie=>{k.current.delete(ie.pointerId),k.current.size===0&&(v.current=null);const fe=W.current;W.current=null,fe&&k.current.size===0&&Math.hypot(ie.clientX-fe.x,ie.clientY-fe.y)<5&&J(fe.id,!1)},onPointerCancel:ie=>{k.current.delete(ie.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(ie=>{const fe=B[ie.source],$e=B[ie.target];if(!fe||!$e)return null;const Le=fe.x+m.node_w/2,We=fe.y+m.node_h/2,Ue=$e.x+m.node_w/2,nt=$e.y+m.node_h/2,ut=Ue-Le,xt=nt-We,bt=rs(Le,We,ut,xt),Tt=rs(Ue,nt,-ut,-xt),zt=ie.source!==ie.target&&N.has(`${ie.target}->${ie.source}`),ct=Math.max(1,Math.hypot(ut,xt)),Yt=-xt/ct,vn=ut/ct,hn=String(ie.source)<String(ie.target)?1:-1,Ht=Math.abs(ut)>=Math.abs(xt)?ut>=0:xt>=0,is=!zt||Ht,Be=Math.max(28,Math.min(72,ct*.14)),Qt=Math.min(200,Be*3.5),Rt=zt&&!is?Qt*hn:0,Fn=(bt.x+Tt.x)/2+Yt*Rt,fn=(bt.y+Tt.y)/2+vn*Rt,Xe=zt&&!is?`M ${bt.x} ${bt.y} Q ${Fn} ${fn} ${Tt.x} ${Tt.y}`:`M ${bt.x} ${bt.y} L ${Tt.x} ${Tt.y}`,nn=c&&ve&&ve[ie.source]!==void 0&&ve[ie.target]!==void 0;return s.jsx("path",{d:Xe,className:`graph_edge ${nn?"visited":""}`,markerEnd:"url(#arrow)",fill:"none"},ie.id)}),d.map(ie=>{const $e=(typeof ue[ie.id]=="number"?ue[ie.id]:0)>t,Le=se&&ie.id===se,We=c&&ve&&ve[ie.id]!==void 0,Ue=tt(ie.id),nt=!!re&&ie.id===re,ut=`graph_node ${Le?"active":$e?"recent":""} ${We?"visited":""}${nt?" here":""}`,xt=ie.color||"rgba(255,255,255,0.16)",{label:bt,type:Tt}=_t(ie,!!Le),zt=hk(bt,22),ct=hk(Tt,22),Yt=nt?ge(Ue):"",vn=Yt?Math.round(Yt.length*6.2+14):0,hn=Ue==="waiting"?Z1(Ot[ie.id]):Y1[Ue],sn=($==null?void 0:$.id)===ie.id;return s.jsxs("g",{ref:Ht=>{P.current[ie.id]=Ht},className:ut,transform:`translate(${ie.x}, ${ie.y})`,"data-flow-node":ie.id,"data-run-status":Ue,tabIndex:0,role:"button","aria-label":`${bt} (${Tt}): ${hn}${Yt?`, ${Yt}`:""}`,"aria-haspopup":"dialog","aria-expanded":sn,"aria-describedby":sn?V:void 0,onPointerDown:Ht=>{W.current={id:ie.id,x:Ht.clientX,y:Ht.clientY}},onMouseEnter:()=>{($==null?void 0:$.mode)!=="pinned"&&(M(),!sn&&(I.current=window.setTimeout(()=>{v.current||O(ie.id,"hover")},150)))},onMouseLeave:()=>{sn&&($==null?void 0:$.mode)==="hover"?L(ie.id):($==null?void 0:$.mode)!=="pinned"&&M()},onFocus:()=>{G.current||sn&&($==null?void 0:$.mode)==="pinned"||O(ie.id,"focus")},onBlur:Ht=>{var is;sn&&($==null?void 0:$.mode)==="focus"&&!((is=R.current)!=null&&is.contains(Ht.relatedTarget))&&L(ie.id)},onKeyDown:Ht=>{Ht.key!=="Enter"&&Ht.key!==" "||(Ht.preventDefault(),J(ie.id,!0))},children:[Ue==="running"||Ue==="waiting"||Ue==="failed"||nt?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:ct}),ie.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(YD,{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]},ie.id)})]}),$&&Me&&S&&typeof document<"u"?jg.createPortal(s.jsx("div",{ref:R,id:V,className:"flow_facts_pop",role:"dialog","aria-label":`About the node ${_t(Me,Me.id===se).label}`,tabIndex:-1,style:{top:S.top,left:S.left,width:S.width},onMouseEnter:M,onMouseLeave:()=>$.mode==="hover"?L($.id):void 0,onBlur:ie=>{$.mode==="focus"&&!ie.currentTarget.contains(ie.relatedTarget)&&L($.id)},children:s.jsx(ZD,{node:{id:Me.id,..._t(Me,Me.id===se)},facts:Ot[Me.id]||null,status:tt(Me.id),here:Me.id===re,finished:ft,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 e5(){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 t5(){return wk||(wk=1,rw.exports=e5()),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 n5(){if(vk)return sw;vk=1;var e=vm(),t=t5();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(P){if(!$){if($=!0,C=P,P=g(P),y!==void 0&&k.hasValue){var R=k.value;if(y(R,P))return S=R}return S=P}if(R=S,r(C,P))return R;var I=g(P);return y!==void 0&&y(R,I)?(C=P,R):(C=P,S=I)}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 s5(){return xk||(xk=1,nw.exports=n5()),nw.exports}var r5=s5();const i5=Yv(r5),o5={},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:()=>{(o5?"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},a5=e=>e?bk(e):bk,{useDebugValue:l5}=Ce,{useSyncExternalStoreWithSelector:c5}=i5,u5=e=>e;function Q1(e,t=u5,n){const r=c5(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return l5(r),r}const kk=(e,t)=>{const n=a5(e),r=(i,o=t)=>Q1(n,i,o);return Object.assign(r,n),r},d5=(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 f5={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 h5(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=h5(e+"",n),i,o=-1,c=r.length;if(arguments.length<2){for(;++o<c;)if((i=(e=r[o]).type)&&(i=m5(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 m5(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]=f5,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 _5(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 p5(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function e$(e){var t=Wg(e);return(t.local?p5:_5)(t)}function g5(){}function $x(e){return e==null?g5:function(){return this.querySelector(e)}}function y5(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 w5(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function v5(){return[]}function t$(e){return e==null?v5:function(){return this.querySelectorAll(e)}}function x5(e){return function(){return w5(e.apply(this,arguments))}}function b5(e){typeof e=="function"?e=x5(e):e=t$(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 n$(e){return function(){return this.matches(e)}}function s$(e){return function(t){return t.matches(e)}}var k5=Array.prototype.find;function j5(e){return function(){return k5.call(this.children,e)}}function S5(){return this.firstElementChild}function N5(e){return this.select(e==null?S5:j5(typeof e=="function"?e:s$(e)))}var $5=Array.prototype.filter;function C5(){return Array.from(this.children)}function E5(e){return function(){return $5.call(this.children,e)}}function A5(e){return this.selectAll(e==null?C5:E5(typeof e=="function"?e:s$(e)))}function T5(e){typeof e!="function"&&(e=n$(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 r$(e){return new Array(e.length)}function M5(){return new zi(this._enter||this._groups.map(r$),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 R5(e){return function(){return e}}function L5(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 I5(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 O5(e){return e.__data__}function P5(e,t){if(!arguments.length)return Array.from(this,O5);var n=t?I5:L5,r=this._parents,i=this._groups;typeof e!="function"&&(e=R5(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=D5(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 D5(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function F5(){return new zi(this._exit||this._groups.map(r$),this._parents)}function z5(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 B5(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 U5(){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 W5(e){e||(e=q5);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 q5(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function V5(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function H5(){return Array.from(this)}function G5(){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 K5(){let e=0;for(const t of this)++e;return e}function J5(){return!this.node()}function Y5(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 X5(e){return function(){this.removeAttribute(e)}}function Z5(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Q5(e,t){return function(){this.setAttribute(e,t)}}function eF(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function tF(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function nF(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 sF(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?Z5:X5:typeof t=="function"?n.local?nF:tF:n.local?eF:Q5)(n,t))}function i$(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function rF(e){return function(){this.style.removeProperty(e)}}function iF(e,t,n){return function(){this.style.setProperty(e,t,n)}}function oF(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function aF(e,t,n){return arguments.length>1?this.each((t==null?rF:typeof t=="function"?oF:iF)(e,t,n??"")):tf(this.node(),e)}function tf(e,t){return e.style.getPropertyValue(t)||i$(e).getComputedStyle(e,null).getPropertyValue(t)}function lF(e){return function(){delete this[e]}}function cF(e,t){return function(){this[e]=t}}function uF(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function dF(e,t){return arguments.length>1?this.each((t==null?lF:typeof t=="function"?uF:cF)(e,t)):this.node()[e]}function o$(e){return e.trim().split(/^|\s+/)}function Cx(e){return e.classList||new a$(e)}function a$(e){this._node=e,this._names=o$(e.getAttribute("class")||"")}a$.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 l$(e,t){for(var n=Cx(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function c$(e,t){for(var n=Cx(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function fF(e){return function(){l$(this,e)}}function hF(e){return function(){c$(this,e)}}function mF(e,t){return function(){(t.apply(this,arguments)?l$:c$)(this,e)}}function _F(e,t){var n=o$(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"?mF:t?fF:hF)(n,t))}function pF(){this.textContent=""}function gF(e){return function(){this.textContent=e}}function yF(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function wF(e){return arguments.length?this.each(e==null?pF:(typeof e=="function"?yF:gF)(e)):this.node().textContent}function vF(){this.innerHTML=""}function xF(e){return function(){this.innerHTML=e}}function bF(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function kF(e){return arguments.length?this.each(e==null?vF:(typeof e=="function"?bF:xF)(e)):this.node().innerHTML}function jF(){this.nextSibling&&this.parentNode.appendChild(this)}function SF(){return this.each(jF)}function NF(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function $F(){return this.each(NF)}function CF(e){var t=typeof e=="function"?e:e$(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function EF(){return null}function AF(e,t){var n=typeof e=="function"?e:e$(e),r=t==null?EF:typeof t=="function"?t:$x(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function TF(){var e=this.parentNode;e&&e.removeChild(this)}function MF(){return this.each(TF)}function RF(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function LF(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function IF(e){return this.select(e?LF:RF)}function OF(e){return arguments.length?this.property("__data__",e):this.node().__data__}function PF(e){return function(t){e.call(this,t,this.__data__)}}function DF(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 FF(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 zF(e,t,n){return function(){var r=this.__on,i,o=PF(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 BF(e,t,n){var r=DF(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?zF:FF,i=0;i<o;++i)this.each(l(r[i],t,n));return this}function u$(e,t,n){var r=i$(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 UF(e,t){return function(){return u$(this,e,t)}}function WF(e,t){return function(){return u$(this,e,t.apply(this,arguments))}}function qF(e,t){return this.each((typeof t=="function"?WF:UF)(e,t))}function*VF(){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 d$=[null];function zi(e,t){this._groups=e,this._parents=t}function Lm(){return new zi([[document.documentElement]],d$)}function HF(){return this}zi.prototype=Lm.prototype={constructor:zi,select:y5,selectAll:b5,selectChild:N5,selectChildren:A5,filter:T5,data:P5,enter:M5,exit:F5,join:z5,merge:B5,selection:HF,order:U5,sort:W5,call:V5,nodes:H5,node:G5,size:K5,empty:J5,each:Y5,attr:sF,style:aF,property:dF,classed:_F,text:wF,html:kF,raise:SF,lower:$F,append:CF,insert:AF,remove:MF,clone:IF,datum:OF,on:BF,dispatch:qF,[Symbol.iterator]:VF};function vo(e){return typeof e=="string"?new zi([[document.querySelector(e)]],[document.documentElement]):new zi([[e]],d$)}function GF(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Ho(e,t){if(e=GF(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 KF={passive:!1},lm={capture:!0,passive:!1};function ow(e){e.stopImmediatePropagation()}function Vd(e){e.preventDefault(),e.stopImmediatePropagation()}function f$(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 h$(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 JF(e){return!e.ctrlKey&&!e.button}function YF(){return this.parentNode}function XF(e,t){return t??{x:e.x,y:e.y}}function ZF(){return navigator.maxTouchPoints||"ontouchstart"in this}function QF(){var e=JF,t=YF,n=XF,r=ZF,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,KF).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 P=C(this,t.call(this,S,D),S,D,"mouse");P&&(vo(S.view).on("mousemove.drag",x,lm).on("mouseup.drag",k,lm),f$(S.view),ow(S),h=!1,l=S.clientX,d=S.clientY,P("start",S))}}function x(S){if(Vd(S),!h){var D=S.clientX-l,P=S.clientY-d;h=D*D+P*P>_}i.mouse("drag",S)}function k(S){vo(S.view).on("mousemove.drag mouseup.drag",null),h$(S.view,h),Vd(S),i.mouse("end",S)}function v(S,D){if(e.call(this,S,D)){var P=S.changedTouches,R=t.call(this,S,D),I=P.length,W,G;for(W=0;W<I;++W)(G=C(this,R,S,D,P[W].identifier,P[W]))&&(ow(S),G("start",S,P[W]))}}function N(S){var D=S.changedTouches,P=D.length,R,I;for(R=0;R<P;++R)(I=i[D[R].identifier])&&(Vd(S),I("drag",S,D[R]))}function $(S){var D=S.changedTouches,P=D.length,R,I;for(m&&clearTimeout(m),m=setTimeout(function(){m=null},500),R=0;R<P;++R)(I=i[D[R].identifier])&&(ow(S),I("end",S,D[R]))}function C(S,D,P,R,I,W){var G=o.copy(),K=Ho(W||P,D),V,M,A;if((A=n.call(S,new gv("beforestart",{sourceEvent:P,target:g,identifier:I,active:c,x:K[0],y:K[1],dx:0,dy:0,dispatch:G}),R))!=null)return V=A.x-K[0]||0,M=A.y-K[1]||0,function O(L,J,H){var z=K,te;switch(L){case"start":i[I]=O,te=c++;break;case"end":delete i[I],--c;case"drag":K=Ho(H||J,D),te=c;break}G.call(L,S,new gv(L,{sourceEvent:J,subject:A,target:g,identifier:I,active:te,x:K[0]+V,y:K[1]+M,dx:K[0]-z[0],dy:K[1]-z[1],dispatch:G}),R)}}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 m$(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*",e6=/^#([0-9a-f]{3,8})$/,t6=new RegExp(`^rgb\\(${Hd},${Hd},${Hd}\\)$`),n6=new RegExp(`^rgb\\(${ja},${ja},${ja}\\)$`),s6=new RegExp(`^rgba\\(${Hd},${Hd},${Hd},${um}\\)$`),r6=new RegExp(`^rgba\\(${ja},${ja},${ja},${um}\\)$`),i6=new RegExp(`^hsl\\(${um},${ja},${ja}\\)$`),o6=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:a6,formatHsl:l6,formatRgb:Ck,toString:Ck});function $k(){return this.rgb().formatHex()}function a6(){return this.rgb().formatHex8()}function l6(){return _$(this).formatHsl()}function Ck(){return this.rgb().formatRgb()}function dm(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=e6.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=t6.exec(e))?new Si(t[1],t[2],t[3],1):(t=n6.exec(e))?new Si(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=s6.exec(e))?dp(t[1],t[2],t[3],t[4]):(t=r6.exec(e))?dp(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=i6.exec(e))?Mk(t[1],t[2]/100,t[3]/100,1):(t=o6.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 c6(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?c6(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,m$(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:u6,formatRgb:Tk,toString:Tk}));function Ak(){return`#${iu(this.r)}${iu(this.g)}${iu(this.b)}`}function u6(){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 _$(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 d6(e,t,n,r){return arguments.length===1?_$(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,d6,m$(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 p$=e=>()=>e;function f6(e,t){return function(n){return e+n*t}}function h6(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 m6(e){return(e=+e)==1?g$:function(t,n){return n-t?h6(t,n,e):p$(isNaN(t)?n:t)}}function g$(e,t){var n=t-e;return n?f6(e,n):p$(isNaN(e)?t:e)}const Lk=(function e(t){var n=m6(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=g$(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 _6(e){return function(){return e}}function p6(e){return function(t){return e(t)+""}}function g6(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]?p6(d[0].x):_6(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 y$(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 y6(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?vv:y$(t.a,t.b,t.c,t.d,t.e,t.f)}function w6(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,y$(e.a,e.b,e.c,e.d,e.e,e.f))}function w$(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 v6=w$(y6,"px, ","px)","deg)"),x6=w$(w6,", ",")",")"),b6=1e-12;function Ok(e){return((e=Math.exp(e))+1/e)/2}function k6(e){return((e=Math.exp(e))-1/e)/2}function j6(e){return((e=Math.exp(2*e))-1)/(e+1)}const S6=(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<b6)N=Math.log(g/h)/t,v=function(R){return[l+R*y,d+R*x,h*Math.exp(t*R*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),P=Math.log(Math.sqrt(S*S+1)-S);N=(P-D)/t,v=function(R){var I=R*N,W=Ok(D),G=h/(n*$)*(W*j6(t*I+D)-k6(D));return[l+G*y,d+G*x,h*W/Ok(t*I+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,v$=1e3,fg,Hh,hg=0,vu=0,qg=0,fm=typeof performance=="object"&&performance.now?performance:Date,x$=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Ax(){return vu||(x$(N6),vu=fm.now()+qg)}function N6(){vu=0}function mg(){this._call=this._time=this._next=null}mg.prototype=b$.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 b$(e,t,n){var r=new mg;return r.restart(e,t,n),r}function $6(){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{$6()}finally{nf=0,E6(),vu=0}}function C6(){var e=fm.now(),t=e-hg;t>v$&&(qg-=t,hg=e)}function E6(){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(C6,v$)),nf=1,x$(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 A6=Ug("start","end","cancel","interrupt"),T6=[],k$=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;M6(e,n,{name:t,index:r,group:i,on:A6,tween:T6,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:k$})}function Tx(e,t){var n=Xo(e,t);if(n.state>k$)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 M6(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=b$(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 R6(e){return this.each(function(){Fp(this,e)})}function L6(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 I6(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 O6(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?L6:I6)(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 j$(e,t){var n;return(typeof t=="number"?Ql:t instanceof dm?Lk:(n=dm(t))?(t=n,Lk):g6)(e,t)}function P6(e){return function(){this.removeAttribute(e)}}function D6(e){return function(){this.removeAttributeNS(e.space,e.local)}}function F6(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 z6(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 B6(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 U6(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 W6(e,t){var n=Wg(e),r=n==="transform"?x6:j$;return this.attrTween(e,typeof t=="function"?(n.local?U6:B6)(n,r,Mx(this,"attr."+e,t)):t==null?(n.local?D6:P6)(n):(n.local?z6:F6)(n,r,t))}function q6(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function V6(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function H6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&V6(e,o)),n}return i._value=t,i}function G6(e,t){var n,r;function i(){var o=t.apply(this,arguments);return o!==r&&(n=(r=o)&&q6(e,o)),n}return i._value=t,i}function K6(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?H6:G6)(r,t))}function J6(e,t){return function(){Tx(this,e).delay=+t.apply(this,arguments)}}function Y6(e,t){return t=+t,function(){Tx(this,e).delay=t}}function X6(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?J6:Y6)(t,e)):Xo(this.node(),t).delay}function Z6(e,t){return function(){Na(this,e).duration=+t.apply(this,arguments)}}function Q6(e,t){return t=+t,function(){Na(this,e).duration=t}}function e8(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Z6:Q6)(t,e)):Xo(this.node(),t).duration}function t8(e,t){if(typeof t!="function")throw new Error;return function(){Na(this,e).ease=t}}function n8(e){var t=this._id;return arguments.length?this.each(t8(t,e)):Xo(this.node(),t).ease}function s8(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Na(this,e).ease=n}}function r8(e){if(typeof e!="function")throw new Error;return this.each(s8(this._id,e))}function i8(e){typeof e!="function"&&(e=n$(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 o8(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 a8(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 l8(e,t,n){var r,i,o=a8(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 c8(e,t){var n=this._id;return arguments.length<2?Xo(this.node(),n).on.on(e):this.each(l8(n,e,t))}function u8(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function d8(){return this.on("end.remove",u8(this._id))}function f8(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 h8(e){var t=this._name,n=this._id;typeof e!="function"&&(e=t$(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 m8=Lm.prototype.constructor;function _8(){return new m8(this._groups,this._parents)}function p8(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 S$(e){return function(){this.style.removeProperty(e)}}function g8(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 y8(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 w8(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=S$(t)):void 0;(h!==n||i!==m)&&(r=(n=h).copy()).on(c,i=m),d.on=r}}function v8(e,t,n){var r=(e+="")=="transform"?v6:j$;return t==null?this.styleTween(e,p8(e,r)).on("end.style."+e,S$(e)):typeof t=="function"?this.styleTween(e,y8(e,r,Mx(this,"style."+e,t))).each(w8(this._id,e)):this.styleTween(e,g8(e,r,t),n).on("end.style."+e,null)}function x8(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function b8(e,t,n){var r,i;function o(){var c=t.apply(this,arguments);return c!==i&&(r=(i=c)&&x8(e,c,n)),r}return o._value=t,o}function k8(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,b8(e,t,n??""))}function j8(e){return function(){this.textContent=e}}function S8(e){return function(){var t=e(this);this.textContent=t??""}}function N8(e){return this.tween("text",typeof e=="function"?S8(Mx(this,"text",e)):j8(e==null?"":e+""))}function $8(e){return function(t){this.textContent=e.call(this,t)}}function C8(e){var t,n;function r(){var i=e.apply(this,arguments);return i!==n&&(t=(n=i)&&$8(i)),t}return r._value=e,r}function E8(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,C8(e))}function A8(){for(var e=this._name,t=this._id,n=N$(),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 T8(){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 M8=0;function ll(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function N$(){return++M8}var Xa=Lm.prototype;ll.prototype={constructor:ll,select:f8,selectAll:h8,selectChild:Xa.selectChild,selectChildren:Xa.selectChildren,filter:i8,merge:o8,selection:_8,transition:A8,call:Xa.call,nodes:Xa.nodes,node:Xa.node,size:Xa.size,empty:Xa.empty,each:Xa.each,on:c8,attr:W6,attrTween:K6,style:v8,styleTween:k8,text:N8,textTween:E8,remove:d8,tween:O6,delay:X6,duration:e8,ease:n8,easeVarying:r8,end:T8,[Symbol.iterator]:Xa[Symbol.iterator]};function R8(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var L8={time:null,delay:0,duration:250,ease:R8};function I8(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 O8(e){var t,n;e instanceof ll?(t=e._id,e=e._name):(t=N$(),(n=L8).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||I8(d,t));return new ll(r,this._parents,e,t)}Lm.prototype.interrupt=R6;Lm.prototype.transition=O8;const mp=e=>()=>e;function P8(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 D8(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function F8(){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 z8(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function B8(){return navigator.maxTouchPoints||"ontouchstart"in this}function U8(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 $$(){var e=D8,t=F8,n=U8,r=z8,i=B8,o=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],l=250,d=S6,h=Ug("start","zoom","end"),m,_,g,y=500,x=150,k=0,v=10;function N(A){A.property("__zoom",Bk).on("wheel.zoom",I,{passive:!1}).on("mousedown.zoom",W).on("dblclick.zoom",G).filter(i).on("touchstart.zoom",K).on("touchmove.zoom",V).on("touchend.zoom touchcancel.zoom",M).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}N.transform=function(A,O,L,J){var H=A.selection?A.selection():A;H.property("__zoom",Bk),A!==H?D(A,O,L,J):H.interrupt().each(function(){P(this,arguments).event(J).start().zoom(null,typeof O=="function"?O.apply(this,arguments):O).end()})},N.scaleBy=function(A,O,L,J){N.scaleTo(A,function(){var H=this.__zoom.k,z=typeof O=="function"?O.apply(this,arguments):O;return H*z},L,J)},N.scaleTo=function(A,O,L,J){N.transform(A,function(){var H=t.apply(this,arguments),z=this.__zoom,te=L==null?S(H):typeof L=="function"?L.apply(this,arguments):L,B=z.invert(te),ne=typeof O=="function"?O.apply(this,arguments):O;return n(C($(z,ne),te,B),H,c)},L,J)},N.translateBy=function(A,O,L,J){N.transform(A,function(){return n(this.__zoom.translate(typeof O=="function"?O.apply(this,arguments):O,typeof L=="function"?L.apply(this,arguments):L),t.apply(this,arguments),c)},null,J)},N.translateTo=function(A,O,L,J,H){N.transform(A,function(){var z=t.apply(this,arguments),te=this.__zoom,B=J==null?S(z):typeof J=="function"?J.apply(this,arguments):J;return n(sl.translate(B[0],B[1]).scale(te.k).translate(typeof O=="function"?-O.apply(this,arguments):-O,typeof L=="function"?-L.apply(this,arguments):-L),z,c)},J,H)};function $(A,O){return O=Math.max(o[0],Math.min(o[1],O)),O===A.k?A:new tl(O,A.x,A.y)}function C(A,O,L){var J=O[0]-L[0]*A.k,H=O[1]-L[1]*A.k;return J===A.x&&H===A.y?A:new tl(A.k,J,H)}function S(A){return[(+A[0][0]+ +A[1][0])/2,(+A[0][1]+ +A[1][1])/2]}function D(A,O,L,J){A.on("start.zoom",function(){P(this,arguments).event(J).start()}).on("interrupt.zoom end.zoom",function(){P(this,arguments).event(J).end()}).tween("zoom",function(){var H=this,z=arguments,te=P(H,z).event(J),B=t.apply(H,z),ne=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]),ue=H.__zoom,ve=typeof O=="function"?O.apply(H,z):O,Te=d(ue.invert(ne).concat(se/ue.k),ve.invert(ne).concat(se/ve.k));return function(ke){if(ke===1)ke=ve;else{var le=Te(ke),xe=se/le[2];ke=new tl(xe,ne[0]-le[0]*xe,ne[1]-le[1]*xe)}te.zoom(null,ke)}})}function P(A,O,L){return!L&&A.__zooming||new R(A,O)}function R(A,O){this.that=A,this.args=O,this.active=0,this.sourceEvent=null,this.extent=t.apply(A,O),this.taps=0}R.prototype={event:function(A){return A&&(this.sourceEvent=A),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(A,O){return this.mouse&&A!=="mouse"&&(this.mouse[1]=O.invert(this.mouse[0])),this.touch0&&A!=="touch"&&(this.touch0[1]=O.invert(this.touch0[0])),this.touch1&&A!=="touch"&&(this.touch1[1]=O.invert(this.touch1[0])),this.that.__zoom=O,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(A){var O=vo(this.that).datum();h.call(A,this.that,new P8(A,{sourceEvent:this.sourceEvent,target:N,transform:this.that.__zoom,dispatch:h}),O)}};function I(A,...O){if(!e.apply(this,arguments))return;var L=P(this,O).event(A),J=this.__zoom,H=Math.max(o[0],Math.min(o[1],J.k*Math.pow(2,r.apply(this,arguments)))),z=Ho(A);if(L.wheel)(L.mouse[0][0]!==z[0]||L.mouse[0][1]!==z[1])&&(L.mouse[1]=J.invert(L.mouse[0]=z)),clearTimeout(L.wheel);else{if(J.k===H)return;L.mouse=[z,J.invert(z)],Fp(this),L.start()}Ch(A),L.wheel=setTimeout(te,x),L.zoom("mouse",n(C($(J,H),L.mouse[0],L.mouse[1]),L.extent,c));function te(){L.wheel=null,L.end()}}function W(A,...O){if(g||!e.apply(this,arguments))return;var L=A.currentTarget,J=P(this,O,!0).event(A),H=vo(A.view).on("mousemove.zoom",ne,!0).on("mouseup.zoom",se,!0),z=Ho(A,L),te=A.clientX,B=A.clientY;f$(A.view),cw(A),J.mouse=[z,this.__zoom.invert(z)],Fp(this),J.start();function ne(ue){if(Ch(ue),!J.moved){var ve=ue.clientX-te,Te=ue.clientY-B;J.moved=ve*ve+Te*Te>k}J.event(ue).zoom("mouse",n(C(J.that.__zoom,J.mouse[0]=Ho(ue,L),J.mouse[1]),J.extent,c))}function se(ue){H.on("mousemove.zoom mouseup.zoom",null),h$(ue.view,J.moved),Ch(ue),J.event(ue).end()}}function G(A,...O){if(e.apply(this,arguments)){var L=this.__zoom,J=Ho(A.changedTouches?A.changedTouches[0]:A,this),H=L.invert(J),z=L.k*(A.shiftKey?.5:2),te=n(C($(L,z),J,H),t.apply(this,O),c);Ch(A),l>0?vo(this).transition().duration(l).call(D,te,J,A):vo(this).call(N.transform,te,J,A)}}function K(A,...O){if(e.apply(this,arguments)){var L=A.touches,J=L.length,H=P(this,O,A.changedTouches.length===J).event(A),z,te,B,ne;for(cw(A),te=0;te<J;++te)B=L[te],ne=Ho(B,this),ne=[ne,this.__zoom.invert(ne),B.identifier],H.touch0?!H.touch1&&H.touch0[2]!==ne[2]&&(H.touch1=ne,H.taps=0):(H.touch0=ne,z=!0,H.taps=1+!!m);m&&(m=clearTimeout(m)),z&&(H.taps<2&&(_=ne[0],m=setTimeout(function(){m=null},y)),Fp(this),H.start())}}function V(A,...O){if(this.__zooming){var L=P(this,O).event(A),J=A.changedTouches,H=J.length,z,te,B,ne;for(Ch(A),z=0;z<H;++z)te=J[z],B=Ho(te,this),L.touch0&&L.touch0[2]===te.identifier?L.touch0[0]=B:L.touch1&&L.touch1[2]===te.identifier&&(L.touch1[0]=B);if(te=L.that.__zoom,L.touch1){var se=L.touch0[0],ue=L.touch0[1],ve=L.touch1[0],Te=L.touch1[1],ke=(ke=ve[0]-se[0])*ke+(ke=ve[1]-se[1])*ke,le=(le=Te[0]-ue[0])*le+(le=Te[1]-ue[1])*le;te=$(te,Math.sqrt(ke/le)),B=[(se[0]+ve[0])/2,(se[1]+ve[1])/2],ne=[(ue[0]+Te[0])/2,(ue[1]+Te[1])/2]}else if(L.touch0)B=L.touch0[0],ne=L.touch0[1];else return;L.zoom("touch",n(C(te,B,ne),L.extent,c))}}function M(A,...O){if(this.__zooming){var L=P(this,O).event(A),J=A.changedTouches,H=J.length,z,te;for(cw(A),g&&clearTimeout(g),g=setTimeout(function(){g=null},y),z=0;z<H;++z)te=J[z],L.touch0&&L.touch0[2]===te.identifier?delete L.touch0:L.touch1&&L.touch1[2]===te.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&&(te=Ho(te,this),Math.hypot(_[0]-te[0],_[1]-te[1])<v)){var B=vo(this).on("dblclick.zoom");B&&B.apply(this,arguments)}}}return N.wheelDelta=function(A){return arguments.length?(r=typeof A=="function"?A:mp(+A),N):r},N.filter=function(A){return arguments.length?(e=typeof A=="function"?A:mp(!!A),N):e},N.touchable=function(A){return arguments.length?(i=typeof A=="function"?A:mp(!!A),N):i},N.extent=function(A){return arguments.length?(t=typeof A=="function"?A:mp([[+A[0][0],+A[0][1]],[+A[1][0],+A[1][1]]]),N):t},N.scaleExtent=function(A){return arguments.length?(o[0]=+A[0],o[1]=+A[1],N):[o[0],o[1]]},N.translateExtent=function(A){return arguments.length?(c[0][0]=+A[0][0],c[1][0]=+A[1][0],c[0][1]=+A[0][1],c[1][1]=+A[1][1],N):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},N.constrain=function(A){return arguments.length?(n=A,N):n},N.duration=function(A){return arguments.length?(l=+A,N):l},N.interpolate=function(A){return arguments.length?(d=A,N):d},N.on=function(){var A=h.on.apply(h,arguments);return A===h?N:A},N.clickDistance=function(A){return arguments.length?(k=(A=+A)*A,N):Math.sqrt(k)},N.tapDistance=function(A){return arguments.length?(v=+A,N):v},N}const Hg=p.createContext(null),W8=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.`},C$=cl.error001();function ms(e,t){const n=p.useContext(Hg);if(n===null)throw new Error(C$);return Q1(n,e,t)}const tr=()=>{const e=p.useContext(Hg);if(e===null)throw new Error(C$);return p.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},q8=e=>e.userSelectionActive?"none":"all";function hm({position:e,children:t,className:n,style:r,...i}){const o=ms(q8),c=`${e}`.split("-");return Ce.createElement("div",{className:Er(["react-flow__panel",n,...c]),style:{...r,pointerEvents:o},...i},t)}function V8({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:Ce.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"},Ce.createElement("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution"},"React Flow"))}const H8=({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:Ce.createElement("g",{transform:`translate(${e-g.width/2} ${t-g.height/2})`,className:x,visibility:g.width?"visible":"hidden",...m},i&&Ce.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}),Ce.createElement("text",{className:"react-flow__edge-text",y:g.height/2,dy:"0.3em",ref:_,style:r},n),d)};var G8=p.memo(H8);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,E$=(e,t)=>{const n=Uk(e.x,35,t.width-35)*20,r=Uk(e.y,35,t.height-35)*20;return[n,r]},A$=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},T$=(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}),M$=({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}),K8=(e,t)=>M$(T$(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)},J8=e=>xo(e.width)&&xo(e.height)&&xo(e.x)&&xo(e.y),xo=e=>!isNaN(e)&&isFinite(e),Gs=Symbol.for("internals"),R$=["Enter"," ","Escape"],Y8=(e,t)=>{},X8=e=>"nativeEvent"in e;function Sv(e){var i,o;const t=X8(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 L$=e=>"clientX"in e,ac=(e,t)=>{var o,c;const n=L$(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})=>Ce.createElement(Ce.Fragment,null,Ce.createElement("path",{id:e,style:m,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:_,markerStart:g}),y&&Ce.createElement("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:y,className:"react-flow__edge-interaction"}),i&&xo(n)&&xo(r)?Ce.createElement(G8,{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 I$({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 O$({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 P$({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]=O$({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,$]=P$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o});return Ce.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}},Z8=({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 Q8({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=Z8({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]=I$({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(c[_]*l[_]===-1){x=i.x||$,k=i.y||C;const R=[{x,y:d.y},{x,y:h.y}],I=[{x:d.x,y:k},{x:h.x,y:k}];c[_]===g?y=_==="x"?R:I:y=_==="x"?I:R}else{const R=[{x:d.x,y:h.y}],I=[{x:h.x,y:d.y}];if(_==="x"?y=c.x===g?I:R:y=c.y===g?R:I,t===r){const M=Math.abs(e[_]-n[_]);if(M<=o){const A=Math.min(o-1,o-M);c[_]===g?v[_]=(d[_]>e[_]?-1:1)*A:N[_]=(h[_]>n[_]?-1:1)*A}}if(t!==r){const M=_==="x"?"y":"x",A=c[_]===l[M],O=d[M]>h[M],L=d[M]<h[M];(c[_]===1&&(!A&&O||A&&L)||c[_]!==1&&(!A&&L||A&&O))&&(y=_==="x"?R:I)}const W={x:d.x+v.x,y:d.y+v.y},G={x:h.x+N.x,y:h.y+N.y},K=Math.max(Math.abs(W.x-y[0].x),Math.abs(G.x-y[0].x)),V=Math.max(Math.abs(W.y-y[0].y),Math.abs(G.y-y[0].y));K>=V?(x=(W.x+G.x)/2,k=y[0].y):(x=y[0].x,k=(W.y+G.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 ez(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]=Q8({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=ez(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 Ce.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 Ce.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 tz({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,c,l]=I$({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]=tz({sourceX:e,sourceY:t,targetX:n,targetY:r});return Ce.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 D$({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]=O$({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]=D$({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o,curvature:k==null?void 0:k.curvature});return Ce.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),nz=Dx.Provider;Dx.Consumer;const sz=()=>p.useContext(Dx),rz=e=>"id"in e&&"source"in e&&"target"in e,iz=({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("&")}`,oz=(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)),az=(e,t)=>{if(!e.source||!e.target)return t;let n;return rz(e)?n={...e}:n={...e,id:iz(e)},oz(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},F$=({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 T$(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 M$(n)},z$=(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},B$=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},U$=(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 lz(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:W$()};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 cz={source:null,target:null,sourceHandle:null,targetHandle:null},W$=()=>({handleDomNode:null,isValid:!1,connection:cz,endHandle:null});function q$(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={...W$(),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 uz({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 dz(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function V$({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:i,getState:o,setState:c,isValidConnection:l,edgeUpdaterType:d,onEdgeUpdateEnd:h}){const m=A$(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:P}=ac(e),R=m==null?void 0:m.elementFromPoint(D,P),I=Fx(d,R),W=g==null?void 0:g.getBoundingClientRect();if(!W||!I)return;let G,K=ac(e,W),V=!1,M=null,A=!1,O=null;const L=uz({nodes:N(),nodeId:n,handleId:t,handleType:I}),J=()=>{if(!y)return;const[te,B]=E$(K,W);v({x:te,y:B}),C=requestAnimationFrame(J)};c({connectionPosition:K,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:I,connectionStartHandle:{nodeId:n,handleId:t,type:I},connectionEndHandle:null}),k==null||k(e,{nodeId:n,handleId:t,handleType:I});function H(te){const{transform:B}=o();K=ac(te,W);const{handle:ne,validHandleResult:se}=lz(te,m,Cv(K,B,!1,[1,1]),x,L,ue=>q$(ue,_,n,t,i?"target":"source",l,m));if(S=ne,V||(J(),V=!0),O=se.handleDomNode,M=se.connection,A=se.isValid,c({connectionPosition:S&&A?F$({x:S.x,y:S.y},B):K,connectionStatus:dz(!!S,A),connectionEndHandle:se.endHandle}),!S&&!A&&!O)return uw(G);M.source!==M.target&&O&&(uw(G),G=O,O.classList.add("connecting","react-flow__handle-connecting"),O.classList.toggle("valid",A),O.classList.toggle("react-flow__handle-valid",A))}function z(te){var B,ne;(S||O)&&M&&A&&(r==null||r(M)),(ne=(B=o()).onConnectEnd)==null||ne.call(B,te),d&&(h==null||h(te)),uw(G),$(),cancelAnimationFrame(C),V=!1,A=!1,M=null,O=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,fz=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),hz=(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}},H$=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,G;const x=c||null,k=e==="target",v=tr(),N=sz(),{connectOnClick:$,noPanClassName:C}=ms(fz,mr),{connecting:S,clickConnecting:D}=ms(hz(N,x,e),mr);N||(G=(W=v.getState()).onError)==null||G.call(W,"010",cl.error010());const P=K=>{const{defaultEdgeOptions:V,onConnect:M,hasDefaultEdges:A}=v.getState(),O={...V,...K};if(A){const{edges:L,setEdges:J}=v.getState();J(az(O,L))}M==null||M(O),l==null||l(O)},R=K=>{if(!N)return;const V=L$(K);i&&(V&&K.button===0||!V)&&V$({event:K,handleId:x,nodeId:N,onConnect:P,isTarget:k,getState:v.getState,setState:v.setState,isValidConnection:n||v.getState().isValidConnection||Jk}),V?m==null||m(K):_==null||_(K)},I=K=>{const{onClickConnectStart:V,onClickConnectEnd:M,connectionClickStartHandle:A,connectionMode:O,isValidConnection:L}=v.getState();if(!N||!A&&!i)return;if(!A){V==null||V(K,{nodeId:N,handleId:x,handleType:e}),v.setState({connectionClickStartHandle:{nodeId:N,type:e,handleId:x}});return}const J=A$(K.target),H=n||L||Jk,{connection:z,isValid:te}=q$({nodeId:N,id:x,type:e},O,A.nodeId,A.handleId||null,A.type,H,J);te&&P(z),M==null||M(K),v.setState({connectionClickStartHandle:null})};return Ce.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:R,onTouchStart:R,onClick:$?I:void 0,ref:y,...g},d)});H$.displayName="Handle";var gg=p.memo(H$);const G$=({data:e,isConnectable:t,targetPosition:n=Ut.Top,sourcePosition:r=Ut.Bottom})=>Ce.createElement(Ce.Fragment,null,Ce.createElement(gg,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,Ce.createElement(gg,{type:"source",position:r,isConnectable:t}));G$.displayName="DefaultNode";var Ev=p.memo(G$);const K$=({data:e,isConnectable:t,sourcePosition:n=Ut.Bottom})=>Ce.createElement(Ce.Fragment,null,e==null?void 0:e.label,Ce.createElement(gg,{type:"source",position:n,isConnectable:t}));K$.displayName="InputNode";var J$=p.memo(K$);const Y$=({data:e,isConnectable:t,targetPosition:n=Ut.Top})=>Ce.createElement(Ce.Fragment,null,Ce.createElement(gg,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label);Y$.displayName="OutputNode";var X$=p.memo(Y$);const zx=()=>null;zx.displayName="GroupNode";const mz=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),pp=e=>e.id;function _z(e,t){return mr(e.selectedNodes.map(pp),t.selectedNodes.map(pp))&&mr(e.selectedEdges.map(pp),t.selectedEdges.map(pp))}const Z$=p.memo(({onSelectionChange:e})=>{const t=tr(),{selectedNodes:n,selectedEdges:r}=ms(mz,_z);return p.useEffect(()=>{const i={nodes:n,edges:r};e==null||e(i),t.getState().onSelectionChange.forEach(o=>o(i))},[n,r,e]),null});Z$.displayName="SelectionListener";const pz=e=>!!e.onSelectionChange;function gz({onSelectionChange:e}){const t=ms(pz);return e||t?Ce.createElement(Z$,{onSelectionChange:e}):null}const yz=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 wz=({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:P,snapToGrid:R,translateExtent:I,connectOnClick:W,defaultEdgeOptions:G,fitView:K,fitViewOptions:V,onNodesDelete:M,onEdgesDelete:A,onNodeDrag:O,onNodeDragStart:L,onNodeDragStop:J,onSelectionDrag:H,onSelectionDragStart:z,onSelectionDragStop:te,noPanClassName:B,nodeOrigin:ne,rfId:se,autoPanOnConnect:ue,autoPanOnNodeDrag:ve,onError:Te,connectionRadius:ke,isValidConnection:le,nodeDragThreshold:xe})=>{const{setNodes:Ee,setEdges:Ve,setDefaultNodesAndEdges:_t,setMinZoom:Qe,setMaxZoom:ot,setTranslateExtent:ze,setNodeExtent:He,reset:ft}=ms(yz,mr),et=tr();return p.useEffect(()=>{const Ot=r==null?void 0:r.map(Ne=>({...Ne,...G}));return _t(n,Ot),()=>{ft()}},[]),Nn("defaultEdgeOptions",G,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",R,et.setState),Nn("snapGrid",P,et.setState),Nn("onNodesChange",$,et.setState),Nn("onEdgesChange",C,et.setState),Nn("connectOnClick",W,et.setState),Nn("fitViewOnInit",K,et.setState),Nn("fitViewOnInitOptions",V,et.setState),Nn("onNodesDelete",M,et.setState),Nn("onEdgesDelete",A,et.setState),Nn("onNodeDrag",O,et.setState),Nn("onNodeDragStart",L,et.setState),Nn("onNodeDragStop",J,et.setState),Nn("onSelectionDrag",H,et.setState),Nn("onSelectionDragStart",z,et.setState),Nn("onSelectionDragStop",te,et.setState),Nn("noPanClassName",B,et.setState),Nn("nodeOrigin",ne,et.setState),Nn("rfId",se,et.setState),Nn("autoPanOnConnect",ue,et.setState),Nn("autoPanOnNodeDrag",ve,et.setState),Nn("onError",Te,et.setState),Nn("connectionRadius",ke,et.setState),Nn("isValidConnection",le,et.setState),Nn("nodeDragThreshold",xe,et.setState),jd(e,Ee),jd(t,Ve),jd(k,Qe),jd(v,ot),jd(I,ze),jd(N,He),null},Yk={display:"none"},vz={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Q$="react-flow__node-desc",eC="react-flow__edge-desc",xz="react-flow__aria-live",bz=e=>e.ariaLiveMessage;function kz({rfId:e}){const t=ms(bz);return Ce.createElement("div",{id:`${xz}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:vz},t)}function jz({rfId:e,disableKeyboardA11y:t}){return Ce.createElement(Ce.Fragment,null,Ce.createElement("div",{id:`${Q$}-${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."," "),Ce.createElement("div",{id:`${eC}-${e}`,style:Yk},"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."),!t&&Ce.createElement(kz,{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 tC(e,t,n,r){var c,l;if(!e.parentNode)return n;const i=t.get(e.parentNode),o=du(i,r);return tC(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 nC(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}=tC(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)}),nC(i,n,o),i}function sC(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}=U$(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 Sz(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 Nz(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:Sz(e,i)}),c==null||c(e)),t!=null&&t.length&&(h&&r({edges:Nz(t,o)}),l==null||l(t))}const Sd=()=>{},$z={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},Cz=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),Ez=()=>{const e=tr(),{d3Zoom:t,d3Selection:n}=ms(Cz,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=>sC(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}=U$(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=F$(i,o);return{x:h.x+l,y:h.y+d}},viewportInitialized:!0}:$z,[t,n])};function Bx(){const e=Ez(),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 P=D.length===0?S.map(R=>({type:"remove",id:R.id})):D.map(R=>({item:R,type:"reset"}));C(P)}},[]),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(P=>({type:"remove",id:P.id})):S.map(P=>({item:P,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 P=[...N(),...v];$(P)}else if(S){const D=v.map(P=>({item:P,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(P=>({item:P,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:P,onEdgesDelete:R,onNodesChange:I,onEdgesChange:W}=t.getState(),G=(k||[]).map(O=>O.id),K=(v||[]).map(O=>O.id),V=$().reduce((O,L)=>{const J=!G.includes(L.id)&&L.parentNode&&O.find(z=>z.id===L.parentNode);return(typeof L.deletable=="boolean"?L.deletable:!0)&&(G.includes(L.id)||J)&&O.push(L),O},[]),M=C.filter(O=>typeof O.deletable=="boolean"?O.deletable:!0),A=M.filter(O=>K.includes(O.id));if(V||A){const O=B$(V,M),L=[...A,...O],J=L.reduce((H,z)=>(H.includes(z.id)||H.push(z.id),H),[]);if((D||S)&&(D&&t.setState({edges:C.filter(H=>!J.includes(H.id))}),S&&(V.forEach(H=>{N.delete(H.id)}),t.setState({nodeInternals:new Map(N)}))),J.length>0&&(R==null||R(L),W&&W(J.map(H=>({id:H,type:"remove"})))),V.length>0&&(P==null||P(V),I)){const H=V.map(z=>({id:z.id,type:"remove"}));I(H)}}},[]),g=p.useCallback(k=>{const v=J8(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 P=Wk(D),R=jv(P,$);return v&&R>0||R>=$.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 Az={actInsideInputWithModifier:!1};var Tz=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=tr(),{deleteElements:r}=Bx(),i=gm(e,Az),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 Mz(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},Rz=(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},Lz=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),Iz=({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(),P=tr(),R=p.useRef(!1),I=p.useRef(!1),W=p.useRef(null),G=p.useRef({x:0,y:0,zoom:0}),{d3Zoom:K,d3Selection:V,d3ZoomHandler:M,userSelectionActive:A}=ms(Lz,mr),O=gm(v),L=p.useRef(0),J=p.useRef(!1),H=p.useRef();return Mz(W),p.useEffect(()=>{if(W.current){const z=W.current.getBoundingClientRect(),te=$$().scaleExtent([x,k]).translateExtent(y),B=vo(W.current).call(te),ne=sl.translate(g.x,g.y).scale(sf(g.zoom,x,k)),se=[[0,0],[z.width,z.height]],ue=te.constrain()(ne,se,y);te.transform(B,ue),te.wheelDelta(ej),P.setState({d3Zoom:te,d3Selection:B,d3ZoomHandler:B.on("wheel.zoom"),transform:[ue.x,ue.y,ue.k],domNode:W.current.closest(".react-flow")})}},[]),p.useEffect(()=>{V&&K&&(c&&!O&&!A?V.on("wheel.zoom",z=>{if(Nd(z,C))return!1;z.preventDefault(),z.stopImmediatePropagation();const te=V.property("__zoom").k||1,B=_g();if(z.ctrlKey&&o&&B){const xe=Ho(z),Ee=ej(z),Ve=te*Math.pow(2,Ee);K.scaleTo(V,Ve,xe,z);return}const ne=z.deltaMode===1?20:1;let se=d===ou.Vertical?0:z.deltaX*ne,ue=d===ou.Horizontal?0:z.deltaY*ne;!B&&z.shiftKey&&d!==ou.Vertical&&(se=z.deltaY*ne,ue=0),K.translateBy(V,-(se/te)*l,-(ue/te)*l,{internal:!0});const ve=yp(V.property("__zoom")),{onViewportChangeStart:Te,onViewportChange:ke,onViewportChangeEnd:le}=P.getState();clearTimeout(H.current),J.current||(J.current=!0,t==null||t(z,ve),Te==null||Te(ve)),J.current&&(e==null||e(z,ve),ke==null||ke(ve),H.current=setTimeout(()=>{n==null||n(z,ve),le==null||le(ve),J.current=!1},150))},{passive:!1}):typeof M<"u"&&V.on("wheel.zoom",function(z,te){if(!N||Nd(z,C))return null;z.preventDefault(),M.call(this,z,te)},{passive:!1}))},[A,c,d,V,K,M,O,o,N,C,t,e,n]),p.useEffect(()=>{K&&K.on("start",z=>{var ne,se;if(!z.sourceEvent||z.sourceEvent.internal)return null;L.current=(ne=z.sourceEvent)==null?void 0:ne.button;const{onViewportChangeStart:te}=P.getState(),B=yp(z.transform);R.current=!0,G.current=B,((se=z.sourceEvent)==null?void 0:se.type)==="mousedown"&&P.setState({paneDragging:!0}),te==null||te(B),t==null||t(z.sourceEvent,B)})},[K,t]),p.useEffect(()=>{K&&(A&&!R.current?K.on("zoom",null):A||K.on("zoom",z=>{var B;const{onViewportChange:te}=P.getState();if(P.setState({transform:[z.transform.x,z.transform.y,z.transform.k]}),I.current=!!(r&&Qk(_,L.current??0)),(e||te)&&!((B=z.sourceEvent)!=null&&B.internal)){const ne=yp(z.transform);te==null||te(ne),e==null||e(z.sourceEvent,ne)}}))},[A,K,e,_,r]),p.useEffect(()=>{K&&K.on("end",z=>{if(!z.sourceEvent||z.sourceEvent.internal)return null;const{onViewportChangeEnd:te}=P.getState();if(R.current=!1,P.setState({paneDragging:!1}),r&&Qk(_,L.current??0)&&!I.current&&r(z.sourceEvent),I.current=!1,(n||te)&&Rz(G.current,z.transform)){const B=yp(z.transform);G.current=B,clearTimeout(D.current),D.current=setTimeout(()=>{te==null||te(B),n==null||n(z.sourceEvent,B)},c?150:0)}})},[K,c,_,n,r]),p.useEffect(()=>{K&&K.filter(z=>{const te=O||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(!_&&!te&&!c&&!h&&!o||A||!h&&z.type==="dblclick"||Nd(z,C)&&z.type==="wheel"||Nd(z,S)&&(z.type!=="wheel"||c&&z.type==="wheel"&&!O)||!o&&z.ctrlKey&&z.type==="wheel"||!te&&!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 ne=Array.isArray(_)&&_.includes(z.button)||!z.button||z.button<=1;return(!z.ctrlKey||z.type==="wheel")&&ne})},[A,K,i,o,c,h,_,m,O]),Ce.createElement("div",{className:"react-flow__renderer",ref:W,style:Ux},$)},Oz=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Pz(){const{userSelectionActive:e,userSelectionRect:t}=ms(Oz,mr);return e&&t?Ce.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 Dz(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 Fz(e,t){return Dz(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))},zz=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),rC=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(zz,mr),S=()=>{y.setState({userSelectionActive:!1,userSelectionRect:null}),x.current=0,k.current=0},D=M=>{o==null||o(M),y.getState().resetSelectedElements(),y.setState({nodesSelectionActive:!1})},P=M=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){M.preventDefault();return}c==null||c(M)},R=l?M=>l(M):void 0,I=M=>{const{resetSelectedElements:A,domNode:O}=y.getState();if(v.current=O==null?void 0:O.getBoundingClientRect(),!$||!e||M.button!==0||M.target!==g.current||!v.current)return;const{x:L,y:J}=ac(M,v.current);A(),y.setState({userSelectionRect:{width:0,height:0,startX:L,startY:J,x:L,y:J}}),r==null||r(M)},W=M=>{const{userSelectionRect:A,nodeInternals:O,edges:L,transform:J,onNodesChange:H,onEdgesChange:z,nodeOrigin:te,getNodes:B}=y.getState();if(!e||!v.current||!A)return;y.setState({userSelectionActive:!0,nodesSelectionActive:!1});const ne=ac(M,v.current),se=A.startX??0,ue=A.startY??0,ve={...A,x:ne.x<se?ne.x:se,y:ne.y<ue?ne.y:ue,width:Math.abs(ne.x-se),height:Math.abs(ne.y-ue)},Te=B(),ke=z$(O,ve,J,t===_m.Partial,!0,te),le=B$(ke,L).map(Ee=>Ee.id),xe=ke.map(Ee=>Ee.id);if(x.current!==xe.length){x.current=xe.length;const Ee=Fd(Te,xe);Ee.length&&(H==null||H(Ee))}if(k.current!==le.length){k.current=le.length;const Ee=Fd(L,le);Ee.length&&(z==null||z(Ee))}y.setState({userSelectionRect:ve})},G=M=>{if(M.button!==0)return;const{userSelectionRect:A}=y.getState();!N&&A&&M.target===g.current&&(D==null||D(M)),y.setState({nodesSelectionActive:x.current>0}),S(),i==null||i(M)},K=M=>{N&&(y.setState({nodesSelectionActive:x.current>0}),i==null||i(M)),S()},V=$&&(e||N);return Ce.createElement("div",{className:Er(["react-flow__pane",{dragging:C,selection:e}]),onClick:V?void 0:fw(D,g),onContextMenu:fw(P,g),onWheel:fw(R,g),onMouseEnter:V?void 0:d,onMouseDown:V?I:void 0,onMouseMove:V?W:h,onMouseUp:V?G:void 0,onMouseLeave:V?K:m,ref:g,style:Ux},_,Ce.createElement(Pz,null))});rC.displayName="Pane";function iC(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:iC(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 Bz(e,t,n,r){return Array.from(e.values()).filter(i=>(i.selected||i.id===r)&&(!i.parentNode||!iC(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 Uz(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function oC(e,t,n,r,i=[0,0],o){const c=Uz(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 Wz(){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 aC({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),$=Wz();return p.useEffect(()=>{if(e!=null&&e.current){const C=vo(e.current),S=({x:R,y:I})=>{const{nodeInternals:W,onNodeDrag:G,onSelectionDrag:K,updateNodePositions:V,nodeExtent:M,snapGrid:A,snapToGrid:O,nodeOrigin:L,onError:J}=l.getState();_.current={x:R,y:I};let H=!1,z={x:0,y:0,x2:0,y2:0};if(m.current.length>1&&M){const B=Kg(m.current,L);z=mm(B)}if(m.current=m.current.map(B=>{const ne={x:R-B.distance.x,y:I-B.distance.y};O&&(ne.x=A[0]*Math.round(ne.x/A[0]),ne.y=A[1]*Math.round(ne.y/A[1]));const se=[[M[0][0],M[0][1]],[M[1][0],M[1][1]]];m.current.length>1&&M&&!B.extent&&(se[0][0]=B.positionAbsolute.x-z.x+M[0][0],se[1][0]=B.positionAbsolute.x+(B.width??0)-z.x2+M[1][0],se[0][1]=B.positionAbsolute.y-z.y+M[0][1],se[1][1]=B.positionAbsolute.y+(B.height??0)-z.y2+M[1][1]);const ue=oC(B,ne,W,se,L,J);return H=H||B.position.x!==ue.position.x||B.position.y!==ue.position.y,B.position=ue.position,B.positionAbsolute=ue.positionAbsolute,B}),!H)return;V(m.current,!0,!0),h(!0);const te=i?G:mw(K);if(te&&k.current){const[B,ne]=hw({nodeId:i,dragItems:m.current,nodeInternals:W});te(k.current,B,ne)}},D=()=>{if(!y.current)return;const[R,I]=E$(x.current,y.current);if(R!==0||I!==0){const{transform:W,panBy:G}=l.getState();_.current.x=(_.current.x??0)-R/W[2],_.current.y=(_.current.y??0)-I/W[2],G({x:R,y:I})&&S(_.current)}g.current=requestAnimationFrame(D)},P=R=>{var L;const{nodeInternals:I,multiSelectionActive:W,nodesDraggable:G,unselectNodesAndEdges:K,onNodeDragStart:V,onSelectionDragStart:M}=l.getState();N.current=!0;const A=i?V:mw(M);(!c||!o)&&!W&&i&&((L=I.get(i))!=null&&L.selected||K()),i&&o&&c&&Av({id:i,store:l,nodeRef:e});const O=$(R);if(_.current=O,m.current=Bz(I,G,O,i),A&&m.current){const[J,H]=hw({nodeId:i,dragItems:m.current,nodeInternals:I});A(R.sourceEvent,J,H)}};if(t)C.on(".drag",null);else{const R=QF().on("start",I=>{const{domNode:W,nodeDragThreshold:G}=l.getState();G===0&&P(I);const K=$(I);_.current=K,y.current=(W==null?void 0:W.getBoundingClientRect())||null,x.current=ac(I.sourceEvent,y.current)}).on("drag",I=>{var V,M;const W=$(I),{autoPanOnNodeDrag:G,nodeDragThreshold:K}=l.getState();if(!v.current&&N.current&&G&&(v.current=!0,D()),!N.current){const A=W.xSnapped-(((V=_==null?void 0:_.current)==null?void 0:V.x)??0),O=W.ySnapped-(((M=_==null?void 0:_.current)==null?void 0:M.y)??0);Math.sqrt(A*A+O*O)>K&&P(I)}(_.current.x!==W.xSnapped||_.current.y!==W.ySnapped)&&m.current&&N.current&&(k.current=I.sourceEvent,x.current=ac(I.sourceEvent,y.current),S(W))}).on("end",I=>{if(N.current&&(h(!1),v.current=!1,N.current=!1,cancelAnimationFrame(g.current),m.current)){const{updateNodePositions:W,nodeInternals:G,onNodeDragStop:K,onSelectionDragStop:V}=l.getState(),M=i?K:mw(V);if(W(m.current,!1,!1),M){const[A,O]=hw({nodeId:i,dragItems:m.current,nodeInternals:G});M(I.sourceEvent,A,O)}}}).filter(I=>{const W=I.target;return!I.button&&(!n||!nj(W,`.${n}`,e))&&(!r||nj(W,r,e))});return C.call(R),()=>{C.on(".drag",null)}}}},[e,t,n,r,o,l,i,c,$]),d}function lC(){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}=oC($,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:P,sourcePosition:R,targetPosition:I,hidden:W,resizeObserver:G,dragHandle:K,zIndex:V,isParent:M,noDragClassName:A,noPanClassName:O,initialized:L,disableKeyboardA11y:J,ariaLabel:H,rfId:z,hasHandleBounds:te})=>{const B=tr(),ne=p.useRef(null),se=p.useRef(R),ue=p.useRef(I),ve=p.useRef(r),Te=C||$||m||_||g||y,ke=lC(),le=Ah(n,B.getState,_),xe=Ah(n,B.getState,g),Ee=Ah(n,B.getState,y),Ve=Ah(n,B.getState,x),_t=Ah(n,B.getState,k),Qe=He=>{const{nodeDragThreshold:ft}=B.getState();if(C&&(!P||!$||ft>0)&&Av({id:n,store:B,nodeRef:ne}),m){const et=B.getState().nodeInternals.get(n);et&&m(He,{...et})}},ot=He=>{if(!Sv(He))if(R$.includes(He.key)&&C){const ft=He.key==="Escape";Av({id:n,store:B,unselect:ft,nodeRef:ne})}else!J&&$&&h&&Object.prototype.hasOwnProperty.call(Gd,He.key)&&(B.setState({ariaLiveMessage:`Moved selected node ${He.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~o}, y: ${~~c}`}),ke({x:Gd[He.key].x,y:Gd[He.key].y,isShiftPressed:He.shiftKey}))};p.useEffect(()=>()=>{ne.current&&(G==null||G.unobserve(ne.current))},[]),p.useEffect(()=>{if(ne.current&&!W){const He=ne.current;(!L||!te)&&(G==null||G.unobserve(He),G==null||G.observe(He))}},[W,L,te]),p.useEffect(()=>{const He=ve.current!==r,ft=se.current!==R,et=ue.current!==I;ne.current&&(He||ft||et)&&(He&&(ve.current=r),ft&&(se.current=R),et&&(ue.current=I),B.getState().updateNodeDimensions([{id:n,nodeElement:ne.current,forceUpdate:!0}]))},[n,r,R,I]);const ze=aC({nodeRef:ne,disabled:W||!$,noDragClassName:A,handleSelector:K,nodeId:n,isSelectable:C,selectNodesOnDrag:P});return W?null:Ce.createElement("div",{className:Er(["react-flow__node",`react-flow__node-${r}`,{[O]:$},N,{selected:h,selectable:C,parent:M,dragging:ze}]),ref:ne,style:{zIndex:V,transform:`translate(${l}px,${d}px)`,pointerEvents:Te?"all":"none",visibility:L?"visible":"hidden",...v},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:le,onMouseMove:xe,onMouseLeave:Ee,onContextMenu:Ve,onClick:Qe,onDoubleClick:_t,onKeyDown:D?ot:void 0,tabIndex:D?0:void 0,role:D?"button":void 0,"aria-describedby":J?void 0:`${Q$}-${z}`,"aria-label":H},Ce.createElement(nz,{value:n},Ce.createElement(e,{id:n,data:i,type:r,xPos:o,yPos:c,selected:h,isConnectable:S,sourcePosition:R,targetPosition:I,dragging:ze,dragHandle:K,zIndex:V})))};return t.displayName="NodeWrapper",p.memo(t)};const qz=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 Vz({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=tr(),{width:i,height:o,x:c,y:l,transformString:d,userSelectionActive:h}=ms(qz,mr),m=lC(),_=p.useRef(null);if(p.useEffect(()=>{var x;n||(x=_.current)==null||x.focus({preventScroll:!0})},[n]),aC({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 Ce.createElement("div",{className:Er(["react-flow__nodesselection","react-flow__container",t]),style:{transform:d}},Ce.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 Hz=p.memo(Vz);const Gz=e=>e.nodesSelectionActive,cC=({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:P,panOnScrollSpeed:R,panOnScrollMode:I,zoomOnDoubleClick:W,panOnDrag:G,defaultViewport:K,translateExtent:V,minZoom:M,maxZoom:A,preventScrolling:O,onSelectionContextMenu:L,noWheelClassName:J,noPanClassName:H,disableKeyboardA11y:z})=>{const te=ms(Gz),B=gm(_),ne=gm(N),se=ne||G,ue=ne||P,ve=B||g&&se!==!0;return Tz({deleteKeyCode:l,multiSelectionKeyCode:v}),Ce.createElement(Iz,{onMove:d,onMoveStart:h,onMoveEnd:m,onPaneContextMenu:o,elementsSelectable:C,zoomOnScroll:S,zoomOnPinch:D,panOnScroll:ue,panOnScrollSpeed:R,panOnScrollMode:I,zoomOnDoubleClick:W,panOnDrag:!B&&se,defaultViewport:K,translateExtent:V,minZoom:M,maxZoom:A,zoomActivationKeyCode:$,preventScrolling:O,noWheelClassName:J,noPanClassName:H},Ce.createElement(rC,{onSelectionStart:x,onSelectionEnd:k,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:c,panOnDrag:se,isSelecting:!!ve,selectionMode:y},e,te&&Ce.createElement(Hz,{onSelectionContextMenu:L,noPanClassName:H,disableKeyboardA11y:z})))};cC.displayName="FlowRenderer";var Kz=p.memo(cC);function Jz(e){return ms(p.useCallback(n=>e?z$(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}function Yz(e){const t={input:Th(e.input||J$),default:Th(e.default||Ev),output:Th(e.output||X$),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 Xz=({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]},Zz=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),uC=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,updateNodeDimensions:o,onError:c}=ms(Zz,mr),l=Jz(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()},[]),Ce.createElement("div",{className:"react-flow__nodes",style:Ux},l.map(m=>{var D,P,R;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=Xz({x:$,y:C,width:m.width??0,height:m.height??0,origin:e.nodeOrigin});return Ce.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:!!((P=m[Gs])!=null&&P.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!m.width&&!!m.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:m.ariaLabel,hasHandleBounds:!!((R=m[Gs])!=null&&R.handleBounds)})}))};uC.displayName="NodeRenderer";var Qz=p.memo(uC);const eB=(e,t,n)=>n===Ut.Left?e-t:n===Ut.Right?e+t:e,tB=(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})=>Ce.createElement("circle",{onMouseDown:i,onMouseEnter:o,onMouseOut:c,className:Er([rj,`${rj}-${l}`]),cx:eB(t,r,e),cy:tB(n,r,e),r,stroke:"transparent",fill:"transparent"}),nB=()=>!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:P,sourcePosition:R,targetPosition:I,elementsSelectable:W,hidden:G,sourceHandleId:K,targetHandleId:V,onContextMenu:M,onMouseEnter:A,onMouseMove:O,onMouseLeave:L,edgeUpdaterRadius:J,onEdgeUpdate:H,onEdgeUpdateStart:z,onEdgeUpdateEnd:te,markerEnd:B,markerStart:ne,rfId:se,ariaLabel:ue,isFocusable:ve,isUpdatable:Te,pathOptions:ke,interactionWidth:le})=>{const xe=p.useRef(null),[Ee,Ve]=p.useState(!1),[_t,Qe]=p.useState(!1),ot=tr(),ze=p.useMemo(()=>`url('#${$v(ne,se)}')`,[ne,se]),He=p.useMemo(()=>`url('#${$v(B,se)}')`,[B,se]);if(G)return null;const ft=at=>{var Lt;const{edges:Et,addSelectedEdges:yt,unselectNodesAndEdges:jt,multiSelectionActive:st}=ot.getState(),Pt=Et.find(mn=>mn.id===n);Pt&&(W&&(ot.setState({nodesSelectionActive:!1}),Pt.selected&&st?(jt({nodes:[],edges:[Pt]}),(Lt=xe.current)==null||Lt.blur()):yt([n])),c&&c(at,Pt))},et=Eh(n,ot.getState,l),Ot=Eh(n,ot.getState,M),Ne=Eh(n,ot.getState,A),Re=Eh(n,ot.getState,O),tt=Eh(n,ot.getState,L),re=(at,Et)=>{if(at.button!==0)return;const{edges:yt,isValidConnection:jt}=ot.getState(),st=Et?$:N,Pt=(Et?V:K)||null,Lt=Et?"target":"source",mn=jt||nB,wn=Et,On=yt.find(_e=>_e.id===n);Qe(!0),z==null||z(at,On,Lt);const Ks=_e=>{Qe(!1),te==null||te(_e,On,Lt)};V$({event:at,handleId:Pt,nodeId:st,onConnect:_e=>H==null?void 0:H(On,_e),isTarget:wn,getState:ot.getState,setState:ot.setState,isValidConnection:mn,edgeUpdaterType:Lt,onEdgeUpdateEnd:Ks})},ge=at=>re(at,!0),de=at=>re(at,!1),je=()=>Ve(!0),X=()=>Ve(!1),Oe=!W&&!c,pt=at=>{var Et;if(R$.includes(at.key)&&W){const{unselectNodesAndEdges:yt,addSelectedEdges:jt,edges:st}=ot.getState();at.key==="Escape"?((Et=xe.current)==null||Et.blur(),yt({edges:[st.find(Lt=>Lt.id===n)]})):jt([n])}};return Ce.createElement("g",{className:Er(["react-flow__edge",`react-flow__edge-${i}`,r,{selected:d,animated:h,inactive:Oe,updating:Ee}]),onClick:ft,onDoubleClick:et,onContextMenu:Ot,onMouseEnter:Ne,onMouseMove:Re,onMouseLeave:tt,onKeyDown:ve?pt:void 0,tabIndex:ve?0:void 0,role:ve?"button":"img","data-testid":`rf__edge-${n}`,"aria-label":ue===null?void 0:ue||`Edge from ${N} to ${$}`,"aria-describedby":ve?`${eC}-${se}`:void 0,ref:xe},!_t&&Ce.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:P,sourcePosition:R,targetPosition:I,sourceHandleId:K,targetHandleId:V,markerStart:ze,markerEnd:He,pathOptions:ke,interactionWidth:le}),Te&&Ce.createElement(Ce.Fragment,null,(Te==="source"||Te===!0)&&Ce.createElement(ij,{position:R,centerX:C,centerY:S,radius:J,onMouseDown:ge,onMouseEnter:je,onMouseOut:X,type:"source"}),(Te==="target"||Te===!0)&&Ce.createElement(ij,{position:I,centerX:D,centerY:P,radius:J,onMouseDown:de,onMouseEnter:je,onMouseOut:X,type:"target"})))};return t.displayName="EdgeWrapper",p.memo(t)};function sB(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 rB=(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 iB({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 oB=[{level:0,isMaxLevel:!0,edges:[]}];function aB(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?oB:o}function lB(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)&&iB({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 aB(r,t,n)}const cB=({color:e="none",strokeWidth:t=1})=>Ce.createElement("polyline",{style:{stroke:e,strokeWidth:t},strokeLinecap:"round",strokeLinejoin:"round",fill:"none",points:"-5,-4 0,0 -5,4"}),uB=({color:e="none",strokeWidth:t=1})=>Ce.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]:cB,[pm.ArrowClosed]:uB};function dB(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 fB=({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=dB(t);return d?Ce.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"},Ce.createElement(d,{color:n,strokeWidth:c})):null},hB=({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))},dC=({defaultColor:e,rfId:t})=>{const n=ms(p.useCallback(hB({defaultColor:e,rfId:t}),[e,t]),(r,i)=>!(r.length!==i.length||r.some((o,c)=>o.id!==i[c].id)));return Ce.createElement("defs",null,n.map(r=>Ce.createElement(fB,{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})))};dC.displayName="MarkerDefinitions";var mB=p.memo(dC);const _B=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}),fC=({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:P,nodeInternals:R,onError:I}=ms(_B,mr),W=lB(t,R,n);return S?Ce.createElement(Ce.Fragment,null,W.map(({level:G,edges:K,isMaxLevel:V})=>Ce.createElement("svg",{key:G,style:{zIndex:G},width:S,height:D,className:"react-flow__edges react-flow__container"},V&&Ce.createElement(mB,{defaultColor:e,rfId:r}),Ce.createElement("g",null,K.map(M=>{const[A,O,L]=lj(R.get(M.source)),[J,H,z]=lj(R.get(M.target));if(!L||!z)return null;let te=M.type||"default";i[te]||(I==null||I("011",cl.error011(te)),te="default");const B=i[te]||i.default,ne=P===xu.Strict?H.target:(H.target??[]).concat(H.source??[]),se=aj(O.source,M.sourceHandle),ue=aj(ne,M.targetHandle),ve=(se==null?void 0:se.position)||Ut.Bottom,Te=(ue==null?void 0:ue.position)||Ut.Top,ke=!!(M.focusable||N&&typeof M.focusable>"u"),le=typeof c<"u"&&(M.updatable||$&&typeof M.updatable>"u");if(!se||!ue)return I==null||I("008",cl.error008(se,M)),null;const{sourceX:xe,sourceY:Ee,targetX:Ve,targetY:_t}=rB(A,se,ve,J,ue,Te);return Ce.createElement(B,{key:M.id,id:M.id,className:Er([M.className,o]),type:te,data:M.data,selected:!!M.selected,animated:!!M.animated,hidden:!!M.hidden,label:M.label,labelStyle:M.labelStyle,labelShowBg:M.labelShowBg,labelBgStyle:M.labelBgStyle,labelBgPadding:M.labelBgPadding,labelBgBorderRadius:M.labelBgBorderRadius,style:M.style,source:M.source,target:M.target,sourceHandleId:M.sourceHandle,targetHandleId:M.targetHandle,markerEnd:M.markerEnd,markerStart:M.markerStart,sourceX:xe,sourceY:Ee,targetX:Ve,targetY:_t,sourcePosition:ve,targetPosition:Te,elementsSelectable:C,onEdgeUpdate:c,onContextMenu:l,onMouseEnter:d,onMouseMove:h,onMouseLeave:m,onClick:_,edgeUpdaterRadius:g,onEdgeDoubleClick:y,onEdgeUpdateStart:x,onEdgeUpdateEnd:k,rfId:r,ariaLabel:M.ariaLabel,isFocusable:ke,isUpdatable:le,pathOptions:"pathOptions"in M?M.pathOptions:void 0,interactionWidth:M.interactionWidth})})))),v):null};fC.displayName="EdgeRenderer";var pB=p.memo(fC);const gB=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function yB({children:e}){const t=ms(gB);return Ce.createElement("div",{className:"react-flow__viewport react-flow__container",style:{transform:t}},e)}function wB(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 vB={[Ut.Left]:Ut.Right,[Ut.Right]:Ut.Left,[Ut.Top]:Ut.Bottom,[Ut.Bottom]:Ut.Top},hC=({nodeId:e,handleType:t,style:n,type:r=nc.Bezier,CustomComponent:i,connectionStatus:o})=>{var P,R,I;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),_=(P=c==null?void 0:c[Gs])==null?void 0:P.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=(((R=c.positionAbsolute)==null?void 0:R.x)??0)+x,N=(((I=c.positionAbsolute)==null?void 0:I.y)??0)+k,$=y==null?void 0:y.position,C=$?vB[$]:null;if(!$||!C)return null;if(i)return Ce.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]=D$(D):r===nc.Step?[S]=Nv({...D,borderRadius:0}):r===nc.SmoothStep?[S]=Nv(D):r===nc.SimpleBezier?[S]=P$(D):S=`M${v},${N} ${d},${h}`,Ce.createElement("path",{d:S,fill:"none",className:"react-flow__connection-path",style:n})};hC.displayName="ConnectionLine";const xB=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function bB({containerStyle:e,style:t,type:n,component:r}){const{nodeId:i,handleType:o,nodesConnectable:c,width:l,height:d,connectionStatus:h}=ms(xB,mr);return!(i&&o&&l&&c)?null:Ce.createElement("svg",{style:e,width:l,height:d,className:"react-flow__edges react-flow__connectionline react-flow__container"},Ce.createElement("g",{className:Er(["react-flow__connection",h])},Ce.createElement(hC,{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 mC=({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:P,selectionMode:R,multiSelectionKeyCode:I,panActivationKeyCode:W,zoomActivationKeyCode:G,deleteKeyCode:K,onlyRenderVisibleElements:V,elementsSelectable:M,selectNodesOnDrag:A,defaultViewport:O,translateExtent:L,minZoom:J,maxZoom:H,preventScrolling:z,defaultMarkerColor:te,zoomOnScroll:B,zoomOnPinch:ne,panOnScroll:se,panOnScrollSpeed:ue,panOnScrollMode:ve,zoomOnDoubleClick:Te,panOnDrag:ke,onPaneClick:le,onPaneMouseEnter:xe,onPaneMouseMove:Ee,onPaneMouseLeave:Ve,onPaneScroll:_t,onPaneContextMenu:Qe,onEdgeUpdate:ot,onEdgeContextMenu:ze,onEdgeMouseEnter:He,onEdgeMouseMove:ft,onEdgeMouseLeave:et,edgeUpdaterRadius:Ot,onEdgeUpdateStart:Ne,onEdgeUpdateEnd:Re,noDragClassName:tt,noWheelClassName:re,noPanClassName:ge,elevateEdgesOnSelect:de,disableKeyboardA11y:je,nodeOrigin:X,nodeExtent:Oe,rfId:pt})=>{const at=uj(e,Yz),Et=uj(t,sB);return wB(o),Ce.createElement(Kz,{onPaneClick:le,onPaneMouseEnter:xe,onPaneMouseMove:Ee,onPaneMouseLeave:Ve,onPaneContextMenu:Qe,onPaneScroll:_t,deleteKeyCode:K,selectionKeyCode:D,selectionOnDrag:P,selectionMode:R,onSelectionStart:k,onSelectionEnd:v,multiSelectionKeyCode:I,panActivationKeyCode:W,zoomActivationKeyCode:G,elementsSelectable:M,onMove:n,onMoveStart:r,onMoveEnd:i,zoomOnScroll:B,zoomOnPinch:ne,zoomOnDoubleClick:Te,panOnScroll:se,panOnScrollSpeed:ue,panOnScrollMode:ve,panOnDrag:ke,defaultViewport:O,translateExtent:L,minZoom:J,maxZoom:H,onSelectionContextMenu:x,preventScrolling:z,noDragClassName:tt,noWheelClassName:re,noPanClassName:ge,disableKeyboardA11y:je},Ce.createElement(yB,null,Ce.createElement(pB,{edgeTypes:Et,onEdgeClick:l,onEdgeDoubleClick:h,onEdgeUpdate:ot,onlyRenderVisibleElements:V,onEdgeContextMenu:ze,onEdgeMouseEnter:He,onEdgeMouseMove:ft,onEdgeMouseLeave:et,onEdgeUpdateStart:Ne,onEdgeUpdateEnd:Re,edgeUpdaterRadius:Ot,defaultMarkerColor:te,noPanClassName:ge,elevateEdgesOnSelect:!!de,disableKeyboardA11y:je,rfId:pt},Ce.createElement(bB,{style:$,type:N,component:C,containerStyle:S})),Ce.createElement("div",{className:"react-flow__edgelabel-renderer"}),Ce.createElement(Qz,{nodeTypes:at,onNodeClick:c,onNodeDoubleClick:d,onNodeMouseEnter:m,onNodeMouseMove:_,onNodeMouseLeave:g,onNodeContextMenu:y,selectNodesOnDrag:A,onlyRenderVisibleElements:V,noPanClassName:ge,noDragClassName:tt,disableKeyboardA11y:je,nodeOrigin:X,nodeExtent:Oe,rfId:pt})))};mC.displayName="GraphView";var kB=p.memo(mC);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:Y8,isValidConnection:void 0},jB=()=>d5((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},[]);nC(i,h);const x=c||o&&!c&&sC(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=Fz(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=jB()),Ce.createElement(W8,{value:t.current},e)};Wx.displayName="ReactFlowProvider";const _C=({children:e})=>p.useContext(Hg)?Ce.createElement(Ce.Fragment,null,e):Ce.createElement(Wx,null,e);_C.displayName="ReactFlowWrapper";const SB={input:J$,default:Ev,output:X$,group:zx},NB={default:pg,straight:Px,step:Ox,smoothstep:Gg,simplebezier:Ix},$B=[0,0],CB=[15,15],EB={x:0,y:0,zoom:1},AB={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},pC=p.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:o=SB,edgeTypes:c=NB,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:P,onNodeDragStart:R,onNodeDrag:I,onNodeDragStop:W,onNodesDelete:G,onEdgesDelete:K,onSelectionChange:V,onSelectionDragStart:M,onSelectionDrag:A,onSelectionDragStop:O,onSelectionContextMenu:L,onSelectionStart:J,onSelectionEnd:H,connectionMode:z=xu.Strict,connectionLineType:te=nc.Bezier,connectionLineStyle:B,connectionLineComponent:ne,connectionLineContainerStyle:se,deleteKeyCode:ue="Backspace",selectionKeyCode:ve="Shift",selectionOnDrag:Te=!1,selectionMode:ke=_m.Full,panActivationKeyCode:le="Space",multiSelectionKeyCode:xe=_g()?"Meta":"Control",zoomActivationKeyCode:Ee=_g()?"Meta":"Control",snapToGrid:Ve=!1,snapGrid:_t=CB,onlyRenderVisibleElements:Qe=!1,selectNodesOnDrag:ot=!0,nodesDraggable:ze,nodesConnectable:He,nodesFocusable:ft,nodeOrigin:et=$B,edgesFocusable:Ot,edgesUpdatable:Ne,elementsSelectable:Re,defaultViewport:tt=EB,minZoom:re=.5,maxZoom:ge=2,translateExtent:de=Tv,preventScrolling:je=!0,nodeExtent:X,defaultMarkerColor:Oe="#b1b1b7",zoomOnScroll:pt=!0,zoomOnPinch:at=!0,panOnScroll:Et=!1,panOnScrollSpeed:yt=.5,panOnScrollMode:jt=ou.Free,zoomOnDoubleClick:st=!0,panOnDrag:Pt=!0,onPaneClick:Lt,onPaneMouseEnter:mn,onPaneMouseMove:wn,onPaneMouseLeave:On,onPaneScroll:Ks,onPaneContextMenu:rs,children:_e,onEdgeUpdate:Me,onEdgeContextMenu:wt,onEdgeDoubleClick:ie,onEdgeMouseEnter:fe,onEdgeMouseMove:$e,onEdgeMouseLeave:Le,onEdgeUpdateStart:We,onEdgeUpdateEnd:Ue,edgeUpdaterRadius:nt=10,onNodesChange:ut,onEdgesChange:xt,noDragClassName:bt="nodrag",noWheelClassName:Tt="nowheel",noPanClassName:zt="nopan",fitView:ct=!1,fitViewOptions:Yt,connectOnClick:vn=!0,attributionPosition:hn,proOptions:sn,defaultEdgeOptions:Ht,elevateNodesOnSelect:is=!0,elevateEdgesOnSelect:Be=!1,disableKeyboardA11y:Qt=!1,autoPanOnConnect:Rt=!0,autoPanOnNodeDrag:Fn=!0,connectionRadius:fn=20,isValidConnection:Xe,onError:nn,style:cn,id:Ar,nodeDragThreshold:As,...ws},_r)=>{const ye=Ar||"1";return Ce.createElement("div",{...ws,style:{...cn,...AB},ref:_r,className:Er(["react-flow",i]),"data-testid":"rf__wrapper",id:Ar},Ce.createElement(_C,null,Ce.createElement(kB,{onInit:h,onMove:m,onMoveStart:_,onMoveEnd:g,onNodeClick:l,onEdgeClick:d,onNodeMouseEnter:$,onNodeMouseMove:C,onNodeMouseLeave:S,onNodeContextMenu:D,onNodeDoubleClick:P,nodeTypes:o,edgeTypes:c,connectionLineType:te,connectionLineStyle:B,connectionLineComponent:ne,connectionLineContainerStyle:se,selectionKeyCode:ve,selectionOnDrag:Te,selectionMode:ke,deleteKeyCode:ue,multiSelectionKeyCode:xe,panActivationKeyCode:le,zoomActivationKeyCode:Ee,onlyRenderVisibleElements:Qe,selectNodesOnDrag:ot,defaultViewport:tt,translateExtent:de,minZoom:re,maxZoom:ge,preventScrolling:je,zoomOnScroll:pt,zoomOnPinch:at,zoomOnDoubleClick:st,panOnScroll:Et,panOnScrollSpeed:yt,panOnScrollMode:jt,panOnDrag:Pt,onPaneClick:Lt,onPaneMouseEnter:mn,onPaneMouseMove:wn,onPaneMouseLeave:On,onPaneScroll:Ks,onPaneContextMenu:rs,onSelectionContextMenu:L,onSelectionStart:J,onSelectionEnd:H,onEdgeUpdate:Me,onEdgeContextMenu:wt,onEdgeDoubleClick:ie,onEdgeMouseEnter:fe,onEdgeMouseMove:$e,onEdgeMouseLeave:Le,onEdgeUpdateStart:We,onEdgeUpdateEnd:Ue,edgeUpdaterRadius:nt,defaultMarkerColor:Oe,noDragClassName:bt,noWheelClassName:Tt,noPanClassName:zt,elevateEdgesOnSelect:Be,rfId:ye,disableKeyboardA11y:Qt,nodeOrigin:et,nodeExtent:X}),Ce.createElement(wz,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:y,onConnectStart:x,onConnectEnd:k,onClickConnectStart:v,onClickConnectEnd:N,nodesDraggable:ze,nodesConnectable:He,nodesFocusable:ft,edgesFocusable:Ot,edgesUpdatable:Ne,elementsSelectable:Re,elevateNodesOnSelect:is,minZoom:re,maxZoom:ge,nodeExtent:X,onNodesChange:ut,onEdgesChange:xt,snapToGrid:Ve,snapGrid:_t,connectionMode:z,translateExtent:de,connectOnClick:vn,defaultEdgeOptions:Ht,fitView:ct,fitViewOptions:Yt,onNodesDelete:G,onEdgesDelete:K,onNodeDragStart:R,onNodeDrag:I,onNodeDragStop:W,onSelectionDrag:A,onSelectionDragStart:M,onSelectionDragStop:O,noPanClassName:zt,nodeOrigin:et,rfId:ye,autoPanOnConnect:Rt,autoPanOnNodeDrag:Fn,onError:nn,connectionRadius:fn,isValidConnection:Xe,nodeDragThreshold:As}),Ce.createElement(gz,{onSelectionChange:V}),_e,Ce.createElement(V8,{proOptions:sn,position:hn}),Ce.createElement(jz,{rfId:ye,disableKeyboardA11y:Qt})))});pC.displayName="ReactFlow";const gC=({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 Ce.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})};gC.displayName="MiniMapNode";var TB=p.memo(gC);const MB=e=>e.nodeOrigin,RB=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),_w=e=>e instanceof Function?e:()=>e;function LB({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:i=2,nodeComponent:o=TB,onClick:c}){const l=ms(RB,mr),d=ms(MB),h=_w(t),m=_w(e),_=_w(n),g=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return Ce.createElement(Ce.Fragment,null,l.map(y=>{const{x,y:k}=du(y,d).positionAbsolute;return Ce.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 IB=p.memo(LB);const OB=200,PB=150,DB=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?K8(Kg(t,e.nodeOrigin),n):n,rfId:e.rfId}},FB="react-flow__minimap-desc";function yC({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:P,viewBB:R,rfId:I}=ms(DB,mr),W=(e==null?void 0:e.width)??OB,G=(e==null?void 0:e.height)??PB,K=P.width/W,V=P.height/G,M=Math.max(K,V),A=M*W,O=M*G,L=C*M,J=P.x-(A-P.width)/2-L,H=P.y-(O-P.height)/2-L,z=A+L*2,te=O+L*2,B=`${FB}-${I}`,ne=p.useRef(0);ne.current=M,p.useEffect(()=>{if(D.current){const ve=vo(D.current),Te=xe=>{const{transform:Ee,d3Selection:Ve,d3Zoom:_t}=S.getState();if(xe.sourceEvent.type!=="wheel"||!Ve||!_t)return;const Qe=-xe.sourceEvent.deltaY*(xe.sourceEvent.deltaMode===1?.05:xe.sourceEvent.deltaMode?1:.002)*$,ot=Ee[2]*Math.pow(2,Qe);_t.scaleTo(Ve,ot)},ke=xe=>{const{transform:Ee,d3Selection:Ve,d3Zoom:_t,translateExtent:Qe,width:ot,height:ze}=S.getState();if(xe.sourceEvent.type!=="mousemove"||!Ve||!_t)return;const He=ne.current*Math.max(1,Ee[2])*(N?-1:1),ft={x:Ee[0]-xe.sourceEvent.movementX*He,y:Ee[1]-xe.sourceEvent.movementY*He},et=[[0,0],[ot,ze]],Ot=sl.translate(ft.x,ft.y).scale(Ee[2]),Ne=_t.constrain()(Ot,et,Qe);_t.transform(Ve,Ne)},le=$$().on("zoom",x?ke:null).on("zoom.wheel",k?Te:null);return ve.call(le),()=>{ve.on("zoom",null)}}},[x,k,N,$]);const se=g?ve=>{const Te=Ho(ve);g(ve,{x:Te[0],y:Te[1]})}:void 0,ue=y?(ve,Te)=>{const ke=S.getState().nodeInternals.get(Te);y(ve,ke)}:void 0;return Ce.createElement(hm,{position:_,style:e,className:Er(["react-flow__minimap",t]),"data-testid":"rf__minimap"},Ce.createElement("svg",{width:W,height:G,viewBox:`${J} ${H} ${z} ${te}`,role:"img","aria-labelledby":B,ref:D,onClick:se},v&&Ce.createElement("title",{id:B},v),Ce.createElement(IB,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:o,nodeClassName:i,nodeStrokeWidth:c,nodeComponent:l}),Ce.createElement("path",{className:"react-flow__minimap-mask",d:`M${J-L},${H-L}h${z+L*2}v${te+L*2}h${-z-L*2}z
|
|
156
|
+
M${R.x},${R.y}h${R.width}v${R.height}h${-R.width}z`,fill:d,fillRule:"evenodd",stroke:h,strokeWidth:m,pointerEvents:"none"})))}yC.displayName="MiniMap";var zB=p.memo(yC);function BB(){return Ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32"},Ce.createElement("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"}))}function UB(){return Ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5"},Ce.createElement("path",{d:"M0 0h32v4.2H0z"}))}function WB(){return Ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30"},Ce.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 qB(){return Ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ce.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 VB(){return Ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32"},Ce.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})=>Ce.createElement("button",{type:"button",className:Er(["react-flow__controls-button",t]),...n},e);zd.displayName="ControlButton";const HB=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom}),wC=({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(HB,mr),{zoomIn:$,zoomOut:C,fitView:S}=Bx();if(p.useEffect(()=>{x(!0)},[]),!y)return null;const D=()=>{$(),o==null||o()},P=()=>{C(),c==null||c()},R=()=>{S(i),l==null||l()},I=()=>{g.setState({nodesDraggable:!k,nodesConnectable:!k,elementsSelectable:!k}),d==null||d(!k)};return Ce.createElement(hm,{className:Er(["react-flow__controls",h]),position:_,style:e,"data-testid":"rf__controls"},t&&Ce.createElement(Ce.Fragment,null,Ce.createElement(zd,{onClick:D,className:"react-flow__controls-zoomin",title:"zoom in","aria-label":"zoom in",disabled:N},Ce.createElement(BB,null)),Ce.createElement(zd,{onClick:P,className:"react-flow__controls-zoomout",title:"zoom out","aria-label":"zoom out",disabled:v},Ce.createElement(UB,null))),n&&Ce.createElement(zd,{className:"react-flow__controls-fitview",onClick:R,title:"fit view","aria-label":"fit view"},Ce.createElement(WB,null)),r&&Ce.createElement(zd,{className:"react-flow__controls-interactive",onClick:I,title:"toggle interactivity","aria-label":"toggle interactivity"},k?Ce.createElement(VB,null):Ce.createElement(qB,null)),m)};wC.displayName="Controls";var GB=p.memo(wC),Yo;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Yo||(Yo={}));function KB({color:e,dimensions:t,lineWidth:n}){return Ce.createElement("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function JB({color:e,radius:t}){return Ce.createElement("circle",{cx:t,cy:t,r:t,fill:e})}const YB={[Yo.Dots]:"#91919a",[Yo.Lines]:"#eee",[Yo.Cross]:"#e2e2e2"},XB={[Yo.Dots]:1,[Yo.Lines]:1,[Yo.Cross]:6},ZB=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function vC({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(ZB,mr),g=c||YB[t],y=r||XB[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 Ce.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"},Ce.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?Ce.createElement(JB,{color:g,radius:$/o}):Ce.createElement(KB,{dimensions:C,color:g,lineWidth:i})),Ce.createElement("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${_+e})`}))}vC.displayName="Background";var QB=p.memo(vC);function xC(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 eU(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 tU(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 bC(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 nU(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 P=y+2*Math.PI*D/v.length;r[v[D]]={x:80*Math.cos(P),y:80*Math.sin(P)}}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 nU(i,r);if(n==="radial")return dj(i,e.edges,r);if(n==="force"){const o=dj(i,e.edges,r),c=bC(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 sU(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 rU(e,t={}){const n=!!(t.groupEdges??!0),r=Math.max(1,t.maxEdgeLabelPredicates??3),i=sU(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:tU(g),kind:eU(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 R of y){const I=String(R.predicate||"").trim();I&&N.set(I,(N.get(I)||0)+1)}const $=Array.from(N.entries());$.sort((R,I)=>I[1]-R[1]||R[0].localeCompare(I[0]));const S=$.slice(0,r).map(([R,I])=>I>1?`${yg(R)}×${I}`:yg(R)).join(" | "),D=$.length>r?` +${$.length-r}`:"",P=`${S}${D}`.trim();_.push({id:g,source:k,target:v,label:P,animated:!1,data:{assertions:y,predicateSummary:P}})}return{nodes:d,edges:_}}function iU(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=bC(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 oU(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),P=y/S,R=P*$*D,I=P*C*D;e.acc[2*x]-=R,e.acc[2*x+1]-=I,e.acc[2*N]+=R,e.acc[2*N+1]+=I}}}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,P=S*S+D*D+1e-6,R=Math.sqrt(P),I=d*(R-l),W=I*S/R,G=I*D/R;e.acc[2*x]+=W,e.acc[2*x+1]+=G,e.acc[2*k]-=W,e.acc[2*k+1]-=G}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 aU(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 lU(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 cU(){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 uU(){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 kC(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=kC(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,jC=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 dU(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=dU(v);N&&(g[String(k)]=N)}const y=xC(l.viewport,{minZoom:Lv,maxZoom:Iv,maxAbsTranslate:jC})??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 fU(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 hU(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 mU(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 _U(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 pU(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 gU(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 yU(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=yU(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 SC(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 wU(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=SC(d);return h>1?`${m}×${h}`:m}).join(" | "),l=i.length>n?` +${i.length-n}`:"";return`${c}${l}`.trim()}function vU({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],he=n==null?void 0:n[n.length-1],Ie=Y?`${Y.subject}|${Y.predicate}|${Y.object}`:"",De=he?`${he.subject}|${he.predicate}|${he.object}`:"";return`${(n==null?void 0:n.length)||0}:${Ie}:${De}`},[n]),N=String(e??v),$=t==="replace"?"replace":"override",[C,S]=p.useState(null),[D,P]=p.useState(null),[R,I]=p.useState(!1),[W,G]=p.useState(""),[K,V]=p.useState(!1),[M,A]=p.useState("");p.useEffect(()=>{S(null),P(null),G(""),I(!1),A(""),V(!1)},[N]);const[O,L]=p.useState(""),[J,H]=p.useState(!0),[z,te]=p.useState(!1),[B,ne]=p.useState(!0),[se]=p.useState(()=>({compact:cU(),show:!1})),ue=se.compact,[ve,Te]=p.useState(se.show),[ke,le]=p.useState(!1),xe=N,Ee=p.useMemo(()=>Rv(xe),[xe]),[Ve,_t]=p.useState("grid"),[Qe,ot]=p.useState(Ee),[ze,He]=p.useState(!1),[ft,et]=p.useState(1),Ot=p.useRef(null),Ne=p.useRef(null),Re=p.useRef(!1),[tt,re]=p.useState(0),ge=p.useRef(null),de=p.useRef(0),je=p.useRef(0),X=p.useRef(0),Oe=p.useRef(0),[pt,at]=p.useState(!1),[Et,yt]=p.useState(""),[jt,st]=p.useState({}),Pt=p.useRef({});p.useEffect(()=>{Pt.current=jt},[jt]);const[Lt,mn]=p.useState(""),[wn,On]=p.useState(""),Ks=p.useMemo(()=>{var he;const Y=(he=n==null?void 0:n[0])==null?void 0:he.scope;return hj(Y,"session")},[n]),[rs,_e]=p.useState(Ks),[Me,wt]=p.useState("standard"),[ie,fe]=p.useState(""),[$e,Le]=p.useState(""),[We,Ue]=p.useState(""),[nt,ut]=p.useState(""),[xt,bt]=p.useState(""),[Tt,zt]=p.useState(""),[ct,Yt]=p.useState(""),[vn,hn]=p.useState("qwen/qwen3-next-80b");p.useEffect(()=>{_e(Ks)},[N]);const sn=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,Rt=typeof l=="number"?l:void 0,Fn=typeof d=="number"?d:void 0,fn=h,Xe=m,nn=$==="override"&&(C!=null&&C.items)&&Array.isArray(C.items)?C.items:sn,cn=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)??fn,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?nn:(nn||[]).filter(Y=>!gw(Y==null?void 0:Y.predicate,ws)),[nn,B,ws]),ye=p.useMemo(()=>rU(nn,{groupEdges:J}),[nn,J]),Nt=p.useMemo(()=>{if(B)return ye;const Y=[];for(const he of ye.edges){const De=(he&&he.data&&Array.isArray(he.data.assertions)?he.data.assertions:[]).filter(mt=>!gw(mt==null?void 0:mt.predicate,ws));if(!De.length)continue;const Ye=wU(De);Y.push({...he,label:Ye,data:{...he.data,assertions:De,predicateSummary:Ye}})}return{nodes:ye.nodes,edges:Y}},[ye,B,ws]),zn=p.useMemo(()=>Nt.nodes.map(Y=>Y.id),[Nt.nodes]),nr=p.useMemo(()=>{const Y=zn[0]||"",he=zn[zn.length-1]||"";return`${zn.length}:${Y}:${he}`},[zn]),$i=p.useMemo(()=>{var he;const Y=new Map;for(const Ie of Nt.nodes)Y.set(Ie.id,String(((he=Ie.data)==null?void 0:he.label)||Ie.id));return Y},[Nt.nodes]),sr=p.useMemo(()=>{var he;const Y=new Map;for(const Ie of Nt.nodes)Y.set(Ie.id,String(((he=Ie.data)==null?void 0:he.kind)||""));return Y},[Nt.nodes]),bo=O.trim().toLowerCase(),dc=p.useMemo(()=>{var he;if(!bo)return new Set;const Y=new Set;for(const Ie of Nt.nodes){const De=String(Ie.id||"").toLowerCase(),Ye=String(((he=Ie.data)==null?void 0:he.label)||"").toLowerCase();(De.includes(bo)||Ye.includes(bo))&&Y.add(Ie.id)}return Y},[Nt.nodes,bo]),ul=p.useCallback((Y,he)=>{const Ie={};for(const De of zn){const Ye=Y[De]||he[De];Ie[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Ie},[zn]);p.useEffect(()=>{st(Y=>{const he=Md(Nt,{kind:Ve,seed:Qe}),Ie={};for(const De of zn){const Ye=Y[De]||he[De];Ie[De]=Ye?{x:Ye.x,y:Ye.y}:{x:0,y:0}}return Ie})},[Nt,Ve,Qe,zn,nr]),p.useEffect(()=>{if(!Re.current)return;const Y=k.current;if(!(!Y||typeof Y.fitView!="function")&&zn.length){Re.current=!1;try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}}},[zn.length,nr,jt]),p.useEffect(()=>{He(!1),Ot.current=null,Ne.current=null,Re.current=!1,de.current=0,je.current=0,X.current=0;const Y=mj(xe);if(Y&&Object.keys(Y.positions||{}).length){if(_t(Y.kind),ot(Y.seed),at(!0),yt(Y.saved_at||""),Y.viewport){Ne.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{}}Ne.current=null}}else Re.current=!0;const De=Md(Nt,{kind:Y.kind,seed:Y.seed});st(ul(Y.positions,De));return}at(!1),yt("");const he=Rv(xe);ot(he);const Ie=Md(Nt,{kind:Ve,seed:he});st(Ie),Ve==="force"&&Nt.nodes.length>0&&Nt.nodes.length<=320&&(Ot.current=wp(Nt,{seed:he,positions:Ie,...Mh(ft)}),He(!0))},[xe]);const js=p.useMemo(()=>{const Y=String(Lt||"").trim(),he=String(wn||"").trim();return!Y||!he?null:iU(Nt,Y,he,{directed:z})},[Nt,Lt,wn,z]),pr=!!(js&&String(Lt||"").trim()&&String(wn||"").trim()),Rs=p.useMemo(()=>{const Y=String(Lt||"").trim(),he=String(wn||"").trim();if(!Y||!he)return null;const Ie=z,De=new Map,Ye=(Dt,Bt)=>{const pn=De.get(Dt);pn?pn.push(Bt):De.set(Dt,[Bt])};for(const Dt of Nt.edges)Ye(Dt.source,Dt.target),Ie||Ye(Dt.target,Dt.source);const mt=new Set,Wt=[];for(mt.add(Y),Wt.push(Y);Wt.length;){const Dt=Wt.shift(),Bt=De.get(Dt)||[];for(const pn of Bt)mt.has(pn)||(mt.add(pn),Wt.push(pn))}return{reachableFromStart:mt.size,endReachable:mt.has(he),nodes:Nt.nodes.length,edges:Nt.edges.length,assertions:_r.length}},[z,Nt.edges,Nt.nodes.length,wn,Lt,_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,he=new Set,Ie=String(vs||"").trim(),De=String(Ls||"").trim();if(Ie){Y.add(Ie);for(const Ye of Nt.edges)(Ye.source===Ie||Ye.target===Ie)&&(he.add(Ye.id),Y.add(Ye.source),Y.add(Ye.target));return{nodes:Y,edges:he}}if(De){const Ye=Nt.edges.find(mt=>mt.id===De);Ye&&(he.add(Ye.id),Y.add(Ye.source),Y.add(Ye.target))}return{nodes:Y,edges:he}},[Nt.edges,Ls,vs]);p.useEffect(()=>{ri(""),ii(""),mn(""),On("")},[N]);const[Ui,In]=p.useState(!1);p.useEffect(()=>{In(!1)},[N]),p.useEffect(()=>{ze||(Ot.current=null)},[ze]),p.useEffect(()=>{if(Ve!=="force")return;const Y=Ot.current;if(!Y)return;const he=Mh(ft);Y.options.springLength=he.springLength,Y.options.repulsionStrength=he.repulsionStrength},[Ve,ft]),p.useEffect(()=>{Ve!=="force"&&ze&&He(!1)},[Ve,ze]),p.useEffect(()=>{if(!ze||Ve!=="force"||Nt.nodes.length===0||typeof window>"u"||typeof window.requestAnimationFrame!="function")return;Ot.current||(Ot.current=wp(Nt,{seed:Qe,positions:Pt.current,...Mh(ft)}));let Y=0,he=0,Ie=0;const De=Nt.nodes.length<=140?2:1,Ye=1600,mt=.08,Wt=Dt=>{if(Y=window.requestAnimationFrame(Wt),Dt-he<33)return;he=Dt;const Bt=Ot.current;if(!Bt){He(!1);return}oU(Bt,De),Ie+=De,st(lU(Bt)),(aU(Bt)<=mt||Ie>=Ye)&&He(!1)};return Y=window.requestAnimationFrame(Wt),()=>{window.cancelAnimationFrame(Y)}},[Nt,Ve,ze,Qe]);const $a=p.useMemo(()=>Nt.nodes.map(Y=>{var bn;const he=Bi.has(Y.id),Ie=dc.has(Y.id),De=vs===Y.id,Ye=Ss&&oi.nodes.has(Y.id),mt=Rh((bn=Y.data)==null?void 0:bn.kind),Wt="rgba(34, 211, 238, 0.88)",Dt=Ie?"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=he?"rgba(168, 85, 247, 0.9)":Ie?Wt:mt.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=he?"rgba(168, 85, 247, 0.10)":Ie?"rgba(34, 211, 238, 0.08)":mt.bg,Ft=pr?he||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"}}}),[Nt.nodes,pr,dc,jt,vs,Bi,Ss,oi.nodes]),fl=p.useMemo(()=>Nt.edges.map(Y=>{const he=dl.has(Y.id),Ie=Ls===Y.id,De=Ss&&oi.edges.has(Y.id),Ye=he?"rgba(168, 85, 247, 0.9)":Ss?De||Ie?"rgba(96, 165, 250, 0.55)":"rgba(255,255,255,0.14)":"rgba(255,255,255,0.18)",mt=he?2.75:Ss?De||Ie?2.25:1.25:1.5,Wt=Ie?"drop-shadow(0 0 10px rgba(168, 85, 247, 0.25))":void 0,Dt=he?"rgba(168, 85, 247, 0.9)":pr?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.28)",Bt=pr?he||Ie?1:.1:Ss?De||Ie?1:.08:1,pn=pr?he||Ie?1:0:Ss?De||Ie?1:0:1,En=pr?he||Ie?String(Y.label||""):"":String(Y.label||"");return{...Y,label:En,style:{...Y.style||{},stroke:Ye,strokeWidth:mt,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"}}}),[Nt.edges,pr,Ls,dl,Ss,oi.edges]),hl=p.useMemo(()=>{if(!Ls)return[];const Y=Nt.edges.find(Ie=>Ie.id===Ls),he=Y&&Y.data&&Array.isArray(Y.data.assertions)?Y.data.assertions:[];return Array.isArray(he)?he:[]},[Nt.edges,Ls]),Tr=p.useMemo(()=>Ls&&Nt.edges.find(Y=>Y.id===Ls)||null,[Nt.edges,Ls]),fc=p.useMemo(()=>{const Y=String(vs||"").trim();return Y?nn.filter(he=>!he||typeof he!="object"||!(he.subject===Y||he.object===Y)?!1:B?!0:!gw(he.predicate,ws)):[]},[nn,vs,B,ws]),Wi=p.useMemo(()=>Ls?hl:fc,[hl,Ls,fc]),Ca=p.useMemo(()=>{const Y=new Map;for(const he of Wi){if(!he||typeof he!="object")continue;const Ie=he.provenance&&typeof he.provenance=="object"&&!Array.isArray(he.provenance)?he.provenance:null,De=Ie&&typeof Ie.span_id=="string"?Ie.span_id.trim():"",Ye=Ie&&typeof Ie.writer_run_id=="string"?Ie.writer_run_id.trim():"",mt=typeof he.owner_id=="string"?he.owner_id.trim():"",Wt=Ye||mt;if(!Wt||!De)continue;const Dt=`${Wt}|${De}`,Bt=Y.get(Dt),pn=typeof he.observed_at=="string"?he.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=he)):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:he})}return Array.from(Y.values()).sort((he,Ie)=>String(Ie.last_observed_at||"").localeCompare(String(he.last_observed_at||"")))},[Wi]),ko=p.useMemo(()=>{const Y=new Map;for(const he of Wi){if(!he||typeof he!="object")continue;const Ie=he.provenance&&typeof he.provenance=="object"&&!Array.isArray(he.provenance)?he.provenance:null,De=Ie&&typeof Ie.span_id=="string"?Ie.span_id.trim():"",Ye=Ie&&typeof Ie.writer_run_id=="string"?Ie.writer_run_id.trim():"";if(!Ye||De)continue;const mt=Y.get(Ye),Wt=typeof he.observed_at=="string"?he.observed_at.trim():"";mt?(mt.count+=1,Wt&&(!mt.last_observed_at||Wt>mt.last_observed_at)&&(mt.last_observed_at=Wt,mt.last_observed_at_fmt=Lh(Wt),mt.assertion=he)):Y.set(Ye,{run_id:Ye,count:1,last_observed_at:Wt,last_observed_at_fmt:Lh(Wt),assertion:he})}return Array.from(Y.values()).sort((he,Ie)=>String(Ie.last_observed_at||"").localeCompare(String(he.last_observed_at||"")))},[Wi]),Fs=p.useCallback(Y=>{const he=String(Y.run_id||"").trim(),Ie=typeof Y.span_id=="string"?String(Y.span_id).trim():"";if(he){if(x){try{x({run_id:he,span_id:Ie||void 0,assertion:Y.assertion})}catch{}return}if(y&&Ie)try{y({run_id:he,span_id:Ie,assertion:Y.assertion})}catch{}}},[y,x]),zs=p.useCallback(async Y=>{var Ie;const he=String(Y??"");if(he){try{if(typeof((Ie=navigator.clipboard)==null?void 0:Ie.writeText)=="function"){await navigator.clipboard.writeText(he);return}}catch{}try{const De=document.createElement("textarea");De.value=he,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 he=Y.getNode(vs);if(he){Y.fitView({nodes:[he],padding:.55,duration:350});return}}Y.fitView({padding:.2,duration:350})}},[vs]),jo=p.useCallback(Y=>{const he=Y.kind,Ie=Math.trunc(Y.seed);He(!1),Ot.current=null,Ne.current=null,_t(he),ot(Ie);const De=Md(Nt,{kind:he,seed:Ie});st(De),he==="force"&&(Y.autoPlay??!0)&&Nt.nodes.length>0&&Nt.nodes.length<=320&&(Ot.current=wp(Nt,{seed:Ie,positions:De,...Mh(ft)}),He(!0))},[Nt,ft]),qr=p.useCallback(()=>{if(Ve==="force"){if(ze){He(!1);return}Ot.current=wp(Nt,{seed:Qe,positions:Pt.current,...Mh(ft)}),He(!0)}},[Nt,Ve,ze,Qe,ft]);p.useEffect(()=>()=>{typeof window>"u"||typeof window.cancelAnimationFrame=="function"&&Oe.current&&window.cancelAnimationFrame(Oe.current)},[]);const Mr=p.useCallback(()=>{const Y=k.current;if(!Y||typeof Y.getViewport!="function"||!zn.length)return null;const he=ge.current;if(!he)return null;const Ie=he.getBoundingClientRect();if(!Number.isFinite(Ie.width)||!Number.isFinite(Ie.height)||Ie.width<64||Ie.height<64)return null;const De=Y.getViewport(),Ye=typeof(De==null?void 0:De.zoom)=="number"&&Number.isFinite(De.zoom)?De.zoom:null,mt=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||mt===null||Wt===null||Ye<=0)return null;const Dt=140,Bt=Math.min(zn.length,180),pn=Pt.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+mt,yr=Hn.y*Ye+Wt;if(Rr>-Dt&&Rr<Ie.width+Dt&&yr>-Dt&&yr<Ie.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"||Oe.current||(Oe.current=window.requestAnimationFrame(()=>{Oe.current=0;const he=Mr();if(he===null){if(X.current>=12)return;X.current+=1,window.setTimeout(()=>Vr(`${Y}:probe`),120);return}if(he!==!0){X.current=0,je.current=0;return}X.current=0;const Ie=k.current;if(Ie&&typeof Ie.fitView=="function")try{Ie.fitView({padding:.2,duration:0})}catch{try{Ie.fitView({padding:.2})}catch{}}if(je.current+=1,je.current>=4&&de.current<1){je.current=0,de.current+=1,re(De=>De+1);return}je.current<8&&window.setTimeout(()=>Vr(`${Y}:retry`),220)}))},[Mr]);p.useEffect(()=>{je.current=0,de.current=0,X.current=0,Vr("mount")},[N,Vr]),p.useEffect(()=>{Vr("graph change")},[nr,Vr]),p.useEffect(()=>{const Y=ge.current;if(!Y||typeof window>"u"||typeof ResizeObserver!="function")return;const he=new ResizeObserver(()=>Vr("resize"));return he.observe(Y),()=>he.disconnect()},[Vr]);const hc=p.useCallback(()=>{const Y=new Date().toISOString(),he={};for(const Wt of zn){const Dt=Pt.current[Wt];Dt&&typeof Dt.x=="number"&&typeof Dt.y=="number"&&(he[Wt]={x:Dt.x,y:Dt.y})}const Ie=k.current,De=Ie&&typeof Ie.toObject=="function"?Ie.toObject():null,Ye=De&&De.viewport?De.viewport:Ie&&typeof Ie.getViewport=="function"?Ie.getViewport():null,mt=xC(Ye,{minZoom:Lv,maxZoom:Iv,maxAbsTranslate:jC})??void 0;fU(xe,{version:1,kind:Ve,seed:Qe,positions:he,viewport:mt,saved_at:Y}),at(!0),yt(Y),He(!1)},[xe,Ve,Qe,zn]),Hr=p.useCallback(()=>{const Y=mj(xe);if(!Y)return;He(!1),Ot.current=null,_t(Y.kind),ot(Y.seed),at(!0),yt(Y.saved_at||""),Ne.current=Y.viewport||null,Re.current=!Y.viewport;const he=Md(Nt,{kind:Y.kind,seed:Y.seed});if(st(ul(Y.positions,he)),Y.viewport){const Ie=k.current;if(Ie&&typeof Ie.setViewport=="function"){try{Ie.setViewport(Y.viewport,{duration:0})}catch{try{Ie.setViewport(Y.viewport)}catch{}}Ne.current=null}}},[ul,Nt,xe]),ku=p.useCallback(()=>{hU(xe),at(!1),yt("")},[xe]),Ci=p.useCallback(Y=>{if(!Array.isArray(Y)||Y.length===0)return;let he=!1;st(Ie=>{let De=Ie,Ye=!1;for(const mt of Y){const Wt=mt&&typeof mt=="object"&&"id"in mt&&typeof mt.id=="string"?String(mt.id):"",Dt=(mt==null?void 0:mt.type)==="position"?mt==null?void 0:mt.position:null;Wt&&Dt&&typeof Dt.x=="number"&&typeof Dt.y=="number"&&(Ye||(De={...Ie},Ye=!0),De[Wt]={x:Dt.x,y:Dt.y},mt!=null&&mt.dragging&&(he=!0))}return Ye?De:Ie}),he&&ze&&He(!1)},[ze]),Zo=p.useMemo(()=>{const Y=new Map;for(const he of Nt.edges)Y.set(he.id,he);return Y},[Nt.edges]),ml=p.useMemo(()=>{var De;if(!js)return[];const Y=js.nodeIds||[],he=js.edgeIds||[],Ie=[];for(let Ye=0;Ye<Math.min(Y.length-1,he.length);Ye++){const mt=Y[Ye],Wt=Y[Ye+1],Dt=he[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===mt&&Bt.target===Wt?"forward":Bt&&Bt.source===Wt&&Bt.target===mt?"reverse":"unknown";Ie.push({from:mt,to:Wt,edgeId:Dt,predicate:pn,dir:En})}return Ie},[Zo,js]),So=p.useCallback(async()=>{if(_){G(""),A(""),I(!0);try{const Y=mU(xt),he=pw(Tt,{allowZero:!0,allowNegativeOne:!0}),Ie=pw(ct,{allowZero:!0}),De=await _({scope:rs,owner_id:void 0,recall_level:Me,query_text:ie||void 0,subject:$e||void 0,predicate:We||void 0,object:nt||void 0,min_score:Y,limit:he,max_input_tokens:Ie,model:vn||void 0});S(De),P("live query"),$==="replace"&&g&&De&&Array.isArray(De.items)&&g(De.items,{kind:"live query",result:De})}catch(Y){const he=Y instanceof Error?Y.message:String(Y);G(he||"Query failed")}finally{I(!1)}}},[Tt,ct,xt,vn,nt,g,_,We,$,ie,Me,rs,$e]),ai=p.useCallback(async()=>{if(!_)return;const Y=String(Lt||"").trim(),he=String(wn||"").trim();if(!Y||!he)return;const Ie=Math.max(200,pw(Tt)??80),De=60;A(""),G(""),V(!0);try{const Ye=[],mt=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||"")}`;mt.has(bn)||(mt.add(bn),Ye.push(Ft))};for(const Ft of nn)Wt(Ft);const Dt=z,Bt=new Set,pn=[Y],En=new Set([Y]),Js=async Ft=>{const bn=await _({scope:rs,recall_level:Me,min_score:0,limit:Ie,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:Me,min_score:0,limit:Ie,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(he);){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:cn,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:En.size,merged:Ye.length,directed:Dt}}),P("expanded neighborhood"),$==="replace"&&g&&g(Ye,{kind:"expanded neighborhood",result:{ok:!0,count:Ye.length,items:Ye,active_memory_text:cn,raw:{expanded_for_path:!0,expanded_nodes:Bt.size,discovered_nodes:En.size,merged:Ye.length,directed:Dt}}})}catch(Ye){const mt=Ye instanceof Error?Ye.message:String(Ye);A(mt||"Expand neighborhood failed")}finally{V(!1)}},[z,cn,nn,Tt,g,_,wn,Lt,$,Me,rs]),Ea=p.useCallback(()=>{S(null),P(null),G(""),I(!1),A(""),V(!1),mn(""),On(""),ri(""),ii("")},[]),qi="Search KG",rr=Nt.nodes.length,uf=Nt.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:ft,onChange:Y=>et(kC(Number(Y.target.value),.7,2.2,1))}),s.jsxs("span",{className:"amx-small",children:[ft.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:ze?"Pause simulation":"Play simulation"})]})}),s.jsxs("div",{className:"amx-graph","aria-label":"Knowledge graph",ref:ge,children:[s.jsx(Wx,{children:s.jsxs(pC,{nodes:$a,edges:fl,defaultViewport:{x:0,y:0,zoom:1},minZoom:Lv,maxZoom:Iv,onInit:Y=>{k.current=Y;const he=Ne.current;if(he&&typeof Y.setViewport=="function")try{Y.setViewport(he,{duration:0})}catch{try{Y.setViewport(he)}catch{}}if(Re.current&&typeof Y.fitView=="function")try{Y.fitView({padding:.2,duration:0})}catch{try{Y.fitView({padding:.2})}catch{}}Ne.current=null,Re.current=!1,Vr("init")},nodesDraggable:!0,nodesConnectable:!1,elementsSelectable:!0,onNodesChange:Ci,onNodeClick:(Y,he)=>{ii(""),ri(he.id)},onEdgeClick:(Y,he)=>{ri(""),ii(he.id)},onPaneClick:()=>{ri(""),ii("")},children:[s.jsx(GB,{className:"amx-flow-controls",children:s.jsx(zd,{type:"button",className:`amx-control-legend ${ke?"amx-control-legend-active":""}`,onClick:()=>le(Y=>!Y),title:ke?"Hide node color legend":"Show node color legend","aria-label":ke?"Hide node color legend":"Show node color legend",children:s.jsx(uU,{})})}),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:()=>Te(Y=>!Y),title:ve?"Hide minimap preview":"Show minimap preview","aria-label":ve?"Hide minimap preview":"Show minimap preview",children:ve?"minimap on":"minimap off"})})}),ve?s.jsx(zB,{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:ue?120:160,height:ue?80:110,marginBottom:56},nodeColor:Y=>{var he;return Rh((he=Y.data)==null?void 0:he.kind).minimap}}):null,ke?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:he})=>s.jsx("span",{className:"amx-legend-item",style:{borderColor:Rh(Y).stroke},children:he},Y))})]}):null,s.jsx(QB,{gap:20,size:1,color:"rgba(255,255,255,0.06)"})]})},tt),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:O,onChange:Y=>L(Y.target.value),placeholder:"filter nodes by id/label"})]}),s.jsxs("label",{children:["group edges",s.jsxs("select",{value:String(J),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=>ne(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=>te(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=>ot(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:ze?"Pause simulation":"Play simulation"}):null,s.jsx("button",{type:"button",className:"amx-btn",onClick:hc,disabled:!zn.length,children:"Save layout"}),pt?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.",pt?s.jsxs("span",{children:[" ","(saved",Et?`: ${Et}`:"",")"]}):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:Lt,onChange:Y=>mn(Y.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),zn.map(Y=>s.jsx("option",{value:Y,children:(()=>{const he=$i.get(Y)||Y;return he===Y?he:`${he} (${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 he=$i.get(Y)||Y;return he===Y?he:`${he} (${Y})`})()},Y))]})]})]}),js?s.jsx("div",{className:"amx-small",style:{marginTop:10},children:ml.map((Y,he)=>{const Ie=$i.get(Y.from)||Y.from,De=$i.get(Y.to)||Y.to,Ye=Y.dir==="reverse"?" ← ":" → ",mt=Y.predicate?` (${Y.predicate})`:"";return s.jsxs("div",{children:[he===0?s.jsx("span",{children:Ie}):null,Ye,s.jsxs("span",{children:[De,mt]})]},`${Y.edgeId}:${he}`)})}):Lt&&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)??Nt.nodes.length," nodes ·"," ",(Rs==null?void 0:Rs.edges)??Nt.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:K,children:K?"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:ie,onChange:Y=>fe(Y.target.value),placeholder:"e.g. emotion chip"})]}),s.jsxs("label",{children:["subject (exact)",s.jsx("input",{value:$e,onChange:Y=>Le(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:nt,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:Tt,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=>_e(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:Me,onChange:Y=>wt(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:ct,onChange:Y=>Yt(Y.target.value),placeholder:"(auto)"})]}),s.jsxs("label",{children:["model (budgeting)",s.jsx("input",{value:vn,onChange:Y=>hn(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:!_||R,children:R?"Querying…":"Query store"}),s.jsx("button",{type:"button",className:"amx-btn",onClick:Ea,disabled:!C&&!W&&!R,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,M?s.jsx("span",{className:"amx-small",style:{color:"var(--error, rgba(255, 80, 80, 0.95))"},children:M}):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=_U(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 he=typeof Y=="string"?Y:Array.isArray(Y)?Y.map(Ie=>String(Ie)).join(" · "):JSON.stringify(Y);return!he||!he.trim()?null:s.jsx("div",{className:"amx-small",style:{marginBottom:8,color:"var(--warning, rgba(255, 180, 90, 0.95))"},children:he})})(),s.jsx("div",{className:"amx-small",style:{marginBottom:8,opacity:.9},children:(()=>{const Y=(C==null?void 0:C.packets_version)??Be,he=(C==null?void 0:C.packed_count)??Qt,Ie=(C==null?void 0:C.dropped)??Rt,De=(C==null?void 0:C.estimated_tokens)??Fn,Ye=[];return typeof Y=="number"&&Ye.push(`packets_v${Y}`),typeof he=="number"&&Ye.push(`packed=${he}`),typeof Ie=="number"&&Ye.push(`dropped=${Ie}`),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:gU(cn||"(empty)",O)}),(()=>{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(he=>!he),children:[Ui?"Hide":"Show"," packets (",Y.length,")"]}),Ui?s.jsx("div",{className:"amx-list",style:{marginTop:10},children:Y.slice(0,120).map((he,Ie)=>{const De=he&&typeof he=="object"&&!Array.isArray(he)?he:null,Ye=De&&typeof De.statement=="string"?De.statement:typeof he=="string"?he:"",mt=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||mt!==null?s.jsxs("div",{className:"amx-small",children:[Wt?`[${Wt}]`:null,Wt&&mt!==null?" ":null,mt!==null?`score:${mt}`:null]}):null]},Ie)})}):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,he)=>{const Ie=String(Y.subject||"").trim(),De=String(Y.predicate||"").trim(),Ye=String(Y.object||"").trim(),mt=$i.get(Ie)||Ie,Wt=$i.get(Ye)||Ye,Dt=sr.get(Ie)||"entity",Bt=sr.get(Ye)||"entity",pn=Rh(Dt),En=Rh(Bt),Js=Lh(Y.observed_at),Ft=pU(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:Ie,onClick:()=>{Ie&&(ii(""),ri(Ie))},children:mt||Ie||"(subject)"}),s.jsx("span",{className:"amx-arrow",children:"—"}),s.jsx("span",{className:"amx-predicate",title:De,children:SC(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]},he)})})]}),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 xU(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 NC(e){return String(e??"").replace(/[*_`~]/g,"")}function vp(e,t){const n=!!(t!=null&&t.strip_punct),r=Vx(e);let i=NC(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(NC(t)),n}function bU(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 kU(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 jU({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(""),[P,R]=p.useState(!1),[I,W]=p.useState([]),[G,K]=p.useState(!1),[V,M]=p.useState(!1),[A,O]=p.useState(""),[L,J]=p.useState(""),[H,z]=p.useState(""),[te,B]=p.useState(""),[ne,se]=p.useState("artifact"),[ue,ve]=p.useState(null),[Te,ke]=p.useState(""),[le,xe]=p.useState(null),Ee=p.useRef(!1),Ve=p.useMemo(()=>{const _e=le,Me=_e!=null&&_e.attributes&&typeof _e.attributes=="object"&&!Array.isArray(_e.attributes)?_e.attributes:null;return(Me&&typeof Me.evidence_quote=="string"?String(Me.evidence_quote):"").trim()},[le]),_t=p.useMemo(()=>{const _e=ue,Me=_e&&typeof _e=="object"&&!Array.isArray(_e)?_e:null,wt=Me&&typeof Me.note=="string"?String(Me.note):"";return Vx(wt).trim()},[ue]),Qe=p.useMemo(()=>{const _e=ue&&typeof ue=="object"&&!Array.isArray(ue)?ue:null,Me=_e&&Array.isArray(_e.messages)?_e.messages:null;return Array.isArray(Me)?Me:null},[ue]),ot=p.useMemo(()=>{const _e=_t,Me=Ve;return!_e||!Me?!1:xp(_e,Me)},[Ve,_t]),ze=p.useMemo(()=>{const _e=Qe,Me=Ve;if(!_e||!Me)return[];const wt=[];for(let ie=0;ie<Math.min(_e.length,500);ie++){const fe=_e[ie],$e=(fe==null?void 0:fe.content)==null?"":String(fe.content);xp($e,Me)&&wt.push(ie)}return wt},[Ve,Qe]),He=p.useMemo(()=>new Set(ze),[ze]),ft=ze.length?ze[0]:null,et=p.useCallback(_e=>{const Me=document.getElementById(`source_msg_${_e}`);Me&&typeof Me.scrollIntoView=="function"&&Me.scrollIntoView({block:"center",behavior:"smooth"})},[]),Ot=p.useCallback(()=>{const _e=document.getElementById("source_note_hit_0")||document.getElementById("source_note_msg_hit_0");_e&&typeof _e.scrollIntoView=="function"&&_e.scrollIntoView({block:"center",behavior:"smooth"})},[]);p.useEffect(()=>{if(G&&!(V||A)&&!Ee.current){if(ft!==null){Ee.current=!0,window.setTimeout(()=>et(ft),0);return}if(ot){Ee.current=!0,window.setTimeout(()=>Ot(),0);return}}},[et,Ot,A,ft,V,ot,G]);const Ne=p.useRef(new Set),Re=p.useRef(""),tt=p.useRef(null),re=p.useRef(null);p.useEffect(()=>{i(String(t||"").trim())},[t]),p.useEffect(()=>{c(String(n||"").trim())},[n]);const ge=p.useMemo(()=>{const _e=String(r||"").trim(),Me=String(o||"").trim();return`mindmap:${l}:${_e}:${Me}`},[r,o,l]),de=p.useMemo(()=>{let _e=null,Me=null;for(const wt of v){const ie=Xl(wt==null?void 0:wt.observed_at);ie!==null&&(_e=_e===null?ie:Math.min(_e,ie),Me=Me===null?ie:Math.max(Me,ie))}return{min_ms:_e,max_ms:Me}},[v]),je=1e3,X=p.useMemo(()=>{const _e=de.min_ms,Me=de.max_ms;if(typeof _e!="number"||typeof Me!="number"||!Number.isFinite(_e)||!Number.isFinite(Me))return null;if(Me<=_e)return{min_ms:_e,max_ms:_e,real_max_ms:Me};const wt=_e+Math.ceil((Me-_e)/je)*je;return{min_ms:_e,max_ms:wt,real_max_ms:Me}},[de.max_ms,de.min_ms]),[Oe,pt]=p.useState(!0),[at,Et]=p.useState(null);p.useEffect(()=>{Oe&&X&&Et(X.max_ms)},[Oe,X]);const yt=p.useMemo(()=>{const _e=typeof at=="number"?at:null;return _e===null?v:v.filter(Me=>{const wt=Xl(Me==null?void 0:Me.observed_at);return wt===null?!0:wt<=_e})},[v,at]),jt=p.useCallback((_e,Me)=>{const wt=Array.isArray(_e)?_e:[],ie=String(Re.current||"").trim(),fe=new Set,$e=[];let Le="";for(const We of wt){if(!We||typeof We!="object"||typeof We.subject!="string"||typeof We.predicate!="string"||typeof We.object!="string")continue;const Ue=gj(We);if(fe.has(Ue))continue;fe.add(Ue),$e.push(We);const nt=String(We.observed_at||"").trim();nt&&(Le=pj(Le,nt))}N($e),C(Me==null?void 0:Me.warnings),Ne.current=fe,Re.current=Le||ie},[]),st=p.useCallback(async _e=>{const Me=yw(_e.scope,"session"),wt=String(_e.subject||"").trim(),ie=String(_e.predicate||"").trim(),fe=String(_e.object||"").trim(),$e=String(_e.since||"").trim(),Le=String(_e.until||"").trim(),We=String(_e.active_at||"").trim(),Ue=String(_e.query_text||"").trim(),nt=typeof _e.min_score=="number"&&Number.isFinite(_e.min_score)?Number(_e.min_score):void 0,ut=_e.order==="asc"?"asc":"desc",xt=typeof _e.limit=="number"&&Number.isFinite(_e.limit)?Number(_e.limit):0,bt=String(r||"").trim(),Tt=String(o||"").trim(),zt={scope:Me,all_owners:h,limit:xt,order:ut};wt&&(zt.subject=wt),ie&&(zt.predicate=ie),fe&&(zt.object=fe),$e&&(zt.since=$e),Le&&(zt.until=Le),We&&(zt.active_at=We),Ue&&(zt.query_text=Ue),typeof nt=="number"&&(zt.min_score=nt),h||(Me==="run"?bt&&(zt.run_id=bt):Me==="session"?Tt?zt.session_id=Tt:bt&&(zt.run_id=bt):Me==="all"&&(bt?zt.run_id=bt:Tt&&(zt.session_id=Tt)));try{const ct=await e.kg_query(zt),Yt=Array.isArray(ct==null?void 0:ct.items)?ct.items:[],vn=ct==null?void 0:ct.warnings;return{ok:(ct==null?void 0:ct.ok)!==!1,count:Number((ct==null?void 0:ct.count)||Yt.length),items:Yt,warnings:vn,raw:ct}}catch(ct){const Yt=ct instanceof Error?ct.message:String(ct);if(Yt.includes("Run '")&&Yt.includes("not found")&&!Tt&&(Me==="session"||Me==="all")&&bt){const hn=await e.kg_query({...zt,run_id:void 0,session_id:bt}),sn=Array.isArray(hn==null?void 0:hn.items)?hn.items:[],Ht=hn==null?void 0:hn.warnings;return{ok:(hn==null?void 0:hn.ok)!==!1,count:Number((hn==null?void 0:hn.count)||sn.length),items:sn,warnings:Ht,raw:hn}}throw new Error(Yt||"KG query failed")}},[h,e,r,o]),Pt=p.useCallback(async _e=>{var ie;const Me=String(_e.run_id||"").trim(),wt=String(_e.span_id||"").trim();if(!(!Me||!wt)){K(!0),M(!0),O(""),z(Me),B(wt),se("artifact"),J(`source span:${wt}`),ve(null),ke(""),xe(_e.assertion&&typeof _e.assertion=="object"?_e.assertion:null),Ee.current=!1;try{const fe=[Me],$e=typeof((ie=_e.assertion)==null?void 0:ie.owner_id)=="string"?String(_e.assertion.owner_id).trim():"";$e&&$e!==Me&&fe.push($e);let Le=null,We=null;for(const Ue of fe)try{We=await(await e.download_run_artifact_content(Ue,wt)).text(),Ue!==Me&&z(Ue);break}catch(nt){Le=nt instanceof Error?nt.message:String(nt)}if(We==null)throw new Error(Le||"Failed to load source span");ke(We);try{const Ue=JSON.parse(We);ve(Ue)}catch{ve(null)}}catch(fe){const $e=fe instanceof Error?fe.message:String(fe);O($e||"Failed to load source span")}finally{M(!1)}}},[e]),Lt=p.useCallback(async _e=>{const Me=String(_e.run_id||"").trim();if(!Me)return null;try{const wt=await e.list_run_artifacts(Me,{limit:200}),fe=(Array.isArray(wt==null?void 0:wt.items)?wt.items:[]).map(nt=>{const ut=typeof(nt==null?void 0:nt.artifact_id)=="string"?String(nt.artifact_id).trim():"",xt=nt!=null&&nt.tags&&typeof nt.tags=="object"&&!Array.isArray(nt.tags)?nt.tags:null,bt=xt&&typeof xt.kind=="string"?String(xt.kind).trim():"";return{artifact_id:ut,kind:bt}}).filter(nt=>!!(nt.artifact_id&&(nt.kind==="conversation_span"||nt.kind==="memory_note")));if(!fe.length)return null;if(fe.length===1)return fe[0].artifact_id;const $e=_e.assertion,Le=$e!=null&&$e.attributes&&typeof $e.attributes=="object"&&!Array.isArray($e.attributes)?$e.attributes:null,Ue=(Le&&typeof Le.evidence_quote=="string"?String(Le.evidence_quote):"").trim();if(!Ue)return null;for(const nt of fe.slice(0,10))try{const xt=await(await e.download_run_artifact_content(Me,nt.artifact_id)).text(),bt=JSON.parse(xt);if(bt&&typeof bt=="object"){const Tt=typeof bt.note=="string"?String(bt.note):"";if(Tt&&Tt.includes(Ue))return nt.artifact_id;const zt=Array.isArray(bt.messages)?bt.messages:null;if(zt){for(const ct of zt.slice(0,200))if(((ct==null?void 0:ct.content)==null?"":String(ct.content)).includes(Ue))return nt.artifact_id}}}catch{}}catch{}return null},[e]),mn=p.useCallback(async _e=>{const Me=String(_e.run_id||"").trim();if(Me){K(!0),M(!0),O(""),z(Me),B(""),se("run_input"),J(`transcript run:${Me}`),ve(null),ke(""),xe(_e.assertion&&typeof _e.assertion=="object"?_e.assertion:null),Ee.current=!1;try{const wt=await Lt({run_id:Me,assertion:_e.assertion});if(wt){await Pt({run_id:Me,span_id:wt,assertion:_e.assertion});return}const ie=await e.get_run_input_data(Me),fe=ie&&typeof ie=="object"&&!Array.isArray(ie)?ie.input_data:null,$e={kind:"run_input_data",run_id:Me};if(ie&&typeof(ie==null?void 0:ie.workflow_id)=="string"&&($e.workflow_id=String(ie.workflow_id)),fe&&typeof fe=="object"&&!Array.isArray(fe)){const Le=fe.context,Ue=(Le&&typeof Le=="object"&&Array.isArray(Le.messages)?Le.messages:null)||(Array.isArray(fe.messages)?fe.messages:null);Array.isArray(Ue)&&($e.messages=Ue);const nt=["text","prompt","task","message"];for(const ut of nt){const xt=fe[ut];if(typeof xt=="string"&&xt.trim()){$e.note=xt.trim();break}}$e.input_data=fe}!$e.messages&&!$e.note&&($e.note=JSON.stringify(fe??ie??{},null,2));try{const Le=await e.get_run(Me),We=Le&&typeof(Le==null?void 0:Le.created_at)=="string"?String(Le.created_at):"";We&&($e.created_at=We)}catch{}ve($e),ke(JSON.stringify(ie,null,2))}catch(wt){const ie=wt instanceof Error?wt.message:String(wt);O(ie||"Failed to load run input transcript")}finally{M(!1)}}},[e,Pt,Lt]),wn=p.useCallback(async()=>{D(""),R(!0);try{const _e=l==="all"?"all":l,Me=await st({scope:_e,limit:0,order:"desc"});jt(Me.items||[],{warnings:Me.warnings}),tt.current={scope:_e}}catch(_e){const Me=_e instanceof Error?_e.message:String(_e);D(Me||"Load failed")}finally{R(!1)}},[st,jt,l]);p.useEffect(()=>{v.length||wn()},[]);const On=p.useCallback(async _e=>{const Me=yw(_e.scope,"session");return re.current=_e,await st({scope:Me,subject:_e.subject,predicate:_e.predicate,object:_e.object,query_text:_e.query_text,min_score:_e.min_score,since:_e.since,until:_e.until,active_at:_e.active_at,limit:typeof _e.limit=="number"?_e.limit:0,order:"desc"})},[st]),Ks=p.useCallback((_e,Me)=>{var wt;if((Me==null?void 0:Me.kind)==="live query"){const ie=re.current;ie&&(tt.current={scope:yw(ie.scope,"session"),subject:typeof ie.subject=="string"?ie.subject:void 0,predicate:typeof ie.predicate=="string"?ie.predicate:void 0,object:typeof ie.object=="string"?ie.object:void 0})}jt(_e,{warnings:(wt=Me==null?void 0:Me.result)==null?void 0:wt.warnings})},[jt]),rs=p.useCallback(async()=>{const _e=tt.current;if(!_e)return;const Me=String(Re.current||"").trim(),wt=await st({scope:_e.scope,subject:_e.subject,predicate:_e.predicate,object:_e.object,since:Me||void 0,order:"asc",limit:0}),ie=Array.isArray(wt.items)?wt.items:[];if(!ie.length)return;const $e=Date.now()+Math.max(250,Math.min(2e4,x)),Le=Ne.current,We=[],Ue=[];let nt=String(Re.current||"").trim();for(const ut of ie){if(!ut||typeof ut!="object"||typeof ut.subject!="string"||typeof ut.predicate!="string"||typeof ut.object!="string")continue;const xt=gj(ut);if(Le.has(xt))continue;Le.add(xt),We.push(ut),Ue.push({id:xt,assertion:ut,expires_at_ms:$e});const bt=String(ut.observed_at||"").trim();bt&&(nt=pj(nt,bt))}We.length&&(Re.current=nt,N(ut=>{const xt=ut.concat(We);return xt.sort((bt,Tt)=>String((Tt==null?void 0:Tt.observed_at)||"").localeCompare(String((bt==null?void 0:bt.observed_at)||""))),xt}),W(ut=>{const xt=ut.concat(Ue);return xt.sort((bt,Tt)=>Tt.expires_at_ms-bt.expires_at_ms),xt.slice(0,30)}))},[x,st]);return p.useEffect(()=>{if(!m)return;let _e=!1,Me=null;const wt=async()=>{if(!_e){try{await rs()}catch{}_e||(Me=window.setTimeout(()=>void wt(),Math.max(250,Math.min(6e4,g))))}};return wt(),()=>{_e=!0,Me!==null&&window.clearTimeout(Me)}},[m,g,rs]),p.useEffect(()=>{if(!I.length)return;const _e=window.setInterval(()=>{const Me=Date.now();W(wt=>wt.filter(ie=>ie.expires_at_ms>Me))},250);return()=>window.clearInterval(_e)},[I.length]),s.jsxs("div",{className:"mindmap_root",children:[s.jsxs("div",{className:"mindmap_bar",children:[s.jsx("button",{className:"btn",onClick:()=>void wn(),disabled:P,children:P?"Loading…":"Load snapshot"}),s.jsxs("label",{className:"field_inline",children:[s.jsx("span",{className:"mono muted",children:"source"}),s.jsxs("select",{value:l,onChange:_e=>{const Me=String(_e.target.value||"").trim();(Me==="all"||Me==="global"||Me==="session"||Me==="run")&&d(Me)},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(qP,{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:_e=>c(String(_e.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:_e=>i(String(_e.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:_e=>y(Math.max(250,Number(_e.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:_e=>k(Math.max(250,Number(_e.target.value||0)||5e3))})]})})]})]}),S?s.jsx("div",{className:"mindmap_error mono",children:S}):null,s.jsxs("div",{className:"mindmap_explorer",children:[s.jsx(vU,{title:"mindmap",resetKey:ge,queryMode:"replace",items:yt,warnings:$,onQuery:On,onItemsReplace:Ks,onOpenSpan:({run_id:_e,span_id:Me,assertion:wt})=>{Pt({run_id:_e,span_id:Me,assertion:wt})},onOpenTranscript:({run_id:_e,span_id:Me,assertion:wt})=>{const ie=String(_e||"").trim(),fe=typeof Me=="string"?String(Me).trim():"";ie&&(fe?Pt({run_id:ie,span_id:fe,assertion:wt}):mn({run_id:ie,assertion:wt}))}},ge),I.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:I.slice().sort((_e,Me)=>Me.expires_at_ms-_e.expires_at_ms).slice(0,12).map(_e=>s.jsx("div",{className:"mindmap_recent_item mono",children:kU(_e.assertion)},_e.id))})]}):null,X?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 at=="number"?at:X.max_ms,X.real_max_ms))}),s.jsx("input",{className:"mindmap_slider",type:"range",min:X.min_ms,max:X.max_ms,step:je,value:typeof at=="number"?at:X.max_ms,onChange:_e=>{const Me=Number(_e.target.value||0);Et(Me),pt(Me>=X.max_ms)}}),s.jsxs("div",{className:"mindmap_timeline_counts mono muted",children:[yt.length.toLocaleString(),"/",v.length.toLocaleString()]})]})}):null]}),s.jsxs(tc,{open:G,title:L||"source",onClose:()=>{K(!1)},children:[V?s.jsx("div",{className:"mono muted",children:"Loading…"}):null,A?s.jsx("div",{className:"mindmap_error mono",children:A}):null,!V&&!A?s.jsxs("div",{className:"source_span",children:[(()=>{const _e=le;if(!_e)return null;const Me=String(_e.subject||"").trim(),wt=String(_e.predicate||"").trim(),ie=String(_e.object||"").trim(),fe=su(Xl(_e.observed_at)),$e=_e.attributes&&typeof _e.attributes=="object"&&!Array.isArray(_e.attributes)?_e.attributes:null,Le=$e&&typeof $e.evidence_quote=="string"?String($e.evidence_quote):"",We=$e&&typeof $e.original_context=="string"?String($e.original_context):"";return s.jsxs("div",{className:"source_header",children:[s.jsxs("div",{className:"mono source_triple",title:`${Me} --${wt}--> ${ie}`,children:[Me," ",s.jsxs("span",{className:"muted",children:["—",wt,"→"]})," ",ie," ",fe?s.jsxs("span",{className:"muted",children:["[",fe,"]"]}):null]}),Le?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:Le}),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," · ",ne==="artifact"?`span_id=${te}`:"source=input_data"]}),s.jsxs("div",{className:"source_actions",children:[ft!==null?s.jsx("button",{className:"btn",onClick:()=>et(ft),children:"Jump to evidence"}):null,ft===null&&ot?s.jsx("button",{className:"btn",onClick:()=>Ot(),children:"Jump to evidence"}):null]}),(()=>{const _e=ue,Me=_e&&typeof _e=="object"&&!Array.isArray(_e)?_e:null,wt=Qe,ie=_t,fe=Me&&typeof Me.created_at=="string"?String(Me.created_at):"",$e=fe?Xl(fe):null,Le=$e!==null?su($e):fe,We=Me&&Me.span&&typeof Me.span=="object"&&!Array.isArray(Me.span)?Me.span:null,Ue=We&&typeof We.from_timestamp=="string"?String(We.from_timestamp):"",nt=We&&typeof We.to_timestamp=="string"?String(We.to_timestamp):"",ut=Ue?Xl(Ue):null,xt=nt?Xl(nt):null,bt=ut!==null&&xt!==null?`${su(ut)} → ${su(xt)}`:"";if(ie){const Tt=bU(ie);if(Tt){const zt=Ve,ct=zt?Tt.messages.findIndex(sn=>xp(sn.content,zt)):-1,Yt=zt?_j(zt):[],vn=Tt.created_at||fe,hn=vn?xU(vn):fe?Le:"";return s.jsx("div",{className:"source_chat",children:Tt.messages.map((sn,Ht)=>{const is=sn.role,Be=!!(zt&&xp(sn.content,zt)),Qt=is==="user"?"USER":is==="assistant"?"ASSISTANT":"SYSTEM";return s.jsxs("div",{id:Ht===ct?"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]}),hn?s.jsx("span",{title:vn||"",children:hn}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:sn.content,highlights:Be&&Yt.length?Yt:void 0,highlightClassName:"source_note_hit",highlightId:Ht===ct?"source_note_hit_0":void 0})})]},`note_msg:${Ht}`)})})}return s.jsxs("div",{className:"source_note",children:[fe?s.jsx("div",{className:"mono muted",style:{marginBottom:10},children:s.jsxs("span",{title:fe,children:["created_at=",Le]})}):null,s.jsx(Ni,{text:ie,highlights:Ve?_j(Ve):void 0,highlightClassName:"source_note_hit",highlightId:"source_note_hit_0"})]})}if(wt){const Tt=new Map;for(const ct of wt){const Yt=typeof(ct==null?void 0:ct.role)=="string"?String(ct.role):"unknown";Tt.set(Yt,(Tt.get(Yt)||0)+1)}const zt=Array.from(Tt.entries()).sort((ct,Yt)=>Yt[1]-ct[1]||ct[0].localeCompare(Yt[0])).map(([ct,Yt])=>`${ct}×${Yt}`).join(" · ");return s.jsxs("div",{className:"source_chat",children:[fe?s.jsxs("div",{className:"mono muted",style:{marginBottom:10},children:[s.jsxs("span",{title:fe,children:["created_at=",Le]})," · messages=",wt.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,wt.slice(0,200).map((ct,Yt)=>{var Rt,Fn;const vn=typeof(ct==null?void 0:ct.role)=="string"?String(ct.role):"unknown",hn=(ct==null?void 0:ct.content)==null?"":String(ct.content),sn=typeof(ct==null?void 0:ct.timestamp)=="string"?String(ct.timestamp):"",Ht=sn?Xl(sn):null,is=Ht!==null?su(Ht):sn,Be=typeof(ct==null?void 0:ct.message_id)=="string"?String(ct.message_id):typeof((Rt=ct==null?void 0:ct.metadata)==null?void 0:Rt.message_id)=="string"?String(ct.metadata.message_id):typeof((Fn=ct==null?void 0:ct.metadata)==null?void 0:Fn.id)=="string"?String(ct.metadata.id):"",Qt=He.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]}),sn?s.jsx("span",{title:sn,children:is}):null]}),s.jsx("div",{className:"source_msg_body",children:s.jsx(Ni,{text:hn})})]},Yt)})]})}return s.jsx("pre",{className:"mono source_raw",style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:(typeof _e=="string"?_e:Te)||"(empty)"})})()]}):null]})]})}const SU=6e4,NU=10*6e4;function $U(e){return Math.min(NU,SU*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 CU(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>=$U(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 EU(e,t){const n=e.get(t.id)||Jg();e.set(t.id,{...n,attempt_version:t.version,inflight:!0})}function AU(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 TU(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 MU(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 RU(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 LU(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 IU(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 OU(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 PU(e){return(e||[]).filter(t=>ks(t)&&OU(t)).map(t=>({id:ks(t),version:""}))}const DU=6e4;function FU(e,t=Date.now(),n=DU){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 zU(e){return{after:Math.max(0,Math.floor(e)-1),limit:1}}function BU(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>=UU)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 UU=50,WU=e=>({run_id:e,status:"missing",updated_at:"",workflow_id:"",error:"not found"});function qU(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 VU(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 HU(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 GU=12;function wj(e,t,n=GU){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:",KU=400,Pv=6e5;function JU(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 YU(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(-KU);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 $C(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}const XU=4,lf={automation:0,wait_detail:1,pulse:1,run_brief:2,outcome:3};class ZU{constructor(t=XU){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 QU(e){let t=vj.get(e);return t||(t=new ZU,vj.set(e,t)),t}const xj=new WeakMap;function e9(e){let t=xj.get(e);return t||(t=e.automations_client(),xj.set(e,t)),t}function t9(e){return e.map(t=>`${t.id}@${t.version}`).sort().join("|")}const bj=new WeakMap;function n9(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?JU(n.storage===void 0?$C():n.storage,t):new Map,r.set(t,i)),i}const ww=new Map;function s9(e,t){if(typeof setTimeout>"u")return;const n=ww.get(e);n!==void 0&&clearTimeout(n),ww.set(e,setTimeout(()=>{ww.delete(e),YU($C(),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?n9(e,r.scope,{persist:r.persist}):new Map,gen:i.current.gen+1});const[o,c]=p.useReducer(x=>x+1,0),l=t9(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=CU(t,x.entries,Date.now(),{immutable:r.immutable});if(!N.length)return;const $=QU(k);for(const C of N)EU(x.entries,C),$.submit(r.priority,async()=>{try{const S=await h.current(k,C);if(i.current.gen!==v)return;AU(x.entries,C,S),r.persist&&s9(r.scope,x.entries)}catch(S){if(i.current.gen!==v)return;TU(x.entries,C,S,Date.now())}c()});c()},[e,l,d,o,r.priority,r.immutable]);const m=p.useMemo(()=>MU(t,i.current.entries,{current_only:r.current_only}),[l,o,r.current_only,e]),_=p.useMemo(()=>RU(t,i.current.entries),[l,o,e]),g=p.useMemo(()=>LU(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 r9(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 i9(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 o9(e,t){const n=p.useMemo(()=>IU(t),[t]),r=cf(e,n,async(o,c)=>r9(await e9(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 a9(e,t){const n=p.useMemo(()=>PU(t),[t]),r=cf(e,n,async(i,o)=>HU(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 l9(e,t){const n=p.useMemo(()=>FU(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,zU(c)),d=Array.isArray(l==null?void 0:l.items)?l.items:[];return d.length?qD(o.id,c,d[d.length-1]):null},{scope:"pulse",priority:lf.pulse});return{map:r.map,pending:r.pending,loading:r.loading}}const c9=!0;function u9(e,t,n){const r=p.useMemo(()=>BU(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:c9});return{map:i.map,pending:i.pending,loading:i.loading}}function d9(e,t,n){const r=p.useMemo(()=>VU(t,n),[t,n]),i=cf(e,r,async(o,c)=>{try{return qU(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 WU(c.id);throw l}},{scope:"subrun_fate",priority:lf.wait_detail});return{map:i.map,pending:i.pending,loading:i.loading}}const f9=!0;function h9(e){return(e||[]).filter(t=>ks(t)&&hs(String((t==null?void 0:t.status)||""))).map(t=>({id:ks(t),version:""}))}function m9(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 _9(e){const t=e==null?void 0:e.total;return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}async function p9(e,t){const[n,r]=await Promise.all([e.get_run(t),e.list_run_artifacts(t,{limit:1}).then(_9,()=>null)]);return{answer:m9(n),artifacts:r}}function g9(e,t){const n=p.useMemo(()=>h9(t),[t]),r=cf(e,n,async(i,o)=>await p9(i,o.id),{scope:"outcome",priority:lf.outcome,immutable:f9,persist:!0});return{map:r.map,pending:r.pending,loading:r.loading}}function y9(){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,w9=6e4,v9=1e4,x9=15e3,b9=["llm_calls","tool_calls","tokens_total"];function k9(e,t){if(!t)return e;const n={...e};for(const r of b9){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 j9{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>=w9||this.early&&r>=x9?!0:n&&r>=v9}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(k9(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 S9(e,t){return`${wg}runs:${String(e||"").trim()}:${String(t||"").trim()}`}function N9(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 $9(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 C9(e,t){let n=Dv.get(e);if(!n||n.epoch!==t){const r=Fv;n=new j9(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 E9(e){return Dv.get(e)||null}function Nj(e){return Fv===e}const bp=["needs_you","working","waiting_on","scheduled","done"],CC={needs_you:"Needs you",working:"Working",waiting_on:"Waiting on…",scheduled:"Scheduled",done:"Done"},A9={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"},T9={needs_you:"nothing needs you",working:"no agent is working",waiting_on:"nothing is blocked",scheduled:"nothing scheduled",done:"no recent runs"},M9=8;function R9(){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 L9(e,t,n,r){const i=(e==null?void 0:e.paused)===!0||(n==null?void 0:n.paused)===!0;return W1({...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:V1(e,t,r),subject:q1(e,t),status_word:L9(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:o1(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 I9(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 O9(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=R9(),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 G=String((v==null?void 0:v.automation_id)||"").trim()||Qs(v);if(g.has(G))continue;g.add(G);const K=kp(v,o,N,(y=e.run_briefs)==null?void 0:y.get(Qs(v)));t[K.lane].push(K);continue}const $=kp(v,o,N,(x=e.run_briefs)==null?void 0:x.get(Qs(v))),C=[],S=[];let D=N.verb==="running",P=!!N.stuck,R=0;const I=(G,K)=>{var O;const V=d(G),M=K<6?_(Qs(G)):[],A=M.length>0;if(C.length>=M9)R+=1;else{const L=A?U1(G,o):"";C.push({run_id:Qs(G),depth:K,name:Bg(String((G==null?void 0:G.workflow_id)||""))||Qd(Qs(G)),title:UD(String((G==null?void 0:G.workflow_id)||""))||Qs(G),words:A?L?`waits at ${L} ↓`:"waits for ↓":V.brief||V.text,stuck:!!V.stuck,asks:V.lane==="needs_you"&&!V.stuck,running:V.verb==="running"&&!A,stuck_facts:V.stuck_facts,since_ms:Vt(String((G==null?void 0:G.updated_at)||(G==null?void 0:G.created_at)||""))})}K>0?(V.lane==="needs_you"&&!V.stuck&&S.push(kp(G,o,V,(O=e.run_briefs)==null?void 0:O.get(Qs(G)))),V.stuck&&(P=!0),V.verb==="running"&&(D=!0)):A&&V.lane==="needs_you"&&!V.stuck&&S.push($);for(const L of M)I(L,K+1)};I(v,0),R&&C.push({run_id:"",depth:1,name:`+${R} more`,title:"",words:"",stuck:!1,asks:!1,running:!1}),P&&!S.length&&($.status_word="stuck"),$.chain=C.length>1?C:[],$.asks=S,$.stuck=P;const W=N.lane==="needs_you"&&!N.stuck;if($.lane=W||S.length||P?"needs_you":D?"working":N.lane,S.length){const G=S.map(K=>K.since_ms).filter(K=>K!==null);G.length&&($.since_ms=Math.min(...G))}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 O9(t)}function P9(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 EC="board_stall_after_ms",Hx=[{ms:5*6e4,label:"5m"},{ms:15*6e4,label:"15m"},{ms:60*6e4,label:"1h"}];function AC(e){try{const t=Number(e==null?void 0:e.getItem(EC));return Hx.some(n=>n.ms===t)?t:mv}catch{return mv}}function TC(e){var t;return((t=Hx.find(n=>n.ms===e))==null?void 0:t.label)||er(e)}function D9(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function MC(e){const t=String((e==null?void 0:e.actor_id)||"").trim();return t&&t.toLowerCase()!=="gateway"?t:""}const RC=["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`${RC[n.getMonth()]} ${n.getDate()}${r}, ${vg(n.getHours())}:${vg(n.getMinutes())}`}function F9(e){const t=new Date(e);return`${RC[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 z9(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=MC(e.row);return r==="approve"?{who:i,text:`needs approval for ${z9(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 B9(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 LC(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 U9(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 IC(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 W9(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 q9={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 V9=[25e3,5e4,1e5,2e5];function OC(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 H9(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 G9(e){return{context:{mode:"growing",growing:{max_tokens:e}}}}function K9(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 J9={phase:"idle",custom:"",error:"",optimistic:null};function Y9(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 X9(e,t){const n=t.optimistic;return n&&n.base===e.growing_max_tokens?n.value:e.growing_max_tokens}async function Z9(e,t,n,r){try{return await e(t,G9(r),n),{type:"saved"}}catch(i){return{type:"failed",error:Pi(i).message||"the change was not saved"}}}function Q9(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 eW(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?F9(n):fu(n,r),aside:zv(n,r),copy:new Date(n).toISOString()}}function tW(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 nW(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:q9[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:MC(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:tW(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:B9($),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 ${TC(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 sW(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 rW(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 iW(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 oW=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 aW(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 lW=["asleep","sleep","dream"],cW=["rest"],uW=["awake","idle"];function dW(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":lW.some(c=>n.includes(c))?t.initial:cW.some(c=>n.includes(c))&&t.phases.includes("personal")?"personal":uW.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 fW=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]),hW=new Set(["visit","work","personal","sleep","paused","resting","stopped","unknown"]);function mW(e){if(!e)return fW;const t=e.phases.filter(n=>hW.has(n));return new Set([...t,"paused","stopped","unknown"])}const _W={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 pW(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 gW="mc_entities mc_entities_reserved",yW="mc_entities mc_entities_empty",wW=4,PC=12;function vW(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={},xW=["needs_you","working","waiting_on"];function bW(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 DC(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 kW(e,t,n,r=0){const i=n??t,o=`Cancel all ${i} task${i===1?"":"s"} in ${CC[e]}`;return i<t||r>0?`${o} (${t} run${t===1?"":"s"} asked)`:o}function jW(e,t,n,r){const[i,o]=p.useReducer(bW,{phase:"idle"}),c=t.length,l=r==null?void 0:r.targets,d=l?l.ids:[...t],h=d.length,m=!!n&&c>0&&xW.includes(e),_=kW(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 DC(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 SW(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 NW(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:OW}),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 $W(e){var i,o,c,l,d;(i=rl.lane)==null||i.call(rl,e.col);const t=`mc_column_title_${e.col}`,n=jW(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(SW,{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(NW,{state:n.state,label:n.label,on_run:()=>void n.run(),on_keep:n.keep}):null,e.children]})}const Ds=e=>e.stopPropagation(),CW=typeof window>"u"?p.useEffect:p.useLayoutEffect;function EW(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 AW(){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(AW,{})})}const TW=320,MW=6;function RW(e){const[t,n]=p.useState(!1),r=e.text,i=r.length>TW||r.split(`
|
|
169
|
+
`).length>MW;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 LW(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(RW,{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 IW="Cancel this task: this run, its parents below the automation, and everything working under them";function FC(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 OW="Everything working under those tasks stops too; automation schedules are not touched.";function PW(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 zC(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:W9(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 BC(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:IW,"aria-label":"Cancel this task",onClick:()=>e.on_event({type:"ask"}),children:e.variant==="icon"?s.jsx(qe,{name:"x",size:15}):"Cancel"})}function DW(e){return s.jsxs(s.Fragment,{children:[e.state.phase==="idle"?BC(e):null,Qx(e)]})}function FW(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 UC(e.on_cancel_run,e.run_id,r,e.on_cancel_runs))};return s.jsx(DW,{state:t,on_event:n,on_send:()=>void i(),variant:e.variant,question:FC(r,e.run_id)})}async function UC(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 DC(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 zW(e){const{card:t}=e,n=t.automation,r=nW(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(Ce.Fragment,{children:[s.jsx(LW,{row:d}),l.id==="automation"&&d.id==="title"&&(n!=null&&n.can_revise)?s.jsx(PW,{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(zC,{card:t,code_app:e.code_app}),Aj(t)&&e.on_cancel_run?s.jsx(FW,{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 BW=500,UW=580;let hu=null;function ba(){hu!==null&&window.clearTimeout(hu),hu=null}function Oj(e,t=BW){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 WW(e){const{anchor:t,on_close:n,on_hover:r,...i}=e;return s.jsx(WC,{anchor:t,on_close:n,on_hover:r,label:`About ${e.card.title.text}`,children:s.jsx(zW,{...i})})}function WC(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,CW(()=>{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 qW(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(WC,{anchor:r,label:`The full ${o}`,width:UW,className:"mc_pop_text",on_close:()=>n(""),on_hover:c=>c?ba():t==="hover"?i():void 0,children:s.jsx(qW,{kind:e.kind,text:e.full,about:e.about,on_open:e.on_open,on_close:()=>n("")})}):null]})}function VW(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(WW,{...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 HW(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 qC(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(Ce.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 GW(e){const{card:t}=e,n=t.automation,[r,i]=p.useReducer(Y9,J9),o=n?OC(n,e.now_ms):null,c=n?X9(n,r):null,l=n?H9({...n,growing_max_tokens:c}):null,d=!!(n!=null&&n.can_revise&&e.on_revise_automation),h=K9(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}),Z9(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:[V9.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 KW={busy:"",error:""},Pj={enabled:!1,reason:"commands are not wired on this host"},JW={enabled:!0},YW="Stop this subrun and everything under it? Its parent continues and may delegate again",XW="Stop this subrun and everything under it: its parent continues and may delegate again";function ZW(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 VC(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:[QW(ZW(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 QW(e){return e&&e[0].toUpperCase()+e.slice(1)}function eq(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:XW,"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:YW})}):null]})}function tq(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(eq,{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=LC(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(qC,{...e,card:o,detail:c,busy:i(o)})]},o.run_id)}),n?s.jsx(VC,{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 nq(e){var V,M;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(KW),c=t.status_word,l=HW(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?LC(t,e.detail):null,y=d?null:U9(t,e.outcome),x=IC(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?(M=e.cancel_targets)==null?void 0:M.call(e,t.run_id):void 0,D=async()=>{C&&(r({type:"send"}),r(await UC(C,t.run_id,S,e.on_cancel_runs)))},P=A=>{!e.on_automation_command||i.busy||(o({busy:A,error:""}),eW(e.on_automation_command,t.automation_id,A).then(O=>{var L;o({busy:"",error:O||""}),O||(L=e.on_renamed)==null||L.call(e,t.automation_id)}))},R=d?Q9(t.automation,i.busy!==""):null,I=n.phase!=="idle"||n.error||i.error,G=!(d||_&&(!!Kx(t)||!!C))&&x.length>0,K=x.length?s.jsx("div",{className:`mc_card_metrics${G?" 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:A=>{A.key==="Enter"&&A.target===A.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(GW,{...e}):h?s.jsx(tq,{...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(EW,{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 ${TC(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:A=>{A.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(VC,{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(qC,{...e}):null,G?null:K,I?s.jsxs("div",{className:"mc_card_notice",onClick:Ds,onKeyDown:Ds,children:[Qx({state:n,on_event:r,on_send:()=>void D(),question:FC(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&&R?s.jsxs(s.Fragment,{children:[s.jsx($w,{state:e.on_open_automation?JW:{enabled:!1,reason:"not available here"},label:"Open automation",hint:"Open this automation on the Automations page",icon:"loop",onClick:()=>{var A;return(A=e.on_open_automation)==null?void 0:A.call(e,t.automation_id)}}),s.jsx($w,{state:e.on_automation_command?R.run_now:Pj,label:"Run now",icon:"playCircle",busy:i.busy==="automation.run_now",onClick:()=>P("automation.run_now")}),s.jsx($w,{state:e.on_automation_command?R.toggle.state:Pj,label:R.toggle.label,icon:R.toggle.command==="automation.resume"?"play":"pause",busy:i.busy===R.toggle.command,onClick:()=>P(R.toggle.command)})]}):s.jsxs(s.Fragment,{children:[_?s.jsx(zC,{card:t,code_app:e.code_app,variant:"icon"}):null,C?n.phase==="idle"?BC({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]}),G?K: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(VW,{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 sq(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 rq(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function iq(e,t){const n=e.line,r=e.row||{},i=e.role==="controller"&&e.automation?OC(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(","),rq(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,IC(e).join("·"),e.llm_calls,r.session_id,r.actor_id,r.pause_reason,r.created_at,r.updated_at,r.status,sq(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=iq(e,t);return zj.set(e,{now_ms:t,sig:r}),r}function oq(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 aq=Ce.memo(nq,oq),Cw=8;function lq(e){var ze,He,ft,et,Ot,Ne,Re,tt;(ze=rl.page)==null||ze.call(rl);const t=Date.now(),[n,r]=p.useState(()=>AC(D9())),i=p.useMemo(()=>P9(e.runs,e.all_runs),[e.runs,e.all_runs]),o=p.useMemo(()=>[...i.active,...i.done],[i]),c=o9(e.client,o),l=l9(e.client,i.active),d=y9(),h=p.useMemo(()=>Object.fromEntries(bp.map(re=>[re,ge=>d.attach(re,ge)])),[d.attach]),[m,_]=p.useState(""),[g,y]=p.useState(""),[x,k]=p.useState(!1),[v,N]=p.useState(()=>{try{const re=localStorage.getItem("abstractobserver_done_window_v1");return re&&re in Wv?re: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(re=>re.row),[C,x]),D=p.useMemo(()=>wj(bp.map(re=>re==="done"?S:$[re].flatMap(ge=>[ge.row,...ge.asks.map(de=>de.row)])),d.visible),[$,S,d.visible]),P=u9(e.client,D,i.active),R=p.useMemo(()=>new Set(i.active.map(re=>Qs(re))),[i.active]),I=d9(e.client,P.map,R),W=a9(e.client,D),G=p.useMemo(()=>wj([S],d.visible),[S,d.visible]),K=g9(e.client,G),V=p.useRef(new WeakMap),M=p.useMemo(()=>{const re=new Map;for(const[ge,de]of c.records){const je=de.raw&&typeof de.raw=="object"?de.raw:null;let X=je?V.current.get(je):void 0;X||(X=i9(de.raw),je&&V.current.set(je,X)),re.set(ge,X)}return re},[c.records]),A=p.useMemo(()=>W.map.size||P.map.size?Cj({active:i.active,done:i.done,details:P.map,fates:I.map,pulses:l.map,automations:c.map,run_briefs:W.map,now_ms:Date.now(),stall_after_ms:n}):$,[$,W.map,i,P.map,l.map,c.map,n]),O=p.useMemo(()=>Rj(A.done,v,t),[A.done,v]),L=bp.map(re=>A[re].map(ge=>[ge.run_id,...ge.asks.map(de=>de.run_id)].join("+")).join(",")).join("|")+`|${x}|${v}`;p.useEffect(()=>{d.refresh()},[L,d.refresh]);const[J,H]=p.useState(""),[z,te]=p.useState(null),B=e.entities===null,ne=e.entities??[],se=re=>`${re.run_id}:${re.wait_key}:${re.since_ms??""}`;p.useEffect(()=>{m&&(A.needs_you.some(re=>se(re)===m||re.asks.some(ge=>se(ge)===m))||_(""))},[A,m]);async function ue(re,ge){_(se(re)),y("");try{await e.on_resume_wait(re.run_id,re.wait_key,ge)}catch(de){y(`${re.title.text}: ${String((de==null?void 0:de.message)||de||"resume failed")}`),_("")}}async function ve(re){if(e.on_resume_run){_(se(re)),y("");try{const ge=await e.on_resume_run(re.run_id);if(typeof ge=="string"&&ge)throw new Error(ge)}catch(ge){y(`${re.title.text}: ${String((ge==null?void 0:ge.message)||ge||"resume failed")}`),_("")}}}const Te=p.useRef(e);Te.current=e;const ke=p.useRef(ue);ke.current=ue;const le=p.useRef(ve);le.current=ve;const xe=p.useRef(i.active);xe.current=i.active;const Ee=p.useMemo(()=>({open_run:re=>Te.current.on_open_run(re),open_automation:re=>Te.current.on_open_automation(re),rename:((re,ge,de)=>Te.current.on_rename_automation(re,ge,de)),revise:((re,ge,de)=>Te.current.on_revise_automation(re,ge,de)),command:((re,ge)=>Te.current.on_automation_command(re,ge)),cancel:(re=>Te.current.on_cancel_run(re)),cancel_batch:((re,ge)=>Te.current.on_cancel_runs(re,ge)),cancel_targets:re=>Ij([re],xe.current),act:(re,ge)=>void ke.current(re,ge),resume:re=>void le.current(re)}),[]),Ve=String(((He=e.code_app)==null?void 0:He.url)||"").trim(),_t=p.useMemo(()=>Ve?{url:Ve}:null,[Ve]),Qe=p.useMemo(()=>re=>{c.invalidate(re),window.setTimeout(()=>c.invalidate(re),2e3)},[c.invalidate]),ot=re=>({now_ms:t,stall_after_ms:n,busy:m===se(re),on_open_run:Ee.open_run,on_act:Ee.act,on_resume:e.on_resume_run?Ee.resume:void 0,on_open_automation:Ee.open_automation,on_rename_automation:e.on_rename_automation?Ee.rename:void 0,on_renamed:Qe,revision:re.automation_id?c.revisions.get(re.automation_id)??null:null,detail:P.map.get(re.run_id),outcome:K.map.get(re.run_id)??null,facts:re.automation_id?M.get(re.automation_id)??null:null,code_app:_t,on_cancel_run:e.on_cancel_run?Ee.cancel:void 0,on_cancel_runs:e.on_cancel_runs?Ee.cancel_batch:void 0,cancel_targets:Ee.cancel_targets,ask_detail:re.asks.length?Object.fromEntries(re.asks.map(ge=>[ge.run_id,P.map.get(ge.run_id)])):void 0,ask_loading:re.asks.length?re.asks.filter(ge=>P.loading.has(ge.run_id)).map(ge=>ge.run_id).join(","):void 0,busy_wait:re.asks.length?m:void 0,stale:e.runs_stale===!0?!0:void 0,on_automation_command:e.on_automation_command?Ee.command:void 0,on_revise_automation:e.on_revise_automation?Ee.revise:void 0,detail_loading:P.loading.has(re.run_id),brief_loading:W.loading.has(re.run_id),outcome_loading:K.loading.has(re.run_id),automation_loading:re.automation_id?c.loading.has(re.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&&!ne.length?yW:gW,"aria-busy":B||void 0,children:[s.jsxs("div",{className:"mc_entities_head",children:[s.jsxs("span",{children:["Entities",!B&&e.entities_total>ne.length?` (${ne.length} of ${e.entities_total} — open the entity app for all)`:"",!B&&!ne.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(vW,{n:e.entities_total?Math.min(e.entities_total,PC):wW})]}):null,ne.length?s.jsx("div",{className:"mc_entities_row",children:ne.map(re=>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(re.name)}&live=1`,target:"_blank",rel:"noreferrer",title:[re.error,re.age_days!==null?`${re.age_days.toFixed(0)} days old`:"",re.last_moment].filter(Boolean).join(" — ")||re.name,children:[s.jsx("span",{className:"mc_entity_name",children:re.name}),(()=>{var at;const ge=String(re.live_phase||re.state||"").trim(),de=dW(ge,e.phase_graph),je=mW(e.phase_graph).has(de)?de:"other",X=((at=e.phase_graph)==null?void 0:at.initial)??"sleep",Oe=/awake|idle/i.test(ge)&&de===X,pt=ge&&ge.toLowerCase()!==de?` — wire word: ${ge}${Oe?" (settling)":""}`:"";return s.jsx("span",{className:`mc_entity_phase mc_phase_${je}`,title:(re.live_phase?"phase (cognition wire)":"phase from card state — cognition wire unavailable")+pt,children:de})})(),re.last_moment?s.jsx("span",{className:"mc_entity_moment",title:re.last_moment,children:re.last_moment.replace(/_/g," ")}):null,(()=>{if(re.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 ge=iW(re.last_moment_at,t);return re.working===!1?s.jsxs("span",{className:"mc_entity_live muted",title:"idle (cognition wire)",children:["idle",ge!==null?` · ${Sw(t-ge,t)} ago`:""]}):ge===null?null:ge<=oW?s.jsx("span",{className:"mc_entity_live",title:`last moment ${Sw(t-ge,t)} ago`,children:"● active"}):s.jsxs("span",{className:"mc_entity_live muted",title:"time since the last recorded moment",children:[Sw(t-ge,t)," ago"]})})(),re.tokens_total!==null?s.jsxs("span",{className:"muted mc_entity_spend",title:`lifetime billed tokens (home run ledger)${re.live_visit_tokens!==null?`; open visit: ${lc(re.live_visit_tokens)} tk`:""}${re.spend_warning?`; ${re.spend_warning}`:""}`,children:[lc(re.tokens_total)," tk",re.live_visit_tokens!==null?` (+${lc(re.live_visit_tokens)})`:"",re.spend_warning?"*":""]}):null]}),re.open_questions_total||re.open_problems_total||re.lessons_total||re.dreams_brief?s.jsx("button",{type:"button",className:"mc_entity_hints_btn","aria-expanded":J===re.name,title:"open questions / problems + distilled lessons + night signals from the entity card — click to expand",onClick:()=>H(J===re.name?"":re.name),children:[re.open_questions_total?`${re.open_questions_total} question${re.open_questions_total>1?"s":""}`:"",re.open_problems_total?`${re.open_problems_total} problem${re.open_problems_total>1?"s":""}`:"",re.lessons_total?`${re.lessons_total} lesson${re.lessons_total>1?"s":""}`:"",re.dreams_brief?`night: ${re.dreams_brief.count} signal${re.dreams_brief.count>1?"s":""}`:""].filter(Boolean).join(" · ")}):null]},re.name))}):null,(()=>{if(!J)return null;const re=ne.find(je=>je.name===J);if(!re||!re.open_questions.length&&!re.open_problems.length&&!re.lessons.length&&!re.dreams_brief)return null;const ge=e.on_read_diary?async je=>{const X=await e.on_read_diary(re.name,je);te({entity:re.name,entry:(X==null?void 0:X.entry)??X,seq:typeof(X==null?void 0:X.read_recorded_at_seq)=="number"?X.read_recorded_at_seq:null})}:void 0,de=re.open_questions_total-re.open_questions.length+(re.open_problems_total-re.open_problems.length)+(re.lessons_total-re.lessons.length);return s.jsxs("div",{className:"mc_entity_hints_panel",children:[re.open_questions.map((je,X)=>s.jsx(ky,{kind:"question",label:je.title||Nw(je.statement),entryId:je.entry_id,onOpen:ge,title:je.statement||je.title},`q_${je.record_id||X}`)),re.open_problems.map((je,X)=>s.jsx(ky,{kind:"problem",label:je.title||Nw(je.statement),entryId:je.entry_id,onOpen:ge,title:je.statement||je.title},`p_${je.record_id||X}`)),re.lessons.map((je,X)=>s.jsx(ky,{kind:"lesson",label:je.title||Nw(je.statement),entryId:je.entry_id,onOpen:ge,title:je.statement||je.title},`l_${je.record_id||X}`)),re.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: ",re.dreams_brief.count,re.dreams_brief.dreams?` across ${re.dreams_brief.dreams} dream${re.dreams_brief.dreams>1?"s":""}`:"",re.dreams_brief.kinds.length?` — ${re.dreams_brief.kinds.slice(0,6).join(", ")}${re.dreams_brief.kinds.length>6?` +${re.dreams_brief.kinds.length-6} more`:""}`:"",re.dreams_brief.felt_tones.length?` · felt: ${re.dreams_brief.felt_tones.slice(0,6).join(", ")}`:""]}):null,de>0?s.jsxs("span",{className:"muted mc_entity_hints_more",children:["+",de," more — open the entity app"]}):null]})})()]}),z?s.jsx(tc,{open:!0,title:`${z.entity} — diary entry`,onClose:()=>te(null),children:s.jsxs("div",{className:"mc_diary_entry",children:[s.jsx("div",{className:"mc_diary_meta muted",children:[(ft=z.entry)!=null&&ft.kind?`kind: ${z.entry.kind}`:"",(et=z.entry)!=null&&et.visibility?`visibility: ${z.entry.visibility}`:"",(Ot=z.entry)!=null&&Ot.written_at?`written: ${z.entry.written_at}`:"",(Ne=z.entry)!=null&&Ne.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})`:""]}),(Re=z.entry)!=null&&Re.gist?s.jsx("div",{className:"mc_diary_gist",children:String(z.entry.gist)}):null,s.jsx("pre",{className:"mc_diary_text",children:String(((tt=z.entry)==null?void 0:tt.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 ",I9(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(re=>{const ge=re==="done"?O.visible:A[re],de=re==="done"&&!x?ge.slice(0,Cw):ge,je=e.runs_refreshed_at===null||re==="done"&&e.done_loaded===!1;return s.jsxs($W,{col:re,title:CC[re],count:je?null:ge.length,count_title:re==="done"&&O.hidden_count?`${O.hidden_count} older run(s) outside this window`:re==="needs_you"&&ge.length?`${ge.length} task${ge.length===1?"":"s"} · ${ge.reduce((X,Oe)=>X+(Oe.asks.length||(Oe.line.lane==="needs_you"&&!Oe.stuck?1:0)),0)} asks`:void 0,cancel:{run_ids:ge.map(X=>X.run_id),targets:Ij(ge.map(X=>X.run_id),i.active),on_cancel_run:e.on_cancel_run,on_cancel_runs:e.on_cancel_runs},after:re==="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:X=>{const Oe=Number(X.target.value);r(Oe);try{localStorage.setItem(EC,String(Oe))}catch{}},children:Hx.map(X=>s.jsx("option",{value:String(X.ms),children:X.label},X.ms))})]}):null,tools:re==="done"?s.jsx("select",{className:"mc_window_select",value:v,title:"Show terminal runs from this time window",onClick:X=>X.stopPropagation(),onChange:X=>{const Oe=X.target.value;N(Oe),k(!1);try{localStorage.setItem("abstractobserver_done_window_v1",Oe)}catch{}},children:Object.keys(Wv).map(X=>s.jsx("option",{value:X,children:kw[X]},X))}):null,children:[s.jsx("div",{className:"mc_column_hint muted",children:A9[re]}),s.jsxs("div",{className:"mc_column_cards",ref:h[re],"aria-busy":je||void 0,children:[je&&!de.length?s.jsxs(s.Fragment,{children:[s.jsx(ol,{what:re==="done"&&e.runs_refreshed_at!==null?"finished runs":"runs"}),s.jsx(pW,{n:_W[re]})]}):null,de.map(X=>s.jsx(aq,{card:X,...ot(X)},X.run_id)),!ge.length&&!je?s.jsx("div",{className:"mc_empty muted",children:re==="done"&&O.hidden_count?`none in the ${kw[v]} — ${O.hidden_count} older`:T9[re]}):null,re==="done"&&ge.length>Cw&&!x?s.jsxs("button",{className:"btn mc_more",onClick:()=>k(!0),children:["show all ",ge.length]}):null,re==="done"&&O.hidden_count&&ge.length?s.jsxs("div",{className:"mc_window_note muted",title:"Widen the window above to see older terminal runs",children:["+",O.hidden_count," older outside ",kw[v]]}):null]})]},re)})})]})}function At(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ln(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 HC(e){const t=At(e);return!!t&&(mu(t,"definition")||mu(t,"summary"))}function cq(e,t,n){var v,N,$,C;const r=At((v=At(t))==null?void 0:v.input_data),i=At((N=At(t))==null?void 0:N.workspace),o=HC(n)?n:null,c=o?Rm(o):n??null,l=At(o==null?void 0:o.definition),d=At(($=At(l==null?void 0:l.target))==null?void 0:$.input_data),h=At(d==null?void 0:d._runtime),m=At(l==null?void 0:l.policy),_={},g=(S,...D)=>{for(const[P,R]of D){const I=ln(R);if(I)return _[S]=P,I}return _[S]="",""},y=(S,D,...P)=>{for(const[R,I]of P){const W=D(I);if(W!==null)return _[S]=R,W}return _[S]="",[]},x=(S,...D)=>{for(const[P,R]of D){const I=Gn(R);if(I!==null)return _[S]=P,I}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=At(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 GC(e){const t=At(e);if(!t)return null;if(Array.isArray(t.nodes))return t;const n=At(t.flow);return n&&Array.isArray(n.nodes)?n:null}function Hv(e){const t=At(e==null?void 0:e.data)||{};return ln(t.nodeType)||ln(e==null?void 0:e.type)}const uq=new Set(["exec-out","exec-in","exec"]);function Gv(e,t){const n=At(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=At(i);if(!o)return!1;const c=ln(o.id);return!!c&&ln(o.type)!=="execution"&&!uq.has(c)})}function Uj(e,t,n,r){const i=ln(e.id),o=ln(e.type)||"any";return{id:i,label:ln(e.label)||i,type:o,typed:!0,required:e.required===!0,description:ln(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 dq(e,t,n){var R;const r=GC(e),i=r?r.nodes:[],o=i.find(I=>Hv(I)==="on_flow_start")||null,c=i.filter(I=>Hv(I)==="on_flow_end"),l=At(t),d=At(l==null?void 0:l.input_data),h=At((R=At(o==null?void 0:o.data))==null?void 0:R.pinDefaults)||{},m=[],_=new Set,g=I=>d?mu(d,I)?{state:"value",value:d[I]}:{state:"not_provided",value:void 0}:{state:"unknown",value:void 0};for(const I of o?Gv(o,"outputs"):[]){const W=ln(I.id);if(_.has(W))continue;_.add(W);const{state:G,value:K}=g(W),V=G==="not_provided"&&mu(h,W)?{value:h[W]}:null;m.push(Uj(I,G,K,V))}for(const I of Array.isArray(l==null?void 0:l.pin_ids)?l.pin_ids:[]){const W=ln(I);if(!W||_.has(W))continue;_.add(W);const{state:G,value:K}=g(W);m.push(Wj(W,G,K))}const y=d?Object.keys(d).filter(I=>!_.has(I)).map(I=>[I,d[I]]):[],x=At(n),k=!!x&&hs(x.status),v=x?x.output:void 0,N=At(v),$=I=>x?N&&mu(N,I)?{state:"value",value:N[I]}:{state:"absent",value:void 0}:{state:"unknown",value:void 0},C=[],S=new Set;for(const I of c)for(const W of Gv(I,"inputs")){const G=ln(W.id);if(S.has(G))continue;S.add(G);const{state:K,value:V}=$(G);C.push(Uj(W,K,V,null))}const D=c.length>0&&S.size===0;let P=[];if(D){const I=!!x&&v!==null&&v!==void 0;C.push(Wj("output",x?I?"value":"absent":"unknown",I?v:void 0))}else N?P=Object.keys(N).filter(I=>!S.has(I)).map(I=>[I,N[I]]):x&&v!==null&&v!==void 0&&(P=[["output",v]]);return{inputs:m,outputs:C,also_sent:y,also_returned:P,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 fq(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=At(e),n=At(t==null?void 0:t.session_history),r=At((l=At(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:ln(n==null?void 0:n.policy),...c,strict:qp(n==null?void 0:n.strict),token_estimator:ln(n==null?void 0:n.token_estimator),session_kind:ln(n==null?void 0:n.session_kind),tokens:i,flow_warnings:o,window_note:n?fq(c):""}}const hq=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 mq(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 KC(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=mq(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<hq?[...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 JC(e){const t=[],n=r=>{t.push(r);for(const i of r.children)n(i)};return e&&n(e),t}function _q(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=JC(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 pq(e){var r,i,o,c;const t=Cm(e),n=At((o=At((i=At((r=e.record)==null?void 0:r.result))==null?void 0:i.metadata))==null?void 0:o._provider_request);return{provider:t.provider||ln(n==null?void 0:n.provider),model:t.model||ln(n==null?void 0:n.model)||ln((c=At(n==null?void 0:n.payload))==null?void 0:c.model)}}function gq(e){var c,l,d,h,m;const t=At((l=At((c=e.started)==null?void 0:c.effect))==null?void 0:l.payload),n=At((h=At((d=e.record)==null?void 0:d.effect))==null?void 0:h.payload),r=At(t==null?void 0:t.vars)&&!((m=At(t==null?void 0:t.vars))!=null&&m.$slim)?At(t==null?void 0:t.vars):At(n==null?void 0:n.vars),i=At(r==null?void 0:r._runtime),o=At(r==null?void 0:r._limits);return{run_id:Am(e.record),workflow_id:ln(t==null?void 0:t.workflow_id)||ln(n==null?void 0:n.workflow_id),from_run_id:e.run_id,provider:ln(i==null?void 0:i.provider),model:ln(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 yq(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),P=Vt(S.ended_at);for(const R of[D,P])R!==null&&((r.first_ms===null||R<r.first_ms)&&(r.first_ms=R),(r.last_ms===null||R>r.last_ms)&&(r.last_ms=R));if(S.kind==="llm_call"){C.llm_calls+=1;const R=pq(S),I=`${R.provider}\0${R.model}`,W=c.get(I)||{provider:R.provider,model:R.model,calls:0,run_ids:[]};W.calls+=1,W.run_ids.includes($)||W.run_ids.push($),c.set(I,W)}else if(S.kind==="tool"){const R=Em(S),I=new Map;for(const G of R.calls){const K=I.get(G.name)||{calls:0,results:0,failures:0};K.calls+=1,I.set(G.name,K)}for(const G of R.results){const K=I.get(G.name)||{calls:0,results:0,failures:0};K.results+=1,G.success===!1&&(K.failures+=1),I.set(G.name,K)}for(const[G,K]of I){const V=Math.max(K.calls,K.results);C.tool_calls+=V,C.tool_failures+=K.failures;const M=l.get(G)||{name:G,calls:0,failures:0,run_ids:[],outside_declared:null};M.calls+=V,M.failures+=K.failures,M.run_ids.includes($)||M.run_ids.push($),l.set(G,M)}const W=ti((x=At((y=(g=S.started)==null?void 0:g.effect)==null?void 0:y.payload))==null?void 0:x.allowed_tools)??ti((N=At((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 R=gq(S);r.subruns.push(R),R.run_id&&d.push(R.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=ln(e);return t||null}function tu(e,t){const n=ln(e),r=ln(t);return n||r?{provider:n,model:r,calls:null}:null}const wq=new Set(["controller","occurrence","descendant","discussion"]);function vq(e,t,n,r,i,o,c=Date.now(),l={}){var hn,sn,Ht,is,Be,Qt,Rt,Fn,fn;const d=At(e),h=At(t),m=At(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)||((hn=l.row)==null?void 0:hn.run_id)||"").trim(),g=Array.isArray(o)?o:[],y=Xe=>g.find(nn=>String((nn==null?void 0:nn.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=HC(r)?r:null,v=k?Rm(k):r??null,N=At(k==null?void 0:k.definition),$=At(k==null?void 0:k.summary),C=At((sn=At(N==null?void 0:N.target))==null?void 0:sn.input_data),S=At(C==null?void 0:C._runtime),D=At(N==null?void 0:N.policy),P=ln(x.role),R=!!ln(x.automation_id)||wq.has(P)||ln(x.session_kind)==="automation",I=R?v?Ps.wire:Ps.automation_not_loaded:Ps.not_automation,W=GC(n),G=W&&W.nodes.find(Xe=>Hv(Xe)==="on_flow_start")||null,K=At((Ht=At(G==null?void 0:G.data))==null?void 0:Ht.pinDefaults),V=new Set(G?Gv(G,"outputs").map(Xe=>ln(Xe.id)):[]),M=Xe=>m&&mu(m,Xe)?void 0:K&&mu(K,Xe)?K[Xe]:void 0,A=KC(_,g),O=JC(A.root).filter(Xe=>ji(Xe.run)!==_&&xq(Xe,_,A.root)).map(Xe=>ji(Xe.run)),L=yq(i,_,O),J=L.loaded?Ps.ledger_no_records:Ps.ledger_not_loaded,H=L.loaded&&L.subject_found,z=cq(e,t,k??v),te=Xe=>z.source[Xe]==="run"?"run":z.source[Xe]==="automation"?"automation":"",B=At(d==null?void 0:d.output),ne=At(B==null?void 0:B.meta),se=ln(x.workflow_id)||ln(h==null?void 0:h.workflow_id),ue=ln(h==null?void 0:h.bundle_version)||(se.includes("@")?se.split("@")[1].split(":")[0]:""),ve=se?gn({id:se,name:si(se),version:ue,flow_name:ln(W==null?void 0:W.name)},"run"):ts(Ps.wire),Te=R?v?gn({kind:"automation",title:v.title,id:v.automation_id},"automation"):ts(Ps.automation_not_loaded):ln(x.session_id)?gn({kind:"session",title:"",id:ln(x.session_id)},"run"):gn({kind:"run",title:"",id:_},"run"),ke=ln(x.parent_run_id),le=ke?y(ke):void 0,xe=Gn(x.occurrence_index);let Ee="";if(P==="occurrence")Ee=xe!==null?`run #${xe}`:"automation run";else if(P==="controller")Ee="automation controller (the schedule's own run)";else if(P==="discussion")Ee="discussion of the automation";else if(ke){const Xe=ln(le==null?void 0:le.role),nn=Gn(le==null?void 0:le.occurrence_index);Ee=`subrun of ${Xe==="occurrence"&&nn!==null?`run #${nn}`:si(ln(le==null?void 0:le.workflow_id))||"a parent run (row not loaded)"}`}else Ee=ln(x.session_id)?"run in a session":"top-level run";const Ve=gn({text:Ee,parent_run_id:ke},"run"),Qe=[["run",tu(m==null?void 0:m.provider,m==null?void 0:m.model)],["flow default",tu(M("provider"),M("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 ot;H&&L.models.length?ot=gn(L.models.map(Xe=>({provider:Xe.provider,model:Xe.model,calls:Xe.calls})),"used"):tu(ne==null?void 0:ne.provider,ne==null?void 0:ne.model)?ot=gn([tu(ne==null?void 0:ne.provider,ne==null?void 0:ne.model)],"output"):Qe?ot=gn([Qe[1]],Qe[0]):ot=ts(Ps.gateway_default,"gateway");let ze=null;if((ot.source==="used"||ot.source==="output")&&Qe&&ot.value){const Xe=Qe[1];ot.value.some(cn=>(!Xe.provider||cn.provider===Xe.provider)&&(!Xe.model||cn.model===Xe.model))||(ze=gn(Xe,Qe[0]))}const He=m&&typeof m.system=="string"?gn(m.system,"run"):W?Cd(M("system"))!==null?gn(String(M("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),ft=Sp([["run",m&&typeof m.prompt=="string"&&m.prompt.trim()?m.prompt:null],["run",Cd((is=At(m==null?void 0:m.context))==null?void 0:is.task)],["flow default",Cd(M("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(M("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),Ot=((Qt=L.subruns.find(Xe=>Xe.allowed_tools!==null))==null?void 0:Qt.allowed_tools)??null,Ne=Sp([["used",H?L.allowlist:null],["used",H?Ot:null],["automation",ti(S==null?void 0:S.allowed_tools)],["automation",k?null:(v==null?void 0:v.allowed_tools)??null]],R?I:H?"the ledger shows no enforced allowlist":J),Re=et.value,tt=H?gn(L.tools.map(Xe=>({...Xe,outside_declared:Re===null?null:!Re.includes(Xe.name)})),"used"):ts(J),re=(Xe,nn)=>Xe!==null&&z.source[nn]?gn(Xe,te(nn)):ts(I),ge=re(Cd(z.tool_approval),"tool_approval"),de=re(z.source.untrusted_input_tools?z.untrusted_input_tools:null,"untrusted_input_tools"),je=re(z.source.email_allowed_recipients?z.email_allowed_recipients:null,"email_allowed_recipients"),X=(Xe,nn)=>z.source[nn]?gn(Xe,te(nn)):ts(Ps.wire),Oe={mode:X(z.workspace_access_mode,"workspace_access_mode"),root:X(z.workspace_root,"workspace_root"),allowed_paths:X(z.workspace_allowed_paths,"workspace_allowed_paths"),ignored_paths:X(z.workspace_ignored_paths,"workspace_ignored_paths")},pt=y(_)||x,at=H?gn(L.llm_calls,"used"):Gn(pt==null?void 0:pt.llm_calls)!==null?gn(Gn(pt.llm_calls),"listing"):ts(J),Et=H?gn({calls:L.tool_calls,failures:L.tool_failures},"used"):Gn(pt==null?void 0:pt.tool_calls)!==null?gn({calls:Gn(pt.tool_calls),failures:null},"listing"):ts(J),yt=A.root?((Rt=bg(A.root,_))==null?void 0:Rt.children)||[]:[],jt=H?gn(L.subruns,"used"):yt.length?gn(yt.map(Xe=>({run_id:ji(Xe.run),workflow_id:ln(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"),st=[];if(B)for(const[Xe,nn]of Object.entries(B)){const cn=At(nn);cn&&Object.keys(cn).length===1&&typeof cn.$artifact=="string"&&cn.$artifact.trim()&&st.push({pin:Xe,id:cn.$artifact.trim()})}const Pt=hs(x.status);let Lt;d?Pt?B&&typeof B.response=="string"&&B.response.trim()?Lt=gn(B.response,"output"):typeof d.output=="string"&&d.output.trim()?Lt=gn(d.output,"output"):ln(d.error)?Lt=gn(ln(d.error),"run"):Lt=ts("the output carries no response text"):Lt=ts(Ps.not_ended):Lt=ts("run detail not loaded");const mn=Vt(x.created_at||""),wn=Pt?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,_e=Sp([["used",rs],["run",Gn(m==null?void 0:m.max_iterations)],["flow default",Gn(M("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),Me=Gn(ne==null?void 0:ne.iterations)!==null?gn(Gn(ne==null?void 0:ne.iterations),"output"):ts(Pt?"the output carries no iteration count":Ps.not_ended),wt=Kv(e).tokens,ie=At($==null?void 0:$.trigger)||At(N==null?void 0:N.trigger),fe=At(ie==null?void 0:ie.config),$e=v!=null&&v.cadence?gn({text:v.cadence,start_ms:Vt((fe==null?void 0:fe.start_at)||"")},"automation"):ts(I),Le=R?gn({index:xe,count:v?v.occurrence_count:null},v?"automation":"run"):ts(Ps.not_automation),We=Gn(fe==null?void 0:fe.count)!==null?gn(Gn(fe==null?void 0:fe.count),"automation"):ts(R&&ie?"no count limit":I,R&&ie?"automation":""),Ue=Vt((fe==null?void 0:fe.until)||""),nt=Ue!==null?gn(Ue,"automation"):ts(R&&ie?"no end date":I,R&&ie?"automation":""),ut=At(D==null?void 0:D.retry),xt=At(ut==null?void 0:ut.backoff),bt=D?gn({max_attempts:Gn(ut==null?void 0:ut.max_attempts),backoff_initial:ln(xt==null?void 0:xt.initial),backoff_factor:Gn(xt==null?void 0:xt.factor),backoff_max:ln(xt==null?void 0:xt.max),failure:ln(D.failure),misfire:ln(D.misfire),serial:qp(D.serial)},"automation"):ts(I),Tt=N&&Array.isArray((fn=At(N.notify))==null?void 0:fn.channels)?gn(ti(N.notify.channels),"automation"):ts(I),zt=Kv(e),ct=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(R?I:"no session history on this run"),Yt=Oe.root.value?gn(Oe.root.value,Oe.root.source):ts(Ps.wire);let vn;if(!R)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&&xe!==null&&v.last.index===xe?{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 nn=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)}${nn?` (in ${nn})`:""}`},"automation")}else if(ln(ie==null?void 0:ie.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(ie)){const nn=v.cadence||"when something new arrives";vn=gn({kind:"on_trigger",at_ms:null,text:`next run ${nn.charAt(0).toLowerCase()}${nn.slice(1)}`},"automation")}else vn=ts("no next fire time on this wire","automation")}return{subject_id:_,is_automation:R,who:{workflow:ve,subject:Te,role:Ve,model:ot,model_declared:ze,system_prompt:He,task:ft},access:{tools_allowed:et,runtime_allowlist:Ne,tools_called:tt,tool_approval:ge,untrusted_input_tools:de,email_recipients:je,operator_email:ln(S==null?void 0:S.operator_email),workspace:Oe},does:{llm_calls:at,tool_calls:Et,subruns:jt,artifacts:st,outcome:Lt,children_not_loaded:L.missing_run_ids},how_long:{started_ms:mn,finished_ms:wn,running:!Pt,duration:Ks,max_iterations:_e,iterations_used:Me,tokens:wt,cadence:$e,next_fire_ms:(v==null?void 0:v.next_fire_ms)??null,occurrence:Le,stop_after:We,stop_at:nt,retry:bt},after:{notify:Tt,context:ct,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 xq(e,t,n){const r=n?bg(n,t):null;return!!r&&r!==e&&!!bg(r,ji(e.run))}const bq=["status","updated_at","current_node","paused","error","waiting"],kq=["workflow_id","created_at","parent_run_id","session_id","automation_id","role","occurrence_index","session_kind"];function YC(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 XC(e,t){if(!t||typeof t!="object")return e;const n={...e};for(const r of kq)(n[r]===void 0||n[r]===null||n[r]==="")&&t[r]!==void 0&&t[r]!==null&&(n[r]=t[r]);if(YC(e,t))for(const r of bq)Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function jq(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 Sq={approve:"Review approval",answer:"Answer",resume:"Resume",open_subrun:"Open subrun",inspect:"Inspect"};function ZC(e,t,n,r){return W1(e,t,n??null,r??null)}function Nq(e,t){const n=Sq[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 $q(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 Cq(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 Eq={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 QC(e){return e.source?s.jsx("span",{className:"ap_source","data-source":e.source,title:Eq[e.source],children:e.source}):null}function Aq(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(QC,{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(Aq,{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 Tq(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 Mq(e){var D,P;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=R=>{const I=i.by_id.get(R);return si(String((I==null?void 0:I.workflow_id)||""))||"a run (row not loaded)"},l=(R,I)=>s.jsx("button",{type:"button",className:"ap_link_btn ap_run_link",title:`Open run ${R}`,"data-run-id":R,onClick:()=>n.on_open_run(R),children:I}),{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 R;return(R=n.on_reveal_workspace)==null?void 0:R.call(n)},children:"show folder"}):null,k=t.ledger.runs,v=R=>k.length>1?s.jsx("span",{className:"ap_breakdown",children:k.map((I,W)=>s.jsxs("span",{"data-run-id":I.run_id,children:[W?" · ":"",as(R(I))," ",I.run_id===t.subject_id?"in this run":s.jsxs(s.Fragment,{children:["in ",l(I.run_id,c(I.run_id))]})]},I.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((R,I)=>s.jsxs("span",{children:[I?", ":"",l(R,c(R))]},R)),")"]}):null,C=R=>R.source==="listing"?s.jsx("span",{className:"ap_breakdown",children:"tree-inclusive: this run and every run below it"}):null,S=R=>s.jsx(Jl,{items:R.map(I=>I==="self"&&h.operator_email?`self (${h.operator_email})`:I),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:R=>s.jsxs("span",{children:[R.name||R.id,R.flow_name?s.jsxs("span",{className:"ap_muted",children:[" · flow “",R.flow_name,"”"]}):null]}),copy:R=>R.id}),s.jsx(es,{id:"subject",label:"Subject",fact:d.subject,render:R=>R.kind==="automation"?s.jsx(am,{value:R.title||"untitled automation"}):s.jsx("span",{children:R.kind==="session"?"a session (id on copy)":"a standalone run (id on copy)"}),copy:R=>R.id}),s.jsx(es,{id:"role",label:"Role",fact:d.role,render:R=>{var I,W;return s.jsxs("span",{children:[R.text,R.parent_run_id&&t.is_automation&&((I=_.occurrence.value)==null?void 0:I.count)!==null&&((W=_.occurrence.value)==null?void 0:W.count)!==void 0&&R.text.startsWith("run #")?s.jsxs("span",{className:"ap_muted",children:[" of ",as(_.occurrence.value.count)," so far"]}):null,R.parent_run_id?s.jsxs(s.Fragment,{children:[" · ",l(R.parent_run_id,"open parent")]}):null]})},copy:R=>R.parent_run_id||R.text}),s.jsx(es,{id:"model",label:"Model · provider",fact:d.model,render:R=>{var I;return s.jsxs("span",{className:"ap_stack",children:[R.map((W,G)=>s.jsxs("span",{children:[Aw(W),W.calls!==null?s.jsxs("span",{className:"ap_muted",children:[" × ",ga(W.calls,"call")]}):null]},G)),(I=d.model_declared)!=null&&I.value?s.jsxs("span",{className:"ap_finding",children:["asked for ",Aw(d.model_declared.value)," ",s.jsx(QC,{source:d.model_declared.source})]}):null]})},copy:R=>R.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:R=>s.jsx(Jl,{items:R})}),s.jsx(es,{id:"runtime_allowlist",label:"Runtime allowlist",fact:h.runtime_allowlist,render:R=>h.tools_allowed.value&&R.length&&Tq(R,h.tools_allowed.value)?s.jsxs("span",{children:["the same ",ga(R.length,"tool")," as above"]}):s.jsx(Jl,{items:R})}),s.jsx(es,{id:"tools_called",label:"Did call",fact:h.tools_called,render:R=>s.jsxs("span",{className:"ap_stack",children:[R.length?s.jsx("span",{className:"ap_tags",children:R.map(I=>s.jsxs("span",{className:`ap_tool_use ${I.outside_declared?"ap_tool_outside":""}`,"data-tool":I.name,children:[s.jsxs("code",{className:"ap_tag",children:[I.name," × ",as(I.calls),I.failures?`, ${as(I.failures)} failed`:""]}),I.outside_declared?s.jsx("span",{className:"ap_finding",children:"called outside the declared list"}):null]},I.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:R=>s.jsx("span",{children:R})}),s.jsx(es,{id:"untrusted_input_tools",label:"Untrusted-input tools",fact:h.untrusted_input_tools,render:R=>s.jsx(Jl,{items:R})}),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:R=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("span",{children:R||"mode not set"}),y.root.value?s.jsx("code",{className:"ap_path",children:y.root.value}):null,x]}),copy:R=>y.root.value?`${R}
|
|
171
|
+
${y.root.value}`:R}),y.allowed_paths.value!==null?s.jsx(es,{id:"allowed_paths",label:"Allowed paths",fact:y.allowed_paths,render:R=>s.jsx(Jl,{items:R})}):null,y.ignored_paths.value!==null?s.jsx(es,{id:"ignored_paths",label:"Ignored paths",fact:y.ignored_paths,render:R=>s.jsx(Jl,{items:R})}):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:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:as(R)}),m.llm_calls.source==="used"?v(I=>I.llm_calls):C(m.llm_calls)]})}),s.jsx(es,{id:"tool_calls",label:"Tool calls",fact:m.tool_calls,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsxs("span",{children:[as(R.calls),R.failures?`, ${as(R.failures)} failed`:R.failures===0&&R.calls?", none failed":""]}),m.tool_calls.source==="used"?v(I=>I.tool_calls):C(m.tool_calls),m.tool_calls.source==="used"?$:null]})}),s.jsx(es,{id:"subruns",label:"Delegated subruns",fact:m.subruns,render:R=>R.length?s.jsx("span",{className:"ap_stack",children:R.map((I,W)=>{const G=[[I.provider,I.model].filter(Boolean).join(" · "),I.allowed_tools!==null?ga(I.allowed_tools.length,"tool"):"",I.max_iterations!==null?`max ${as(I.max_iterations)} iterations`:""].filter(Boolean),K=si(I.workflow_id)||"subrun";return s.jsxs("span",{className:"ap_subrun",children:[I.run_id?l(I.run_id,K):s.jsxs("span",{children:[K," (not started yet)"]}),G.length?s.jsxs("span",{className:"ap_muted",children:[" · handed ",G.join(" · ")]}):null]},`${I.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(R=>R.id).join(`
|
|
172
|
+
`),children:s.jsxs("span",{children:[ga(m.artifacts.length,"artifact"),": ",s.jsx(Jl,{items:m.artifacts.map(R=>R.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:R=>s.jsxs("span",{children:[bu(R),_.running?" so far":""]}),copy:R=>String(R)}),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(((P=(D=n.detail)==null?void 0:D.limits)==null?void 0:P.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:R=>s.jsxs("span",{children:[R.text,R.start_ms!==null?s.jsxs("span",{className:"ap_muted",children:[" · since ",Rd(R.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:R=>s.jsxs("span",{children:[R.index!==null?`#${as(R.index)}`:"this run",R.count!==null?` of ${as(R.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:R=>s.jsx("span",{children:[R.max_attempts!==null?ga(R.max_attempts,"attempt"):"",R.backoff_initial?`backoff ${R.backoff_initial}${R.backoff_factor!==null?` ×${R.backoff_factor}`:""}${R.backoff_max?` up to ${R.backoff_max}`:""}`:"",R.failure?`on failure: ${R.failure}`:"",R.misfire?`misfire: ${R.misfire}`:"",R.serial===!0?"serial":R.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:R=>s.jsx(Jl,{items:R.map(I=>I==="email"?"email → the owner's registered address (not on this wire)":I),empty:"nobody (no channel)"})}),s.jsx(es,{id:"context_plan",label:"Context",fact:g.context,render:R=>s.jsxs("span",{className:"ap_stack",children:[s.jsx("span",{children:R.mode==="growing"?`growing${R.growing_max_tokens!==null?` (cap ${as(R.growing_max_tokens)} tokens)`:""}: each occurrence replays the session so far`:R.mode==="independent"?"independent: each occurrence starts fresh":R.mode||"session history"}),R.replayed_messages!==null||R.replayed_tokens!==null?s.jsxs("span",{className:"ap_muted",children:["this run replayed ",R.replayed_messages!==null?ga(R.replayed_messages,"message"):"?",R.replayed_tokens!==null?` (${as(R.replayed_tokens)} tokens)`:"",R.dropped_messages!==null?`, left out ${ga(R.dropped_messages,"message")}${R.dropped_tokens?` (${as(R.dropped_tokens)} tokens)`:""}`:""]}):null]})}),s.jsx(es,{id:"outputs_to",label:"Outputs go to",fact:g.outputs_to,render:R=>s.jsxs("span",{className:"ap_workspace",children:[s.jsx("code",{className:"ap_path",children:R}),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:R=>s.jsx("span",{children:R.text}),copy:R=>R.at_ms!==null?new Date(R.at_ms).toISOString():R.text})]})]})]})}function Rq(e){const{p:t}=e,n=p.useMemo(()=>dq(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 Lq(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 eE(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 tE(e){const{node:t,ctx:n}=e,r=t.run,i=ef(r,n),o=ZC(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:eE(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(tE,{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 Iq(e){var C,S;const t=typeof e.now_ms=="number"?e.now_ms:Date.now(),n=p.useMemo(()=>XC(e.run,e.detail),[e.run,e.detail]),r=String(n.run_id||"").trim(),i=YC(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(()=>jq(e.runs||[],n),[e.runs,n]),l=p.useMemo(()=>{const D=new Map;e.detail&&i&&D.set(r,e.detail);const P=new Map;return o!=null&&o.automation_id&&P.set(o.automation_id,o),Sx(c,{now_ms:t,details:D,pulses:e.pulses,automations:P,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=q1(n,l),m=String(((S=(C=e.input_data)==null?void 0:C.input_data)==null?void 0:S.prompt)||"").trim(),_=V1(n,l,m?{excerpt:m}:null),g=ZC(n,d,tg(e.detail),e.automation),y=[h.label&&h.label!==_.text?h.label:"",h.secondary].filter(Boolean),x=Nq(d,r),k=p.useMemo(()=>vq(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(()=>KC(r,c),[r,c]),N=p.useMemo(()=>_q(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(Cq,{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($q,{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(Mq,{prof:k,p:e,line:d,ctx:l}),s.jsx(Rq,{p:e}),s.jsx(Lq,{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(tE,{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 P=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:P?eE(P):"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 Oq(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 Pq(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 Dq(){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 Fq(e){localStorage.setItem("abstractobserver_settings",JSON.stringify({...e,auth_token:""}))}function zq(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=zq(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 Bq(){return typeof window>"u"?"":ZI(window.location)}function Uq(){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 Wq(){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(()=>Dq()),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(()=>Bq()),[y,x]=p.useState(""),[k,v]=p.useState(""),[N,$]=p.useState(""),[C,S]=p.useState("{}"),[D]=p.useState(()=>Uq()),[P,R]=p.useState(null),[I,W]=p.useState(!1),[G,K]=p.useState(""),[V,M]=p.useState(!1),[A,O]=p.useState(""),[L,J]=p.useState(!1),H=ZE({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,te]=p.useState(null),[B,ne]=p.useState(null),[se,ue]=p.useState(!1),[ve,Te]=p.useState(null),[ke,le]=p.useState("once"),[xe,Ee]=p.useState(!1),[Ve,_t]=p.useState(null);function Qe(b){le(b),Ee(!0)}const[ot,ze]=p.useState(""),[He,ft]=p.useState(iv),[et,Ot]=p.useState([]),[Ne,Re]=p.useState(null),[tt,re]=p.useState(!1),[ge,de]=p.useState([]),je=p.useRef(new o3(Zs)),[X,Oe]=p.useState({available:!1,reason:"Sign in to a gateway to use automations."}),[pt,at]=L2("abstractobserver",{legacyKey:"abstractobserver_settings"}),[Et,yt]=p.useState(!1),[jt,st]=p.useState(!1),[Pt,Lt]=p.useState([]),[mn,wn]=p.useState([]),[On,Ks]=p.useState([]),[rs,_e]=p.useState(!1),[Me,wt]=p.useState(null),[ie,fe]=p.useState(null),[$e,Le]=p.useState(0),[We,Ue]=p.useState(""),nt=p.useRef(!1),ut=p.useRef(0),xt=p.useRef(0),[bt,Tt]=p.useState(!1),[zt,ct]=p.useState([]),[Yt,vn]=p.useState([]),[hn,sn]=p.useState({}),[Ht,is]=p.useState(!1),[Be,Qt]=p.useState(!1),[Rt,Fn]=p.useState(!1),[fn,Xe]=p.useState([]),[nn,cn]=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=>cn(T=>T.concat(b))));const _r=p.useRef({scanned:0,found:null}),[ye,Nt]=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),he=p.useRef(0),[Ie,De]=p.useState(""),[Ye,mt]=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):"",Q=String(b.run_id||"").trim()?String(b.run_id).slice(0,8):"",Z=[T,U&&`(${U})`,Q&&`run ${Q}`].filter(Boolean).join(" • ");return{value:String(b.thread_id||""),label:Z}}),[ff]);p.useEffect(()=>{i&&r4()},[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 Q=U.findIndex(ee=>ee.title===b);if(Q<0)return[...U,{title:b,preview:T,count:1,at:F}].slice(-4);const Z=[...U];return Z[Q]={title:b,preview:T,count:Z[Q].count+1,at:F},Z})},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=qI({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 v3(Ke.automations_client(),g3(Ke,Zs,on)),[Ke]),ui=p.useSyncExternalStore(b=>Un.subscribe(b),()=>Un.state),Df=GO(n.gateway_url),Po=Df?()=>{window.open(Df,"_blank","noopener,noreferrer")}:void 0,Ff=p.useCallback(b=>e3(b,{connections:ui.trigger_connections,mailboxes:ui.mailboxes}),[ui.trigger_connections,ui.mailboxes]),Do=p.useMemo(()=>!ot&&N.trim()&&k.trim()?XO(P,N.trim(),k.trim()):null,[P,N,k,ot]),Rl=p.useRef("");p.useEffect(()=>{if(!xe||ke!=="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=QO(He,T,Do);ft(F.form),S(JSON.stringify(F.input_data,null,2))},[xe,ke,Do,N,k]);const Ll=YS(xe&&ke==="automate"&&L?s3(He,Do):null,Un.preview_schedule);p.useEffect(()=>{xe&&ke==="automate"&&L&&(Un.load_email_status(),Un.load_trigger_vocab())},[e,ke,L,Un]),p.useEffect(()=>{L&&Un.load_trigger_vocab()},[L,Un]),p.useEffect(()=>{const b=()=>{const T=JO(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(()=>GP(),[]),[Uf,Ju]=p.useState(B0),Ua=p.useRef(0);function di(){const b=++Ua.current;Ju(B0),KP(Ke).then(T=>{b===Ua.current&&Ju(T)})}const so=p.useMemo(()=>n.worker_url.trim()?new sD({url:n.worker_url.trim(),auth_token:n.worker_token}):null,[n.worker_url,n.worker_token]),Yu=p.useMemo(()=>eD(Ke.fetch_gateway,dv),[Ke]),ar=fn.length?fn[fn.length-1].record:null,un=p.useMemo(()=>Za(ar),[ar]),_s=p.useMemo(()=>{const b=N.trim();if(!P||!b||String(P.bundle_id||"").trim()&&String(P.bundle_id||"").trim()!==b)return null;const T=Array.isArray(P.entrypoints)?P.entrypoints:[];if(!T.length)return null;const F=k.trim();if(F)return T.find(Q=>String(Q.flow_id||"").trim()===F)||null;if(T.length===1)return T[0];const U=String(P.default_entrypoint||"").trim();return U&&T.find(Q=>String(Q.flow_id||"").trim()===U)||null},[P,N,k]),Nc=p.useMemo(()=>{const b=_s==null?void 0:_s.inputs;return Array.isArray(b)?b:[]},[_s]),Wf=p.useMemo(()=>Pq(Ki),[Ki]),Xr=p.useMemo(()=>Nc.length?Nc:Wf,[Nc,Wf]),Zr=p.useMemo(()=>{const b=typeof(ye==null?void 0:ye.workflow_id)=="string"?String(ye.workflow_id):"",T=Hj(b);if(T&&P&&String(P.bundle_id||"").trim()===T.bundle_id){const Q=(Array.isArray(P.entrypoints)?P.entrypoints:[]).find(Z=>String((Z==null?void 0:Z.flow_id)||"").trim()===T.flow_id);if(Q&&Q.node_index&&typeof Q.node_index=="object")return Q.node_index}const F=_s==null?void 0:_s.node_index;return F&&typeof F=="object"?F:{}},[ye,P,_s]);p.useEffect(()=>{Fq(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 rn=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(rn==null?void 0:rn.prompt)=="string"?String(rn.prompt):"",Il=typeof(rn==null?void 0:rn.provider)=="string"?String(rn.provider):"",a_=typeof(rn==null?void 0:rn.model)=="string"?String(rn.model):"",$c=typeof(rn==null?void 0:rn.workspace_root)=="string"?String(rn.workspace_root):"",ro=p.useMemo(()=>{const b=rn==null?void 0:rn.workspace;return b&&typeof b=="object"&&!Array.isArray(b)?b:null},[rn]),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(()=>{rn!==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 Q=String(F.type||"").trim();if(!Wa(Q))continue;if(String(js[U]||"").trim()){T[U]=typeof b[U]=="string"?b[U]:"";continue}const ee=rn==null?void 0:rn[U];ee===void 0?T[U]="":T[U]=jO(ee)}return T})},[Xr,rn,js]);const jr=ot?{kind:"default",interface:ot}:N.trim()&&k.trim()?{kind:"bundle",bundle_id:N.trim(),flow_id:k.trim()}:null,Xu=WO(jr),fi=Array.isArray(rn==null?void 0:rn.skills)?rn.skills.map(b=>String(b||"").trim()).filter(Boolean):[],hi=p.useMemo(()=>{const b={};for(const T of Pt){const F=String(T.workflow_id||"").trim(),U=String(T.label||"").trim();F&&U&&(b[F]=U)}return b},[Pt]),Ol=tN({interfaceId:null,defaultInterface:Ud,request:(b,T)=>Ke.get_gateway_json(b,T.signal),enabled:L,reloadKey:Pt}),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=hn[b];return T?{models:(Array.isArray(T.models)?T.models:[]).map(U=>String(U||"").trim()).filter(Boolean),error:String(T.error||"")}:{models:[],error:""}},[hn,n.maintenance_ai_provider]),Pl=n.maintenance_ai_provider.trim(),qf=!!(Pl&&L&&!Object.prototype.hasOwnProperty.call(hn,Pl));p.useEffect(()=>{const b=Il.trim();if(!b||hn[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 Q=Array.isArray(U==null?void 0:U.models)?U.models:[],Z=typeof(U==null?void 0:U.error)=="string"?String(U.error):"";sn(ee=>({...ee,[b]:{models:Q,error:Z||void 0}}))}catch(U){if(T)return;sn(Q=>({...Q,[b]:{models:[],error:String((U==null?void 0:U.message)||U||"Failed to load models")}}))}finally{delete kl.current[b]}})(),()=>{T=!0}},[Il,hn,Ke]),p.useEffect(()=>{const b=n.maintenance_ai_provider.trim();if(!b||!L||hn[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 Q=Array.isArray(U==null?void 0:U.models)?U.models:[],Z=typeof(U==null?void 0:U.error)=="string"?String(U.error):"";sn(ee=>({...ee,[b]:{models:Q,error:Z||void 0}}))}catch(U){if(T)return;sn(Q=>({...Q,[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,hn,Ke,L]);function Qn(b,T){const F=String(b||"").trim();if(!F)return;let U={};try{const Q=JSON.parse(C||"{}");typeof Q=="object"&&Q!==null&&!Array.isArray(Q)&&(U=Q)}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 Q=T.map(Z=>Z).filter(Z=>Z!=null);Q.length?U[F]=Q: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 K("Missing bundle_id"),null;K(""),W(!0);try{const F=await Ke.get_bundle(T);return R(F),kn({ts:on(),kind:"info",title:`Loaded bundle ${T}`}),F}catch(F){return R(null),K(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 Q=String((U==null?void 0:U.bundle_id)||"").trim();if(!Q)continue;const Z=Array.isArray(U==null?void 0:U.entrypoints)?U.entrypoints:[];if(Z.length)for(const ee of Z){const ae=String((ee==null?void 0:ee.flow_id)||"").trim();if(!ae||(ee==null?void 0:ee.deprecated)===!0)continue;const Ge=`${Q}:${ae}`,be=String((ee==null?void 0:ee.name)||"").trim(),pe=be?`${Q} · ${be}`:`${Q} · ${ae}`,Fe=String((ee==null?void 0:ee.description)||"").trim(),it=(Array.isArray(ee==null?void 0:ee.interfaces)?ee.interfaces:[]).some(dt=>String(dt||"").trim().length>0),gt=Array.isArray(ee==null?void 0:ee.agent_default_interfaces)?ee.agent_default_interfaces.map(dt=>String(dt||"").trim()).filter(Boolean):[];T.push({workflow_id:Ge,bundle_id:Q,bundle_ref:String((U==null?void 0:U.bundle_ref)||"").trim(),flow_id:ae,label:pe,description:Fe||void 0,has_interface:it,agent_default_interfaces:gt})}}return T.sort((U,Q)=>U.label.localeCompare(Q.label)),T}async function Dn(b=Ke,T){if(nt.current&&!(T!=null&&T.force))return;nt.current=!0;const F=io.current;_e(!0);const U=pe=>pe.map(op).filter(Fe=>!!Fe.run_id),Q=pe=>Array.isArray(pe==null?void 0:pe.items)?pe.items:[],Z=C9(b,F),ee=()=>{const pe=Z.view();wn(pe.roots),Ks(pe.all)},ae=(pe,Fe)=>{if(String((pe==null?void 0:pe.name)||"")==="Superseded")return;const Pe=String((pe==null?void 0:pe.message)||pe||"");if(kn({ts:on(),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 it=Math.min(12e4,Math.max(15e3,xt.current*2||15e3));xt.current=it,ut.current=Date.now()+it,kn({ts:on(),kind:"info",title:`Gateway rate-limited — pausing polls ${Math.round(it/1e3)}s`})}},Ge=yl.current,be=Ge?S9(String(n.gateway_url||""),Ge):"";Xg.current=be,be&&Z.active_at===null&&Z.seed(N9(Sj(),be))&&Z.active_at!==null&&(ee(),wt(Z.active_at),Eu(!0));try{const[pe,Fe]=await Promise.allSettled([b.list_runs({status:"running",limit:kj}),b.list_runs({status:"waiting",limit:jj})]);if(F!==io.current)return;if(pe.status==="rejected"&&Fe.status==="rejected")throw pe.reason;pe.status==="rejected"&&ae(pe.reason,"Runs listing (running) failed"),Fe.status==="rejected"&&ae(Fe.reason,"Runs listing (waiting) failed");const Pe=pe.status==="fulfilled"?pe.value:null,it=Fe.status==="fulfilled"?Fe.value:null,gt=Pe?Q(Pe):Z.active_rows.filter(ht=>String(ht.status||"")==="running"),dt=it?Q(it):Z.active_rows.filter(ht=>String(ht.status||"")==="waiting"),xn=!!(Pe&&it)&>.length<kj&&dt.length<jj&&(Pe==null?void 0:Pe.has_more)!==!0&&(it==null?void 0:it.has_more)!==!0,qt=Z.seeded;Z.apply_active(U(gt),U(dt),xn),!(Pe&&it)&&qt&&(Z.seeded=!0),ee(),wt(Date.now()),Eu(!(Pe&&it)&&qt),Pe&&it&&Fm([]),xt.current=0,ut.current=0,be&&Pe&&it&&window.setTimeout(()=>$9(Sj(),be,Z.snapshot()),0)}catch(pe){ae(pe,"Refresh runs failed");return}finally{nt.current=!1,_e(!1)}Z.sweep_due(Date.now(),(T==null?void 0:T.force)===!0)&&(Z.begin_sweep(Date.now()),b.list_runs({limit:200,root_only:!0,include_metrics:!0}).then(async pe=>{const Fe=Number(pe==null?void 0:pe.archived_sessions);if(Number.isFinite(Fe)&&Fe<=0)return[pe,{items:[]}];const Pe=await b.list_runs({limit:200,root_only:!0,archived_only:!0,include_metrics:!0});return[pe,Pe]}).then(([pe,Fe])=>{if(F!==io.current||!Nj(Z))return Z.fail_sweep();const Pe=l3(Q(pe),Q(Fe));Z.apply_sweep(U(Pe),Date.now()),ee()},pe=>{Z.fail_sweep(),!(F!==io.current||!Nj(Z))&&ae(pe,"Refresh run metrics failed")}))}async function Ac(b){var ae,Ge,be;const T=io.current;J(!0),sn({}),b.list_apps().then(pe=>{if(T!==io.current)return;const Pe=(Array.isArray(pe==null?void 0:pe.apps)?pe.apps:[]).find(gt=>String((gt==null?void 0:gt.id)||"")==="code"),it=Pe&&Pe.installed===!0&&Pe.running===!0?String(Pe.url||"").trim():"";_t(it?{url:it}:null)}).catch(()=>{T===io.current&&_t(null)});const[F,,U,Q,Z]=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"&&Q.status==="rejected"){J(!1),O(Rw(F.reason,n)),kn({ts:on(),kind:"error",title:"Discovery failed",preview:tn(String(F.reason||""))});return}Oe(Z.status==="fulfilled"?c3(Z.value):{available:!1,reason:`Could not read the gateway capabilities: ${String(((ae=Z.reason)==null?void 0:ae.message)||Z.reason)}`});let ee=0;if(F.status==="fulfilled"){const pe=$s(F.value);ee=pe.length,Lt(pe)}else Lt([]),kn({ts:on(),kind:"error",title:"Discovery bundles failed",preview:tn(String(F.reason||""))});if(U.status==="fulfilled"){const pe=Array.isArray((Ge=U.value)==null?void 0:Ge.items)?U.value.items:[];ct(pe)}else ct([]),kn({ts:on(),kind:"error",title:"Discovery tools failed",preview:tn(String(U.reason||""))});if(Q.status==="fulfilled"){const pe=Array.isArray((be=Q.value)==null?void 0:be.items)?Q.value.items:[];vn(pe)}else vn([]),kn({ts:on(),kind:"error",title:"Discovery providers failed",preview:tn(String(Q.reason||""))});kn({ts:on(),kind:"info",title:"Gateway discovery loaded",preview:tn(`workflows: ${ee}`)})}async function Fo(b){var T,F;O(""),J(!1),M(!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 Q=String(n.gateway_url||"").trim();if(Q){const ee=Q.toLowerCase();if(!ee.startsWith("http://")&&!ee.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:"&&ee.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(Q),be=String(((F=window==null?void 0:window.location)==null?void 0:F.hostname)||"").trim().toLowerCase(),pe=String(Ge.hostname||"").trim().toLowerCase(),Fe=Pe=>Pe==="localhost"||Pe==="127.0.0.1"||Pe==="::1";if(Fe(pe)&&be&&!Fe(be))throw new Error("Gateway URL points to localhost, which from this device is not your machine. Use the gateway's public URL (e.g. an ngrok https URL) or leave Gateway URL blank to use same origin /api proxy.")}catch(ae){throw new Error(String((ae==null?void 0:ae.message)||ae||"Invalid Gateway URL"))}}const Z=new Xy({base_url:Q,auth_token:U});await Z.list_bundles(),r(ee=>({...ee,gateway_auth_mode:"direct"})),await Ac(Z)}catch(U){O(Rw(U,n))}finally{M(!1)}}const qa=p.useRef(!1),io=p.useRef(0),Bs=p.useRef(!1);function Vf(b){var F,U,Q;te(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 Z=String(((Q=(U=b==null?void 0:b.gateway)==null?void 0:U.principal)==null?void 0:Q.user_id)||"").trim();if(r(ee=>({...ee,gateway_auth_mode:"session",auth_token:"",gateway_user:Z||ee.gateway_user})),L&&n.gateway_auth_mode==="session")return;O(""),M(!0),Ac(new Xy({base_url:"",auth_token:""})).catch(ee=>O(Rw(ee,n))).finally(()=>M(!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)){Tt(!0);try{await Ke.reload_bundles();const b=await Ke.list_bundles(),T=$s(b);Lt(T),kn({ts:on(),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:on(),kind:"error",title:"Bundle reload failed",preview:tn(T),data:{error:T}})}finally{Tt(!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:on(),kind:"info",title:"Bundle uploaded",preview:tn(String((F==null?void 0:F.bundle_ref)||""))});const U=await Ke.list_bundles(),Q=$s(U);Lt(Q)}catch(F){const U=String((F==null?void 0:F.message)||F||"Upload failed");An(U),kn({ts:on(),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(""),R(null),K(""),W(!1),Lt([]),wn([]),Ks([]),wt(null),fe(null),Le(0),ct([]),vn([]),sn({}),O(""),J(!1),te(null),r(T=>({...T,auth_token:""})),kn({ts:on(),kind:"info",title:"Gateway disconnected"})}async function Pr(b){const T=String(b??"");T&&Us(await Mm(T)?"Copied to clipboard":u1,2)}p.useEffect(()=>{const b=l.trim();if(!Ht||!b)return;let T=!1;const F=async()=>{if(!(ut.current>Date.now()))try{const Q=await Ke.get_run(b);T||Nt(Q)}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=ee=>{T||(b!==null&&window.clearTimeout(b),b=window.setTimeout(()=>void Q(),ee))},Q=async()=>{if(F)return;const ee=ut.current-Date.now();if(ee>0){U(ee+500);return}F=!0;const ae=Date.now();try{await Dn(Ke)}finally{F=!1;const Ge=Date.now()-ae,be=document.visibilityState==="hidden"?3e4:5e3;U(Math.max(be,Ge*3))}},Z=()=>{document.visibilityState==="visible"&&Q()};return Q(),document.addEventListener("visibilitychange",Z),()=>{T=!0,b!==null&&window.clearTimeout(b),document.removeEventListener("visibilitychange",Z)}},[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=aW(T);if(Mc(F),F)try{const U=localStorage.getItem("abstractobserver_phase_graph_id_v1"),Q=U?JSON.parse(U):null;Q&&Q.sha256&&F.sha256&&Q.sha256!==F.sha256&&Q.version===F.version&&kn({ts:on(),kind:"error",title:"Phase-graph drift: served bytes changed without a version bump",preview:tn(`v${F.version}: ${String(Q.sha256).slice(0,12)}… -> ${String(F.sha256).slice(0,12)}…`),data:{prev:Q,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:on(),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){fe(null),Le(0),Ue("");return}let b=!1,T=null;const F=async()=>{if(!(ut.current>Date.now())){try{const U=await Ke.list_entities();b||Le(U.entities.length);const Q=U.entities.map(ee=>String((ee==null?void 0:ee.name)||(ee==null?void 0:ee.slug)||"").trim()).filter(Boolean).slice(0,PC),Z=await Promise.all(Q.map(async ee=>{var ae,Ge;try{const[be,pe]=await Promise.all([Ke.get_entity_card(ee),Ke.get_entity_cognition(ee).catch(()=>null)]),Fe=be!=null&&be.state&&typeof be.state=="object"?be.state:null,Pe=Array.isArray(be==null?void 0:be.moments)?be.moments:[],it=Pe.length?Pe[Pe.length-1]:null,gt=(ae=pe==null?void 0:pe.spend)==null?void 0:ae.lifetime,dt=(Ge=pe==null?void 0:pe.spend)==null?void 0:Ge.live_visit,xn=Array.isArray(pe==null?void 0:pe.warnings)?pe.warnings.map(ht=>String(ht||"")).filter(Boolean):[],qt=rW(be);return{name:ee,state:String((Fe==null?void 0:Fe.state)??(typeof(be==null?void 0:be.state)=="string"?be.state:"")).trim(),age_days:typeof(be==null?void 0:be.age_days)=="number"?be.age_days:null,last_moment:String((it==null?void 0:it.kind)||"").trim(),last_moment_at:String((it==null?void 0:it.at)||"").trim(),working:typeof(pe==null?void 0:pe.working)=="boolean"?pe.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(pe==null?void 0:pe.phase)=="string"?pe.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:sW(be),error:""}}catch(be){return{name:ee,state:"",age_days:null,last_moment:"",last_moment_at:"",working:null,tokens_total:null,live_visit_tokens:null,spend_warning:"",live_phase:"",open_questions:[],open_questions_total:0,open_problems:[],open_problems_total:0,lessons:[],lessons_total:0,dreams_brief:null,error:String((be==null?void 0:be.message)||be||"card failed")}}}));b||(fe(Z),Le(U.entities.length),Ue(""))}catch(U){if(!b){fe([]);const Q=String((U==null?void 0:U.message)||U||"");Ue(/404|not found/i.test(Q)?"":Q)}}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:on(),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=ye==null?void 0:ye.session_id;return typeof b=="string"?b.trim():b==null?"":String(b||"").trim()},[ye]),l_=p.useMemo(()=>{const b=String(oa||"").trim();return b||String(D||"").trim()},[oa,D]);p.useEffect(()=>{L||Dt("")},[L]);const[Rc,c_]=h1(),Jf=m1(L?Ke:null,L),oo=_1({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]);p1(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(KI,{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 Q=await Ke.download_run_artifact_content(T,F,{access:"preview"});d_(Q,$0(U)),Us("Downloaded artifact",2)}catch(Q){Us(String((Q==null?void 0:Q.message)||Q||"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),Q=String((b==null?void 0:b.content_type)||"").trim().toLowerCase(),Z=Yh(b);if(Oo(U||F),ia(""),eo(""),El(Z),Tl(b),Cl(!0),or&&(URL.revokeObjectURL(or),Vu("")),Z==="binary"){ia(`(Binary artifact: ${Q||"unknown"}; download to view.)`);return}if(Z==="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 ee=await Ke.download_run_artifact_content(T,F,{access:"preview"});if(Z==="text"){const ae=await ee.text(),Ge=ig(b,ae),be=Ge==="json"?15e5:Ge==="markdown"?25e4:Ge==="html"?3e5:22e3;ia(ae.length>be&&Ge!=="text"?`${ru(b.size_bytes??ae.length)} ${Ge.toUpperCase()} artifact. Download to inspect it.`:ae.length>be?`${ae.slice(0,Math.max(0,be-1))}…`:ae)}else Vu(URL.createObjectURL(ee))}catch(ee){eo(String((ee==null?void 0:ee.message)||ee||"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 Q=await Ke.download_run_artifact_content(F,T,{access:"preview"});if(U==="text"){const Z=await Q.text(),ee=ig(b,Z),ae=ee==="json"?5e5:ee==="markdown"?12e4:ee==="html"?3e5:8e3;return{artifact_id:T,kind:U,render_kind:ee,text:Z.length>ae&&ee!=="text"?`${ru(b.size_bytes??Z.length)} ${ee.toUpperCase()} artifact. Use Larger preview or Download to inspect it.`:Z.length>ae?`${Z.slice(0,Math.max(0,ae-1))}…`:Z,url:"",loading:!1,error:""}}return{artifact_id:T,kind:U,render_kind:"",text:"",url:URL.createObjectURL(Q),loading:!1,error:""}}catch(Q){return{artifact_id:T,kind:U,render_kind:"",text:"",url:"",loading:!1,error:String((Q==null?void 0:Q.message)||Q||"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 Q=F?String(vc.current[F]||"").trim():"";return Q?`${Q}::${U}`:U}function nd(b,T,F){const U=String(b||"").trim(),Q=String(T||"").trim(),Z=String(F||"").trim();if(!U||!Q||!Z)return;const ee=lr(U,Q);ee&&(vc.current[Z]=ee,Kr.current[Z]=U,xc.current[Z]={parent_run_id:U,parent_node_id:Q},Pa.current.has(Z)||(Pa.current.add(Z),Ou(ae=>ae.includes(Z)?ae:[...ae,Z])))}function Lc(b){const T=String(b||"").trim();if(!T)return;const F=Date.now(),U=$o.current;$o.current=T,Ia(F),Oa(Q=>{const Z={};for(const[be,pe]of Object.entries(Q))typeof pe=="number"&&pe>F&&(Z[be]=pe);Z[T]=Math.max(Z[T]||0,F+2e3),U&&U!==T&&(Z[U]=Math.max(Z[U]||0,F+2e3));const ee=Object.keys(Z);if(ee.length<=200)return Z;const ae=ee.sort((be,pe)=>(Z[pe]||0)-(Z[be]||0)).slice(0,200),Ge={};for(const be of ae)Ge[be]=Z[be]||0;return Ge}),Iu(Q=>{if(typeof Q[T]=="number")return Q;const Z={...Q,[T]:F};if(bl.current.push(T),bl.current.length>8e3){const ee=bl.current.splice(0,1500);for(const ae of ee)delete Z[ae]}return Z}),Gr.current&&window.clearTimeout(Gr.current),Gr.current=window.setTimeout(()=>{const Q=Date.now();Oa(Z=>{const ee={};for(const[ae,Ge]of Object.entries(Z))typeof Ge=="number"&&Ge>Q&&(ee[ae]=Ge);return ee}),Ia(Q),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),Q=U&&U.name?Ph(U.name):"",Z=b.record,ee=typeof(Z==null?void 0:Z.node_id)=="string"?Z.node_id:"",ae=typeof(Z==null?void 0:Z.status)=="string"?Z.status:"",Ge=typeof((xn=Z==null?void 0:Z.effect)==null?void 0:xn.type)=="string"?Z.effect.type:"",be=typeof(Z==null?void 0:Z.run_id)=="string"?Z.run_id:"",pe=be||F;if(Q==="abstract.status"&&pe===F){const{text:ht,duration:en}=kd(U==null?void 0:U.payload);Us(ht,en)}const Fe=ee?lr(pe,ee):"";if(ae==="waiting"){const ht=Za(Z);if(String((ht==null?void 0:ht.reason)||"").trim()==="subworkflow"){const Yn=typeof((qt=ht==null?void 0:ht.details)==null?void 0:qt.sub_run_id)=="string"?String(ht.details.sub_run_id):"";Yn&&ee&&nd(pe,ee,Yn)}}if(ee&&(Lc(lr(pe,ee)),ae==="waiting"||ae==="running")){const ht=lr(pe,ee);ht&&($o.current=ht,ea(ht))}let Pe="step",it=Fe||ee||"(node?)",gt="";if(U&&U.name&&Mw(U.name))Pe=Q==="abstract.message"?"message":"event",it=Q||U.name,gt=tn(Q==="abstract.steer_seen"?Tw(U==null?void 0:U.payload):kd(U==null?void 0:U.payload).text);else if(Z!=null&&Z.error)Pe="error",it="error",gt=tn(Br(Z.error,360));else if(ae==="waiting"){const ht=Za(Z),en=String((ht==null?void 0:ht.reason)||"").trim();gt=tn(en?`waiting • ${en}`:"waiting")}else Z!=null&&Z.result?gt=tn(Br(Z.result,360)):Ge?gt=tn(Ge):gt=tn(Lp(Z));kn({id:`step:${be||F||"?"}:${b.cursor}`,ts:String((Z==null?void 0:Z.ended_at)||(Z==null?void 0:Z.started_at)||on()),kind:Pe,title:it,preview:gt,data:Z,cursor:b.cursor,run_id:be||F||void 0,node_id:Fe||ee,status:ae,effect_type:Ge,emit_name:Q||(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 Q=cp(T.record),Z=Q&&Q.name?Ph(Q.name):"",ee=T.record,ae=typeof(ee==null?void 0:ee.node_id)=="string"?ee.node_id:"",Ge=ae?lr(b,ae):"",be=typeof(ee==null?void 0:ee.status)=="string"?ee.status:"",pe=typeof((dt=ee==null?void 0:ee.effect)==null?void 0:dt.type)=="string"?ee.effect.type:"";if(be==="waiting"){const qt=Za(ee);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&&ae&&nd(b,ae,en),en&&xr.current.trim()===String(b||"").trim()&&(xr.current=en,Ai(en))}}if(ae&&(Lc(lr(b,ae)),be==="waiting"||be==="running")){const qt=lr(b,ae);qt&&($o.current=qt,ea(qt))}if((be==="completed"||be==="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(Z==="abstract.status"&&b===l.trim()){const{text:qt,duration:ht}=kd(Q==null?void 0:Q.payload);Us(qt,ht)}let Fe="step",Pe=Ge||ae||"(node?)",it="";if(Q&&Q.name&&Mw(Q.name))Fe=Z==="abstract.message"?"message":"event",Pe=`subrun • ${Z||Q.name}`,it=tn(Z==="abstract.steer_seen"?Tw(Q==null?void 0:Q.payload):kd(Q==null?void 0:Q.payload).text);else if(ee!=null&&ee.error)Fe="error",Pe="error",it=tn(Br(ee.error,360));else if(be==="waiting"){const qt=Za(ee),ht=String((qt==null?void 0:qt.reason)||"").trim();it=tn(ht?`waiting • ${ht}`:"waiting")}else ee!=null&&ee.result?it=tn(Br(ee.result,360)):pe?it=tn(pe):it=tn(Lp(ee));kn({id:`step:${b}:${T.cursor}`,ts:String((ee==null?void 0:ee.ended_at)||(ee==null?void 0:ee.started_at)||on()),kind:Fe,title:Pe,preview:it,data:ee,cursor:T.cursor,run_id:b,node_id:Ge||ae,status:be,effect_type:pe,emit_name:Z||(Q==null?void 0:Q.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 Z=cp(T.record),ee=Z&&Z.name?Ph(Z.name):"",ae=T.record,Ge=typeof(ae==null?void 0:ae.node_id)=="string"?ae.node_id:"",be=Ge?lr(F,Ge):"",pe=typeof(ae==null?void 0:ae.status)=="string"?ae.status:"",Fe=typeof((xn=ae==null?void 0:ae.effect)==null?void 0:xn.type)=="string"?ae.effect.type:"";if(pe==="waiting"){const ht=Za(ae);if(String((ht==null?void 0:ht.reason)||"").trim()==="subworkflow"){const Yn=typeof((qt=ht==null?void 0:ht.details)==null?void 0:qt.sub_run_id)=="string"?String(ht.details.sub_run_id):"";Yn&&Ge&&nd(F,Ge,Yn)}}if(Ge&&(Lc(lr(F,Ge)),pe==="waiting"||pe==="running")){const ht=lr(F,Ge);ht&&($o.current=ht,ea(ht))}if(ee==="abstract.status"&&F===l.trim()){const{text:ht,duration:en}=kd(Z==null?void 0:Z.payload);Us(ht,en)}let Pe="step",it=be||Ge||"(node?)",gt="";if(Z&&Z.name&&Mw(Z.name))Pe=ee==="abstract.message"?"message":"event",it=`subrun • ${ee||Z.name}`,gt=tn(ee==="abstract.steer_seen"?Tw(Z==null?void 0:Z.payload):kd(Z==null?void 0:Z.payload).text);else if(ae!=null&&ae.error)Pe="error",it="error",gt=tn(Br(ae.error,360));else if(pe==="waiting"){const ht=Za(ae),en=String((ht==null?void 0:ht.reason)||"").trim();gt=tn(en?`waiting • ${en}`:"waiting")}else ae!=null&&ae.result?gt=tn(Br(ae.result,360)):Fe?gt=tn(Fe):gt=tn(Lp(ae));kn({id:`step:${F}:${T.cursor}`,ts:String((ae==null?void 0:ae.ended_at)||(ae==null?void 0:ae.started_at)||on()),kind:Pe,title:it,preview:gt,data:ae,cursor:T.cursor,run_id:F,node_id:be||Ge,status:pe,effect_type:Fe,emit_name:ee||(Z==null?void 0:Z.name)||""})}async function Yf(b,T){var U,Q;let F=T.after;for(;;){if((U=T.signal)!=null&&U.aborted)return F;const Z=await Ke.get_ledger(b,{after:F,limit:200,signal:T.signal});if((Q=T.signal)!=null&&Q.aborted)return F;const ee=Array.isArray(Z.items)?Z.items:[];if(!ee.length)return Ar.current=F,F;const ae=F;for(let Ge=0;Ge<ee.length;Ge++){const be=ee[Ge];sd({cursor:ae+Ge+1,record:be},b)}F=typeof Z.next_after=="number"?Z.next_after:F}}async function rd(b){var Z,ee,ae,Ge;const T=String(b||"").trim();An(""),Qt(!0),is(!1),(Z=As.current)==null||Z.reset(),(ee=ws.current)==null||ee.reset(),_r.current={scanned:0,found:null},Xe([]),Ar.current=0,cn([]),Ei.current=new Set,pf([]),Vm(""),ml(""),Nt(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 be="",pe="";try{const Fe=await Ke.get_run(T);Nt(Fe);const Pe=typeof(Fe==null?void 0:Fe.workflow_id)=="string"?String(Fe.workflow_id):"",it=Hj(Pe);it&&(be=it.bundle_id,pe=it.flow_id)}catch{}try{const Fe=await Ke.get_run_input_data(T);typeof(Fe==null?void 0:Fe.bundle_id)=="string"&&(be=String(Fe.bundle_id||"").trim()||be),typeof(Fe==null?void 0:Fe.flow_id)=="string"&&(pe=String(Fe.flow_id||"").trim()||pe);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 it=Fe==null?void 0:Fe.workspace,gt=typeof(it==null?void 0:it.workspace_root)=="string"?String(it.workspace_root).trim():"";Sf(gt)}catch{Sf("")}be&&pe&&($(be),v(pe),wr(pe),await cs(be)),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((ae=Pe==null?void 0:Pe[T])==null?void 0:ae.total)=="number"?Number(Pe[T].total):0;let xn="",qt=-1;for(const ht of gt){const en=typeof((Ge=Pe==null?void 0:Pe[ht])==null?void 0:Ge.total)=="number"?Number(Pe[ht].total):0;en>qt&&(xn=ht,qt=en)}xn&&qt>Math.max(dt*3,dt+20)&&(xr.current=xn,Ai(xn))}catch{}}}catch{}is(!0),kn({ts:on(),kind:"info",title:`Attached to run ${T}`,data:{run_id:T}}),U=!0}catch(be){if(F.signal.aborted||String((be==null?void 0:be.name)||"")==="Superseded")return;const pe=String((be==null?void 0:be.message)||be||"unknown error");An(pe),kn({ts:on(),kind:"error",title:"Connection error",preview:tn(pe),data:{error:pe}}),is(!1)}finally{F.signal.aborted||Qt(!1)}if(!U||F.signal.aborted)return;(async()=>{let be=250;for(;!F.signal.aborted;){try{const pe=await Yf(T,{after:Ar.current,signal:F.signal});await Ke.stream_ledger(T,{after:pe,on_step:Fe=>sd(Fe,T),signal:F.signal})}catch(pe){if(F.signal.aborted)break;const Fe=String((pe==null?void 0:pe.message)||pe||"stream error");kn({ts:on(),kind:"error",title:"Ledger stream error (will retry)",preview:tn(Fe),data:{error:Fe}})}if(F.signal.aborted)break;await new Promise(pe=>setTimeout(pe,be)),be=Math.min(5e3,Math.floor(be*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 Q=C.trim();if(Q)try{if(U=JSON.parse(Q),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 it=Pe.trim();it?U[Fe]=it:delete U[Fe]}const Z=(Xr||[]).find(Fe=>Fe&&typeof Fe=="object"&&Fe.id==="prompt"),ee=Z&&typeof Z=="object"&&Object.prototype.hasOwnProperty.call(Z,"default"),ae=U==null?void 0:U.prompt,Ge=typeof ae=="string"?ae.trim():"";if(Z&&!ee&&!Ge){const Fe="Missing required input_data.prompt";return An(Fe),Fe}const be=U.workspace&&typeof U.workspace=="object"?U.workspace:null;delete U.workspace;const pe=await Ke.start_run(T,U,{...be?{workspace:be}:{},...F?{bundle_id:F}:{},...b.kind==="default"?{interface:b.interface}:{},session_id:String(D||"").trim()||null});return m(pe),d(pe),nr(""),await rd(pe),Dn(),null}catch(U){const Q=String((U==null?void 0:U.message)||U||"start failed");return An(Q),Q}finally{Qt(!1)}}async function ty(){if(Ot([]),Re(null),!X.available){Ot([X.reason]);return}const b=a3(He,{choice:jr,bundle_ref_for:T=>{var F;return((F=Pt.find(U=>U.bundle_id===T))==null?void 0:F.bundle_ref)||""},input_data:rn,email_usable:Un.email_usable,defaults:Do,mailboxes:ui.mailboxes,connections:ui.trigger_connections},je.current);if(!b.ok){Ot(b.errors);return}re(!0);try{const T=await Ke.automations_client().createAutomation(b.body);je.current.reset(),de([]),ft(iv),Rl.current="",kn({ts:on(),kind:"info",title:"Automation created",preview:tn(`${b.body.title} · ${T.automation_id}`)}),Ee(!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")};Re(F)}finally{re(!1)}}async function ny(){if(nr(""),ke==="automate"){await ty();return}const b=await p_();if(b){nr(b);return}Ee(!1),No("ledger"),t("observe")}async function Xf(b){if(Qn("skills",void 0),!!b){if(b.kind==="default"){ze(b.interface),$(""),v(""),R(null);return}ze(""),$(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=_3(T,F);await Xf(U.choice),S(JSON.stringify(U.input_data,null,2)),ft(U.form),de([`Recreating the legacy schedule ${Ln(b,14)} as an automation. The legacy schedule keeps running until you suspend it.`,...U.notes]),je.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([]),cn([]),Ei.current=new Set,Nt(null),pf([]),ea(""),$o.current="",Oa({}),Iu({}),bl.current=[],Ia(Date.now()),Us("",-1),An(""),bn([]),Hn(null),De(""),mt(""),pn(!1),Vi(!1),Hi(""),mc(""),Ta(""),_c([]),ju(!1),Su(""),Nu(""),pl(!1),Ma("")}p.useEffect(()=>{bn([]),Hn(null),De(""),mt(""),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,ye==null?void 0:ye.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 Q={},Z=String((F==null?void 0:F.reason)||"").trim();Z&&(Q.reason=Z),await Ke.submit_command({command_id:Zs(),run_id:U,type:T,payload:Q,client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:`${T} submitted`,preview:Z?`reason: ${Z}`:"",data:{run_id:U,type:T,reason:Z}});try{if(U===l.trim()){const ee=await Ke.get_run(U);Nt(ee)}}catch{}return Dn(Ke,{force:!0}),window.setTimeout(()=>void Dn(Ke,{force:!0}),900),window.setTimeout(()=>void Dn(Ke,{force:!0}),2400),null}catch(Q){const Z=String((Q==null?void 0:Q.message)||Q||`${T} failed`);return An(Z),Z}}async function sy(b,T){const F=b.map(Ge=>String(Ge||"").trim()).filter(Boolean),U=[];let Q=0,Z=0,ee=0;const ae=async()=>{for(;ee<F.length;){const Ge=F[ee++];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(be){Z+=1,U.push({run_id:Ge,error:String((be==null?void 0:be.message)||be||"cancel failed")})}Q+=1,T==null||T(Q,Z)}};return await Promise.all(Array.from({length:Math.min(4,F.length)},ae)),kn({ts:on(),kind:Z?"error":"info",title:`cancel submitted ×${F.length}${Z?` · ${Z} failed`:""}`,preview:"",data:{run_ids:F,failed:Z}}),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(Rt)return;const T=String(((F=ye==null?void 0:ye.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:on()}},Q=String(cr||"").trim();Q&&(U.wait_key=Q),await Ke.submit_command({command_id:Zs(),run_id:b,type:"resume",payload:U,client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Scheduled run triggered",preview:tn(`run ${b}`),data:{run_id:b,until:ao||null}});try{const Z=await Ke.get_run(b);Nt(Z)}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 Q="Invalid interval (expected like '20m', '1h', '0.5s', '250ms')";return Ss(Q),Q}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:on(),kind:"info",title:"Schedule updated",preview:tn(`interval: ${F}`),data:{interval:F},run_id:T});try{const Q=await Ke.get_run(T);Nt(Q)}catch{}return null}catch(Q){const Z=String((Q==null?void 0:Q.message)||Q||"update_schedule failed");return Ss(Z),An(Z),Z}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))),Q=(b==null?void 0:b.compression_mode)||Tr,Z=String((b==null?void 0:b.focus)??Wi??"").trim();Fs(""),An(""),gr(!0),Qt(!0);try{const ee={preserve_recent:U,compression_mode:Q};return Z&&(ee.focus=Z),await Ke.submit_command({command_id:Zs(),run_id:T,type:"compact_memory",payload:ee,client_id:"web_pwa"}),kn({ts:on(),kind:"info",title:"Compaction requested",preview:tn(`mode: ${Q} • preserve_recent: ${U}`),data:ee,run_id:T}),null}catch(ee){const ae=String((ee==null?void 0:ee.message)||ee||"compact_memory failed");return Fs(ae),An(ae),ae}finally{Qt(!1),gr(!1)}}async function y_(){const b=l.trim();if(!b){mt("Select a run first.");return}if(!L){mt("Connect to the gateway first.");return}const T=Ie.trim();if(!T||Bt)return;if(oo.voice_ptt_busy){Dt("Wait for transcription to finish.");return}mt(""),Dt(""),pn(!0);const U={id:`local:${Zs()}`,role:"user",content:T,ts:on()};bn(Q=>[...Q,U]),De("");try{const Q=VI(Ft,U),Z=n.maintenance_ai_provider.trim(),ee=n.maintenance_ai_model.trim(),ae=await Ke.run_chat(b,{provider:Z||void 0,model:ee||void 0,include_subruns:!0,messages:Q}),Ge=String((ae==null?void 0:ae.answer)||"").trim()||"(empty response)",be=String((ae==null?void 0:ae.generated_at)||"").trim()||on();Hn((ae==null?void 0:ae.history)??null),bn(pe=>[...pe,{id:`local:${Zs()}`,role:"assistant",content:Ge,ts:be}])}catch(Q){const Z=CO(Q);mt(Z),bn(ee=>[...ee,{id:`local:${Zs()}`,role:"assistant",content:`(error: ${Z})`,ts:on(),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=dN(Ft.map(Q=>({role:Q.role,content:Q.content,ts:Q.ts})),{heading:F});if(b==="download"){const Q=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),Z=`abstractobserver-chat-${$0(T||"run")}-${Q}.md`;fN({filename:Z,text:U,mime:"text/markdown;charset=utf-8"});return}(async()=>{const Q=await il(U);Js(Q?"copied":"failed"),window.setTimeout(()=>Js("idle"),900)})()}async function Oc(){const b=typeof(ye==null?void 0:ye.workflow_id)=="string"?String(ye.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 be of F){const pe=typeof(be==null?void 0:be.run_id)=="string"?String(be.run_id).trim():"";if(!pe)continue;const Fe=typeof(be==null?void 0:be.ledger_len)=="number"?Number(be.ledger_len):0;U.push({run_id:pe,ledger_len:Number.isFinite(Fe)?Fe:0})}if(!U.length){_c([]);return}const Q=400,Z=U.map(be=>({run_id:be.run_id,after:Math.max(0,(be.ledger_len||0)-Q)})),ee=await Ke.get_ledger_batch({runs:Z,limit:Q}),ae=[],Ge=new Set;for(const be of U){const pe=ee!=null&&ee.runs&&typeof ee.runs=="object"?ee.runs[be.run_id]:null,Fe=Array.isArray(pe==null?void 0:pe.items)?pe.items:[];for(const Pe of Fe){const it=Pe==null?void 0:Pe.effect;if(!it||typeof it!="object"||String(it.type||"")!=="emit_event")continue;const gt=it.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):"",ht=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):be.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&&ae.push({thread_id:xn,created_at:qt,title:ht||`Chat ${xn.slice(0,8)}`,run_id:Yn,workflow_id:en,message_count:wi,provider:ds,model:dr,artifact_id:Vl})}}ae.sort((be,pe)=>String(pe.created_at||"").localeCompare(String(be.created_at||""))),_c(ae)}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(ee=>({role:ee.role,content:ee.content,ts:ee.ts}))}),Q=typeof(U==null?void 0:U.created_at)=="string"?String(U.created_at):on();mc(Q);try{const ee=JSON.stringify(Ft.map(ae=>({role:ae.role,content:ae.content,ts:ae.ts})));Ta(ee)}catch{Ta("1")}typeof(U==null?void 0:U.thread_id)=="string"&&String(U.thread_id).trim()&&Nu(String(U.thread_id).trim());const Z=!!(U!=null&&U.duplicate);Us(Z?"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(Q=>String(Q.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(Z=>({role:Z.role,content:Z.content,ts:Z.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 Z=await(await Ke.download_run_artifact_content(T.run_id,T.artifact_id)).text(),ee=JSON.parse(Z),ae=Array.isArray(ee==null?void 0:ee.messages)?ee.messages:[],Ge=typeof(ee==null?void 0:ee.created_at)=="string"?String(ee.created_at):String(T.created_at||""),be=[];for(let pe=0;pe<ae.length;pe++){const Fe=ae[pe];if(!Fe||typeof Fe!="object")continue;const Pe=String(Fe.role||"").trim()==="assistant"?"assistant":"user",it=typeof Fe.content=="string"?String(Fe.content):"";if(!it.trim())continue;const gt=typeof Fe.ts=="string"?String(Fe.ts):Ge||on();be.push({id:`thread:${b}:${pe}`,role:Pe,content:it.trim(),ts:gt})}bn(be),Hn(null),De(""),mt(""),Hi(""),mc(Ge||"");try{const pe=JSON.stringify(be.map(Fe=>({role:Fe.role,content:Fe.content,ts:Fe.ts})));Ta(pe)}catch{Ta("1")}Us("Loaded discussion",2)}catch(Q){Ma(String((Q==null?void 0:Q.message)||Q||"Failed to load saved discussion"))}finally{pl(!1)}}}async function Pc(b){const T=l.trim(),F=String((un==null?void 0:un.wait_key)||"").trim();if(!T||!F){An("No active wait to resume");return}if(String((un==null?void 0:un.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:on(),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);Nt(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(!Rt){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(un),[un]),cr=String((un==null?void 0:un.wait_key)||"").trim(),Ws=String((un==null?void 0:un.reason)||"").trim(),ao=typeof(un==null?void 0:un.until)=="string"?String(un.until):"",Cs=typeof(ye==null?void 0:ye.status)=="string"?String(ye.status):"",xs=!!(ye!=null&&ye.paused),pi=Cs==="completed"||Cs==="failed"||Cs==="cancelled",x_=Ws==="until"&&!!ao,Dc=!pi&&A4(ar)&&(!!cr||x_),b_=Ws==="user",od=Ws==="event"?Ph(Oq(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=un==null?void 0:un.details)==null?void 0:_d.sub_run_id)=="string"?String(un.details.sub_run_id):"",zl={run_id:l.trim(),workflow_id:typeof(ye==null?void 0:ye.workflow_id)=="string"?String(ye.workflow_id):null,status:Cs,created_at:typeof(ye==null?void 0:ye.created_at)=="string"?String(ye.created_at):null,updated_at:typeof(ye==null?void 0:ye.updated_at)=="string"?String(ye.updated_at):null,session_id:typeof(ye==null?void 0:ye.session_id)=="string"?String(ye.session_id):null,current_node:typeof(ye==null?void 0:ye.current_node)=="string"?String(ye.current_node):null},ld=fn.slice(-10).map(b=>{var T,F,U,Q,Z,ee;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(((Q=(U=b.record)==null?void 0:U.effect)==null?void 0:Q.type)||"").trim(),ts:String(((Z=b.record)==null?void 0:Z.ended_at)||((ee=b.record)==null?void 0:ee.started_at)||"").trim(),summary:M1(b.record)}}),cd=xx(un,aa),j_=C1(un,aa),ud=E1(un,rn),zo=ud.text,iy=ud.runtime_metadata,Fc=String((un==null?void 0:un.prompt)||"").trim(),dd=_4(rn,6),S_=!!(Fc&&S1(Fc)),Bl=!!(Fc&&!S_),Bo=Bl?"Question from workflow":zo&&zo!==Fc?"Closest prior user request":"Request context",oy=y4(rn,C),N_=!!C.trim(),Sr=ye!=null&&ye.schedule&&typeof ye.schedule=="object"?ye.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=!!(ye!=null&&ye.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||Rt||pi:!l.trim()||Be||Rt||pi||zc==="resume"&&!xs,ay=l.trim()?pi?"The schedule has ended.":null:"No run selected.",St=Jn&&!xs&&!pi&&!Be&&!Rt&&Cs.toLowerCase()==="waiting"&&(String(((ma=ye==null?void 0:ye.waiting)==null?void 0:ma.reason)||"").trim().toLowerCase()==="until"||Ws==="until")&&!!String(ao||"").trim(),qs=(pd=ye==null?void 0:ye.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;fn.length<b.scanned&&(b.scanned=0,b.found=null);for(let T=b.scanned;T<fn.length;T++){const F=fn[T],U=F==null?void 0:F.record;if(!U)continue;const Q=cp(U);if((Q&&Q.name?Ph(Q.name):"")!=="abstract.summary")continue;const ee=Q!=null&&Q.payload&&typeof Q.payload=="object"?Q.payload:{},ae=typeof(ee==null?void 0:ee.text)=="string"?String(ee.text):"";ae.trim()&&(b.found={cursor:F.cursor,ts:String((U==null?void 0:U.ended_at)||(U==null?void 0:U.started_at)||""),text:ae,provider:typeof(ee==null?void 0:ee.provider)=="string"?String(ee.provider):void 0,model:typeof(ee==null?void 0:ee.model)=="string"?String(ee.model):void 0,generated_at:typeof(ee==null?void 0:ee.generated_at)=="string"?String(ee.generated_at):void 0,source:ee==null?void 0:ee.source})}return b.scanned=fn.length,b.found},[fn]);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(P==null?void 0:P.entrypoints)?P==null?void 0:P.entrypoints:[])||[]).map(T=>String((T==null?void 0:T.flow_id)||"").trim()).filter(Boolean),[P]),Li=p.useMemo(()=>{const b=String((ye==null?void 0:ye.workflow_id)||"").trim();return Ht&&Jn?b:""},[Ht,Jn,ye==null?void 0:ye.workflow_id]),A_=p.useMemo(()=>{var ee;if(!Ht||!l.trim()||!Li.trim())return Lr;const b=String((ye==null?void 0:ye.status)||"").trim().toLowerCase(),T=String((ye==null?void 0:ye.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||((ee=ye==null?void 0:ye.waiting)==null?void 0:ee.reason)||"").trim().toLowerCase(),Q=typeof(ar==null?void 0:ar.node_id)=="string"?String(ar.node_id).trim():"",Z=typeof(ar==null?void 0:ar.status)=="string"?String(ar.status).trim().toLowerCase():"";return b==="waiting"&&U==="until"||!Lr.trim()||(Z==="waiting"||Z==="running")&&!Q?F:Lr},[Ht,l,Li,ye==null?void 0:ye.status,ye==null?void 0:ye.current_node,(_a=ye==null?void 0:ye.waiting)==null?void 0:_a.reason,Ws,Lr,ar]),T_=p.useMemo(()=>{const b={},T=l.trim(),F=(U,Q)=>{if(!Q)return;const Z=typeof(Q==null?void 0:Q.node_id)=="string"?String(Q.node_id).trim():"";if(!Z)return;const ee=lr(U,Z);if(!ee)return;const ae=String((Q==null?void 0:Q.ended_at)||(Q==null?void 0:Q.started_at)||"").trim(),Ge=Vt(ae);Ge!==null&&(b[ee]=Math.max(b[ee]||0,Ge))};for(const U of fn)U&&U.record&&F(T,U.record);for(const U of nn)U&&U.record&&F(String(U.run_id||"").trim(),U.record);return b},[fn,nn,l,Co]);p.useEffect(()=>{var F;if(!Ht||!l.trim()||!Li.trim())return;const b=String((ye==null?void 0:ye.current_node)||"").trim();!b||String(((F=ye==null?void 0:ye.waiting)==null?void 0:F.reason)||"").trim()==="subworkflow"||Lc(lr(l.trim(),b))},[Ht,l,Li,ye==null?void 0:ye.current_node,(fh=ye==null?void 0:ye.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 Q=!1;return Ra(!0),wc(""),Ke.get_workflow_flow(b).then(Z=>{if(Q)return;const ee=Z==null?void 0:Z.flow;xl(ee&&typeof ee=="object"?ee:null)}).catch(Z=>{Q||(xl(null),wc(String((Z==null?void 0:Z.message)||Z||"Failed to load workflow flow")))}).finally(()=>{Q||Ra(!1)}),()=>{Q=!0}}if(!T||!F){xl(null),wc(""),Ra(!1);return}let U=!1;return Ra(!0),wc(""),Ke.get_bundle_flow(T,F).then(Q=>{if(U)return;const Z=Q==null?void 0:Q.flow,ee=Z&&typeof Z=="object"?Z:null;xl(ee),ee&&Ru(ae=>({...ae,[F]:ee}))}).catch(Q=>{U||(xl(null),wc(String((Q==null?void 0:Q.message)||Q||"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=be=>{const pe=Array.isArray(be==null?void 0:be.nodes)?be.nodes:[],Fe=[];for(const Pe of pe){const it=Pe!=null&&Pe.data&&typeof Pe.data=="object"?Pe.data:{};if(String((it==null?void 0:it.nodeType)||(Pe==null?void 0:Pe.type)||"").trim()!=="subflow")continue;const dt=(it==null?void 0:it.subflowId)||(it==null?void 0:it.flowId),xn=typeof dt=="string"?dt.trim():"";xn&&Fe.push(xn.includes(":")?xn.split(":",2)[1]:xn)}return Fe},Q=new Set,Z=new Set,ee=(be,pe)=>{if(!(!be||pe>=F))for(const Fe of U(be)){const Pe=String(Fe||"").trim();if(!Pe||Q.has(Pe))continue;Q.add(Pe),Z.add(Pe);const it=yc[Pe];it&&ee(it,pe+1)}};ee(Ki,0);const ae=Array.from(Z).filter(be=>!yc[be]).slice(0,20);return ae.length?((async()=>{for(const be of ae){if(T)return;try{const pe=await Ke.get_bundle_flow(b,be),Fe=pe==null?void 0:pe.flow,Pe=Fe&&typeof Fe=="object"?Fe:null;if(!Pe)continue;Ru(it=>it[be]?it:{...it,[be]:Pe})}catch{}}})(),()=>{T=!0}):void 0},[Ji,N,Ki,yc,Ke]);const oh=p.useMemo(()=>{const T=(Array.isArray(P==null?void 0:P.flows)?P==null?void 0:P.flows:[]).map(F=>String(F||"").trim()).filter(Boolean);return T.length?Array.from(new Set(T)).sort():Array.from(new Set(Bc)).sort()},[P,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:on(),kind:"info",title:`Following run ${b} (status/events)`});let Q=250;return(async()=>{for(;!U.signal.aborted;){try{await Ke.stream_ledger(b,{after:Bn.current,on_step:ee=>m_(b,ee),signal:U.signal});return}catch(ee){if(U.signal.aborted)break;const ae=String((ee==null?void 0:ee.message)||ee||"stream error");kn({ts:on(),kind:"error",title:"Child ledger stream error (will retry)",preview:tn(ae),data:{child_run_id:b,error:ae}})}if(U.signal.aborted)break;await new Promise(ee=>setTimeout(ee,Q)),Q=Math.min(5e3,Math.floor(Q*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(ae=>String(ae||"").trim()).filter(Boolean);if(!U.length)return;const Q=U.map(ae=>({run_id:ae,after:Number(ta.current[ae]||0)})),Z=await Ke.get_ledger_batch({runs:Q,limit:200}),ee=Z&&typeof Z=="object"?Z.runs:{};for(const ae of U){if(b)return;const Ge=ee&&typeof ee=="object"?ee[ae]:null,be=Array.isArray(Ge==null?void 0:Ge.items)?Ge.items:[],pe=typeof(Ge==null?void 0:Ge.next_after)=="number"?Ge.next_after:Number(ta.current[ae]||0),Fe=Number(ta.current[ae]||0);for(let Pe=0;Pe<be.length;Pe++){const it=be[Pe];__(ae,{cursor:Fe+Pe+1,record:it})}ta.current[ae]=pe}}catch(U){if(b||String((U==null?void 0:U.name)||"")==="Superseded")return;kn({ts:on(),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 fn)!F||!F.record||T.push({run_id:b,cursor:F.cursor,record:F.record});for(const F of nn)!F||!F.record||T.push({run_id:String(F.run_id||"").trim(),cursor:F.cursor,record:F.record});return T},[fn,nn,l]),Uc=p.useMemo(()=>{var T,F,U,Q;const b={};for(const Z of Ii){const ee=String(Z.run_id||((T=Z.record)==null?void 0:T.run_id)||"").trim();!ee||String(((U=(F=Z.record)==null?void 0:F.effect)==null?void 0:U.type)||"").trim()!=="llm_call"||String(((Q=Z.record)==null?void 0:Q.status)||"")!=="started"&&(b[ee]=(b[ee]||0)+1)}return b},[Ii]),Ys=p.useMemo(()=>{const b=Ir.trim();if(b)return b;let T="",F=-1;for(const[U,Q]of Object.entries(Uc))Q>F&&(T=U,F=Q);return T||l.trim()},[Uc,Ir,l]),Oi=(Qg.trim()||Ys).trim(),ca=p.useMemo(()=>{var Q;const b=new Set,T=l.trim(),F=Ir.trim();T&&b.add(T),F&&b.add(F);for(const Z of Co){const ee=String(Z||"").trim();ee&&b.add(ee)}for(const Z of Ii){const ee=String(Z.run_id||((Q=Z.record)==null?void 0:Q.run_id)||"").trim();ee&&b.add(ee)}const U=Array.from(b);return U.sort((Z,ee)=>T&&Z===T&&ee!==T?-1:T&&ee===T&&Z!==T?1:F&&Z===F&&ee!==F?-1:F&&ee===F&&Z!==F?1:Z<ee?-1:Z>ee?1:0),U},[l,Ir,Co,Ii]),ah=p.useMemo(()=>{var b;for(let T=fn.length-1;T>=0;T--){const F=R1((b=fn[T])==null?void 0:b.record);if(F)return F}return""},[fn]);function M_(b){jf(b);const T=l.trim();if(!(!T||typeof window>"u"))try{window.history.replaceState(null,"",yO(YI(T),b))}catch{}}const Cn=p.useMemo(()=>{const b=l.trim();return b&&(On.find(T=>String(T.run_id||"").trim()===b)||mn.find(T=>String(T.run_id||"").trim()===b))||null},[On,mn,l]),gs=p.useMemo(()=>Cn||(ye&&String((ye==null?void 0:ye.run_id)||"").trim()?op(ye):null),[Cn,ye]),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=he.current;Ke.list_runs({session_id:R_,include_metrics:!0,limit:200}).then(T=>{if(b!==he.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===he.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=++he.current;Y({...Vj,key:us,loading:!0});const U=String(b.workflow_id||"").trim(),Q=()=>{const ae=U.indexOf("@"),Ge=ae>=0?U.indexOf(":",ae):-1;return ae>=0&&Ge>ae?Ke.get_bundle_flow(U.slice(0,Ge),U.slice(Ge+1)):Ke.get_workflow_flow(U)},Z=String(b.automation_id||"").trim(),ee=String(b.session_id||"").trim();Promise.allSettled([Ke.get_run_input_data(T),U?Q():Promise.reject(new Error("the run names no workflow")),Z?Ke.automations_client().getAutomation(Z):Promise.resolve(null),ee?Ke.list_runs({session_id:ee,include_metrics:!0,limit:200}):Promise.resolve({items:[]})]).then(([ae,Ge,be,pe])=>{var gt;if(F!==he.current)return;const Fe=dt=>{var xn;return dt.status==="rejected"?String(((xn=dt.reason)==null?void 0:xn.message)||dt.reason||"failed"):""},Pe=be.status==="fulfilled"?be.value:null,it=pe.status==="fulfilled"&&Array.isArray((gt=pe.value)==null?void 0:gt.items)?pe.value.items.map(op):[];Y({key:us,loading:!1,input_data:ae.status==="fulfilled"?ae.value:null,input_error:Fe(ae),flow:Ge.status==="fulfilled"?Ge.value:null,flow_error:Fe(Ge),automation_body:Pe,automation:Pe?Rm(Pe):null,automation_error:Fe(be),runs:it,runs_error:Fe(pe)})})},[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(()=>dD(Ii,l.trim(),lr),[Ii,l,Co]),ly=p.useMemo(()=>{if(!gs)return null;const b=XC(gs,ye),T=new Map;return ye&&T.set(String(b.run_id||"").trim(),ye),ef(b,Sx(fd,{now_ms:Lu,details:T}))},[gs,ye,fd,Lu]),co=String((ye==null?void 0:ye.status)||(Cn==null?void 0:Cn.status)||"").trim(),lh=String(Ws||((hh=ye==null?void 0:ye.waiting)==null?void 0:hh.reason)||(Cn==null?void 0:Cn.waiting_reason)||"").trim().toLowerCase(),Qr=!!(ye!=null&&ye.is_scheduled||Cn!=null&&Cn.is_scheduled),Tn=!!(ye!=null&&ye.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(ye),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=S4(sa),Q=Nl.length?Nl.join(","):"",Z=N4(Ro),ee=Math.max(0,Zi)*$p,ae=await Ke.search_artifacts({scope:b,session_id:T||void 0,run_id:F||void 0,query:Yi||void 0,artifact_kind:Q||void 0,created_after:U||void 0,include_stats:!0,limit:$p,offset:ee,order_by:Z.order_by,order:Z.order}),Ge=[],be=new Set;for(const gt of Array.isArray(ae==null?void 0:ae.items)?ae.items:[]){const dt=b4(gt,"search");!dt||be.has(dt.artifact_id)||(be.add(dt.artifact_id),Ge.push(dt))}const pe=ae!=null&&ae.stats&&typeof ae.stats=="object"?ae.stats:{},Fe=Number((pe==null?void 0:pe.total)??(ae==null?void 0:ae.total)??Ge.length),Pe=G0(ae);let it=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:Z.order_by,order:Z.order});it=G0(gt)}catch{it=Pe}Fu(Number.isFinite(Fe)?Math.max(0,Fe):Ge.length),zu(Number((pe==null?void 0:pe.total_bytes)??(pe==null?void 0:pe.byte_total)??0)||0),Xm(Pe),Qm(it),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((Z,ee)=>({cursor:ee+1,record:Z})));const Q=typeof F.next_after=="number"?Number(F.next_after):U.length;Ml(`${U.length.toLocaleString()} record${U.length===1?"":"s"}${Q>=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[...mn,...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(ye==null?void 0:ye.workflow_id)=="string"?String(ye.workflow_id):null,status:typeof(ye==null?void 0:ye.status)=="string"?String(ye.status):"",created_at:typeof(ye==null?void 0:ye.created_at)=="string"?String(ye.created_at):null,updated_at:typeof(ye==null?void 0:ye.updated_at)=="string"?String(ye.updated_at):null,ledger_len:fn.length||null,parent_run_id:typeof(ye==null?void 0:ye.parent_run_id)=="string"?String(ye.parent_run_id):null,session_id:typeof(ye==null?void 0:ye.session_id)=="string"?String(ye.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,mn,l,ye,fn.length,Co,oa]),qc=p.useMemo(()=>iD(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):k4(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,Q;if(Mo==="time"){const Z=Vt((U=T.items[0])==null?void 0:U.created_at)??0,ee=Vt((Q=F.items[0])==null?void 0:Q.created_at)??0;if(Z!==ee)return ee-Z}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||(ne(T),Te(F),ue(!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(tD,{connected:L,request:Yu,value:ro,onChange:b=>Qn("workspace",b===null?void 0:b),disabled:Be||Rt}),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 Q;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&&((Q=b.reasons)!=null&&Q.length)?`blocked: ${b.reasons.join("; ")}`:""].filter(Boolean).join(`
|
|
175
|
+
`),children:[s.jsx("input",{type:"checkbox",checked:T,disabled:F||Be||Rt||tt,onChange:Z=>{const ee=Z.target.checked?Array.from(new Set([...fi,b.name])):fi.filter(ae=>ae!==b.name);Qn("skills",ee.length?ee: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||Rt}),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||Rt,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||Rt,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(B2,{docs:{open:jt,onToggle:()=>st(b=>!b),label:"Docs assistant"},appearance:{onOpen:()=>yt(!0)},about:{identity:Bf,versions:Uf,onOpen:di},connection:{phase:H.phase,signingOut:H.signingOut,onConnect:()=>H.openModal(),onDisconnect:()=>mi()}})]})]}),s.jsx(n2,{...H.modalProps}),s.jsx(oS,{open:Et,onClose:()=>yt(!1),value:pt,onChange:at}),s.jsx(DI,{open:jt,onClose:()=>st(!1),connected:L,topOffset:44,gateway:Ke}),s.jsxs("div",{className:"app-body shell_content",children:[e==="board"?L?s.jsx(lq,{gateway_connected:L,runs:mn,all_runs:On,runs_refreshed_at:Me,runs_stale:Yg,notice:gf,entities:ie,entities_total:$e,entities_error:We,on_open_run:b=>{t("observe"),No("agent"),Ri(b)},on_resume_wait:Kf,on_open_automation:b=>{Ee(!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=E9(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.",A?` Last attempt: ${A}`:""]}),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]})]}),A?s.jsx("div",{className:"warn_callout",children:A}):null,s.jsx("div",{className:"settings_row",children:s.jsx(zP,{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(BP,{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(Q=>Q!==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(X3,{gateway:L?Ke:null,connected:L,defaults:Jf,value:Rc,onChange:c_})})]})]})}):null,s.jsx(tc,{open:xe,title:ke==="automate"?"New automation":"Run once",variant:"fullscreen",onClose:()=>Ee(!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(k3,{mode:ke,automate_available:X.available,automate_reason:X.reason,on_change:le}),ke==="automate"&&!X.available&&L?s.jsx("div",{className:"warn_callout",role:"note",children:X.reason}):null,ke==="automate"&&ge.length?s.jsx("div",{className:"help_text",role:"note",children:ge.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."]}),ke==="automate"?s.jsx("div",{className:"section_title",children:"What"}):null,s.jsx("div",{className:"launch_workflow_bar",children:s.jsx(sN,{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=UO(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,I?s.jsx("div",{className:"help_text muted",style:{fontSize:"var(--font-size-sm)"},children:"Loading flow…"}):null,G?s.jsx("div",{className:"mono",style:{color:"rgba(239, 68, 68, 0.9)",fontSize:"var(--font-size-sm)"},children:G}):null]}),s.jsx("div",{className:"section_divider"}),s.jsx("div",{className:"section_title",children:"Inputs"}),jr?rn===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:on()})]}),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||Rt,T=[],F=[];for(const Z of Xr){if(!Z||typeof Z!="object")continue;const ee=String(Z.id||"").trim();if(!ee||ke==="automate"&&n1.includes(ee)||ke==="automate"&&s1.includes(ee))continue;const ae=String(Z.type||"").trim().toLowerCase();ae==="tools"||ae==="skills"||ae==="mcp"||ae==="mcp_servers"||ee==="skills"||ee==="mcp"||ee==="mcp_servers"||ae==="array"||Wa(ae)||ee==="prompt"||ee==="system"?T.push(Z):F.push(Z)}const U=Z=>String(Z||"").trim().replace(/_/g," ").replace(/\b\w/g,ee=>ee.toUpperCase()),Q=(Z,ee)=>{const ae=String(Z.id||"").trim();if(!ae)return null;const Ge=String(Z.label||ae).trim()||ae,be=Ge===ae?U(ae):Ge,pe=String(Z.type||"").trim().toLowerCase(),Fe=Object.prototype.hasOwnProperty.call(Z,"default"),Pe=Fe?Z.default:void 0,it=Fe?typeof Pe=="string"?Pe:Br(Pe,80):"",gt=rn==null?void 0:rn[ae],dt=Fe?`${it}`:"";if(pe==="tools"){if(ke==="automate"&&ae==="tools")return null;const ht=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,...ht,...en])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx(Hw,{options:Yn,value:ht,disabled:b,placeholder:"(no tools selected)",onChange:ds=>Qn(ae,ds)})]},ae)}if(pe==="skills"||ae==="skills")return null;if(pe==="mcp"||pe==="mcp_servers"||ae==="mcp"||ae==="mcp_servers"){const ht=Array.isArray(gt)?gt.map(ds=>String(ds||"").trim()).filter(Boolean):[];if(ve===null&&!ht.length)return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("div",{className:"help_text muted",children:"This gateway does not serve an MCP server inventory yet — MCP selection lights up here when it ships."})]},ae);const en=(ve||[]).map(ds=>ds.name),Yn=Array.from(new Set([...en,...ht])).sort();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx(Hw,{options:Yn,value:ht,disabled:b,placeholder:"(no MCP servers selected)",onChange:ds=>Qn(ae,ds)})]},ae)}if(pe==="provider"||pe==="provider_text"){const ht=typeof gt=="string"?String(gt):"";return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsxs("select",{value:ht,onChange:en=>Qn(ae,en.target.value),disabled:b,children:[s.jsx("option",{value:"",children:dt||"(select)"}),ps.map(en=>s.jsx("option",{value:en,children:en},en))]})]},ae)}if(pe==="model"||pe==="model_text"){const ht=typeof gt=="string"?String(gt):"",en=String((rn==null?void 0:rn.provider)||"").trim(),Yn=en?hn[en]:void 0,ds=Yn&&Array.isArray(Yn.models)?Yn.models.map(dr=>String(dr||"").trim()).filter(Boolean):[];return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),ds.length?s.jsxs("select",{value:ht,onChange:dr=>Qn(ae,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:ht,onChange:dr=>Qn(ae,dr.target.value),placeholder:dt||"model id",disabled:b})]},ae)}if(pe==="boolean"){const ht=typeof gt=="boolean"?gt?"true":"false":"";return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsxs("select",{value:ht,onChange:en=>{const Yn=String(en.target.value||"").trim();Yn?Qn(ae,Yn==="true"):Qn(ae,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"})]})]},ae)}if(pe==="number"){const ht=typeof gt=="number"&&Number.isFinite(gt)?String(gt):"";return s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("input",{type:"number",value:ht,onChange:en=>{const Yn=String(en.target.value||"").trim();if(!Yn){Qn(ae,void 0);return}const ds=Number(Yn);Number.isFinite(ds)&&Qn(ae,ds)},placeholder:dt,disabled:b})]},ae)}if(pe==="array"){const ht=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:be}),s.jsx("textarea",{className:"mono",value:ht,onChange:en=>{const Yn=String(en.target.value||"").split(/\r?\n/g).map(ds=>String(ds||"").trim()).filter(Boolean);Qn(ae,Yn.length?Yn:void 0)},placeholder:dt||"(one item per line)",rows:2,disabled:b})]},ae)}if(Wa(pe)){const ht=typeof dc[ae]=="string"?dc[ae]:"",en=String(js[ae]||"").trim();return s.jsxs("div",{className:"launch_field_wide",children:[s.jsxs("label",{className:"launch_label",children:[be," ",s.jsx("span",{className:"launch_label_type",children:pe})]}),s.jsx("textarea",{className:"mono",value:ht,onChange:Yn=>{const ds=String(Yn.target.value??"");ul(wi=>({...wi,[ae]:ds}));const dr=ds.trim();if(!dr){pr(wi=>{const vi={...wi};return delete vi[ae],vi}),Qn(ae,void 0);return}try{const wi=JSON.parse(dr);pr(vi=>{const Vl={...vi};return delete Vl[ae],Vl}),Qn(ae,wi)}catch(wi){pr(vi=>({...vi,[ae]: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]},ae)}const xn=typeof gt=="string"?String(gt):"";return ae==="prompt"||ae==="system"?s.jsxs("div",{className:"launch_field_wide",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("textarea",{value:xn,onChange:ht=>Qn(ae,ht.target.value),placeholder:dt||(ae==="prompt"?"What should the agent do?":"System instructions (optional)"),rows:3,disabled:b})]},ae):s.jsxs("div",{className:ee||"launch_field",children:[s.jsx("label",{className:"launch_label",children:be}),s.jsx("input",{value:xn,onChange:ht=>Qn(ae,ht.target.value),placeholder:dt,disabled:b})]},ae)};return T.sort((Z,ee)=>{const ae={system:0,prompt:1,tools:2};return(ae[String(Z.id||"")]??10)-(ae[String(ee.id||"")]??10)}),s.jsxs(s.Fragment,{children:[T.map(Z=>Q(Z)),F.length>0?s.jsx("div",{className:"launch_grid",children:F.map(Z=>Q(Z,"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||Rt})]}),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||Rt})]})}),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||Rt})]})})]})]}):s.jsx("div",{className:"help_text muted",style:{marginTop:"8px"},children:"Choose a flow above to set its inputs."}),ke==="automate"?s.jsxs(s.Fragment,{children:[s.jsx(j3,{form:He,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:wS(rn||{})??void 0,available_tools:Ec,on_tools_change:b=>S(JSON.stringify(vS(rn||{},b),null,2)),disabled:tt,on_change:b=>ft(T=>({...T,...b})),workspaces:Wo}),s.jsx(S3,{form:He,disabled:tt,on_change:b=>ft(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,ke==="automate"&&et.length?s.jsx("ul",{className:"automate_errors",role:"alert",children:et.map(b=>s.jsx("li",{children:b},b))}):null,ke==="automate"&&Ne?s.jsxs("div",{className:"observe_context_card error",role:"alert","data-code":Ne.code,style:{marginBottom:"10px"},children:[s.jsx("span",{className:"chip mono danger",children:Ne.code}),s.jsxs("span",{children:[s.jsx("strong",{children:Gp(Ne).title})," ",Gp(Ne).detail,Ne.field?s.jsxs("span",{className:"mono",children:[" (",Ne.field,")"]}):null]})]}):null,s.jsx("div",{className:"launch_actions_bar launch_actions_stack",children:(()=>{const b=ke==="automate",T=L?jr?rn===null?"Inputs contain invalid JSON":b&&!X.available?"Automations unavailable on this gateway":Be||Rt?"Attaching to a run…":V||I?"Loading…":tt?"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?tt?"Creating…":"Create automation":Be?"Launching…":"Launch now"}),T&&!tt&&!Be?s.jsx("span",{className:"mono muted launch_disabled_reason",children:T}):null]})})()})]})})})}),e==="automations"?s.jsx(FP,{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:X,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:on(),kind:"info",title:"Discussion started",preview:tn(T),data:b})}}}):null,e==="runtime"?s.jsx(K4,{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(jU,{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(Y4,{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:XI(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(WP,{active:!xs,unavailableReason:ay,busy:Be||Rt,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_}),St?s.jsx("button",{className:"btn primary",onClick:()=>void eh(),disabled:Be||Rt||pi||xs,children:"Run now"}):null,s.jsx("button",{className:"btn danger",onClick:()=>{Vr("cancel"),Hr(""),Ci(""),qr(!0)},disabled:Be||Rt||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(l2,{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:on(),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"&&(fn.length>0||nn.length>0)?s.jsx("div",{className:"tab_bar_controls",children:s.jsx("button",{className:"seg_action",disabled:!fn.length&&!nn.length,title:"Copy full ledger as JSONL",onClick:()=>{const F=[...fn.map(Z=>({run_id:l.trim()||Z.record.run_id||"",cursor:Z.cursor,record:Z.record})),...nn.map(Z=>({run_id:Z.run_id,cursor:Z.cursor,record:Z.record}))].map(Z=>{var Ge,be;const ee=String(((Ge=Z.record)==null?void 0:Ge.ended_at)||((be=Z.record)==null?void 0:be.started_at)||"").trim(),ae=Vt(ee);return{...Z,_ms:ae??0}});F.sort((Z,ee)=>(Z._ms||0)-(ee._ms||0));const Q=(F.length>5e3?F.slice(F.length-5e3):F).map(({_ms:Z,...ee})=>JSON.stringify(ee)).join(`
|
|
177
|
+
`);Pr(Q)},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(Iq,{run:gs,detail:ye,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:AC(typeof localStorage>"u"?null:localStorage),loading:{detail:Be&&!ye,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(IO,{status:ys||co||"unknown",duration:Cn?yu(Cn):"",facts:kO(bO(Ii)),error:im(Cn)||String((ye==null?void 0:ye.error)||"").trim(),answer:ah||String((lo==null?void 0:lo.text)||"").trim(),waiting_for_user:!!(un!=null&&un.wait_key)&&String((un==null?void 0:un.reason)||"")==="user",on_answer_wait:()=>li(""),workspace_root:Hm,on_reveal_workspace:()=>void Dl(),speak:L?s.jsx(sP,{voice:oo,speak_key:`outcome:${l.trim()}`,text:im(Cn)||String((ye==null?void 0:ye.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(LO,{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:on()})]}),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(QD,{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(""),mt(""),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:on()})]}),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:on()})]}),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(GI,{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:Ie,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(g1,{voice:oo,defaults:Jf.value,prefs:Rc,blocked:L?Bt?"Wait for the answer.":null:"Connect to the gateway first."})}),d1()?null:s.jsx("div",{className:"mono muted","data-testid":"voice-https-hint",style:{fontSize:"var(--font-size-sm)",marginTop:"6px"},children:c1})]})]}):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(I1,{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:on()})]}),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(VP,{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:on()})]}),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||Rt,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||Rt,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:on()})]}),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:Rt,children:"Dismiss"}),aa.length?s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"btn danger",disabled:Rt,onClick:()=>Pc({approved:!1}),children:"Reject"}),s.jsx("button",{className:"btn",disabled:Rt,onClick:()=>Pc({approved:!0}),children:"Approve only"}),s.jsx("button",{className:"btn primary",disabled:!so||Rt,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"}),$1(b).map(F=>s.jsxs("span",{className:"chip mono muted",title:N1,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()||Rt,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:un||{},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(J4,{wait:un,disabled:Rt,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()||Rt,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:un||{},collapseAfterDepth:3,showCopy:!0})})]})]})]}):null]})]})]})}if("serviceWorker"in navigator){window.addEventListener("load",()=>{navigator.serviceWorker.register(JI).then(t=>t.update()).catch(()=>{})});let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,window.location.reload())})}kE();gE.createRoot(document.getElementById("root")).render(s.jsx(Ce.StrictMode,{children:s.jsx(Wq,{})}));
|
|
178
|
+
//# sourceMappingURL=index-DRRbcUk2.js.map
|