@abstractframework/code 0.10.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ var Bv=Object.defineProperty;var Wv=(e,t,n)=>t in e?Bv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Nn=(e,t,n)=>Wv(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 c of i)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(i){if(i.ep)return;i.ep=!0;const c=n(i);fetch(i.href,c)}})();function xg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _d={exports:{}},ri={},bd={exports:{}},Ke={};/**
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 Gm;function Vv(){if(Gm)return Ke;Gm=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"),c=Symbol.for("react.provider"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),v=Symbol.iterator;function _(P){return P===null||typeof P!="object"?null:(P=v&&P[v]||P["@@iterator"],typeof P=="function"?P:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,x={};function j(P,B,W){this.props=P,this.context=B,this.refs=x,this.updater=W||b}j.prototype.isReactComponent={},j.prototype.setState=function(P,B){if(typeof P!="object"&&typeof P!="function"&&P!=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,P,B,"setState")},j.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function N(){}N.prototype=j.prototype;function $(P,B,W){this.props=P,this.context=B,this.refs=x,this.updater=W||b}var S=$.prototype=new N;S.constructor=$,C(S,j.prototype),S.isPureReactComponent=!0;var E=Array.isArray,A=Object.prototype.hasOwnProperty,I={current:null},F={key:!0,ref:!0,__self:!0,__source:!0};function L(P,B,W){var de,ee={},le=null,fe=null;if(B!=null)for(de in B.ref!==void 0&&(fe=B.ref),B.key!==void 0&&(le=""+B.key),B)A.call(B,de)&&!F.hasOwnProperty(de)&&(ee[de]=B[de]);var oe=arguments.length-2;if(oe===1)ee.children=W;else if(1<oe){for(var we=Array(oe),Oe=0;Oe<oe;Oe++)we[Oe]=arguments[Oe+2];ee.children=we}if(P&&P.defaultProps)for(de in oe=P.defaultProps,oe)ee[de]===void 0&&(ee[de]=oe[de]);return{$$typeof:e,type:P,key:le,ref:fe,props:ee,_owner:I.current}}function J(P,B){return{$$typeof:e,type:P.type,key:B,ref:P.ref,props:P.props,_owner:P._owner}}function V(P){return typeof P=="object"&&P!==null&&P.$$typeof===e}function O(P){var B={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(W){return B[W]})}var Z=/\/+/g;function R(P,B){return typeof P=="object"&&P!==null&&P.key!=null?O(""+P.key):B.toString(36)}function q(P,B,W,de,ee){var le=typeof P;(le==="undefined"||le==="boolean")&&(P=null);var fe=!1;if(P===null)fe=!0;else switch(le){case"string":case"number":fe=!0;break;case"object":switch(P.$$typeof){case e:case t:fe=!0}}if(fe)return fe=P,ee=ee(fe),P=de===""?"."+R(fe,0):de,E(ee)?(W="",P!=null&&(W=P.replace(Z,"$&/")+"/"),q(ee,B,W,"",function(Oe){return Oe})):ee!=null&&(V(ee)&&(ee=J(ee,W+(!ee.key||fe&&fe.key===ee.key?"":(""+ee.key).replace(Z,"$&/")+"/")+P)),B.push(ee)),1;if(fe=0,de=de===""?".":de+":",E(P))for(var oe=0;oe<P.length;oe++){le=P[oe];var we=de+R(le,oe);fe+=q(le,B,W,we,ee)}else if(we=_(P),typeof we=="function")for(P=we.call(P),oe=0;!(le=P.next()).done;)le=le.value,we=de+R(le,oe++),fe+=q(le,B,W,we,ee);else if(le==="object")throw B=String(P),Error("Objects are not valid as a React child (found: "+(B==="[object Object]"?"object with keys {"+Object.keys(P).join(", ")+"}":B)+"). If you meant to render a collection of children, use an array instead.");return fe}function z(P,B,W){if(P==null)return P;var de=[],ee=0;return q(P,de,"","",function(le){return B.call(W,le,ee++)}),de}function se(P){if(P._status===-1){var B=P._result;B=B(),B.then(function(W){(P._status===0||P._status===-1)&&(P._status=1,P._result=W)},function(W){(P._status===0||P._status===-1)&&(P._status=2,P._result=W)}),P._status===-1&&(P._status=0,P._result=B)}if(P._status===1)return P._result.default;throw P._result}var G={current:null},te={transition:null},ue={ReactCurrentDispatcher:G,ReactCurrentBatchConfig:te,ReactCurrentOwner:I};function ne(){throw Error("act(...) is not supported in production builds of React.")}return Ke.Children={map:z,forEach:function(P,B,W){z(P,function(){B.apply(this,arguments)},W)},count:function(P){var B=0;return z(P,function(){B++}),B},toArray:function(P){return z(P,function(B){return B})||[]},only:function(P){if(!V(P))throw Error("React.Children.only expected to receive a single React element child.");return P}},Ke.Component=j,Ke.Fragment=n,Ke.Profiler=i,Ke.PureComponent=$,Ke.StrictMode=r,Ke.Suspense=h,Ke.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ue,Ke.act=ne,Ke.cloneElement=function(P,B,W){if(P==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+P+".");var de=C({},P.props),ee=P.key,le=P.ref,fe=P._owner;if(B!=null){if(B.ref!==void 0&&(le=B.ref,fe=I.current),B.key!==void 0&&(ee=""+B.key),P.type&&P.type.defaultProps)var oe=P.type.defaultProps;for(we in B)A.call(B,we)&&!F.hasOwnProperty(we)&&(de[we]=B[we]===void 0&&oe!==void 0?oe[we]:B[we])}var we=arguments.length-2;if(we===1)de.children=W;else if(1<we){oe=Array(we);for(var Oe=0;Oe<we;Oe++)oe[Oe]=arguments[Oe+2];de.children=oe}return{$$typeof:e,type:P.type,key:ee,ref:le,props:de,_owner:fe}},Ke.createContext=function(P){return P={$$typeof:u,_currentValue:P,_currentValue2:P,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},P.Provider={$$typeof:c,_context:P},P.Consumer=P},Ke.createElement=L,Ke.createFactory=function(P){var B=L.bind(null,P);return B.type=P,B},Ke.createRef=function(){return{current:null}},Ke.forwardRef=function(P){return{$$typeof:d,render:P}},Ke.isValidElement=V,Ke.lazy=function(P){return{$$typeof:p,_payload:{_status:-1,_result:P},_init:se}},Ke.memo=function(P,B){return{$$typeof:m,type:P,compare:B===void 0?null:B}},Ke.startTransition=function(P){var B=te.transition;te.transition={};try{P()}finally{te.transition=B}},Ke.unstable_act=ne,Ke.useCallback=function(P,B){return G.current.useCallback(P,B)},Ke.useContext=function(P){return G.current.useContext(P)},Ke.useDebugValue=function(){},Ke.useDeferredValue=function(P){return G.current.useDeferredValue(P)},Ke.useEffect=function(P,B){return G.current.useEffect(P,B)},Ke.useId=function(){return G.current.useId()},Ke.useImperativeHandle=function(P,B,W){return G.current.useImperativeHandle(P,B,W)},Ke.useInsertionEffect=function(P,B){return G.current.useInsertionEffect(P,B)},Ke.useLayoutEffect=function(P,B){return G.current.useLayoutEffect(P,B)},Ke.useMemo=function(P,B){return G.current.useMemo(P,B)},Ke.useReducer=function(P,B,W){return G.current.useReducer(P,B,W)},Ke.useRef=function(P){return G.current.useRef(P)},Ke.useState=function(P){return G.current.useState(P)},Ke.useSyncExternalStore=function(P,B,W){return G.current.useSyncExternalStore(P,B,W)},Ke.useTransition=function(){return G.current.useTransition()},Ke.version="18.3.1",Ke}var Hm;function bf(){return Hm||(Hm=1,bd.exports=Vv()),bd.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 Km;function Gv(){if(Km)return ri;Km=1;var e=bf(),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,c={key:!0,ref:!0,__self:!0,__source:!0};function u(d,h,m){var p,v={},_=null,b=null;m!==void 0&&(_=""+m),h.key!==void 0&&(_=""+h.key),h.ref!==void 0&&(b=h.ref);for(p in h)r.call(h,p)&&!c.hasOwnProperty(p)&&(v[p]=h[p]);if(d&&d.defaultProps)for(p in h=d.defaultProps,h)v[p]===void 0&&(v[p]=h[p]);return{$$typeof:t,type:d,key:_,ref:b,props:v,_owner:i.current}}return ri.Fragment=n,ri.jsx=u,ri.jsxs=u,ri}var Jm;function Hv(){return Jm||(Jm=1,_d.exports=Gv()),_d.exports}var o=Hv(),y=bf();const ct=xg(y);var ec={},xd={exports:{}},mn={},kd={exports:{}},jd={};/**
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 Qm;function Kv(){return Qm||(Qm=1,(function(e){function t(te,ue){var ne=te.length;te.push(ue);e:for(;0<ne;){var P=ne-1>>>1,B=te[P];if(0<i(B,ue))te[P]=ue,te[ne]=B,ne=P;else break e}}function n(te){return te.length===0?null:te[0]}function r(te){if(te.length===0)return null;var ue=te[0],ne=te.pop();if(ne!==ue){te[0]=ne;e:for(var P=0,B=te.length,W=B>>>1;P<W;){var de=2*(P+1)-1,ee=te[de],le=de+1,fe=te[le];if(0>i(ee,ne))le<B&&0>i(fe,ee)?(te[P]=fe,te[le]=ne,P=le):(te[P]=ee,te[de]=ne,P=de);else if(le<B&&0>i(fe,ne))te[P]=fe,te[le]=ne,P=le;else break e}}return ue}function i(te,ue){var ne=te.sortIndex-ue.sortIndex;return ne!==0?ne:te.id-ue.id}if(typeof performance=="object"&&typeof performance.now=="function"){var c=performance;e.unstable_now=function(){return c.now()}}else{var u=Date,d=u.now();e.unstable_now=function(){return u.now()-d}}var h=[],m=[],p=1,v=null,_=3,b=!1,C=!1,x=!1,j=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 S(te){for(var ue=n(m);ue!==null;){if(ue.callback===null)r(m);else if(ue.startTime<=te)r(m),ue.sortIndex=ue.expirationTime,t(h,ue);else break;ue=n(m)}}function E(te){if(x=!1,S(te),!C)if(n(h)!==null)C=!0,se(A);else{var ue=n(m);ue!==null&&G(E,ue.startTime-te)}}function A(te,ue){C=!1,x&&(x=!1,N(L),L=-1),b=!0;var ne=_;try{for(S(ue),v=n(h);v!==null&&(!(v.expirationTime>ue)||te&&!O());){var P=v.callback;if(typeof P=="function"){v.callback=null,_=v.priorityLevel;var B=P(v.expirationTime<=ue);ue=e.unstable_now(),typeof B=="function"?v.callback=B:v===n(h)&&r(h),S(ue)}else r(h);v=n(h)}if(v!==null)var W=!0;else{var de=n(m);de!==null&&G(E,de.startTime-ue),W=!1}return W}finally{v=null,_=ne,b=!1}}var I=!1,F=null,L=-1,J=5,V=-1;function O(){return!(e.unstable_now()-V<J)}function Z(){if(F!==null){var te=e.unstable_now();V=te;var ue=!0;try{ue=F(!0,te)}finally{ue?R():(I=!1,F=null)}}else I=!1}var R;if(typeof $=="function")R=function(){$(Z)};else if(typeof MessageChannel<"u"){var q=new MessageChannel,z=q.port2;q.port1.onmessage=Z,R=function(){z.postMessage(null)}}else R=function(){j(Z,0)};function se(te){F=te,I||(I=!0,R())}function G(te,ue){L=j(function(){te(e.unstable_now())},ue)}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(te){te.callback=null},e.unstable_continueExecution=function(){C||b||(C=!0,se(A))},e.unstable_forceFrameRate=function(te){0>te||125<te?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):J=0<te?Math.floor(1e3/te):5},e.unstable_getCurrentPriorityLevel=function(){return _},e.unstable_getFirstCallbackNode=function(){return n(h)},e.unstable_next=function(te){switch(_){case 1:case 2:case 3:var ue=3;break;default:ue=_}var ne=_;_=ue;try{return te()}finally{_=ne}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(te,ue){switch(te){case 1:case 2:case 3:case 4:case 5:break;default:te=3}var ne=_;_=te;try{return ue()}finally{_=ne}},e.unstable_scheduleCallback=function(te,ue,ne){var P=e.unstable_now();switch(typeof ne=="object"&&ne!==null?(ne=ne.delay,ne=typeof ne=="number"&&0<ne?P+ne:P):ne=P,te){case 1:var B=-1;break;case 2:B=250;break;case 5:B=1073741823;break;case 4:B=1e4;break;default:B=5e3}return B=ne+B,te={id:p++,callback:ue,priorityLevel:te,startTime:ne,expirationTime:B,sortIndex:-1},ne>P?(te.sortIndex=ne,t(m,te),n(h)===null&&te===n(m)&&(x?(N(L),L=-1):x=!0,G(E,ne-P))):(te.sortIndex=B,t(h,te),C||b||(C=!0,se(A))),te},e.unstable_shouldYield=O,e.unstable_wrapCallback=function(te){var ue=_;return function(){var ne=_;_=ue;try{return te.apply(this,arguments)}finally{_=ne}}}})(jd)),jd}var Ym;function Jv(){return Ym||(Ym=1,kd.exports=Kv()),kd.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 Xm;function Qv(){if(Xm)return mn;Xm=1;var e=bf(),t=Jv();function n(s){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+s,l=1;l<arguments.length;l++)a+="&args[]="+encodeURIComponent(arguments[l]);return"Minified React error #"+s+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=new Set,i={};function c(s,a){u(s,a),u(s+"Capture",a)}function u(s,a){for(i[s]=a,s=0;s<a.length;s++)r.add(a[s])}var d=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),h=Object.prototype.hasOwnProperty,m=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p={},v={};function _(s){return h.call(v,s)?!0:h.call(p,s)?!1:m.test(s)?v[s]=!0:(p[s]=!0,!1)}function b(s,a,l,f){if(l!==null&&l.type===0)return!1;switch(typeof a){case"function":case"symbol":return!0;case"boolean":return f?!1:l!==null?!l.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function C(s,a,l,f){if(a===null||typeof a>"u"||b(s,a,l,f))return!0;if(f)return!1;if(l!==null)switch(l.type){case 3:return!a;case 4:return a===!1;case 5:return isNaN(a);case 6:return isNaN(a)||1>a}return!1}function x(s,a,l,f,g,w,k){this.acceptsBooleans=a===2||a===3||a===4,this.attributeName=f,this.attributeNamespace=g,this.mustUseProperty=l,this.propertyName=s,this.type=a,this.sanitizeURL=w,this.removeEmptyString=k}var j={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){j[s]=new x(s,0,!1,s,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var a=s[0];j[a]=new x(a,1,!1,s[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(s){j[s]=new x(s,2,!1,s.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){j[s]=new x(s,2,!1,s,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(s){j[s]=new x(s,3,!1,s.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(s){j[s]=new x(s,3,!0,s,null,!1,!1)}),["capture","download"].forEach(function(s){j[s]=new x(s,4,!1,s,null,!1,!1)}),["cols","rows","size","span"].forEach(function(s){j[s]=new x(s,6,!1,s,null,!1,!1)}),["rowSpan","start"].forEach(function(s){j[s]=new x(s,5,!1,s.toLowerCase(),null,!1,!1)});var N=/[\-:]([a-z])/g;function $(s){return s[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(s){var a=s.replace(N,$);j[a]=new x(a,1,!1,s,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(s){var a=s.replace(N,$);j[a]=new x(a,1,!1,s,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(s){var a=s.replace(N,$);j[a]=new x(a,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(s){j[s]=new x(s,1,!1,s.toLowerCase(),null,!1,!1)}),j.xlinkHref=new x("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(s){j[s]=new x(s,1,!1,s.toLowerCase(),null,!0,!0)});function S(s,a,l,f){var g=j.hasOwnProperty(a)?j[a]:null;(g!==null?g.type!==0:f||!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(C(a,l,g,f)&&(l=null),f||g===null?_(a)&&(l===null?s.removeAttribute(a):s.setAttribute(a,""+l)):g.mustUseProperty?s[g.propertyName]=l===null?g.type===3?!1:"":l:(a=g.attributeName,f=g.attributeNamespace,l===null?s.removeAttribute(a):(g=g.type,l=g===3||g===4&&l===!0?"":""+l,f?s.setAttributeNS(f,a,l):s.setAttribute(a,l))))}var E=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,A=Symbol.for("react.element"),I=Symbol.for("react.portal"),F=Symbol.for("react.fragment"),L=Symbol.for("react.strict_mode"),J=Symbol.for("react.profiler"),V=Symbol.for("react.provider"),O=Symbol.for("react.context"),Z=Symbol.for("react.forward_ref"),R=Symbol.for("react.suspense"),q=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),se=Symbol.for("react.lazy"),G=Symbol.for("react.offscreen"),te=Symbol.iterator;function ue(s){return s===null||typeof s!="object"?null:(s=te&&s[te]||s["@@iterator"],typeof s=="function"?s:null)}var ne=Object.assign,P;function B(s){if(P===void 0)try{throw Error()}catch(l){var a=l.stack.trim().match(/\n( *(at )?)/);P=a&&a[1]||""}return`
34
+ `+P+s}var W=!1;function de(s,a){if(!s||W)return"";W=!0;var l=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a)if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(a,[])}catch(Y){var f=Y}Reflect.construct(s,[],a)}else{try{a.call()}catch(Y){f=Y}s.call(a.prototype)}else{try{throw Error()}catch(Y){f=Y}s()}}catch(Y){if(Y&&f&&typeof Y.stack=="string"){for(var g=Y.stack.split(`
35
+ `),w=f.stack.split(`
36
+ `),k=g.length-1,M=w.length-1;1<=k&&0<=M&&g[k]!==w[M];)M--;for(;1<=k&&0<=M;k--,M--)if(g[k]!==w[M]){if(k!==1||M!==1)do if(k--,M--,0>M||g[k]!==w[M]){var D=`
37
+ `+g[k].replace(" at new "," at ");return s.displayName&&D.includes("<anonymous>")&&(D=D.replace("<anonymous>",s.displayName)),D}while(1<=k&&0<=M);break}}}finally{W=!1,Error.prepareStackTrace=l}return(s=s?s.displayName||s.name:"")?B(s):""}function ee(s){switch(s.tag){case 5:return B(s.type);case 16:return B("Lazy");case 13:return B("Suspense");case 19:return B("SuspenseList");case 0:case 2:case 15:return s=de(s.type,!1),s;case 11:return s=de(s.type.render,!1),s;case 1:return s=de(s.type,!0),s;default:return""}}function le(s){if(s==null)return null;if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case F:return"Fragment";case I:return"Portal";case J:return"Profiler";case L:return"StrictMode";case R:return"Suspense";case q:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case O:return(s.displayName||"Context")+".Consumer";case V:return(s._context.displayName||"Context")+".Provider";case Z:var a=s.render;return s=s.displayName,s||(s=a.displayName||a.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case z:return a=s.displayName||null,a!==null?a:le(s.type)||"Memo";case se:a=s._payload,s=s._init;try{return le(s(a))}catch{}}return null}function fe(s){var a=s.type;switch(s.tag){case 24:return"Cache";case 9:return(a.displayName||"Context")+".Consumer";case 10:return(a._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return s=a.render,s=s.displayName||s.name||"",a.displayName||(s!==""?"ForwardRef("+s+")":"ForwardRef");case 7:return"Fragment";case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return le(a);case 8:return a===L?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof a=="function")return a.displayName||a.name||null;if(typeof a=="string")return a}return null}function oe(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function we(s){var a=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Oe(s){var a=we(s)?"checked":"value",l=Object.getOwnPropertyDescriptor(s.constructor.prototype,a),f=""+s[a];if(!s.hasOwnProperty(a)&&typeof l<"u"&&typeof l.get=="function"&&typeof l.set=="function"){var g=l.get,w=l.set;return Object.defineProperty(s,a,{configurable:!0,get:function(){return g.call(this)},set:function(k){f=""+k,w.call(this,k)}}),Object.defineProperty(s,a,{enumerable:l.enumerable}),{getValue:function(){return f},setValue:function(k){f=""+k},stopTracking:function(){s._valueTracker=null,delete s[a]}}}}function Je(s){s._valueTracker||(s._valueTracker=Oe(s))}function st(s){if(!s)return!1;var a=s._valueTracker;if(!a)return!0;var l=a.getValue(),f="";return s&&(f=we(s)?s.checked?"true":"false":s.value),s=f,s!==l?(a.setValue(s),!0):!1}function Ce(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}function Ye(s,a){var l=a.checked;return ne({},a,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:l??s._wrapperState.initialChecked})}function he(s,a){var l=a.defaultValue==null?"":a.defaultValue,f=a.checked!=null?a.checked:a.defaultChecked;l=oe(a.value!=null?a.value:l),s._wrapperState={initialChecked:f,initialValue:l,controlled:a.type==="checkbox"||a.type==="radio"?a.checked!=null:a.value!=null}}function Ve(s,a){a=a.checked,a!=null&&S(s,"checked",a,!1)}function ae(s,a){Ve(s,a);var l=oe(a.value),f=a.type;if(l!=null)f==="number"?(l===0&&s.value===""||s.value!=l)&&(s.value=""+l):s.value!==""+l&&(s.value=""+l);else if(f==="submit"||f==="reset"){s.removeAttribute("value");return}a.hasOwnProperty("value")?ge(s,a.type,l):a.hasOwnProperty("defaultValue")&&ge(s,a.type,oe(a.defaultValue)),a.checked==null&&a.defaultChecked!=null&&(s.defaultChecked=!!a.defaultChecked)}function Te(s,a,l){if(a.hasOwnProperty("value")||a.hasOwnProperty("defaultValue")){var f=a.type;if(!(f!=="submit"&&f!=="reset"||a.value!==void 0&&a.value!==null))return;a=""+s._wrapperState.initialValue,l||a===s.value||(s.value=a),s.defaultValue=a}l=s.name,l!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,l!==""&&(s.name=l)}function ge(s,a,l){(a!=="number"||Ce(s.ownerDocument)!==s)&&(l==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+l&&(s.defaultValue=""+l))}var Q=Array.isArray;function pe(s,a,l,f){if(s=s.options,a){a={};for(var g=0;g<l.length;g++)a["$"+l[g]]=!0;for(l=0;l<s.length;l++)g=a.hasOwnProperty("$"+s[l].value),s[l].selected!==g&&(s[l].selected=g),g&&f&&(s[l].defaultSelected=!0)}else{for(l=""+oe(l),a=null,g=0;g<s.length;g++){if(s[g].value===l){s[g].selected=!0,f&&(s[g].defaultSelected=!0);return}a!==null||s[g].disabled||(a=s[g])}a!==null&&(a.selected=!0)}}function be(s,a){if(a.dangerouslySetInnerHTML!=null)throw Error(n(91));return ne({},a,{value:void 0,defaultValue:void 0,children:""+s._wrapperState.initialValue})}function Ee(s,a){var l=a.value;if(l==null){if(l=a.children,a=a.defaultValue,l!=null){if(a!=null)throw Error(n(92));if(Q(l)){if(1<l.length)throw Error(n(93));l=l[0]}a=l}a==null&&(a=""),l=a}s._wrapperState={initialValue:oe(l)}}function Pe(s,a){var l=oe(a.value),f=oe(a.defaultValue);l!=null&&(l=""+l,l!==s.value&&(s.value=l),a.defaultValue==null&&s.defaultValue!==l&&(s.defaultValue=l)),f!=null&&(s.defaultValue=""+f)}function We(s){var a=s.textContent;a===s._wrapperState.initialValue&&a!==""&&a!==null&&(s.value=a)}function Be(s){switch(s){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 bt(s,a){return s==null||s==="http://www.w3.org/1999/xhtml"?Be(a):s==="http://www.w3.org/2000/svg"&&a==="foreignObject"?"http://www.w3.org/1999/xhtml":s}var Nt,Vn=(function(s){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(a,l,f,g){MSApp.execUnsafeLocalFunction(function(){return s(a,l,f,g)})}:s})(function(s,a){if(s.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in s)s.innerHTML=a;else{for(Nt=Nt||document.createElement("div"),Nt.innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=Nt.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;a.firstChild;)s.appendChild(a.firstChild)}});function at(s,a){if(a){var l=s.firstChild;if(l&&l===s.lastChild&&l.nodeType===3){l.nodeValue=a;return}}s.textContent=a}var Js={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},is=["Webkit","ms","Moz","O"];Object.keys(Js).forEach(function(s){is.forEach(function(a){a=a+s.charAt(0).toUpperCase()+s.substring(1),Js[a]=Js[s]})});function go(s,a,l){return a==null||typeof a=="boolean"||a===""?"":l||typeof a!="number"||a===0||Js.hasOwnProperty(s)&&Js[s]?(""+a).trim():a+"px"}function _n(s,a){s=s.style;for(var l in a)if(a.hasOwnProperty(l)){var f=l.indexOf("--")===0,g=go(l,a[l],f);l==="float"&&(l="cssFloat"),f?s.setProperty(l,g):s[l]=g}}var Qs=ne({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function yo(s,a){if(a){if(Qs[s]&&(a.children!=null||a.dangerouslySetInnerHTML!=null))throw Error(n(137,s));if(a.dangerouslySetInnerHTML!=null){if(a.children!=null)throw Error(n(60));if(typeof a.dangerouslySetInnerHTML!="object"||!("__html"in a.dangerouslySetInnerHTML))throw Error(n(61))}if(a.style!=null&&typeof a.style!="object")throw Error(n(62))}}function ma(s,a){if(s.indexOf("-")===-1)return typeof a.is=="string";switch(s){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 Ys=null;function pa(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var ls=null,cs=null,Xs=null;function qs(s){if(s=Wo(s)){if(typeof ls!="function")throw Error(n(280));var a=s.stateNode;a&&(a=pl(a),ls(s.stateNode,s.type,a))}}function wo(s){cs?Xs?Xs.push(s):Xs=[s]:cs=s}function Fi(){if(cs){var s=cs,a=Xs;if(Xs=cs=null,qs(s),a)for(s=0;s<a.length;s++)qs(a[s])}}function ks(s,a){return s(a)}function Lt(){}var Lr=!1;function vo(s,a,l){if(Lr)return s(a,l);Lr=!0;try{return ks(s,a,l)}finally{Lr=!1,(cs!==null||Xs!==null)&&(Lt(),Fi())}}function Gn(s,a){var l=s.stateNode;if(l===null)return null;var f=pl(l);if(f===null)return null;l=f[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(f=!f.disabled)||(s=s.type,f=!(s==="button"||s==="input"||s==="select"||s==="textarea")),s=!f;break e;default:s=!1}if(s)return null;if(l&&typeof l!="function")throw Error(n(231,a,typeof l));return l}var ga=!1;if(d)try{var Zs={};Object.defineProperty(Zs,"passive",{get:function(){ga=!0}}),window.addEventListener("test",Zs,Zs),window.removeEventListener("test",Zs,Zs)}catch{ga=!1}function on(s,a,l,f,g,w,k,M,D){var Y=Array.prototype.slice.call(arguments,3);try{a.apply(l,Y)}catch(ce){this.onError(ce)}}var pt=!1,$t=null,Hn=!1,Or=null,zi={onError:function(s){pt=!0,$t=s}};function _o(s,a,l,f,g,w,k,M,D){pt=!1,$t=null,on.apply(zi,arguments)}function bo(s,a,l,f,g,w,k,M,D){if(_o.apply(this,arguments),pt){if(pt){var Y=$t;pt=!1,$t=null}else throw Error(n(198));Hn||(Hn=!0,Or=Y)}}function js(s){var a=s,l=s;if(s.alternate)for(;a.return;)a=a.return;else{s=a;do a=s,(a.flags&4098)!==0&&(l=a.return),s=a.return;while(s)}return a.tag===3?l:null}function xo(s){if(s.tag===13){var a=s.memoizedState;if(a===null&&(s=s.alternate,s!==null&&(a=s.memoizedState)),a!==null)return a.dehydrated}return null}function er(s){if(js(s)!==s)throw Error(n(188))}function Kc(s){var a=s.alternate;if(!a){if(a=js(s),a===null)throw Error(n(188));return a!==s?null:s}for(var l=s,f=a;;){var g=l.return;if(g===null)break;var w=g.alternate;if(w===null){if(f=g.return,f!==null){l=f;continue}break}if(g.child===w.child){for(w=g.child;w;){if(w===l)return er(g),s;if(w===f)return er(g),a;w=w.sibling}throw Error(n(188))}if(l.return!==f.return)l=g,f=w;else{for(var k=!1,M=g.child;M;){if(M===l){k=!0,l=g,f=w;break}if(M===f){k=!0,f=g,l=w;break}M=M.sibling}if(!k){for(M=w.child;M;){if(M===l){k=!0,l=w,f=g;break}if(M===f){k=!0,f=w,l=g;break}M=M.sibling}if(!k)throw Error(n(189))}}if(l.alternate!==f)throw Error(n(190))}if(l.tag!==3)throw Error(n(188));return l.stateNode.current===l?s:a}function us(s){return s=Kc(s),s!==null?Kn(s):null}function Kn(s){if(s.tag===5||s.tag===6)return s;for(s=s.child;s!==null;){var a=Kn(s);if(a!==null)return a;s=s.sibling}return null}var ya=t.unstable_scheduleCallback,$n=t.unstable_cancelCallback,Ui=t.unstable_shouldYield,ko=t.unstable_requestPaint,lt=t.unstable_now,jo=t.unstable_getCurrentPriorityLevel,So=t.unstable_ImmediatePriority,wa=t.unstable_UserBlockingPriority,Pr=t.unstable_NormalPriority,Bi=t.unstable_LowPriority,No=t.unstable_IdlePriority,va=null,An=null;function Ss(s){if(An&&typeof An.onCommitFiberRoot=="function")try{An.onCommitFiberRoot(va,s,void 0,(s.current.flags&128)===128)}catch{}}var De=Math.clz32?Math.clz32:ds,bn=Math.log,Co=Math.LN2;function ds(s){return s>>>=0,s===0?32:31-(bn(s)/Co|0)|0}var Ns=64,Cs=4194304;function ln(s){switch(s&-s){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 s&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return s&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return s}}function tr(s,a){var l=s.pendingLanes;if(l===0)return 0;var f=0,g=s.suspendedLanes,w=s.pingedLanes,k=l&268435455;if(k!==0){var M=k&~g;M!==0?f=ln(M):(w&=k,w!==0&&(f=ln(w)))}else k=l&~g,k!==0?f=ln(k):w!==0&&(f=ln(w));if(f===0)return 0;if(a!==0&&a!==f&&(a&g)===0&&(g=f&-f,w=a&-a,g>=w||g===16&&(w&4194240)!==0))return a;if((f&4)!==0&&(f|=l&16),a=s.entangledLanes,a!==0)for(s=s.entanglements,a&=f;0<a;)l=31-De(a),g=1<<l,f|=s[l],a&=~g;return f}function Wi(s,a){switch(s){case 1:case 2:case 4:return a+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Jn(s,a){for(var l=s.suspendedLanes,f=s.pingedLanes,g=s.expirationTimes,w=s.pendingLanes;0<w;){var k=31-De(w),M=1<<k,D=g[k];D===-1?((M&l)===0||(M&f)!==0)&&(g[k]=Wi(M,a)):D<=a&&(s.expiredLanes|=M),w&=~M}}function Qn(s){return s=s.pendingLanes&-1073741825,s!==0?s:s&1073741824?1073741824:0}function Es(){var s=Ns;return Ns<<=1,(Ns&4194240)===0&&(Ns=64),s}function Dr(s){for(var a=[],l=0;31>l;l++)a.push(s);return a}function nr(s,a,l){s.pendingLanes|=a,a!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,a=31-De(a),s[a]=l}function Tn(s,a){var l=s.pendingLanes&~a;s.pendingLanes=a,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=a,s.mutableReadLanes&=a,s.entangledLanes&=a,a=s.entanglements;var f=s.eventTimes;for(s=s.expirationTimes;0<l;){var g=31-De(l),w=1<<g;a[g]=0,f[g]=-1,s[g]=-1,l&=~w}}function _a(s,a){var l=s.entangledLanes|=a;for(s=s.entanglements;l;){var f=31-De(l),g=1<<f;g&a|s[f]&a&&(s[f]|=a),l&=~g}}var Ge=0;function Eo(s){return s&=-s,1<s?4<s?(s&268435455)!==0?16:536870912:4:1}var $s,As,Fr,Kt,zr,ba=!1,sr=[],Rn=null,Yn=null,fs=null,rr=new Map,ar=new Map,In=[],Ur="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 Ct(s,a){switch(s){case"focusin":case"focusout":Rn=null;break;case"dragenter":case"dragleave":Yn=null;break;case"mouseover":case"mouseout":fs=null;break;case"pointerover":case"pointerout":rr.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":ar.delete(a.pointerId)}}function Ts(s,a,l,f,g,w){return s===null||s.nativeEvent!==w?(s={blockedOn:a,domEventName:l,eventSystemFlags:f,nativeEvent:w,targetContainers:[g]},a!==null&&(a=Wo(a),a!==null&&As(a)),s):(s.eventSystemFlags|=f,a=s.targetContainers,g!==null&&a.indexOf(g)===-1&&a.push(g),s)}function Ut(s,a,l,f,g){switch(a){case"focusin":return Rn=Ts(Rn,s,a,l,f,g),!0;case"dragenter":return Yn=Ts(Yn,s,a,l,f,g),!0;case"mouseover":return fs=Ts(fs,s,a,l,f,g),!0;case"pointerover":var w=g.pointerId;return rr.set(w,Ts(rr.get(w)||null,s,a,l,f,g)),!0;case"gotpointercapture":return w=g.pointerId,ar.set(w,Ts(ar.get(w)||null,s,a,l,f,g)),!0}return!1}function xa(s){var a=Kr(s.target);if(a!==null){var l=js(a);if(l!==null){if(a=l.tag,a===13){if(a=xo(l),a!==null){s.blockedOn=a,zr(s.priority,function(){Fr(l)});return}}else if(a===3&&l.stateNode.current.memoizedState.isDehydrated){s.blockedOn=l.tag===3?l.stateNode.containerInfo:null;return}}}s.blockedOn=null}function hs(s){if(s.blockedOn!==null)return!1;for(var a=s.targetContainers;0<a.length;){var l=Is(s.domEventName,s.eventSystemFlags,a[0],s.nativeEvent);if(l===null){l=s.nativeEvent;var f=new l.constructor(l.type,l);Ys=f,l.target.dispatchEvent(f),Ys=null}else return a=Wo(l),a!==null&&As(a),s.blockedOn=l,!1;a.shift()}return!0}function or(s,a,l){hs(s)&&l.delete(a)}function $o(){ba=!1,Rn!==null&&hs(Rn)&&(Rn=null),Yn!==null&&hs(Yn)&&(Yn=null),fs!==null&&hs(fs)&&(fs=null),rr.forEach(or),ar.forEach(or)}function ms(s,a){s.blockedOn===a&&(s.blockedOn=null,ba||(ba=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,$o)))}function Br(s){function a(g){return ms(g,s)}if(0<sr.length){ms(sr[0],s);for(var l=1;l<sr.length;l++){var f=sr[l];f.blockedOn===s&&(f.blockedOn=null)}}for(Rn!==null&&ms(Rn,s),Yn!==null&&ms(Yn,s),fs!==null&&ms(fs,s),rr.forEach(a),ar.forEach(a),l=0;l<In.length;l++)f=In[l],f.blockedOn===s&&(f.blockedOn=null);for(;0<In.length&&(l=In[0],l.blockedOn===null);)xa(l),l.blockedOn===null&&In.shift()}var Rs=E.ReactCurrentBatchConfig,Wr=!0;function Ao(s,a,l,f){var g=Ge,w=Rs.transition;Rs.transition=null;try{Ge=1,To(s,a,l,f)}finally{Ge=g,Rs.transition=w}}function Jc(s,a,l,f){var g=Ge,w=Rs.transition;Rs.transition=null;try{Ge=4,To(s,a,l,f)}finally{Ge=g,Rs.transition=w}}function To(s,a,l,f){if(Wr){var g=Is(s,a,l,f);if(g===null)uu(s,a,f,ka,l),Ct(s,f);else if(Ut(g,s,a,l,f))f.stopPropagation();else if(Ct(s,f),a&4&&-1<Ur.indexOf(s)){for(;g!==null;){var w=Wo(g);if(w!==null&&$s(w),w=Is(s,a,l,f),w===null&&uu(s,a,f,ka,l),w===g)break;g=w}g!==null&&f.stopPropagation()}else uu(s,a,f,null,l)}}var ka=null;function Is(s,a,l,f){if(ka=null,s=pa(f),s=Kr(s),s!==null)if(a=js(s),a===null)s=null;else if(l=a.tag,l===13){if(s=xo(a),s!==null)return s;s=null}else if(l===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;s=null}else a!==s&&(s=null);return ka=s,null}function ja(s){switch(s){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(jo()){case So:return 1;case wa:return 4;case Pr:case Bi:return 16;case No:return 536870912;default:return 16}default:return 16}}var At=null,Vr=null,Gr=null;function Sa(){if(Gr)return Gr;var s,a=Vr,l=a.length,f,g="value"in At?At.value:At.textContent,w=g.length;for(s=0;s<l&&a[s]===g[s];s++);var k=l-s;for(f=1;f<=k&&a[l-f]===g[w-f];f++);return Gr=g.slice(s,1<f?1-f:void 0)}function Na(s){var a=s.keyCode;return"charCode"in s?(s=s.charCode,s===0&&a===13&&(s=13)):s=a,s===10&&(s=13),32<=s||s===13?s:0}function Ms(){return!0}function Ro(){return!1}function en(s){function a(l,f,g,w,k){this._reactName=l,this._targetInst=g,this.type=f,this.nativeEvent=w,this.target=k,this.currentTarget=null;for(var M in s)s.hasOwnProperty(M)&&(l=s[M],this[M]=l?l(w):w[M]);return this.isDefaultPrevented=(w.defaultPrevented!=null?w.defaultPrevented:w.returnValue===!1)?Ms:Ro,this.isPropagationStopped=Ro,this}return ne(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var l=this.nativeEvent;l&&(l.preventDefault?l.preventDefault():typeof l.returnValue!="unknown"&&(l.returnValue=!1),this.isDefaultPrevented=Ms)},stopPropagation:function(){var l=this.nativeEvent;l&&(l.stopPropagation?l.stopPropagation():typeof l.cancelBubble!="unknown"&&(l.cancelBubble=!0),this.isPropagationStopped=Ms)},persist:function(){},isPersistent:Ms}),a}var ir={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ca=en(ir),Hr=ne({},ir,{view:0,detail:0}),Qc=en(Hr),Mn,Ea,ot,Ln=ne({},Hr,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:$a,button:0,buttons:0,relatedTarget:function(s){return s.relatedTarget===void 0?s.fromElement===s.srcElement?s.toElement:s.fromElement:s.relatedTarget},movementX:function(s){return"movementX"in s?s.movementX:(s!==ot&&(ot&&s.type==="mousemove"?(Mn=s.screenX-ot.screenX,Ea=s.screenY-ot.screenY):Ea=Mn=0,ot=s),Mn)},movementY:function(s){return"movementY"in s?s.movementY:Ea}}),Ls=en(Ln),Yc=ne({},Ln,{dataTransfer:0}),Xc=en(Yc),qc=ne({},Hr,{relatedTarget:0}),Io=en(qc),Zc=ne({},ir,{animationName:0,elapsedTime:0,pseudoElement:0}),eu=en(Zc),Mo=ne({},ir,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),Vi=en(Mo),Gi=ne({},ir,{data:0}),Hi=en(Gi),Ki={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ji={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"},Qi={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Yi(s){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(s):(s=Qi[s])?!!a[s]:!1}function $a(){return Yi}var Xi=ne({},Hr,{key:function(s){if(s.key){var a=Ki[s.key]||s.key;if(a!=="Unidentified")return a}return s.type==="keypress"?(s=Na(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?Ji[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:$a,charCode:function(s){return s.type==="keypress"?Na(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?Na(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),qi=en(Xi),Zi=ne({},Ln,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Lo=en(Zi),el=ne({},Hr,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:$a}),tl=en(el),nl=ne({},ir,{propertyName:0,elapsedTime:0,pseudoElement:0}),sl=en(nl),rl=ne({},Ln,{deltaX:function(s){return"deltaX"in s?s.deltaX:"wheelDeltaX"in s?-s.wheelDeltaX:0},deltaY:function(s){return"deltaY"in s?s.deltaY:"wheelDeltaY"in s?-s.wheelDeltaY:"wheelDelta"in s?-s.wheelDelta:0},deltaZ:0,deltaMode:0}),al=en(rl),ol=[9,13,27,32],Aa=d&&"CompositionEvent"in window,lr=null;d&&"documentMode"in document&&(lr=document.documentMode);var il=d&&"TextEvent"in window&&!lr,Oo=d&&(!Aa||lr&&8<lr&&11>=lr),T=" ",X=!1;function _e(s,a){switch(s){case"keyup":return ol.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function je(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Ae=!1;function dt(s,a){switch(s){case"compositionend":return je(a);case"keypress":return a.which!==32?null:(X=!0,T);case"textInput":return s=a.data,s===T&&X?null:s;default:return null}}function jt(s,a){if(Ae)return s==="compositionend"||!Aa&&_e(s,a)?(s=Sa(),Gr=Vr=At=null,Ae=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return Oo&&a.locale!=="ko"?null:a.data;default:return null}}var cr={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 Tt(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a==="input"?!!cr[s.type]:a==="textarea"}function tn(s,a,l,f){wo(f),a=fl(a,"onChange"),0<a.length&&(l=new Ca("onChange","change",null,l,f),s.push({event:l,listeners:a}))}var Ot=null,xn=null;function ps(s){ih(s,0)}function ll(s){var a=La(s);if(st(a))return s}function Ww(s,a){if(s==="change")return a}var Vf=!1;if(d){var tu;if(d){var nu="oninput"in document;if(!nu){var Gf=document.createElement("div");Gf.setAttribute("oninput","return;"),nu=typeof Gf.oninput=="function"}tu=nu}else tu=!1;Vf=tu&&(!document.documentMode||9<document.documentMode)}function Hf(){Ot&&(Ot.detachEvent("onpropertychange",Kf),xn=Ot=null)}function Kf(s){if(s.propertyName==="value"&&ll(xn)){var a=[];tn(a,xn,s,pa(s)),vo(ps,a)}}function Vw(s,a,l){s==="focusin"?(Hf(),Ot=a,xn=l,Ot.attachEvent("onpropertychange",Kf)):s==="focusout"&&Hf()}function Gw(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return ll(xn)}function Hw(s,a){if(s==="click")return ll(a)}function Kw(s,a){if(s==="input"||s==="change")return ll(a)}function Jw(s,a){return s===a&&(s!==0||1/s===1/a)||s!==s&&a!==a}var Xn=typeof Object.is=="function"?Object.is:Jw;function Po(s,a){if(Xn(s,a))return!0;if(typeof s!="object"||s===null||typeof a!="object"||a===null)return!1;var l=Object.keys(s),f=Object.keys(a);if(l.length!==f.length)return!1;for(f=0;f<l.length;f++){var g=l[f];if(!h.call(a,g)||!Xn(s[g],a[g]))return!1}return!0}function Jf(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function Qf(s,a){var l=Jf(s);s=0;for(var f;l;){if(l.nodeType===3){if(f=s+l.textContent.length,s<=a&&f>=a)return{node:l,offset:a-s};s=f}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Jf(l)}}function Yf(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?Yf(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Xf(){for(var s=window,a=Ce();a instanceof s.HTMLIFrameElement;){try{var l=typeof a.contentWindow.location.href=="string"}catch{l=!1}if(l)s=a.contentWindow;else break;a=Ce(s.document)}return a}function su(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}function Qw(s){var a=Xf(),l=s.focusedElem,f=s.selectionRange;if(a!==l&&l&&l.ownerDocument&&Yf(l.ownerDocument.documentElement,l)){if(f!==null&&su(l)){if(a=f.start,s=f.end,s===void 0&&(s=a),"selectionStart"in l)l.selectionStart=a,l.selectionEnd=Math.min(s,l.value.length);else if(s=(a=l.ownerDocument||document)&&a.defaultView||window,s.getSelection){s=s.getSelection();var g=l.textContent.length,w=Math.min(f.start,g);f=f.end===void 0?w:Math.min(f.end,g),!s.extend&&w>f&&(g=f,f=w,w=g),g=Qf(l,w);var k=Qf(l,f);g&&k&&(s.rangeCount!==1||s.anchorNode!==g.node||s.anchorOffset!==g.offset||s.focusNode!==k.node||s.focusOffset!==k.offset)&&(a=a.createRange(),a.setStart(g.node,g.offset),s.removeAllRanges(),w>f?(s.addRange(a),s.extend(k.node,k.offset)):(a.setEnd(k.node,k.offset),s.addRange(a)))}}for(a=[],s=l;s=s.parentNode;)s.nodeType===1&&a.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof l.focus=="function"&&l.focus(),l=0;l<a.length;l++)s=a[l],s.element.scrollLeft=s.left,s.element.scrollTop=s.top}}var Yw=d&&"documentMode"in document&&11>=document.documentMode,Ta=null,ru=null,Do=null,au=!1;function qf(s,a,l){var f=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;au||Ta==null||Ta!==Ce(f)||(f=Ta,"selectionStart"in f&&su(f)?f={start:f.selectionStart,end:f.selectionEnd}:(f=(f.ownerDocument&&f.ownerDocument.defaultView||window).getSelection(),f={anchorNode:f.anchorNode,anchorOffset:f.anchorOffset,focusNode:f.focusNode,focusOffset:f.focusOffset}),Do&&Po(Do,f)||(Do=f,f=fl(ru,"onSelect"),0<f.length&&(a=new Ca("onSelect","select",null,a,l),s.push({event:a,listeners:f}),a.target=Ta)))}function cl(s,a){var l={};return l[s.toLowerCase()]=a.toLowerCase(),l["Webkit"+s]="webkit"+a,l["Moz"+s]="moz"+a,l}var Ra={animationend:cl("Animation","AnimationEnd"),animationiteration:cl("Animation","AnimationIteration"),animationstart:cl("Animation","AnimationStart"),transitionend:cl("Transition","TransitionEnd")},ou={},Zf={};d&&(Zf=document.createElement("div").style,"AnimationEvent"in window||(delete Ra.animationend.animation,delete Ra.animationiteration.animation,delete Ra.animationstart.animation),"TransitionEvent"in window||delete Ra.transitionend.transition);function ul(s){if(ou[s])return ou[s];if(!Ra[s])return s;var a=Ra[s],l;for(l in a)if(a.hasOwnProperty(l)&&l in Zf)return ou[s]=a[l];return s}var eh=ul("animationend"),th=ul("animationiteration"),nh=ul("animationstart"),sh=ul("transitionend"),rh=new Map,ah="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 ur(s,a){rh.set(s,a),c(a,[s])}for(var iu=0;iu<ah.length;iu++){var lu=ah[iu],Xw=lu.toLowerCase(),qw=lu[0].toUpperCase()+lu.slice(1);ur(Xw,"on"+qw)}ur(eh,"onAnimationEnd"),ur(th,"onAnimationIteration"),ur(nh,"onAnimationStart"),ur("dblclick","onDoubleClick"),ur("focusin","onFocus"),ur("focusout","onBlur"),ur(sh,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),c("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),c("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),c("onBeforeInput",["compositionend","keypress","textInput","paste"]),c("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),c("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),c("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Fo="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(" "),Zw=new Set("cancel close invalid load scroll toggle".split(" ").concat(Fo));function oh(s,a,l){var f=s.type||"unknown-event";s.currentTarget=l,bo(f,a,void 0,s),s.currentTarget=null}function ih(s,a){a=(a&4)!==0;for(var l=0;l<s.length;l++){var f=s[l],g=f.event;f=f.listeners;e:{var w=void 0;if(a)for(var k=f.length-1;0<=k;k--){var M=f[k],D=M.instance,Y=M.currentTarget;if(M=M.listener,D!==w&&g.isPropagationStopped())break e;oh(g,M,Y),w=D}else for(k=0;k<f.length;k++){if(M=f[k],D=M.instance,Y=M.currentTarget,M=M.listener,D!==w&&g.isPropagationStopped())break e;oh(g,M,Y),w=D}}}if(Hn)throw s=Or,Hn=!1,Or=null,s}function ft(s,a){var l=a[gu];l===void 0&&(l=a[gu]=new Set);var f=s+"__bubble";l.has(f)||(lh(a,s,2,!1),l.add(f))}function cu(s,a,l){var f=0;a&&(f|=4),lh(l,s,f,a)}var dl="_reactListening"+Math.random().toString(36).slice(2);function zo(s){if(!s[dl]){s[dl]=!0,r.forEach(function(l){l!=="selectionchange"&&(Zw.has(l)||cu(l,!1,s),cu(l,!0,s))});var a=s.nodeType===9?s:s.ownerDocument;a===null||a[dl]||(a[dl]=!0,cu("selectionchange",!1,a))}}function lh(s,a,l,f){switch(ja(a)){case 1:var g=Ao;break;case 4:g=Jc;break;default:g=To}l=g.bind(null,a,l,s),g=void 0,!ga||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(g=!0),f?g!==void 0?s.addEventListener(a,l,{capture:!0,passive:g}):s.addEventListener(a,l,!0):g!==void 0?s.addEventListener(a,l,{passive:g}):s.addEventListener(a,l,!1)}function uu(s,a,l,f,g){var w=f;if((a&1)===0&&(a&2)===0&&f!==null)e:for(;;){if(f===null)return;var k=f.tag;if(k===3||k===4){var M=f.stateNode.containerInfo;if(M===g||M.nodeType===8&&M.parentNode===g)break;if(k===4)for(k=f.return;k!==null;){var D=k.tag;if((D===3||D===4)&&(D=k.stateNode.containerInfo,D===g||D.nodeType===8&&D.parentNode===g))return;k=k.return}for(;M!==null;){if(k=Kr(M),k===null)return;if(D=k.tag,D===5||D===6){f=w=k;continue e}M=M.parentNode}}f=f.return}vo(function(){var Y=w,ce=pa(l),me=[];e:{var ie=rh.get(s);if(ie!==void 0){var xe=Ca,Se=s;switch(s){case"keypress":if(Na(l)===0)break e;case"keydown":case"keyup":xe=qi;break;case"focusin":Se="focus",xe=Io;break;case"focusout":Se="blur",xe=Io;break;case"beforeblur":case"afterblur":xe=Io;break;case"click":if(l.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":xe=Ls;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":xe=Xc;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":xe=tl;break;case eh:case th:case nh:xe=eu;break;case sh:xe=sl;break;case"scroll":xe=Qc;break;case"wheel":xe=al;break;case"copy":case"cut":case"paste":xe=Vi;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":xe=Lo}var Ne=(a&4)!==0,St=!Ne&&s==="scroll",H=Ne?ie!==null?ie+"Capture":null:ie;Ne=[];for(var U=Y,K;U!==null;){K=U;var ye=K.stateNode;if(K.tag===5&&ye!==null&&(K=ye,H!==null&&(ye=Gn(U,H),ye!=null&&Ne.push(Uo(U,ye,K)))),St)break;U=U.return}0<Ne.length&&(ie=new xe(ie,Se,null,l,ce),me.push({event:ie,listeners:Ne}))}}if((a&7)===0){e:{if(ie=s==="mouseover"||s==="pointerover",xe=s==="mouseout"||s==="pointerout",ie&&l!==Ys&&(Se=l.relatedTarget||l.fromElement)&&(Kr(Se)||Se[Os]))break e;if((xe||ie)&&(ie=ce.window===ce?ce:(ie=ce.ownerDocument)?ie.defaultView||ie.parentWindow:window,xe?(Se=l.relatedTarget||l.toElement,xe=Y,Se=Se?Kr(Se):null,Se!==null&&(St=js(Se),Se!==St||Se.tag!==5&&Se.tag!==6)&&(Se=null)):(xe=null,Se=Y),xe!==Se)){if(Ne=Ls,ye="onMouseLeave",H="onMouseEnter",U="mouse",(s==="pointerout"||s==="pointerover")&&(Ne=Lo,ye="onPointerLeave",H="onPointerEnter",U="pointer"),St=xe==null?ie:La(xe),K=Se==null?ie:La(Se),ie=new Ne(ye,U+"leave",xe,l,ce),ie.target=St,ie.relatedTarget=K,ye=null,Kr(ce)===Y&&(Ne=new Ne(H,U+"enter",Se,l,ce),Ne.target=K,Ne.relatedTarget=St,ye=Ne),St=ye,xe&&Se)t:{for(Ne=xe,H=Se,U=0,K=Ne;K;K=Ia(K))U++;for(K=0,ye=H;ye;ye=Ia(ye))K++;for(;0<U-K;)Ne=Ia(Ne),U--;for(;0<K-U;)H=Ia(H),K--;for(;U--;){if(Ne===H||H!==null&&Ne===H.alternate)break t;Ne=Ia(Ne),H=Ia(H)}Ne=null}else Ne=null;xe!==null&&ch(me,ie,xe,Ne,!1),Se!==null&&St!==null&&ch(me,St,Se,Ne,!0)}}e:{if(ie=Y?La(Y):window,xe=ie.nodeName&&ie.nodeName.toLowerCase(),xe==="select"||xe==="input"&&ie.type==="file")var $e=Ww;else if(Tt(ie))if(Vf)$e=Kw;else{$e=Gw;var Ie=Vw}else(xe=ie.nodeName)&&xe.toLowerCase()==="input"&&(ie.type==="checkbox"||ie.type==="radio")&&($e=Hw);if($e&&($e=$e(s,Y))){tn(me,$e,l,ce);break e}Ie&&Ie(s,ie,Y),s==="focusout"&&(Ie=ie._wrapperState)&&Ie.controlled&&ie.type==="number"&&ge(ie,"number",ie.value)}switch(Ie=Y?La(Y):window,s){case"focusin":(Tt(Ie)||Ie.contentEditable==="true")&&(Ta=Ie,ru=Y,Do=null);break;case"focusout":Do=ru=Ta=null;break;case"mousedown":au=!0;break;case"contextmenu":case"mouseup":case"dragend":au=!1,qf(me,l,ce);break;case"selectionchange":if(Yw)break;case"keydown":case"keyup":qf(me,l,ce)}var Me;if(Aa)e:{switch(s){case"compositionstart":var ze="onCompositionStart";break e;case"compositionend":ze="onCompositionEnd";break e;case"compositionupdate":ze="onCompositionUpdate";break e}ze=void 0}else Ae?_e(s,l)&&(ze="onCompositionEnd"):s==="keydown"&&l.keyCode===229&&(ze="onCompositionStart");ze&&(Oo&&l.locale!=="ko"&&(Ae||ze!=="onCompositionStart"?ze==="onCompositionEnd"&&Ae&&(Me=Sa()):(At=ce,Vr="value"in At?At.value:At.textContent,Ae=!0)),Ie=fl(Y,ze),0<Ie.length&&(ze=new Hi(ze,s,null,l,ce),me.push({event:ze,listeners:Ie}),Me?ze.data=Me:(Me=je(l),Me!==null&&(ze.data=Me)))),(Me=il?dt(s,l):jt(s,l))&&(Y=fl(Y,"onBeforeInput"),0<Y.length&&(ce=new Hi("onBeforeInput","beforeinput",null,l,ce),me.push({event:ce,listeners:Y}),ce.data=Me))}ih(me,a)})}function Uo(s,a,l){return{instance:s,listener:a,currentTarget:l}}function fl(s,a){for(var l=a+"Capture",f=[];s!==null;){var g=s,w=g.stateNode;g.tag===5&&w!==null&&(g=w,w=Gn(s,l),w!=null&&f.unshift(Uo(s,w,g)),w=Gn(s,a),w!=null&&f.push(Uo(s,w,g))),s=s.return}return f}function Ia(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5);return s||null}function ch(s,a,l,f,g){for(var w=a._reactName,k=[];l!==null&&l!==f;){var M=l,D=M.alternate,Y=M.stateNode;if(D!==null&&D===f)break;M.tag===5&&Y!==null&&(M=Y,g?(D=Gn(l,w),D!=null&&k.unshift(Uo(l,D,M))):g||(D=Gn(l,w),D!=null&&k.push(Uo(l,D,M)))),l=l.return}k.length!==0&&s.push({event:a,listeners:k})}var ev=/\r\n?/g,tv=/\u0000|\uFFFD/g;function uh(s){return(typeof s=="string"?s:""+s).replace(ev,`
38
+ `).replace(tv,"")}function hl(s,a,l){if(a=uh(a),uh(s)!==a&&l)throw Error(n(425))}function ml(){}var du=null,fu=null;function hu(s,a){return s==="textarea"||s==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var mu=typeof setTimeout=="function"?setTimeout:void 0,nv=typeof clearTimeout=="function"?clearTimeout:void 0,dh=typeof Promise=="function"?Promise:void 0,sv=typeof queueMicrotask=="function"?queueMicrotask:typeof dh<"u"?function(s){return dh.resolve(null).then(s).catch(rv)}:mu;function rv(s){setTimeout(function(){throw s})}function pu(s,a){var l=a,f=0;do{var g=l.nextSibling;if(s.removeChild(l),g&&g.nodeType===8)if(l=g.data,l==="/$"){if(f===0){s.removeChild(g),Br(a);return}f--}else l!=="$"&&l!=="$?"&&l!=="$!"||f++;l=g}while(l);Br(a)}function dr(s){for(;s!=null;s=s.nextSibling){var a=s.nodeType;if(a===1||a===3)break;if(a===8){if(a=s.data,a==="$"||a==="$!"||a==="$?")break;if(a==="/$")return null}}return s}function fh(s){s=s.previousSibling;for(var a=0;s;){if(s.nodeType===8){var l=s.data;if(l==="$"||l==="$!"||l==="$?"){if(a===0)return s;a--}else l==="/$"&&a++}s=s.previousSibling}return null}var Ma=Math.random().toString(36).slice(2),gs="__reactFiber$"+Ma,Bo="__reactProps$"+Ma,Os="__reactContainer$"+Ma,gu="__reactEvents$"+Ma,av="__reactListeners$"+Ma,ov="__reactHandles$"+Ma;function Kr(s){var a=s[gs];if(a)return a;for(var l=s.parentNode;l;){if(a=l[Os]||l[gs]){if(l=a.alternate,a.child!==null||l!==null&&l.child!==null)for(s=fh(s);s!==null;){if(l=s[gs])return l;s=fh(s)}return a}s=l,l=s.parentNode}return null}function Wo(s){return s=s[gs]||s[Os],!s||s.tag!==5&&s.tag!==6&&s.tag!==13&&s.tag!==3?null:s}function La(s){if(s.tag===5||s.tag===6)return s.stateNode;throw Error(n(33))}function pl(s){return s[Bo]||null}var yu=[],Oa=-1;function fr(s){return{current:s}}function ht(s){0>Oa||(s.current=yu[Oa],yu[Oa]=null,Oa--)}function ut(s,a){Oa++,yu[Oa]=s.current,s.current=a}var hr={},Jt=fr(hr),cn=fr(!1),Jr=hr;function Pa(s,a){var l=s.type.contextTypes;if(!l)return hr;var f=s.stateNode;if(f&&f.__reactInternalMemoizedUnmaskedChildContext===a)return f.__reactInternalMemoizedMaskedChildContext;var g={},w;for(w in l)g[w]=a[w];return f&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=a,s.__reactInternalMemoizedMaskedChildContext=g),g}function un(s){return s=s.childContextTypes,s!=null}function gl(){ht(cn),ht(Jt)}function hh(s,a,l){if(Jt.current!==hr)throw Error(n(168));ut(Jt,a),ut(cn,l)}function mh(s,a,l){var f=s.stateNode;if(a=a.childContextTypes,typeof f.getChildContext!="function")return l;f=f.getChildContext();for(var g in f)if(!(g in a))throw Error(n(108,fe(s)||"Unknown",g));return ne({},l,f)}function yl(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||hr,Jr=Jt.current,ut(Jt,s),ut(cn,cn.current),!0}function ph(s,a,l){var f=s.stateNode;if(!f)throw Error(n(169));l?(s=mh(s,a,Jr),f.__reactInternalMemoizedMergedChildContext=s,ht(cn),ht(Jt),ut(Jt,s)):ht(cn),ut(cn,l)}var Ps=null,wl=!1,wu=!1;function gh(s){Ps===null?Ps=[s]:Ps.push(s)}function iv(s){wl=!0,gh(s)}function mr(){if(!wu&&Ps!==null){wu=!0;var s=0,a=Ge;try{var l=Ps;for(Ge=1;s<l.length;s++){var f=l[s];do f=f(!0);while(f!==null)}Ps=null,wl=!1}catch(g){throw Ps!==null&&(Ps=Ps.slice(s+1)),ya(So,mr),g}finally{Ge=a,wu=!1}}return null}var Da=[],Fa=0,vl=null,_l=0,On=[],Pn=0,Qr=null,Ds=1,Fs="";function Yr(s,a){Da[Fa++]=_l,Da[Fa++]=vl,vl=s,_l=a}function yh(s,a,l){On[Pn++]=Ds,On[Pn++]=Fs,On[Pn++]=Qr,Qr=s;var f=Ds;s=Fs;var g=32-De(f)-1;f&=~(1<<g),l+=1;var w=32-De(a)+g;if(30<w){var k=g-g%5;w=(f&(1<<k)-1).toString(32),f>>=k,g-=k,Ds=1<<32-De(a)+g|l<<g|f,Fs=w+s}else Ds=1<<w|l<<g|f,Fs=s}function vu(s){s.return!==null&&(Yr(s,1),yh(s,1,0))}function _u(s){for(;s===vl;)vl=Da[--Fa],Da[Fa]=null,_l=Da[--Fa],Da[Fa]=null;for(;s===Qr;)Qr=On[--Pn],On[Pn]=null,Fs=On[--Pn],On[Pn]=null,Ds=On[--Pn],On[Pn]=null}var kn=null,jn=null,gt=!1,qn=null;function wh(s,a){var l=Un(5,null,null,0);l.elementType="DELETED",l.stateNode=a,l.return=s,a=s.deletions,a===null?(s.deletions=[l],s.flags|=16):a.push(l)}function vh(s,a){switch(s.tag){case 5:var l=s.type;return a=a.nodeType!==1||l.toLowerCase()!==a.nodeName.toLowerCase()?null:a,a!==null?(s.stateNode=a,kn=s,jn=dr(a.firstChild),!0):!1;case 6:return a=s.pendingProps===""||a.nodeType!==3?null:a,a!==null?(s.stateNode=a,kn=s,jn=null,!0):!1;case 13:return a=a.nodeType!==8?null:a,a!==null?(l=Qr!==null?{id:Ds,overflow:Fs}:null,s.memoizedState={dehydrated:a,treeContext:l,retryLane:1073741824},l=Un(18,null,null,0),l.stateNode=a,l.return=s,s.child=l,kn=s,jn=null,!0):!1;default:return!1}}function bu(s){return(s.mode&1)!==0&&(s.flags&128)===0}function xu(s){if(gt){var a=jn;if(a){var l=a;if(!vh(s,a)){if(bu(s))throw Error(n(418));a=dr(l.nextSibling);var f=kn;a&&vh(s,a)?wh(f,l):(s.flags=s.flags&-4097|2,gt=!1,kn=s)}}else{if(bu(s))throw Error(n(418));s.flags=s.flags&-4097|2,gt=!1,kn=s}}}function _h(s){for(s=s.return;s!==null&&s.tag!==5&&s.tag!==3&&s.tag!==13;)s=s.return;kn=s}function bl(s){if(s!==kn)return!1;if(!gt)return _h(s),gt=!0,!1;var a;if((a=s.tag!==3)&&!(a=s.tag!==5)&&(a=s.type,a=a!=="head"&&a!=="body"&&!hu(s.type,s.memoizedProps)),a&&(a=jn)){if(bu(s))throw bh(),Error(n(418));for(;a;)wh(s,a),a=dr(a.nextSibling)}if(_h(s),s.tag===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(n(317));e:{for(s=s.nextSibling,a=0;s;){if(s.nodeType===8){var l=s.data;if(l==="/$"){if(a===0){jn=dr(s.nextSibling);break e}a--}else l!=="$"&&l!=="$!"&&l!=="$?"||a++}s=s.nextSibling}jn=null}}else jn=kn?dr(s.stateNode.nextSibling):null;return!0}function bh(){for(var s=jn;s;)s=dr(s.nextSibling)}function za(){jn=kn=null,gt=!1}function ku(s){qn===null?qn=[s]:qn.push(s)}var lv=E.ReactCurrentBatchConfig;function Vo(s,a,l){if(s=l.ref,s!==null&&typeof s!="function"&&typeof s!="object"){if(l._owner){if(l=l._owner,l){if(l.tag!==1)throw Error(n(309));var f=l.stateNode}if(!f)throw Error(n(147,s));var g=f,w=""+s;return a!==null&&a.ref!==null&&typeof a.ref=="function"&&a.ref._stringRef===w?a.ref:(a=function(k){var M=g.refs;k===null?delete M[w]:M[w]=k},a._stringRef=w,a)}if(typeof s!="string")throw Error(n(284));if(!l._owner)throw Error(n(290,s))}return s}function xl(s,a){throw s=Object.prototype.toString.call(a),Error(n(31,s==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":s))}function xh(s){var a=s._init;return a(s._payload)}function kh(s){function a(H,U){if(s){var K=H.deletions;K===null?(H.deletions=[U],H.flags|=16):K.push(U)}}function l(H,U){if(!s)return null;for(;U!==null;)a(H,U),U=U.sibling;return null}function f(H,U){for(H=new Map;U!==null;)U.key!==null?H.set(U.key,U):H.set(U.index,U),U=U.sibling;return H}function g(H,U){return H=xr(H,U),H.index=0,H.sibling=null,H}function w(H,U,K){return H.index=K,s?(K=H.alternate,K!==null?(K=K.index,K<U?(H.flags|=2,U):K):(H.flags|=2,U)):(H.flags|=1048576,U)}function k(H){return s&&H.alternate===null&&(H.flags|=2),H}function M(H,U,K,ye){return U===null||U.tag!==6?(U=md(K,H.mode,ye),U.return=H,U):(U=g(U,K),U.return=H,U)}function D(H,U,K,ye){var $e=K.type;return $e===F?ce(H,U,K.props.children,ye,K.key):U!==null&&(U.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===se&&xh($e)===U.type)?(ye=g(U,K.props),ye.ref=Vo(H,U,K),ye.return=H,ye):(ye=Hl(K.type,K.key,K.props,null,H.mode,ye),ye.ref=Vo(H,U,K),ye.return=H,ye)}function Y(H,U,K,ye){return U===null||U.tag!==4||U.stateNode.containerInfo!==K.containerInfo||U.stateNode.implementation!==K.implementation?(U=pd(K,H.mode,ye),U.return=H,U):(U=g(U,K.children||[]),U.return=H,U)}function ce(H,U,K,ye,$e){return U===null||U.tag!==7?(U=ra(K,H.mode,ye,$e),U.return=H,U):(U=g(U,K),U.return=H,U)}function me(H,U,K){if(typeof U=="string"&&U!==""||typeof U=="number")return U=md(""+U,H.mode,K),U.return=H,U;if(typeof U=="object"&&U!==null){switch(U.$$typeof){case A:return K=Hl(U.type,U.key,U.props,null,H.mode,K),K.ref=Vo(H,null,U),K.return=H,K;case I:return U=pd(U,H.mode,K),U.return=H,U;case se:var ye=U._init;return me(H,ye(U._payload),K)}if(Q(U)||ue(U))return U=ra(U,H.mode,K,null),U.return=H,U;xl(H,U)}return null}function ie(H,U,K,ye){var $e=U!==null?U.key:null;if(typeof K=="string"&&K!==""||typeof K=="number")return $e!==null?null:M(H,U,""+K,ye);if(typeof K=="object"&&K!==null){switch(K.$$typeof){case A:return K.key===$e?D(H,U,K,ye):null;case I:return K.key===$e?Y(H,U,K,ye):null;case se:return $e=K._init,ie(H,U,$e(K._payload),ye)}if(Q(K)||ue(K))return $e!==null?null:ce(H,U,K,ye,null);xl(H,K)}return null}function xe(H,U,K,ye,$e){if(typeof ye=="string"&&ye!==""||typeof ye=="number")return H=H.get(K)||null,M(U,H,""+ye,$e);if(typeof ye=="object"&&ye!==null){switch(ye.$$typeof){case A:return H=H.get(ye.key===null?K:ye.key)||null,D(U,H,ye,$e);case I:return H=H.get(ye.key===null?K:ye.key)||null,Y(U,H,ye,$e);case se:var Ie=ye._init;return xe(H,U,K,Ie(ye._payload),$e)}if(Q(ye)||ue(ye))return H=H.get(K)||null,ce(U,H,ye,$e,null);xl(U,ye)}return null}function Se(H,U,K,ye){for(var $e=null,Ie=null,Me=U,ze=U=0,Ft=null;Me!==null&&ze<K.length;ze++){Me.index>ze?(Ft=Me,Me=null):Ft=Me.sibling;var qe=ie(H,Me,K[ze],ye);if(qe===null){Me===null&&(Me=Ft);break}s&&Me&&qe.alternate===null&&a(H,Me),U=w(qe,U,ze),Ie===null?$e=qe:Ie.sibling=qe,Ie=qe,Me=Ft}if(ze===K.length)return l(H,Me),gt&&Yr(H,ze),$e;if(Me===null){for(;ze<K.length;ze++)Me=me(H,K[ze],ye),Me!==null&&(U=w(Me,U,ze),Ie===null?$e=Me:Ie.sibling=Me,Ie=Me);return gt&&Yr(H,ze),$e}for(Me=f(H,Me);ze<K.length;ze++)Ft=xe(Me,H,ze,K[ze],ye),Ft!==null&&(s&&Ft.alternate!==null&&Me.delete(Ft.key===null?ze:Ft.key),U=w(Ft,U,ze),Ie===null?$e=Ft:Ie.sibling=Ft,Ie=Ft);return s&&Me.forEach(function(kr){return a(H,kr)}),gt&&Yr(H,ze),$e}function Ne(H,U,K,ye){var $e=ue(K);if(typeof $e!="function")throw Error(n(150));if(K=$e.call(K),K==null)throw Error(n(151));for(var Ie=$e=null,Me=U,ze=U=0,Ft=null,qe=K.next();Me!==null&&!qe.done;ze++,qe=K.next()){Me.index>ze?(Ft=Me,Me=null):Ft=Me.sibling;var kr=ie(H,Me,qe.value,ye);if(kr===null){Me===null&&(Me=Ft);break}s&&Me&&kr.alternate===null&&a(H,Me),U=w(kr,U,ze),Ie===null?$e=kr:Ie.sibling=kr,Ie=kr,Me=Ft}if(qe.done)return l(H,Me),gt&&Yr(H,ze),$e;if(Me===null){for(;!qe.done;ze++,qe=K.next())qe=me(H,qe.value,ye),qe!==null&&(U=w(qe,U,ze),Ie===null?$e=qe:Ie.sibling=qe,Ie=qe);return gt&&Yr(H,ze),$e}for(Me=f(H,Me);!qe.done;ze++,qe=K.next())qe=xe(Me,H,ze,qe.value,ye),qe!==null&&(s&&qe.alternate!==null&&Me.delete(qe.key===null?ze:qe.key),U=w(qe,U,ze),Ie===null?$e=qe:Ie.sibling=qe,Ie=qe);return s&&Me.forEach(function(Uv){return a(H,Uv)}),gt&&Yr(H,ze),$e}function St(H,U,K,ye){if(typeof K=="object"&&K!==null&&K.type===F&&K.key===null&&(K=K.props.children),typeof K=="object"&&K!==null){switch(K.$$typeof){case A:e:{for(var $e=K.key,Ie=U;Ie!==null;){if(Ie.key===$e){if($e=K.type,$e===F){if(Ie.tag===7){l(H,Ie.sibling),U=g(Ie,K.props.children),U.return=H,H=U;break e}}else if(Ie.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===se&&xh($e)===Ie.type){l(H,Ie.sibling),U=g(Ie,K.props),U.ref=Vo(H,Ie,K),U.return=H,H=U;break e}l(H,Ie);break}else a(H,Ie);Ie=Ie.sibling}K.type===F?(U=ra(K.props.children,H.mode,ye,K.key),U.return=H,H=U):(ye=Hl(K.type,K.key,K.props,null,H.mode,ye),ye.ref=Vo(H,U,K),ye.return=H,H=ye)}return k(H);case I:e:{for(Ie=K.key;U!==null;){if(U.key===Ie)if(U.tag===4&&U.stateNode.containerInfo===K.containerInfo&&U.stateNode.implementation===K.implementation){l(H,U.sibling),U=g(U,K.children||[]),U.return=H,H=U;break e}else{l(H,U);break}else a(H,U);U=U.sibling}U=pd(K,H.mode,ye),U.return=H,H=U}return k(H);case se:return Ie=K._init,St(H,U,Ie(K._payload),ye)}if(Q(K))return Se(H,U,K,ye);if(ue(K))return Ne(H,U,K,ye);xl(H,K)}return typeof K=="string"&&K!==""||typeof K=="number"?(K=""+K,U!==null&&U.tag===6?(l(H,U.sibling),U=g(U,K),U.return=H,H=U):(l(H,U),U=md(K,H.mode,ye),U.return=H,H=U),k(H)):l(H,U)}return St}var Ua=kh(!0),jh=kh(!1),kl=fr(null),jl=null,Ba=null,ju=null;function Su(){ju=Ba=jl=null}function Nu(s){var a=kl.current;ht(kl),s._currentValue=a}function Cu(s,a,l){for(;s!==null;){var f=s.alternate;if((s.childLanes&a)!==a?(s.childLanes|=a,f!==null&&(f.childLanes|=a)):f!==null&&(f.childLanes&a)!==a&&(f.childLanes|=a),s===l)break;s=s.return}}function Wa(s,a){jl=s,ju=Ba=null,s=s.dependencies,s!==null&&s.firstContext!==null&&((s.lanes&a)!==0&&(dn=!0),s.firstContext=null)}function Dn(s){var a=s._currentValue;if(ju!==s)if(s={context:s,memoizedValue:a,next:null},Ba===null){if(jl===null)throw Error(n(308));Ba=s,jl.dependencies={lanes:0,firstContext:s}}else Ba=Ba.next=s;return a}var Xr=null;function Eu(s){Xr===null?Xr=[s]:Xr.push(s)}function Sh(s,a,l,f){var g=a.interleaved;return g===null?(l.next=l,Eu(a)):(l.next=g.next,g.next=l),a.interleaved=l,zs(s,f)}function zs(s,a){s.lanes|=a;var l=s.alternate;for(l!==null&&(l.lanes|=a),l=s,s=s.return;s!==null;)s.childLanes|=a,l=s.alternate,l!==null&&(l.childLanes|=a),l=s,s=s.return;return l.tag===3?l.stateNode:null}var pr=!1;function $u(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Nh(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,effects:s.effects})}function Us(s,a){return{eventTime:s,lane:a,tag:0,payload:null,callback:null,next:null}}function gr(s,a,l){var f=s.updateQueue;if(f===null)return null;if(f=f.shared,(Xe&2)!==0){var g=f.pending;return g===null?a.next=a:(a.next=g.next,g.next=a),f.pending=a,zs(s,l)}return g=f.interleaved,g===null?(a.next=a,Eu(f)):(a.next=g.next,g.next=a),f.interleaved=a,zs(s,l)}function Sl(s,a,l){if(a=a.updateQueue,a!==null&&(a=a.shared,(l&4194240)!==0)){var f=a.lanes;f&=s.pendingLanes,l|=f,a.lanes=l,_a(s,l)}}function Ch(s,a){var l=s.updateQueue,f=s.alternate;if(f!==null&&(f=f.updateQueue,l===f)){var g=null,w=null;if(l=l.firstBaseUpdate,l!==null){do{var k={eventTime:l.eventTime,lane:l.lane,tag:l.tag,payload:l.payload,callback:l.callback,next:null};w===null?g=w=k:w=w.next=k,l=l.next}while(l!==null);w===null?g=w=a:w=w.next=a}else g=w=a;l={baseState:f.baseState,firstBaseUpdate:g,lastBaseUpdate:w,shared:f.shared,effects:f.effects},s.updateQueue=l;return}s=l.lastBaseUpdate,s===null?l.firstBaseUpdate=a:s.next=a,l.lastBaseUpdate=a}function Nl(s,a,l,f){var g=s.updateQueue;pr=!1;var w=g.firstBaseUpdate,k=g.lastBaseUpdate,M=g.shared.pending;if(M!==null){g.shared.pending=null;var D=M,Y=D.next;D.next=null,k===null?w=Y:k.next=Y,k=D;var ce=s.alternate;ce!==null&&(ce=ce.updateQueue,M=ce.lastBaseUpdate,M!==k&&(M===null?ce.firstBaseUpdate=Y:M.next=Y,ce.lastBaseUpdate=D))}if(w!==null){var me=g.baseState;k=0,ce=Y=D=null,M=w;do{var ie=M.lane,xe=M.eventTime;if((f&ie)===ie){ce!==null&&(ce=ce.next={eventTime:xe,lane:0,tag:M.tag,payload:M.payload,callback:M.callback,next:null});e:{var Se=s,Ne=M;switch(ie=a,xe=l,Ne.tag){case 1:if(Se=Ne.payload,typeof Se=="function"){me=Se.call(xe,me,ie);break e}me=Se;break e;case 3:Se.flags=Se.flags&-65537|128;case 0:if(Se=Ne.payload,ie=typeof Se=="function"?Se.call(xe,me,ie):Se,ie==null)break e;me=ne({},me,ie);break e;case 2:pr=!0}}M.callback!==null&&M.lane!==0&&(s.flags|=64,ie=g.effects,ie===null?g.effects=[M]:ie.push(M))}else xe={eventTime:xe,lane:ie,tag:M.tag,payload:M.payload,callback:M.callback,next:null},ce===null?(Y=ce=xe,D=me):ce=ce.next=xe,k|=ie;if(M=M.next,M===null){if(M=g.shared.pending,M===null)break;ie=M,M=ie.next,ie.next=null,g.lastBaseUpdate=ie,g.shared.pending=null}}while(!0);if(ce===null&&(D=me),g.baseState=D,g.firstBaseUpdate=Y,g.lastBaseUpdate=ce,a=g.shared.interleaved,a!==null){g=a;do k|=g.lane,g=g.next;while(g!==a)}else w===null&&(g.shared.lanes=0);ea|=k,s.lanes=k,s.memoizedState=me}}function Eh(s,a,l){if(s=a.effects,a.effects=null,s!==null)for(a=0;a<s.length;a++){var f=s[a],g=f.callback;if(g!==null){if(f.callback=null,f=l,typeof g!="function")throw Error(n(191,g));g.call(f)}}}var Go={},ys=fr(Go),Ho=fr(Go),Ko=fr(Go);function qr(s){if(s===Go)throw Error(n(174));return s}function Au(s,a){switch(ut(Ko,a),ut(Ho,s),ut(ys,Go),s=a.nodeType,s){case 9:case 11:a=(a=a.documentElement)?a.namespaceURI:bt(null,"");break;default:s=s===8?a.parentNode:a,a=s.namespaceURI||null,s=s.tagName,a=bt(a,s)}ht(ys),ut(ys,a)}function Va(){ht(ys),ht(Ho),ht(Ko)}function $h(s){qr(Ko.current);var a=qr(ys.current),l=bt(a,s.type);a!==l&&(ut(Ho,s),ut(ys,l))}function Tu(s){Ho.current===s&&(ht(ys),ht(Ho))}var yt=fr(0);function Cl(s){for(var a=s;a!==null;){if(a.tag===13){var l=a.memoizedState;if(l!==null&&(l=l.dehydrated,l===null||l.data==="$?"||l.data==="$!"))return a}else if(a.tag===19&&a.memoizedProps.revealOrder!==void 0){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===s)break;for(;a.sibling===null;){if(a.return===null||a.return===s)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var Ru=[];function Iu(){for(var s=0;s<Ru.length;s++)Ru[s]._workInProgressVersionPrimary=null;Ru.length=0}var El=E.ReactCurrentDispatcher,Mu=E.ReactCurrentBatchConfig,Zr=0,wt=null,Rt=null,Pt=null,$l=!1,Jo=!1,Qo=0,cv=0;function Qt(){throw Error(n(321))}function Lu(s,a){if(a===null)return!1;for(var l=0;l<a.length&&l<s.length;l++)if(!Xn(s[l],a[l]))return!1;return!0}function Ou(s,a,l,f,g,w){if(Zr=w,wt=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,El.current=s===null||s.memoizedState===null?hv:mv,s=l(f,g),Jo){w=0;do{if(Jo=!1,Qo=0,25<=w)throw Error(n(301));w+=1,Pt=Rt=null,a.updateQueue=null,El.current=pv,s=l(f,g)}while(Jo)}if(El.current=Rl,a=Rt!==null&&Rt.next!==null,Zr=0,Pt=Rt=wt=null,$l=!1,a)throw Error(n(300));return s}function Pu(){var s=Qo!==0;return Qo=0,s}function ws(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Pt===null?wt.memoizedState=Pt=s:Pt=Pt.next=s,Pt}function Fn(){if(Rt===null){var s=wt.alternate;s=s!==null?s.memoizedState:null}else s=Rt.next;var a=Pt===null?wt.memoizedState:Pt.next;if(a!==null)Pt=a,Rt=s;else{if(s===null)throw Error(n(310));Rt=s,s={memoizedState:Rt.memoizedState,baseState:Rt.baseState,baseQueue:Rt.baseQueue,queue:Rt.queue,next:null},Pt===null?wt.memoizedState=Pt=s:Pt=Pt.next=s}return Pt}function Yo(s,a){return typeof a=="function"?a(s):a}function Du(s){var a=Fn(),l=a.queue;if(l===null)throw Error(n(311));l.lastRenderedReducer=s;var f=Rt,g=f.baseQueue,w=l.pending;if(w!==null){if(g!==null){var k=g.next;g.next=w.next,w.next=k}f.baseQueue=g=w,l.pending=null}if(g!==null){w=g.next,f=f.baseState;var M=k=null,D=null,Y=w;do{var ce=Y.lane;if((Zr&ce)===ce)D!==null&&(D=D.next={lane:0,action:Y.action,hasEagerState:Y.hasEagerState,eagerState:Y.eagerState,next:null}),f=Y.hasEagerState?Y.eagerState:s(f,Y.action);else{var me={lane:ce,action:Y.action,hasEagerState:Y.hasEagerState,eagerState:Y.eagerState,next:null};D===null?(M=D=me,k=f):D=D.next=me,wt.lanes|=ce,ea|=ce}Y=Y.next}while(Y!==null&&Y!==w);D===null?k=f:D.next=M,Xn(f,a.memoizedState)||(dn=!0),a.memoizedState=f,a.baseState=k,a.baseQueue=D,l.lastRenderedState=f}if(s=l.interleaved,s!==null){g=s;do w=g.lane,wt.lanes|=w,ea|=w,g=g.next;while(g!==s)}else g===null&&(l.lanes=0);return[a.memoizedState,l.dispatch]}function Fu(s){var a=Fn(),l=a.queue;if(l===null)throw Error(n(311));l.lastRenderedReducer=s;var f=l.dispatch,g=l.pending,w=a.memoizedState;if(g!==null){l.pending=null;var k=g=g.next;do w=s(w,k.action),k=k.next;while(k!==g);Xn(w,a.memoizedState)||(dn=!0),a.memoizedState=w,a.baseQueue===null&&(a.baseState=w),l.lastRenderedState=w}return[w,f]}function Ah(){}function Th(s,a){var l=wt,f=Fn(),g=a(),w=!Xn(f.memoizedState,g);if(w&&(f.memoizedState=g,dn=!0),f=f.queue,zu(Mh.bind(null,l,f,s),[s]),f.getSnapshot!==a||w||Pt!==null&&Pt.memoizedState.tag&1){if(l.flags|=2048,Xo(9,Ih.bind(null,l,f,g,a),void 0,null),Dt===null)throw Error(n(349));(Zr&30)!==0||Rh(l,a,g)}return g}function Rh(s,a,l){s.flags|=16384,s={getSnapshot:a,value:l},a=wt.updateQueue,a===null?(a={lastEffect:null,stores:null},wt.updateQueue=a,a.stores=[s]):(l=a.stores,l===null?a.stores=[s]:l.push(s))}function Ih(s,a,l,f){a.value=l,a.getSnapshot=f,Lh(a)&&Oh(s)}function Mh(s,a,l){return l(function(){Lh(a)&&Oh(s)})}function Lh(s){var a=s.getSnapshot;s=s.value;try{var l=a();return!Xn(s,l)}catch{return!0}}function Oh(s){var a=zs(s,1);a!==null&&ns(a,s,1,-1)}function Ph(s){var a=ws();return typeof s=="function"&&(s=s()),a.memoizedState=a.baseState=s,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Yo,lastRenderedState:s},a.queue=s,s=s.dispatch=fv.bind(null,wt,s),[a.memoizedState,s]}function Xo(s,a,l,f){return s={tag:s,create:a,destroy:l,deps:f,next:null},a=wt.updateQueue,a===null?(a={lastEffect:null,stores:null},wt.updateQueue=a,a.lastEffect=s.next=s):(l=a.lastEffect,l===null?a.lastEffect=s.next=s:(f=l.next,l.next=s,s.next=f,a.lastEffect=s)),s}function Dh(){return Fn().memoizedState}function Al(s,a,l,f){var g=ws();wt.flags|=s,g.memoizedState=Xo(1|a,l,void 0,f===void 0?null:f)}function Tl(s,a,l,f){var g=Fn();f=f===void 0?null:f;var w=void 0;if(Rt!==null){var k=Rt.memoizedState;if(w=k.destroy,f!==null&&Lu(f,k.deps)){g.memoizedState=Xo(a,l,w,f);return}}wt.flags|=s,g.memoizedState=Xo(1|a,l,w,f)}function Fh(s,a){return Al(8390656,8,s,a)}function zu(s,a){return Tl(2048,8,s,a)}function zh(s,a){return Tl(4,2,s,a)}function Uh(s,a){return Tl(4,4,s,a)}function Bh(s,a){if(typeof a=="function")return s=s(),a(s),function(){a(null)};if(a!=null)return s=s(),a.current=s,function(){a.current=null}}function Wh(s,a,l){return l=l!=null?l.concat([s]):null,Tl(4,4,Bh.bind(null,a,s),l)}function Uu(){}function Vh(s,a){var l=Fn();a=a===void 0?null:a;var f=l.memoizedState;return f!==null&&a!==null&&Lu(a,f[1])?f[0]:(l.memoizedState=[s,a],s)}function Gh(s,a){var l=Fn();a=a===void 0?null:a;var f=l.memoizedState;return f!==null&&a!==null&&Lu(a,f[1])?f[0]:(s=s(),l.memoizedState=[s,a],s)}function Hh(s,a,l){return(Zr&21)===0?(s.baseState&&(s.baseState=!1,dn=!0),s.memoizedState=l):(Xn(l,a)||(l=Es(),wt.lanes|=l,ea|=l,s.baseState=!0),a)}function uv(s,a){var l=Ge;Ge=l!==0&&4>l?l:4,s(!0);var f=Mu.transition;Mu.transition={};try{s(!1),a()}finally{Ge=l,Mu.transition=f}}function Kh(){return Fn().memoizedState}function dv(s,a,l){var f=_r(s);if(l={lane:f,action:l,hasEagerState:!1,eagerState:null,next:null},Jh(s))Qh(a,l);else if(l=Sh(s,a,l,f),l!==null){var g=sn();ns(l,s,f,g),Yh(l,a,f)}}function fv(s,a,l){var f=_r(s),g={lane:f,action:l,hasEagerState:!1,eagerState:null,next:null};if(Jh(s))Qh(a,g);else{var w=s.alternate;if(s.lanes===0&&(w===null||w.lanes===0)&&(w=a.lastRenderedReducer,w!==null))try{var k=a.lastRenderedState,M=w(k,l);if(g.hasEagerState=!0,g.eagerState=M,Xn(M,k)){var D=a.interleaved;D===null?(g.next=g,Eu(a)):(g.next=D.next,D.next=g),a.interleaved=g;return}}catch{}finally{}l=Sh(s,a,g,f),l!==null&&(g=sn(),ns(l,s,f,g),Yh(l,a,f))}}function Jh(s){var a=s.alternate;return s===wt||a!==null&&a===wt}function Qh(s,a){Jo=$l=!0;var l=s.pending;l===null?a.next=a:(a.next=l.next,l.next=a),s.pending=a}function Yh(s,a,l){if((l&4194240)!==0){var f=a.lanes;f&=s.pendingLanes,l|=f,a.lanes=l,_a(s,l)}}var Rl={readContext:Dn,useCallback:Qt,useContext:Qt,useEffect:Qt,useImperativeHandle:Qt,useInsertionEffect:Qt,useLayoutEffect:Qt,useMemo:Qt,useReducer:Qt,useRef:Qt,useState:Qt,useDebugValue:Qt,useDeferredValue:Qt,useTransition:Qt,useMutableSource:Qt,useSyncExternalStore:Qt,useId:Qt,unstable_isNewReconciler:!1},hv={readContext:Dn,useCallback:function(s,a){return ws().memoizedState=[s,a===void 0?null:a],s},useContext:Dn,useEffect:Fh,useImperativeHandle:function(s,a,l){return l=l!=null?l.concat([s]):null,Al(4194308,4,Bh.bind(null,a,s),l)},useLayoutEffect:function(s,a){return Al(4194308,4,s,a)},useInsertionEffect:function(s,a){return Al(4,2,s,a)},useMemo:function(s,a){var l=ws();return a=a===void 0?null:a,s=s(),l.memoizedState=[s,a],s},useReducer:function(s,a,l){var f=ws();return a=l!==void 0?l(a):a,f.memoizedState=f.baseState=a,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:a},f.queue=s,s=s.dispatch=dv.bind(null,wt,s),[f.memoizedState,s]},useRef:function(s){var a=ws();return s={current:s},a.memoizedState=s},useState:Ph,useDebugValue:Uu,useDeferredValue:function(s){return ws().memoizedState=s},useTransition:function(){var s=Ph(!1),a=s[0];return s=uv.bind(null,s[1]),ws().memoizedState=s,[a,s]},useMutableSource:function(){},useSyncExternalStore:function(s,a,l){var f=wt,g=ws();if(gt){if(l===void 0)throw Error(n(407));l=l()}else{if(l=a(),Dt===null)throw Error(n(349));(Zr&30)!==0||Rh(f,a,l)}g.memoizedState=l;var w={value:l,getSnapshot:a};return g.queue=w,Fh(Mh.bind(null,f,w,s),[s]),f.flags|=2048,Xo(9,Ih.bind(null,f,w,l,a),void 0,null),l},useId:function(){var s=ws(),a=Dt.identifierPrefix;if(gt){var l=Fs,f=Ds;l=(f&~(1<<32-De(f)-1)).toString(32)+l,a=":"+a+"R"+l,l=Qo++,0<l&&(a+="H"+l.toString(32)),a+=":"}else l=cv++,a=":"+a+"r"+l.toString(32)+":";return s.memoizedState=a},unstable_isNewReconciler:!1},mv={readContext:Dn,useCallback:Vh,useContext:Dn,useEffect:zu,useImperativeHandle:Wh,useInsertionEffect:zh,useLayoutEffect:Uh,useMemo:Gh,useReducer:Du,useRef:Dh,useState:function(){return Du(Yo)},useDebugValue:Uu,useDeferredValue:function(s){var a=Fn();return Hh(a,Rt.memoizedState,s)},useTransition:function(){var s=Du(Yo)[0],a=Fn().memoizedState;return[s,a]},useMutableSource:Ah,useSyncExternalStore:Th,useId:Kh,unstable_isNewReconciler:!1},pv={readContext:Dn,useCallback:Vh,useContext:Dn,useEffect:zu,useImperativeHandle:Wh,useInsertionEffect:zh,useLayoutEffect:Uh,useMemo:Gh,useReducer:Fu,useRef:Dh,useState:function(){return Fu(Yo)},useDebugValue:Uu,useDeferredValue:function(s){var a=Fn();return Rt===null?a.memoizedState=s:Hh(a,Rt.memoizedState,s)},useTransition:function(){var s=Fu(Yo)[0],a=Fn().memoizedState;return[s,a]},useMutableSource:Ah,useSyncExternalStore:Th,useId:Kh,unstable_isNewReconciler:!1};function Zn(s,a){if(s&&s.defaultProps){a=ne({},a),s=s.defaultProps;for(var l in s)a[l]===void 0&&(a[l]=s[l]);return a}return a}function Bu(s,a,l,f){a=s.memoizedState,l=l(f,a),l=l==null?a:ne({},a,l),s.memoizedState=l,s.lanes===0&&(s.updateQueue.baseState=l)}var Il={isMounted:function(s){return(s=s._reactInternals)?js(s)===s:!1},enqueueSetState:function(s,a,l){s=s._reactInternals;var f=sn(),g=_r(s),w=Us(f,g);w.payload=a,l!=null&&(w.callback=l),a=gr(s,w,g),a!==null&&(ns(a,s,g,f),Sl(a,s,g))},enqueueReplaceState:function(s,a,l){s=s._reactInternals;var f=sn(),g=_r(s),w=Us(f,g);w.tag=1,w.payload=a,l!=null&&(w.callback=l),a=gr(s,w,g),a!==null&&(ns(a,s,g,f),Sl(a,s,g))},enqueueForceUpdate:function(s,a){s=s._reactInternals;var l=sn(),f=_r(s),g=Us(l,f);g.tag=2,a!=null&&(g.callback=a),a=gr(s,g,f),a!==null&&(ns(a,s,f,l),Sl(a,s,f))}};function Xh(s,a,l,f,g,w,k){return s=s.stateNode,typeof s.shouldComponentUpdate=="function"?s.shouldComponentUpdate(f,w,k):a.prototype&&a.prototype.isPureReactComponent?!Po(l,f)||!Po(g,w):!0}function qh(s,a,l){var f=!1,g=hr,w=a.contextType;return typeof w=="object"&&w!==null?w=Dn(w):(g=un(a)?Jr:Jt.current,f=a.contextTypes,w=(f=f!=null)?Pa(s,g):hr),a=new a(l,w),s.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=Il,s.stateNode=a,a._reactInternals=s,f&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=g,s.__reactInternalMemoizedMaskedChildContext=w),a}function Zh(s,a,l,f){s=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(l,f),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(l,f),a.state!==s&&Il.enqueueReplaceState(a,a.state,null)}function Wu(s,a,l,f){var g=s.stateNode;g.props=l,g.state=s.memoizedState,g.refs={},$u(s);var w=a.contextType;typeof w=="object"&&w!==null?g.context=Dn(w):(w=un(a)?Jr:Jt.current,g.context=Pa(s,w)),g.state=s.memoizedState,w=a.getDerivedStateFromProps,typeof w=="function"&&(Bu(s,a,w,l),g.state=s.memoizedState),typeof a.getDerivedStateFromProps=="function"||typeof g.getSnapshotBeforeUpdate=="function"||typeof g.UNSAFE_componentWillMount!="function"&&typeof g.componentWillMount!="function"||(a=g.state,typeof g.componentWillMount=="function"&&g.componentWillMount(),typeof g.UNSAFE_componentWillMount=="function"&&g.UNSAFE_componentWillMount(),a!==g.state&&Il.enqueueReplaceState(g,g.state,null),Nl(s,l,g,f),g.state=s.memoizedState),typeof g.componentDidMount=="function"&&(s.flags|=4194308)}function Ga(s,a){try{var l="",f=a;do l+=ee(f),f=f.return;while(f);var g=l}catch(w){g=`
39
+ Error generating stack: `+w.message+`
40
+ `+w.stack}return{value:s,source:a,stack:g,digest:null}}function Vu(s,a,l){return{value:s,source:null,stack:l??null,digest:a??null}}function Gu(s,a){try{console.error(a.value)}catch(l){setTimeout(function(){throw l})}}var gv=typeof WeakMap=="function"?WeakMap:Map;function em(s,a,l){l=Us(-1,l),l.tag=3,l.payload={element:null};var f=a.value;return l.callback=function(){zl||(zl=!0,od=f),Gu(s,a)},l}function tm(s,a,l){l=Us(-1,l),l.tag=3;var f=s.type.getDerivedStateFromError;if(typeof f=="function"){var g=a.value;l.payload=function(){return f(g)},l.callback=function(){Gu(s,a)}}var w=s.stateNode;return w!==null&&typeof w.componentDidCatch=="function"&&(l.callback=function(){Gu(s,a),typeof f!="function"&&(wr===null?wr=new Set([this]):wr.add(this));var k=a.stack;this.componentDidCatch(a.value,{componentStack:k!==null?k:""})}),l}function nm(s,a,l){var f=s.pingCache;if(f===null){f=s.pingCache=new gv;var g=new Set;f.set(a,g)}else g=f.get(a),g===void 0&&(g=new Set,f.set(a,g));g.has(l)||(g.add(l),s=Av.bind(null,s,a,l),a.then(s,s))}function sm(s){do{var a;if((a=s.tag===13)&&(a=s.memoizedState,a=a!==null?a.dehydrated!==null:!0),a)return s;s=s.return}while(s!==null);return null}function rm(s,a,l,f,g){return(s.mode&1)===0?(s===a?s.flags|=65536:(s.flags|=128,l.flags|=131072,l.flags&=-52805,l.tag===1&&(l.alternate===null?l.tag=17:(a=Us(-1,1),a.tag=2,gr(l,a,1))),l.lanes|=1),s):(s.flags|=65536,s.lanes=g,s)}var yv=E.ReactCurrentOwner,dn=!1;function nn(s,a,l,f){a.child=s===null?jh(a,null,l,f):Ua(a,s.child,l,f)}function am(s,a,l,f,g){l=l.render;var w=a.ref;return Wa(a,g),f=Ou(s,a,l,f,w,g),l=Pu(),s!==null&&!dn?(a.updateQueue=s.updateQueue,a.flags&=-2053,s.lanes&=~g,Bs(s,a,g)):(gt&&l&&vu(a),a.flags|=1,nn(s,a,f,g),a.child)}function om(s,a,l,f,g){if(s===null){var w=l.type;return typeof w=="function"&&!hd(w)&&w.defaultProps===void 0&&l.compare===null&&l.defaultProps===void 0?(a.tag=15,a.type=w,im(s,a,w,f,g)):(s=Hl(l.type,null,f,a,a.mode,g),s.ref=a.ref,s.return=a,a.child=s)}if(w=s.child,(s.lanes&g)===0){var k=w.memoizedProps;if(l=l.compare,l=l!==null?l:Po,l(k,f)&&s.ref===a.ref)return Bs(s,a,g)}return a.flags|=1,s=xr(w,f),s.ref=a.ref,s.return=a,a.child=s}function im(s,a,l,f,g){if(s!==null){var w=s.memoizedProps;if(Po(w,f)&&s.ref===a.ref)if(dn=!1,a.pendingProps=f=w,(s.lanes&g)!==0)(s.flags&131072)!==0&&(dn=!0);else return a.lanes=s.lanes,Bs(s,a,g)}return Hu(s,a,l,f,g)}function lm(s,a,l){var f=a.pendingProps,g=f.children,w=s!==null?s.memoizedState:null;if(f.mode==="hidden")if((a.mode&1)===0)a.memoizedState={baseLanes:0,cachePool:null,transitions:null},ut(Ka,Sn),Sn|=l;else{if((l&1073741824)===0)return s=w!==null?w.baseLanes|l:l,a.lanes=a.childLanes=1073741824,a.memoizedState={baseLanes:s,cachePool:null,transitions:null},a.updateQueue=null,ut(Ka,Sn),Sn|=s,null;a.memoizedState={baseLanes:0,cachePool:null,transitions:null},f=w!==null?w.baseLanes:l,ut(Ka,Sn),Sn|=f}else w!==null?(f=w.baseLanes|l,a.memoizedState=null):f=l,ut(Ka,Sn),Sn|=f;return nn(s,a,g,l),a.child}function cm(s,a){var l=a.ref;(s===null&&l!==null||s!==null&&s.ref!==l)&&(a.flags|=512,a.flags|=2097152)}function Hu(s,a,l,f,g){var w=un(l)?Jr:Jt.current;return w=Pa(a,w),Wa(a,g),l=Ou(s,a,l,f,w,g),f=Pu(),s!==null&&!dn?(a.updateQueue=s.updateQueue,a.flags&=-2053,s.lanes&=~g,Bs(s,a,g)):(gt&&f&&vu(a),a.flags|=1,nn(s,a,l,g),a.child)}function um(s,a,l,f,g){if(un(l)){var w=!0;yl(a)}else w=!1;if(Wa(a,g),a.stateNode===null)Ll(s,a),qh(a,l,f),Wu(a,l,f,g),f=!0;else if(s===null){var k=a.stateNode,M=a.memoizedProps;k.props=M;var D=k.context,Y=l.contextType;typeof Y=="object"&&Y!==null?Y=Dn(Y):(Y=un(l)?Jr:Jt.current,Y=Pa(a,Y));var ce=l.getDerivedStateFromProps,me=typeof ce=="function"||typeof k.getSnapshotBeforeUpdate=="function";me||typeof k.UNSAFE_componentWillReceiveProps!="function"&&typeof k.componentWillReceiveProps!="function"||(M!==f||D!==Y)&&Zh(a,k,f,Y),pr=!1;var ie=a.memoizedState;k.state=ie,Nl(a,f,k,g),D=a.memoizedState,M!==f||ie!==D||cn.current||pr?(typeof ce=="function"&&(Bu(a,l,ce,f),D=a.memoizedState),(M=pr||Xh(a,l,M,f,ie,D,Y))?(me||typeof k.UNSAFE_componentWillMount!="function"&&typeof k.componentWillMount!="function"||(typeof k.componentWillMount=="function"&&k.componentWillMount(),typeof k.UNSAFE_componentWillMount=="function"&&k.UNSAFE_componentWillMount()),typeof k.componentDidMount=="function"&&(a.flags|=4194308)):(typeof k.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=f,a.memoizedState=D),k.props=f,k.state=D,k.context=Y,f=M):(typeof k.componentDidMount=="function"&&(a.flags|=4194308),f=!1)}else{k=a.stateNode,Nh(s,a),M=a.memoizedProps,Y=a.type===a.elementType?M:Zn(a.type,M),k.props=Y,me=a.pendingProps,ie=k.context,D=l.contextType,typeof D=="object"&&D!==null?D=Dn(D):(D=un(l)?Jr:Jt.current,D=Pa(a,D));var xe=l.getDerivedStateFromProps;(ce=typeof xe=="function"||typeof k.getSnapshotBeforeUpdate=="function")||typeof k.UNSAFE_componentWillReceiveProps!="function"&&typeof k.componentWillReceiveProps!="function"||(M!==me||ie!==D)&&Zh(a,k,f,D),pr=!1,ie=a.memoizedState,k.state=ie,Nl(a,f,k,g);var Se=a.memoizedState;M!==me||ie!==Se||cn.current||pr?(typeof xe=="function"&&(Bu(a,l,xe,f),Se=a.memoizedState),(Y=pr||Xh(a,l,Y,f,ie,Se,D)||!1)?(ce||typeof k.UNSAFE_componentWillUpdate!="function"&&typeof k.componentWillUpdate!="function"||(typeof k.componentWillUpdate=="function"&&k.componentWillUpdate(f,Se,D),typeof k.UNSAFE_componentWillUpdate=="function"&&k.UNSAFE_componentWillUpdate(f,Se,D)),typeof k.componentDidUpdate=="function"&&(a.flags|=4),typeof k.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof k.componentDidUpdate!="function"||M===s.memoizedProps&&ie===s.memoizedState||(a.flags|=4),typeof k.getSnapshotBeforeUpdate!="function"||M===s.memoizedProps&&ie===s.memoizedState||(a.flags|=1024),a.memoizedProps=f,a.memoizedState=Se),k.props=f,k.state=Se,k.context=D,f=Y):(typeof k.componentDidUpdate!="function"||M===s.memoizedProps&&ie===s.memoizedState||(a.flags|=4),typeof k.getSnapshotBeforeUpdate!="function"||M===s.memoizedProps&&ie===s.memoizedState||(a.flags|=1024),f=!1)}return Ku(s,a,l,f,w,g)}function Ku(s,a,l,f,g,w){cm(s,a);var k=(a.flags&128)!==0;if(!f&&!k)return g&&ph(a,l,!1),Bs(s,a,w);f=a.stateNode,yv.current=a;var M=k&&typeof l.getDerivedStateFromError!="function"?null:f.render();return a.flags|=1,s!==null&&k?(a.child=Ua(a,s.child,null,w),a.child=Ua(a,null,M,w)):nn(s,a,M,w),a.memoizedState=f.state,g&&ph(a,l,!0),a.child}function dm(s){var a=s.stateNode;a.pendingContext?hh(s,a.pendingContext,a.pendingContext!==a.context):a.context&&hh(s,a.context,!1),Au(s,a.containerInfo)}function fm(s,a,l,f,g){return za(),ku(g),a.flags|=256,nn(s,a,l,f),a.child}var Ju={dehydrated:null,treeContext:null,retryLane:0};function Qu(s){return{baseLanes:s,cachePool:null,transitions:null}}function hm(s,a,l){var f=a.pendingProps,g=yt.current,w=!1,k=(a.flags&128)!==0,M;if((M=k)||(M=s!==null&&s.memoizedState===null?!1:(g&2)!==0),M?(w=!0,a.flags&=-129):(s===null||s.memoizedState!==null)&&(g|=1),ut(yt,g&1),s===null)return xu(a),s=a.memoizedState,s!==null&&(s=s.dehydrated,s!==null)?((a.mode&1)===0?a.lanes=1:s.data==="$!"?a.lanes=8:a.lanes=1073741824,null):(k=f.children,s=f.fallback,w?(f=a.mode,w=a.child,k={mode:"hidden",children:k},(f&1)===0&&w!==null?(w.childLanes=0,w.pendingProps=k):w=Kl(k,f,0,null),s=ra(s,f,l,null),w.return=a,s.return=a,w.sibling=s,a.child=w,a.child.memoizedState=Qu(l),a.memoizedState=Ju,s):Yu(a,k));if(g=s.memoizedState,g!==null&&(M=g.dehydrated,M!==null))return wv(s,a,k,f,M,g,l);if(w){w=f.fallback,k=a.mode,g=s.child,M=g.sibling;var D={mode:"hidden",children:f.children};return(k&1)===0&&a.child!==g?(f=a.child,f.childLanes=0,f.pendingProps=D,a.deletions=null):(f=xr(g,D),f.subtreeFlags=g.subtreeFlags&14680064),M!==null?w=xr(M,w):(w=ra(w,k,l,null),w.flags|=2),w.return=a,f.return=a,f.sibling=w,a.child=f,f=w,w=a.child,k=s.child.memoizedState,k=k===null?Qu(l):{baseLanes:k.baseLanes|l,cachePool:null,transitions:k.transitions},w.memoizedState=k,w.childLanes=s.childLanes&~l,a.memoizedState=Ju,f}return w=s.child,s=w.sibling,f=xr(w,{mode:"visible",children:f.children}),(a.mode&1)===0&&(f.lanes=l),f.return=a,f.sibling=null,s!==null&&(l=a.deletions,l===null?(a.deletions=[s],a.flags|=16):l.push(s)),a.child=f,a.memoizedState=null,f}function Yu(s,a){return a=Kl({mode:"visible",children:a},s.mode,0,null),a.return=s,s.child=a}function Ml(s,a,l,f){return f!==null&&ku(f),Ua(a,s.child,null,l),s=Yu(a,a.pendingProps.children),s.flags|=2,a.memoizedState=null,s}function wv(s,a,l,f,g,w,k){if(l)return a.flags&256?(a.flags&=-257,f=Vu(Error(n(422))),Ml(s,a,k,f)):a.memoizedState!==null?(a.child=s.child,a.flags|=128,null):(w=f.fallback,g=a.mode,f=Kl({mode:"visible",children:f.children},g,0,null),w=ra(w,g,k,null),w.flags|=2,f.return=a,w.return=a,f.sibling=w,a.child=f,(a.mode&1)!==0&&Ua(a,s.child,null,k),a.child.memoizedState=Qu(k),a.memoizedState=Ju,w);if((a.mode&1)===0)return Ml(s,a,k,null);if(g.data==="$!"){if(f=g.nextSibling&&g.nextSibling.dataset,f)var M=f.dgst;return f=M,w=Error(n(419)),f=Vu(w,f,void 0),Ml(s,a,k,f)}if(M=(k&s.childLanes)!==0,dn||M){if(f=Dt,f!==null){switch(k&-k){case 4:g=2;break;case 16:g=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:g=32;break;case 536870912:g=268435456;break;default:g=0}g=(g&(f.suspendedLanes|k))!==0?0:g,g!==0&&g!==w.retryLane&&(w.retryLane=g,zs(s,g),ns(f,s,g,-1))}return fd(),f=Vu(Error(n(421))),Ml(s,a,k,f)}return g.data==="$?"?(a.flags|=128,a.child=s.child,a=Tv.bind(null,s),g._reactRetry=a,null):(s=w.treeContext,jn=dr(g.nextSibling),kn=a,gt=!0,qn=null,s!==null&&(On[Pn++]=Ds,On[Pn++]=Fs,On[Pn++]=Qr,Ds=s.id,Fs=s.overflow,Qr=a),a=Yu(a,f.children),a.flags|=4096,a)}function mm(s,a,l){s.lanes|=a;var f=s.alternate;f!==null&&(f.lanes|=a),Cu(s.return,a,l)}function Xu(s,a,l,f,g){var w=s.memoizedState;w===null?s.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:f,tail:l,tailMode:g}:(w.isBackwards=a,w.rendering=null,w.renderingStartTime=0,w.last=f,w.tail=l,w.tailMode=g)}function pm(s,a,l){var f=a.pendingProps,g=f.revealOrder,w=f.tail;if(nn(s,a,f.children,l),f=yt.current,(f&2)!==0)f=f&1|2,a.flags|=128;else{if(s!==null&&(s.flags&128)!==0)e:for(s=a.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&mm(s,l,a);else if(s.tag===19)mm(s,l,a);else if(s.child!==null){s.child.return=s,s=s.child;continue}if(s===a)break e;for(;s.sibling===null;){if(s.return===null||s.return===a)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}f&=1}if(ut(yt,f),(a.mode&1)===0)a.memoizedState=null;else switch(g){case"forwards":for(l=a.child,g=null;l!==null;)s=l.alternate,s!==null&&Cl(s)===null&&(g=l),l=l.sibling;l=g,l===null?(g=a.child,a.child=null):(g=l.sibling,l.sibling=null),Xu(a,!1,g,l,w);break;case"backwards":for(l=null,g=a.child,a.child=null;g!==null;){if(s=g.alternate,s!==null&&Cl(s)===null){a.child=g;break}s=g.sibling,g.sibling=l,l=g,g=s}Xu(a,!0,l,null,w);break;case"together":Xu(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Ll(s,a){(a.mode&1)===0&&s!==null&&(s.alternate=null,a.alternate=null,a.flags|=2)}function Bs(s,a,l){if(s!==null&&(a.dependencies=s.dependencies),ea|=a.lanes,(l&a.childLanes)===0)return null;if(s!==null&&a.child!==s.child)throw Error(n(153));if(a.child!==null){for(s=a.child,l=xr(s,s.pendingProps),a.child=l,l.return=a;s.sibling!==null;)s=s.sibling,l=l.sibling=xr(s,s.pendingProps),l.return=a;l.sibling=null}return a.child}function vv(s,a,l){switch(a.tag){case 3:dm(a),za();break;case 5:$h(a);break;case 1:un(a.type)&&yl(a);break;case 4:Au(a,a.stateNode.containerInfo);break;case 10:var f=a.type._context,g=a.memoizedProps.value;ut(kl,f._currentValue),f._currentValue=g;break;case 13:if(f=a.memoizedState,f!==null)return f.dehydrated!==null?(ut(yt,yt.current&1),a.flags|=128,null):(l&a.child.childLanes)!==0?hm(s,a,l):(ut(yt,yt.current&1),s=Bs(s,a,l),s!==null?s.sibling:null);ut(yt,yt.current&1);break;case 19:if(f=(l&a.childLanes)!==0,(s.flags&128)!==0){if(f)return pm(s,a,l);a.flags|=128}if(g=a.memoizedState,g!==null&&(g.rendering=null,g.tail=null,g.lastEffect=null),ut(yt,yt.current),f)break;return null;case 22:case 23:return a.lanes=0,lm(s,a,l)}return Bs(s,a,l)}var gm,qu,ym,wm;gm=function(s,a){for(var l=a.child;l!==null;){if(l.tag===5||l.tag===6)s.appendChild(l.stateNode);else if(l.tag!==4&&l.child!==null){l.child.return=l,l=l.child;continue}if(l===a)break;for(;l.sibling===null;){if(l.return===null||l.return===a)return;l=l.return}l.sibling.return=l.return,l=l.sibling}},qu=function(){},ym=function(s,a,l,f){var g=s.memoizedProps;if(g!==f){s=a.stateNode,qr(ys.current);var w=null;switch(l){case"input":g=Ye(s,g),f=Ye(s,f),w=[];break;case"select":g=ne({},g,{value:void 0}),f=ne({},f,{value:void 0}),w=[];break;case"textarea":g=be(s,g),f=be(s,f),w=[];break;default:typeof g.onClick!="function"&&typeof f.onClick=="function"&&(s.onclick=ml)}yo(l,f);var k;l=null;for(Y in g)if(!f.hasOwnProperty(Y)&&g.hasOwnProperty(Y)&&g[Y]!=null)if(Y==="style"){var M=g[Y];for(k in M)M.hasOwnProperty(k)&&(l||(l={}),l[k]="")}else Y!=="dangerouslySetInnerHTML"&&Y!=="children"&&Y!=="suppressContentEditableWarning"&&Y!=="suppressHydrationWarning"&&Y!=="autoFocus"&&(i.hasOwnProperty(Y)?w||(w=[]):(w=w||[]).push(Y,null));for(Y in f){var D=f[Y];if(M=g!=null?g[Y]:void 0,f.hasOwnProperty(Y)&&D!==M&&(D!=null||M!=null))if(Y==="style")if(M){for(k in M)!M.hasOwnProperty(k)||D&&D.hasOwnProperty(k)||(l||(l={}),l[k]="");for(k in D)D.hasOwnProperty(k)&&M[k]!==D[k]&&(l||(l={}),l[k]=D[k])}else l||(w||(w=[]),w.push(Y,l)),l=D;else Y==="dangerouslySetInnerHTML"?(D=D?D.__html:void 0,M=M?M.__html:void 0,D!=null&&M!==D&&(w=w||[]).push(Y,D)):Y==="children"?typeof D!="string"&&typeof D!="number"||(w=w||[]).push(Y,""+D):Y!=="suppressContentEditableWarning"&&Y!=="suppressHydrationWarning"&&(i.hasOwnProperty(Y)?(D!=null&&Y==="onScroll"&&ft("scroll",s),w||M===D||(w=[])):(w=w||[]).push(Y,D))}l&&(w=w||[]).push("style",l);var Y=w;(a.updateQueue=Y)&&(a.flags|=4)}},wm=function(s,a,l,f){l!==f&&(a.flags|=4)};function qo(s,a){if(!gt)switch(s.tailMode){case"hidden":a=s.tail;for(var l=null;a!==null;)a.alternate!==null&&(l=a),a=a.sibling;l===null?s.tail=null:l.sibling=null;break;case"collapsed":l=s.tail;for(var f=null;l!==null;)l.alternate!==null&&(f=l),l=l.sibling;f===null?a||s.tail===null?s.tail=null:s.tail.sibling=null:f.sibling=null}}function Yt(s){var a=s.alternate!==null&&s.alternate.child===s.child,l=0,f=0;if(a)for(var g=s.child;g!==null;)l|=g.lanes|g.childLanes,f|=g.subtreeFlags&14680064,f|=g.flags&14680064,g.return=s,g=g.sibling;else for(g=s.child;g!==null;)l|=g.lanes|g.childLanes,f|=g.subtreeFlags,f|=g.flags,g.return=s,g=g.sibling;return s.subtreeFlags|=f,s.childLanes=l,a}function _v(s,a,l){var f=a.pendingProps;switch(_u(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Yt(a),null;case 1:return un(a.type)&&gl(),Yt(a),null;case 3:return f=a.stateNode,Va(),ht(cn),ht(Jt),Iu(),f.pendingContext&&(f.context=f.pendingContext,f.pendingContext=null),(s===null||s.child===null)&&(bl(a)?a.flags|=4:s===null||s.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,qn!==null&&(cd(qn),qn=null))),qu(s,a),Yt(a),null;case 5:Tu(a);var g=qr(Ko.current);if(l=a.type,s!==null&&a.stateNode!=null)ym(s,a,l,f,g),s.ref!==a.ref&&(a.flags|=512,a.flags|=2097152);else{if(!f){if(a.stateNode===null)throw Error(n(166));return Yt(a),null}if(s=qr(ys.current),bl(a)){f=a.stateNode,l=a.type;var w=a.memoizedProps;switch(f[gs]=a,f[Bo]=w,s=(a.mode&1)!==0,l){case"dialog":ft("cancel",f),ft("close",f);break;case"iframe":case"object":case"embed":ft("load",f);break;case"video":case"audio":for(g=0;g<Fo.length;g++)ft(Fo[g],f);break;case"source":ft("error",f);break;case"img":case"image":case"link":ft("error",f),ft("load",f);break;case"details":ft("toggle",f);break;case"input":he(f,w),ft("invalid",f);break;case"select":f._wrapperState={wasMultiple:!!w.multiple},ft("invalid",f);break;case"textarea":Ee(f,w),ft("invalid",f)}yo(l,w),g=null;for(var k in w)if(w.hasOwnProperty(k)){var M=w[k];k==="children"?typeof M=="string"?f.textContent!==M&&(w.suppressHydrationWarning!==!0&&hl(f.textContent,M,s),g=["children",M]):typeof M=="number"&&f.textContent!==""+M&&(w.suppressHydrationWarning!==!0&&hl(f.textContent,M,s),g=["children",""+M]):i.hasOwnProperty(k)&&M!=null&&k==="onScroll"&&ft("scroll",f)}switch(l){case"input":Je(f),Te(f,w,!0);break;case"textarea":Je(f),We(f);break;case"select":case"option":break;default:typeof w.onClick=="function"&&(f.onclick=ml)}f=g,a.updateQueue=f,f!==null&&(a.flags|=4)}else{k=g.nodeType===9?g:g.ownerDocument,s==="http://www.w3.org/1999/xhtml"&&(s=Be(l)),s==="http://www.w3.org/1999/xhtml"?l==="script"?(s=k.createElement("div"),s.innerHTML="<script><\/script>",s=s.removeChild(s.firstChild)):typeof f.is=="string"?s=k.createElement(l,{is:f.is}):(s=k.createElement(l),l==="select"&&(k=s,f.multiple?k.multiple=!0:f.size&&(k.size=f.size))):s=k.createElementNS(s,l),s[gs]=a,s[Bo]=f,gm(s,a,!1,!1),a.stateNode=s;e:{switch(k=ma(l,f),l){case"dialog":ft("cancel",s),ft("close",s),g=f;break;case"iframe":case"object":case"embed":ft("load",s),g=f;break;case"video":case"audio":for(g=0;g<Fo.length;g++)ft(Fo[g],s);g=f;break;case"source":ft("error",s),g=f;break;case"img":case"image":case"link":ft("error",s),ft("load",s),g=f;break;case"details":ft("toggle",s),g=f;break;case"input":he(s,f),g=Ye(s,f),ft("invalid",s);break;case"option":g=f;break;case"select":s._wrapperState={wasMultiple:!!f.multiple},g=ne({},f,{value:void 0}),ft("invalid",s);break;case"textarea":Ee(s,f),g=be(s,f),ft("invalid",s);break;default:g=f}yo(l,g),M=g;for(w in M)if(M.hasOwnProperty(w)){var D=M[w];w==="style"?_n(s,D):w==="dangerouslySetInnerHTML"?(D=D?D.__html:void 0,D!=null&&Vn(s,D)):w==="children"?typeof D=="string"?(l!=="textarea"||D!=="")&&at(s,D):typeof D=="number"&&at(s,""+D):w!=="suppressContentEditableWarning"&&w!=="suppressHydrationWarning"&&w!=="autoFocus"&&(i.hasOwnProperty(w)?D!=null&&w==="onScroll"&&ft("scroll",s):D!=null&&S(s,w,D,k))}switch(l){case"input":Je(s),Te(s,f,!1);break;case"textarea":Je(s),We(s);break;case"option":f.value!=null&&s.setAttribute("value",""+oe(f.value));break;case"select":s.multiple=!!f.multiple,w=f.value,w!=null?pe(s,!!f.multiple,w,!1):f.defaultValue!=null&&pe(s,!!f.multiple,f.defaultValue,!0);break;default:typeof g.onClick=="function"&&(s.onclick=ml)}switch(l){case"button":case"input":case"select":case"textarea":f=!!f.autoFocus;break e;case"img":f=!0;break e;default:f=!1}}f&&(a.flags|=4)}a.ref!==null&&(a.flags|=512,a.flags|=2097152)}return Yt(a),null;case 6:if(s&&a.stateNode!=null)wm(s,a,s.memoizedProps,f);else{if(typeof f!="string"&&a.stateNode===null)throw Error(n(166));if(l=qr(Ko.current),qr(ys.current),bl(a)){if(f=a.stateNode,l=a.memoizedProps,f[gs]=a,(w=f.nodeValue!==l)&&(s=kn,s!==null))switch(s.tag){case 3:hl(f.nodeValue,l,(s.mode&1)!==0);break;case 5:s.memoizedProps.suppressHydrationWarning!==!0&&hl(f.nodeValue,l,(s.mode&1)!==0)}w&&(a.flags|=4)}else f=(l.nodeType===9?l:l.ownerDocument).createTextNode(f),f[gs]=a,a.stateNode=f}return Yt(a),null;case 13:if(ht(yt),f=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(gt&&jn!==null&&(a.mode&1)!==0&&(a.flags&128)===0)bh(),za(),a.flags|=98560,w=!1;else if(w=bl(a),f!==null&&f.dehydrated!==null){if(s===null){if(!w)throw Error(n(318));if(w=a.memoizedState,w=w!==null?w.dehydrated:null,!w)throw Error(n(317));w[gs]=a}else za(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Yt(a),w=!1}else qn!==null&&(cd(qn),qn=null),w=!0;if(!w)return a.flags&65536?a:null}return(a.flags&128)!==0?(a.lanes=l,a):(f=f!==null,f!==(s!==null&&s.memoizedState!==null)&&f&&(a.child.flags|=8192,(a.mode&1)!==0&&(s===null||(yt.current&1)!==0?It===0&&(It=3):fd())),a.updateQueue!==null&&(a.flags|=4),Yt(a),null);case 4:return Va(),qu(s,a),s===null&&zo(a.stateNode.containerInfo),Yt(a),null;case 10:return Nu(a.type._context),Yt(a),null;case 17:return un(a.type)&&gl(),Yt(a),null;case 19:if(ht(yt),w=a.memoizedState,w===null)return Yt(a),null;if(f=(a.flags&128)!==0,k=w.rendering,k===null)if(f)qo(w,!1);else{if(It!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(k=Cl(s),k!==null){for(a.flags|=128,qo(w,!1),f=k.updateQueue,f!==null&&(a.updateQueue=f,a.flags|=4),a.subtreeFlags=0,f=l,l=a.child;l!==null;)w=l,s=f,w.flags&=14680066,k=w.alternate,k===null?(w.childLanes=0,w.lanes=s,w.child=null,w.subtreeFlags=0,w.memoizedProps=null,w.memoizedState=null,w.updateQueue=null,w.dependencies=null,w.stateNode=null):(w.childLanes=k.childLanes,w.lanes=k.lanes,w.child=k.child,w.subtreeFlags=0,w.deletions=null,w.memoizedProps=k.memoizedProps,w.memoizedState=k.memoizedState,w.updateQueue=k.updateQueue,w.type=k.type,s=k.dependencies,w.dependencies=s===null?null:{lanes:s.lanes,firstContext:s.firstContext}),l=l.sibling;return ut(yt,yt.current&1|2),a.child}s=s.sibling}w.tail!==null&&lt()>Ja&&(a.flags|=128,f=!0,qo(w,!1),a.lanes=4194304)}else{if(!f)if(s=Cl(k),s!==null){if(a.flags|=128,f=!0,l=s.updateQueue,l!==null&&(a.updateQueue=l,a.flags|=4),qo(w,!0),w.tail===null&&w.tailMode==="hidden"&&!k.alternate&&!gt)return Yt(a),null}else 2*lt()-w.renderingStartTime>Ja&&l!==1073741824&&(a.flags|=128,f=!0,qo(w,!1),a.lanes=4194304);w.isBackwards?(k.sibling=a.child,a.child=k):(l=w.last,l!==null?l.sibling=k:a.child=k,w.last=k)}return w.tail!==null?(a=w.tail,w.rendering=a,w.tail=a.sibling,w.renderingStartTime=lt(),a.sibling=null,l=yt.current,ut(yt,f?l&1|2:l&1),a):(Yt(a),null);case 22:case 23:return dd(),f=a.memoizedState!==null,s!==null&&s.memoizedState!==null!==f&&(a.flags|=8192),f&&(a.mode&1)!==0?(Sn&1073741824)!==0&&(Yt(a),a.subtreeFlags&6&&(a.flags|=8192)):Yt(a),null;case 24:return null;case 25:return null}throw Error(n(156,a.tag))}function bv(s,a){switch(_u(a),a.tag){case 1:return un(a.type)&&gl(),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return Va(),ht(cn),ht(Jt),Iu(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 5:return Tu(a),null;case 13:if(ht(yt),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(n(340));za()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return ht(yt),null;case 4:return Va(),null;case 10:return Nu(a.type._context),null;case 22:case 23:return dd(),null;case 24:return null;default:return null}}var Ol=!1,Xt=!1,xv=typeof WeakSet=="function"?WeakSet:Set,ke=null;function Ha(s,a){var l=s.ref;if(l!==null)if(typeof l=="function")try{l(null)}catch(f){xt(s,a,f)}else l.current=null}function Zu(s,a,l){try{l()}catch(f){xt(s,a,f)}}var vm=!1;function kv(s,a){if(du=Wr,s=Xf(),su(s)){if("selectionStart"in s)var l={start:s.selectionStart,end:s.selectionEnd};else e:{l=(l=s.ownerDocument)&&l.defaultView||window;var f=l.getSelection&&l.getSelection();if(f&&f.rangeCount!==0){l=f.anchorNode;var g=f.anchorOffset,w=f.focusNode;f=f.focusOffset;try{l.nodeType,w.nodeType}catch{l=null;break e}var k=0,M=-1,D=-1,Y=0,ce=0,me=s,ie=null;t:for(;;){for(var xe;me!==l||g!==0&&me.nodeType!==3||(M=k+g),me!==w||f!==0&&me.nodeType!==3||(D=k+f),me.nodeType===3&&(k+=me.nodeValue.length),(xe=me.firstChild)!==null;)ie=me,me=xe;for(;;){if(me===s)break t;if(ie===l&&++Y===g&&(M=k),ie===w&&++ce===f&&(D=k),(xe=me.nextSibling)!==null)break;me=ie,ie=me.parentNode}me=xe}l=M===-1||D===-1?null:{start:M,end:D}}else l=null}l=l||{start:0,end:0}}else l=null;for(fu={focusedElem:s,selectionRange:l},Wr=!1,ke=a;ke!==null;)if(a=ke,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,ke=s;else for(;ke!==null;){a=ke;try{var Se=a.alternate;if((a.flags&1024)!==0)switch(a.tag){case 0:case 11:case 15:break;case 1:if(Se!==null){var Ne=Se.memoizedProps,St=Se.memoizedState,H=a.stateNode,U=H.getSnapshotBeforeUpdate(a.elementType===a.type?Ne:Zn(a.type,Ne),St);H.__reactInternalSnapshotBeforeUpdate=U}break;case 3:var K=a.stateNode.containerInfo;K.nodeType===1?K.textContent="":K.nodeType===9&&K.documentElement&&K.removeChild(K.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(ye){xt(a,a.return,ye)}if(s=a.sibling,s!==null){s.return=a.return,ke=s;break}ke=a.return}return Se=vm,vm=!1,Se}function Zo(s,a,l){var f=a.updateQueue;if(f=f!==null?f.lastEffect:null,f!==null){var g=f=f.next;do{if((g.tag&s)===s){var w=g.destroy;g.destroy=void 0,w!==void 0&&Zu(a,l,w)}g=g.next}while(g!==f)}}function Pl(s,a){if(a=a.updateQueue,a=a!==null?a.lastEffect:null,a!==null){var l=a=a.next;do{if((l.tag&s)===s){var f=l.create;l.destroy=f()}l=l.next}while(l!==a)}}function ed(s){var a=s.ref;if(a!==null){var l=s.stateNode;switch(s.tag){case 5:s=l;break;default:s=l}typeof a=="function"?a(s):a.current=s}}function _m(s){var a=s.alternate;a!==null&&(s.alternate=null,_m(a)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(a=s.stateNode,a!==null&&(delete a[gs],delete a[Bo],delete a[gu],delete a[av],delete a[ov])),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}function bm(s){return s.tag===5||s.tag===3||s.tag===4}function xm(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||bm(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function td(s,a,l){var f=s.tag;if(f===5||f===6)s=s.stateNode,a?l.nodeType===8?l.parentNode.insertBefore(s,a):l.insertBefore(s,a):(l.nodeType===8?(a=l.parentNode,a.insertBefore(s,l)):(a=l,a.appendChild(s)),l=l._reactRootContainer,l!=null||a.onclick!==null||(a.onclick=ml));else if(f!==4&&(s=s.child,s!==null))for(td(s,a,l),s=s.sibling;s!==null;)td(s,a,l),s=s.sibling}function nd(s,a,l){var f=s.tag;if(f===5||f===6)s=s.stateNode,a?l.insertBefore(s,a):l.appendChild(s);else if(f!==4&&(s=s.child,s!==null))for(nd(s,a,l),s=s.sibling;s!==null;)nd(s,a,l),s=s.sibling}var Bt=null,es=!1;function yr(s,a,l){for(l=l.child;l!==null;)km(s,a,l),l=l.sibling}function km(s,a,l){if(An&&typeof An.onCommitFiberUnmount=="function")try{An.onCommitFiberUnmount(va,l)}catch{}switch(l.tag){case 5:Xt||Ha(l,a);case 6:var f=Bt,g=es;Bt=null,yr(s,a,l),Bt=f,es=g,Bt!==null&&(es?(s=Bt,l=l.stateNode,s.nodeType===8?s.parentNode.removeChild(l):s.removeChild(l)):Bt.removeChild(l.stateNode));break;case 18:Bt!==null&&(es?(s=Bt,l=l.stateNode,s.nodeType===8?pu(s.parentNode,l):s.nodeType===1&&pu(s,l),Br(s)):pu(Bt,l.stateNode));break;case 4:f=Bt,g=es,Bt=l.stateNode.containerInfo,es=!0,yr(s,a,l),Bt=f,es=g;break;case 0:case 11:case 14:case 15:if(!Xt&&(f=l.updateQueue,f!==null&&(f=f.lastEffect,f!==null))){g=f=f.next;do{var w=g,k=w.destroy;w=w.tag,k!==void 0&&((w&2)!==0||(w&4)!==0)&&Zu(l,a,k),g=g.next}while(g!==f)}yr(s,a,l);break;case 1:if(!Xt&&(Ha(l,a),f=l.stateNode,typeof f.componentWillUnmount=="function"))try{f.props=l.memoizedProps,f.state=l.memoizedState,f.componentWillUnmount()}catch(M){xt(l,a,M)}yr(s,a,l);break;case 21:yr(s,a,l);break;case 22:l.mode&1?(Xt=(f=Xt)||l.memoizedState!==null,yr(s,a,l),Xt=f):yr(s,a,l);break;default:yr(s,a,l)}}function jm(s){var a=s.updateQueue;if(a!==null){s.updateQueue=null;var l=s.stateNode;l===null&&(l=s.stateNode=new xv),a.forEach(function(f){var g=Rv.bind(null,s,f);l.has(f)||(l.add(f),f.then(g,g))})}}function ts(s,a){var l=a.deletions;if(l!==null)for(var f=0;f<l.length;f++){var g=l[f];try{var w=s,k=a,M=k;e:for(;M!==null;){switch(M.tag){case 5:Bt=M.stateNode,es=!1;break e;case 3:Bt=M.stateNode.containerInfo,es=!0;break e;case 4:Bt=M.stateNode.containerInfo,es=!0;break e}M=M.return}if(Bt===null)throw Error(n(160));km(w,k,g),Bt=null,es=!1;var D=g.alternate;D!==null&&(D.return=null),g.return=null}catch(Y){xt(g,a,Y)}}if(a.subtreeFlags&12854)for(a=a.child;a!==null;)Sm(a,s),a=a.sibling}function Sm(s,a){var l=s.alternate,f=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:if(ts(a,s),vs(s),f&4){try{Zo(3,s,s.return),Pl(3,s)}catch(Ne){xt(s,s.return,Ne)}try{Zo(5,s,s.return)}catch(Ne){xt(s,s.return,Ne)}}break;case 1:ts(a,s),vs(s),f&512&&l!==null&&Ha(l,l.return);break;case 5:if(ts(a,s),vs(s),f&512&&l!==null&&Ha(l,l.return),s.flags&32){var g=s.stateNode;try{at(g,"")}catch(Ne){xt(s,s.return,Ne)}}if(f&4&&(g=s.stateNode,g!=null)){var w=s.memoizedProps,k=l!==null?l.memoizedProps:w,M=s.type,D=s.updateQueue;if(s.updateQueue=null,D!==null)try{M==="input"&&w.type==="radio"&&w.name!=null&&Ve(g,w),ma(M,k);var Y=ma(M,w);for(k=0;k<D.length;k+=2){var ce=D[k],me=D[k+1];ce==="style"?_n(g,me):ce==="dangerouslySetInnerHTML"?Vn(g,me):ce==="children"?at(g,me):S(g,ce,me,Y)}switch(M){case"input":ae(g,w);break;case"textarea":Pe(g,w);break;case"select":var ie=g._wrapperState.wasMultiple;g._wrapperState.wasMultiple=!!w.multiple;var xe=w.value;xe!=null?pe(g,!!w.multiple,xe,!1):ie!==!!w.multiple&&(w.defaultValue!=null?pe(g,!!w.multiple,w.defaultValue,!0):pe(g,!!w.multiple,w.multiple?[]:"",!1))}g[Bo]=w}catch(Ne){xt(s,s.return,Ne)}}break;case 6:if(ts(a,s),vs(s),f&4){if(s.stateNode===null)throw Error(n(162));g=s.stateNode,w=s.memoizedProps;try{g.nodeValue=w}catch(Ne){xt(s,s.return,Ne)}}break;case 3:if(ts(a,s),vs(s),f&4&&l!==null&&l.memoizedState.isDehydrated)try{Br(a.containerInfo)}catch(Ne){xt(s,s.return,Ne)}break;case 4:ts(a,s),vs(s);break;case 13:ts(a,s),vs(s),g=s.child,g.flags&8192&&(w=g.memoizedState!==null,g.stateNode.isHidden=w,!w||g.alternate!==null&&g.alternate.memoizedState!==null||(ad=lt())),f&4&&jm(s);break;case 22:if(ce=l!==null&&l.memoizedState!==null,s.mode&1?(Xt=(Y=Xt)||ce,ts(a,s),Xt=Y):ts(a,s),vs(s),f&8192){if(Y=s.memoizedState!==null,(s.stateNode.isHidden=Y)&&!ce&&(s.mode&1)!==0)for(ke=s,ce=s.child;ce!==null;){for(me=ke=ce;ke!==null;){switch(ie=ke,xe=ie.child,ie.tag){case 0:case 11:case 14:case 15:Zo(4,ie,ie.return);break;case 1:Ha(ie,ie.return);var Se=ie.stateNode;if(typeof Se.componentWillUnmount=="function"){f=ie,l=ie.return;try{a=f,Se.props=a.memoizedProps,Se.state=a.memoizedState,Se.componentWillUnmount()}catch(Ne){xt(f,l,Ne)}}break;case 5:Ha(ie,ie.return);break;case 22:if(ie.memoizedState!==null){Em(me);continue}}xe!==null?(xe.return=ie,ke=xe):Em(me)}ce=ce.sibling}e:for(ce=null,me=s;;){if(me.tag===5){if(ce===null){ce=me;try{g=me.stateNode,Y?(w=g.style,typeof w.setProperty=="function"?w.setProperty("display","none","important"):w.display="none"):(M=me.stateNode,D=me.memoizedProps.style,k=D!=null&&D.hasOwnProperty("display")?D.display:null,M.style.display=go("display",k))}catch(Ne){xt(s,s.return,Ne)}}}else if(me.tag===6){if(ce===null)try{me.stateNode.nodeValue=Y?"":me.memoizedProps}catch(Ne){xt(s,s.return,Ne)}}else if((me.tag!==22&&me.tag!==23||me.memoizedState===null||me===s)&&me.child!==null){me.child.return=me,me=me.child;continue}if(me===s)break e;for(;me.sibling===null;){if(me.return===null||me.return===s)break e;ce===me&&(ce=null),me=me.return}ce===me&&(ce=null),me.sibling.return=me.return,me=me.sibling}}break;case 19:ts(a,s),vs(s),f&4&&jm(s);break;case 21:break;default:ts(a,s),vs(s)}}function vs(s){var a=s.flags;if(a&2){try{e:{for(var l=s.return;l!==null;){if(bm(l)){var f=l;break e}l=l.return}throw Error(n(160))}switch(f.tag){case 5:var g=f.stateNode;f.flags&32&&(at(g,""),f.flags&=-33);var w=xm(s);nd(s,w,g);break;case 3:case 4:var k=f.stateNode.containerInfo,M=xm(s);td(s,M,k);break;default:throw Error(n(161))}}catch(D){xt(s,s.return,D)}s.flags&=-3}a&4096&&(s.flags&=-4097)}function jv(s,a,l){ke=s,Nm(s)}function Nm(s,a,l){for(var f=(s.mode&1)!==0;ke!==null;){var g=ke,w=g.child;if(g.tag===22&&f){var k=g.memoizedState!==null||Ol;if(!k){var M=g.alternate,D=M!==null&&M.memoizedState!==null||Xt;M=Ol;var Y=Xt;if(Ol=k,(Xt=D)&&!Y)for(ke=g;ke!==null;)k=ke,D=k.child,k.tag===22&&k.memoizedState!==null?$m(g):D!==null?(D.return=k,ke=D):$m(g);for(;w!==null;)ke=w,Nm(w),w=w.sibling;ke=g,Ol=M,Xt=Y}Cm(s)}else(g.subtreeFlags&8772)!==0&&w!==null?(w.return=g,ke=w):Cm(s)}}function Cm(s){for(;ke!==null;){var a=ke;if((a.flags&8772)!==0){var l=a.alternate;try{if((a.flags&8772)!==0)switch(a.tag){case 0:case 11:case 15:Xt||Pl(5,a);break;case 1:var f=a.stateNode;if(a.flags&4&&!Xt)if(l===null)f.componentDidMount();else{var g=a.elementType===a.type?l.memoizedProps:Zn(a.type,l.memoizedProps);f.componentDidUpdate(g,l.memoizedState,f.__reactInternalSnapshotBeforeUpdate)}var w=a.updateQueue;w!==null&&Eh(a,w,f);break;case 3:var k=a.updateQueue;if(k!==null){if(l=null,a.child!==null)switch(a.child.tag){case 5:l=a.child.stateNode;break;case 1:l=a.child.stateNode}Eh(a,k,l)}break;case 5:var M=a.stateNode;if(l===null&&a.flags&4){l=M;var D=a.memoizedProps;switch(a.type){case"button":case"input":case"select":case"textarea":D.autoFocus&&l.focus();break;case"img":D.src&&(l.src=D.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(a.memoizedState===null){var Y=a.alternate;if(Y!==null){var ce=Y.memoizedState;if(ce!==null){var me=ce.dehydrated;me!==null&&Br(me)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Xt||a.flags&512&&ed(a)}catch(ie){xt(a,a.return,ie)}}if(a===s){ke=null;break}if(l=a.sibling,l!==null){l.return=a.return,ke=l;break}ke=a.return}}function Em(s){for(;ke!==null;){var a=ke;if(a===s){ke=null;break}var l=a.sibling;if(l!==null){l.return=a.return,ke=l;break}ke=a.return}}function $m(s){for(;ke!==null;){var a=ke;try{switch(a.tag){case 0:case 11:case 15:var l=a.return;try{Pl(4,a)}catch(D){xt(a,l,D)}break;case 1:var f=a.stateNode;if(typeof f.componentDidMount=="function"){var g=a.return;try{f.componentDidMount()}catch(D){xt(a,g,D)}}var w=a.return;try{ed(a)}catch(D){xt(a,w,D)}break;case 5:var k=a.return;try{ed(a)}catch(D){xt(a,k,D)}}}catch(D){xt(a,a.return,D)}if(a===s){ke=null;break}var M=a.sibling;if(M!==null){M.return=a.return,ke=M;break}ke=a.return}}var Sv=Math.ceil,Dl=E.ReactCurrentDispatcher,sd=E.ReactCurrentOwner,zn=E.ReactCurrentBatchConfig,Xe=0,Dt=null,Et=null,Wt=0,Sn=0,Ka=fr(0),It=0,ei=null,ea=0,Fl=0,rd=0,ti=null,fn=null,ad=0,Ja=1/0,Ws=null,zl=!1,od=null,wr=null,Ul=!1,vr=null,Bl=0,ni=0,id=null,Wl=-1,Vl=0;function sn(){return(Xe&6)!==0?lt():Wl!==-1?Wl:Wl=lt()}function _r(s){return(s.mode&1)===0?1:(Xe&2)!==0&&Wt!==0?Wt&-Wt:lv.transition!==null?(Vl===0&&(Vl=Es()),Vl):(s=Ge,s!==0||(s=window.event,s=s===void 0?16:ja(s.type)),s)}function ns(s,a,l,f){if(50<ni)throw ni=0,id=null,Error(n(185));nr(s,l,f),((Xe&2)===0||s!==Dt)&&(s===Dt&&((Xe&2)===0&&(Fl|=l),It===4&&br(s,Wt)),hn(s,f),l===1&&Xe===0&&(a.mode&1)===0&&(Ja=lt()+500,wl&&mr()))}function hn(s,a){var l=s.callbackNode;Jn(s,a);var f=tr(s,s===Dt?Wt:0);if(f===0)l!==null&&$n(l),s.callbackNode=null,s.callbackPriority=0;else if(a=f&-f,s.callbackPriority!==a){if(l!=null&&$n(l),a===1)s.tag===0?iv(Tm.bind(null,s)):gh(Tm.bind(null,s)),sv(function(){(Xe&6)===0&&mr()}),l=null;else{switch(Eo(f)){case 1:l=So;break;case 4:l=wa;break;case 16:l=Pr;break;case 536870912:l=No;break;default:l=Pr}l=Fm(l,Am.bind(null,s))}s.callbackPriority=a,s.callbackNode=l}}function Am(s,a){if(Wl=-1,Vl=0,(Xe&6)!==0)throw Error(n(327));var l=s.callbackNode;if(Qa()&&s.callbackNode!==l)return null;var f=tr(s,s===Dt?Wt:0);if(f===0)return null;if((f&30)!==0||(f&s.expiredLanes)!==0||a)a=Gl(s,f);else{a=f;var g=Xe;Xe|=2;var w=Im();(Dt!==s||Wt!==a)&&(Ws=null,Ja=lt()+500,na(s,a));do try{Ev();break}catch(M){Rm(s,M)}while(!0);Su(),Dl.current=w,Xe=g,Et!==null?a=0:(Dt=null,Wt=0,a=It)}if(a!==0){if(a===2&&(g=Qn(s),g!==0&&(f=g,a=ld(s,g))),a===1)throw l=ei,na(s,0),br(s,f),hn(s,lt()),l;if(a===6)br(s,f);else{if(g=s.current.alternate,(f&30)===0&&!Nv(g)&&(a=Gl(s,f),a===2&&(w=Qn(s),w!==0&&(f=w,a=ld(s,w))),a===1))throw l=ei,na(s,0),br(s,f),hn(s,lt()),l;switch(s.finishedWork=g,s.finishedLanes=f,a){case 0:case 1:throw Error(n(345));case 2:sa(s,fn,Ws);break;case 3:if(br(s,f),(f&130023424)===f&&(a=ad+500-lt(),10<a)){if(tr(s,0)!==0)break;if(g=s.suspendedLanes,(g&f)!==f){sn(),s.pingedLanes|=s.suspendedLanes&g;break}s.timeoutHandle=mu(sa.bind(null,s,fn,Ws),a);break}sa(s,fn,Ws);break;case 4:if(br(s,f),(f&4194240)===f)break;for(a=s.eventTimes,g=-1;0<f;){var k=31-De(f);w=1<<k,k=a[k],k>g&&(g=k),f&=~w}if(f=g,f=lt()-f,f=(120>f?120:480>f?480:1080>f?1080:1920>f?1920:3e3>f?3e3:4320>f?4320:1960*Sv(f/1960))-f,10<f){s.timeoutHandle=mu(sa.bind(null,s,fn,Ws),f);break}sa(s,fn,Ws);break;case 5:sa(s,fn,Ws);break;default:throw Error(n(329))}}}return hn(s,lt()),s.callbackNode===l?Am.bind(null,s):null}function ld(s,a){var l=ti;return s.current.memoizedState.isDehydrated&&(na(s,a).flags|=256),s=Gl(s,a),s!==2&&(a=fn,fn=l,a!==null&&cd(a)),s}function cd(s){fn===null?fn=s:fn.push.apply(fn,s)}function Nv(s){for(var a=s;;){if(a.flags&16384){var l=a.updateQueue;if(l!==null&&(l=l.stores,l!==null))for(var f=0;f<l.length;f++){var g=l[f],w=g.getSnapshot;g=g.value;try{if(!Xn(w(),g))return!1}catch{return!1}}}if(l=a.child,a.subtreeFlags&16384&&l!==null)l.return=a,a=l;else{if(a===s)break;for(;a.sibling===null;){if(a.return===null||a.return===s)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function br(s,a){for(a&=~rd,a&=~Fl,s.suspendedLanes|=a,s.pingedLanes&=~a,s=s.expirationTimes;0<a;){var l=31-De(a),f=1<<l;s[l]=-1,a&=~f}}function Tm(s){if((Xe&6)!==0)throw Error(n(327));Qa();var a=tr(s,0);if((a&1)===0)return hn(s,lt()),null;var l=Gl(s,a);if(s.tag!==0&&l===2){var f=Qn(s);f!==0&&(a=f,l=ld(s,f))}if(l===1)throw l=ei,na(s,0),br(s,a),hn(s,lt()),l;if(l===6)throw Error(n(345));return s.finishedWork=s.current.alternate,s.finishedLanes=a,sa(s,fn,Ws),hn(s,lt()),null}function ud(s,a){var l=Xe;Xe|=1;try{return s(a)}finally{Xe=l,Xe===0&&(Ja=lt()+500,wl&&mr())}}function ta(s){vr!==null&&vr.tag===0&&(Xe&6)===0&&Qa();var a=Xe;Xe|=1;var l=zn.transition,f=Ge;try{if(zn.transition=null,Ge=1,s)return s()}finally{Ge=f,zn.transition=l,Xe=a,(Xe&6)===0&&mr()}}function dd(){Sn=Ka.current,ht(Ka)}function na(s,a){s.finishedWork=null,s.finishedLanes=0;var l=s.timeoutHandle;if(l!==-1&&(s.timeoutHandle=-1,nv(l)),Et!==null)for(l=Et.return;l!==null;){var f=l;switch(_u(f),f.tag){case 1:f=f.type.childContextTypes,f!=null&&gl();break;case 3:Va(),ht(cn),ht(Jt),Iu();break;case 5:Tu(f);break;case 4:Va();break;case 13:ht(yt);break;case 19:ht(yt);break;case 10:Nu(f.type._context);break;case 22:case 23:dd()}l=l.return}if(Dt=s,Et=s=xr(s.current,null),Wt=Sn=a,It=0,ei=null,rd=Fl=ea=0,fn=ti=null,Xr!==null){for(a=0;a<Xr.length;a++)if(l=Xr[a],f=l.interleaved,f!==null){l.interleaved=null;var g=f.next,w=l.pending;if(w!==null){var k=w.next;w.next=g,f.next=k}l.pending=f}Xr=null}return s}function Rm(s,a){do{var l=Et;try{if(Su(),El.current=Rl,$l){for(var f=wt.memoizedState;f!==null;){var g=f.queue;g!==null&&(g.pending=null),f=f.next}$l=!1}if(Zr=0,Pt=Rt=wt=null,Jo=!1,Qo=0,sd.current=null,l===null||l.return===null){It=1,ei=a,Et=null;break}e:{var w=s,k=l.return,M=l,D=a;if(a=Wt,M.flags|=32768,D!==null&&typeof D=="object"&&typeof D.then=="function"){var Y=D,ce=M,me=ce.tag;if((ce.mode&1)===0&&(me===0||me===11||me===15)){var ie=ce.alternate;ie?(ce.updateQueue=ie.updateQueue,ce.memoizedState=ie.memoizedState,ce.lanes=ie.lanes):(ce.updateQueue=null,ce.memoizedState=null)}var xe=sm(k);if(xe!==null){xe.flags&=-257,rm(xe,k,M,w,a),xe.mode&1&&nm(w,Y,a),a=xe,D=Y;var Se=a.updateQueue;if(Se===null){var Ne=new Set;Ne.add(D),a.updateQueue=Ne}else Se.add(D);break e}else{if((a&1)===0){nm(w,Y,a),fd();break e}D=Error(n(426))}}else if(gt&&M.mode&1){var St=sm(k);if(St!==null){(St.flags&65536)===0&&(St.flags|=256),rm(St,k,M,w,a),ku(Ga(D,M));break e}}w=D=Ga(D,M),It!==4&&(It=2),ti===null?ti=[w]:ti.push(w),w=k;do{switch(w.tag){case 3:w.flags|=65536,a&=-a,w.lanes|=a;var H=em(w,D,a);Ch(w,H);break e;case 1:M=D;var U=w.type,K=w.stateNode;if((w.flags&128)===0&&(typeof U.getDerivedStateFromError=="function"||K!==null&&typeof K.componentDidCatch=="function"&&(wr===null||!wr.has(K)))){w.flags|=65536,a&=-a,w.lanes|=a;var ye=tm(w,M,a);Ch(w,ye);break e}}w=w.return}while(w!==null)}Lm(l)}catch($e){a=$e,Et===l&&l!==null&&(Et=l=l.return);continue}break}while(!0)}function Im(){var s=Dl.current;return Dl.current=Rl,s===null?Rl:s}function fd(){(It===0||It===3||It===2)&&(It=4),Dt===null||(ea&268435455)===0&&(Fl&268435455)===0||br(Dt,Wt)}function Gl(s,a){var l=Xe;Xe|=2;var f=Im();(Dt!==s||Wt!==a)&&(Ws=null,na(s,a));do try{Cv();break}catch(g){Rm(s,g)}while(!0);if(Su(),Xe=l,Dl.current=f,Et!==null)throw Error(n(261));return Dt=null,Wt=0,It}function Cv(){for(;Et!==null;)Mm(Et)}function Ev(){for(;Et!==null&&!Ui();)Mm(Et)}function Mm(s){var a=Dm(s.alternate,s,Sn);s.memoizedProps=s.pendingProps,a===null?Lm(s):Et=a,sd.current=null}function Lm(s){var a=s;do{var l=a.alternate;if(s=a.return,(a.flags&32768)===0){if(l=_v(l,a,Sn),l!==null){Et=l;return}}else{if(l=bv(l,a),l!==null){l.flags&=32767,Et=l;return}if(s!==null)s.flags|=32768,s.subtreeFlags=0,s.deletions=null;else{It=6,Et=null;return}}if(a=a.sibling,a!==null){Et=a;return}Et=a=s}while(a!==null);It===0&&(It=5)}function sa(s,a,l){var f=Ge,g=zn.transition;try{zn.transition=null,Ge=1,$v(s,a,l,f)}finally{zn.transition=g,Ge=f}return null}function $v(s,a,l,f){do Qa();while(vr!==null);if((Xe&6)!==0)throw Error(n(327));l=s.finishedWork;var g=s.finishedLanes;if(l===null)return null;if(s.finishedWork=null,s.finishedLanes=0,l===s.current)throw Error(n(177));s.callbackNode=null,s.callbackPriority=0;var w=l.lanes|l.childLanes;if(Tn(s,w),s===Dt&&(Et=Dt=null,Wt=0),(l.subtreeFlags&2064)===0&&(l.flags&2064)===0||Ul||(Ul=!0,Fm(Pr,function(){return Qa(),null})),w=(l.flags&15990)!==0,(l.subtreeFlags&15990)!==0||w){w=zn.transition,zn.transition=null;var k=Ge;Ge=1;var M=Xe;Xe|=4,sd.current=null,kv(s,l),Sm(l,s),Qw(fu),Wr=!!du,fu=du=null,s.current=l,jv(l),ko(),Xe=M,Ge=k,zn.transition=w}else s.current=l;if(Ul&&(Ul=!1,vr=s,Bl=g),w=s.pendingLanes,w===0&&(wr=null),Ss(l.stateNode),hn(s,lt()),a!==null)for(f=s.onRecoverableError,l=0;l<a.length;l++)g=a[l],f(g.value,{componentStack:g.stack,digest:g.digest});if(zl)throw zl=!1,s=od,od=null,s;return(Bl&1)!==0&&s.tag!==0&&Qa(),w=s.pendingLanes,(w&1)!==0?s===id?ni++:(ni=0,id=s):ni=0,mr(),null}function Qa(){if(vr!==null){var s=Eo(Bl),a=zn.transition,l=Ge;try{if(zn.transition=null,Ge=16>s?16:s,vr===null)var f=!1;else{if(s=vr,vr=null,Bl=0,(Xe&6)!==0)throw Error(n(331));var g=Xe;for(Xe|=4,ke=s.current;ke!==null;){var w=ke,k=w.child;if((ke.flags&16)!==0){var M=w.deletions;if(M!==null){for(var D=0;D<M.length;D++){var Y=M[D];for(ke=Y;ke!==null;){var ce=ke;switch(ce.tag){case 0:case 11:case 15:Zo(8,ce,w)}var me=ce.child;if(me!==null)me.return=ce,ke=me;else for(;ke!==null;){ce=ke;var ie=ce.sibling,xe=ce.return;if(_m(ce),ce===Y){ke=null;break}if(ie!==null){ie.return=xe,ke=ie;break}ke=xe}}}var Se=w.alternate;if(Se!==null){var Ne=Se.child;if(Ne!==null){Se.child=null;do{var St=Ne.sibling;Ne.sibling=null,Ne=St}while(Ne!==null)}}ke=w}}if((w.subtreeFlags&2064)!==0&&k!==null)k.return=w,ke=k;else e:for(;ke!==null;){if(w=ke,(w.flags&2048)!==0)switch(w.tag){case 0:case 11:case 15:Zo(9,w,w.return)}var H=w.sibling;if(H!==null){H.return=w.return,ke=H;break e}ke=w.return}}var U=s.current;for(ke=U;ke!==null;){k=ke;var K=k.child;if((k.subtreeFlags&2064)!==0&&K!==null)K.return=k,ke=K;else e:for(k=U;ke!==null;){if(M=ke,(M.flags&2048)!==0)try{switch(M.tag){case 0:case 11:case 15:Pl(9,M)}}catch($e){xt(M,M.return,$e)}if(M===k){ke=null;break e}var ye=M.sibling;if(ye!==null){ye.return=M.return,ke=ye;break e}ke=M.return}}if(Xe=g,mr(),An&&typeof An.onPostCommitFiberRoot=="function")try{An.onPostCommitFiberRoot(va,s)}catch{}f=!0}return f}finally{Ge=l,zn.transition=a}}return!1}function Om(s,a,l){a=Ga(l,a),a=em(s,a,1),s=gr(s,a,1),a=sn(),s!==null&&(nr(s,1,a),hn(s,a))}function xt(s,a,l){if(s.tag===3)Om(s,s,l);else for(;a!==null;){if(a.tag===3){Om(a,s,l);break}else if(a.tag===1){var f=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof f.componentDidCatch=="function"&&(wr===null||!wr.has(f))){s=Ga(l,s),s=tm(a,s,1),a=gr(a,s,1),s=sn(),a!==null&&(nr(a,1,s),hn(a,s));break}}a=a.return}}function Av(s,a,l){var f=s.pingCache;f!==null&&f.delete(a),a=sn(),s.pingedLanes|=s.suspendedLanes&l,Dt===s&&(Wt&l)===l&&(It===4||It===3&&(Wt&130023424)===Wt&&500>lt()-ad?na(s,0):rd|=l),hn(s,a)}function Pm(s,a){a===0&&((s.mode&1)===0?a=1:(a=Cs,Cs<<=1,(Cs&130023424)===0&&(Cs=4194304)));var l=sn();s=zs(s,a),s!==null&&(nr(s,a,l),hn(s,l))}function Tv(s){var a=s.memoizedState,l=0;a!==null&&(l=a.retryLane),Pm(s,l)}function Rv(s,a){var l=0;switch(s.tag){case 13:var f=s.stateNode,g=s.memoizedState;g!==null&&(l=g.retryLane);break;case 19:f=s.stateNode;break;default:throw Error(n(314))}f!==null&&f.delete(a),Pm(s,l)}var Dm;Dm=function(s,a,l){if(s!==null)if(s.memoizedProps!==a.pendingProps||cn.current)dn=!0;else{if((s.lanes&l)===0&&(a.flags&128)===0)return dn=!1,vv(s,a,l);dn=(s.flags&131072)!==0}else dn=!1,gt&&(a.flags&1048576)!==0&&yh(a,_l,a.index);switch(a.lanes=0,a.tag){case 2:var f=a.type;Ll(s,a),s=a.pendingProps;var g=Pa(a,Jt.current);Wa(a,l),g=Ou(null,a,f,s,g,l);var w=Pu();return a.flags|=1,typeof g=="object"&&g!==null&&typeof g.render=="function"&&g.$$typeof===void 0?(a.tag=1,a.memoizedState=null,a.updateQueue=null,un(f)?(w=!0,yl(a)):w=!1,a.memoizedState=g.state!==null&&g.state!==void 0?g.state:null,$u(a),g.updater=Il,a.stateNode=g,g._reactInternals=a,Wu(a,f,s,l),a=Ku(null,a,f,!0,w,l)):(a.tag=0,gt&&w&&vu(a),nn(null,a,g,l),a=a.child),a;case 16:f=a.elementType;e:{switch(Ll(s,a),s=a.pendingProps,g=f._init,f=g(f._payload),a.type=f,g=a.tag=Mv(f),s=Zn(f,s),g){case 0:a=Hu(null,a,f,s,l);break e;case 1:a=um(null,a,f,s,l);break e;case 11:a=am(null,a,f,s,l);break e;case 14:a=om(null,a,f,Zn(f.type,s),l);break e}throw Error(n(306,f,""))}return a;case 0:return f=a.type,g=a.pendingProps,g=a.elementType===f?g:Zn(f,g),Hu(s,a,f,g,l);case 1:return f=a.type,g=a.pendingProps,g=a.elementType===f?g:Zn(f,g),um(s,a,f,g,l);case 3:e:{if(dm(a),s===null)throw Error(n(387));f=a.pendingProps,w=a.memoizedState,g=w.element,Nh(s,a),Nl(a,f,null,l);var k=a.memoizedState;if(f=k.element,w.isDehydrated)if(w={element:f,isDehydrated:!1,cache:k.cache,pendingSuspenseBoundaries:k.pendingSuspenseBoundaries,transitions:k.transitions},a.updateQueue.baseState=w,a.memoizedState=w,a.flags&256){g=Ga(Error(n(423)),a),a=fm(s,a,f,l,g);break e}else if(f!==g){g=Ga(Error(n(424)),a),a=fm(s,a,f,l,g);break e}else for(jn=dr(a.stateNode.containerInfo.firstChild),kn=a,gt=!0,qn=null,l=jh(a,null,f,l),a.child=l;l;)l.flags=l.flags&-3|4096,l=l.sibling;else{if(za(),f===g){a=Bs(s,a,l);break e}nn(s,a,f,l)}a=a.child}return a;case 5:return $h(a),s===null&&xu(a),f=a.type,g=a.pendingProps,w=s!==null?s.memoizedProps:null,k=g.children,hu(f,g)?k=null:w!==null&&hu(f,w)&&(a.flags|=32),cm(s,a),nn(s,a,k,l),a.child;case 6:return s===null&&xu(a),null;case 13:return hm(s,a,l);case 4:return Au(a,a.stateNode.containerInfo),f=a.pendingProps,s===null?a.child=Ua(a,null,f,l):nn(s,a,f,l),a.child;case 11:return f=a.type,g=a.pendingProps,g=a.elementType===f?g:Zn(f,g),am(s,a,f,g,l);case 7:return nn(s,a,a.pendingProps,l),a.child;case 8:return nn(s,a,a.pendingProps.children,l),a.child;case 12:return nn(s,a,a.pendingProps.children,l),a.child;case 10:e:{if(f=a.type._context,g=a.pendingProps,w=a.memoizedProps,k=g.value,ut(kl,f._currentValue),f._currentValue=k,w!==null)if(Xn(w.value,k)){if(w.children===g.children&&!cn.current){a=Bs(s,a,l);break e}}else for(w=a.child,w!==null&&(w.return=a);w!==null;){var M=w.dependencies;if(M!==null){k=w.child;for(var D=M.firstContext;D!==null;){if(D.context===f){if(w.tag===1){D=Us(-1,l&-l),D.tag=2;var Y=w.updateQueue;if(Y!==null){Y=Y.shared;var ce=Y.pending;ce===null?D.next=D:(D.next=ce.next,ce.next=D),Y.pending=D}}w.lanes|=l,D=w.alternate,D!==null&&(D.lanes|=l),Cu(w.return,l,a),M.lanes|=l;break}D=D.next}}else if(w.tag===10)k=w.type===a.type?null:w.child;else if(w.tag===18){if(k=w.return,k===null)throw Error(n(341));k.lanes|=l,M=k.alternate,M!==null&&(M.lanes|=l),Cu(k,l,a),k=w.sibling}else k=w.child;if(k!==null)k.return=w;else for(k=w;k!==null;){if(k===a){k=null;break}if(w=k.sibling,w!==null){w.return=k.return,k=w;break}k=k.return}w=k}nn(s,a,g.children,l),a=a.child}return a;case 9:return g=a.type,f=a.pendingProps.children,Wa(a,l),g=Dn(g),f=f(g),a.flags|=1,nn(s,a,f,l),a.child;case 14:return f=a.type,g=Zn(f,a.pendingProps),g=Zn(f.type,g),om(s,a,f,g,l);case 15:return im(s,a,a.type,a.pendingProps,l);case 17:return f=a.type,g=a.pendingProps,g=a.elementType===f?g:Zn(f,g),Ll(s,a),a.tag=1,un(f)?(s=!0,yl(a)):s=!1,Wa(a,l),qh(a,f,g),Wu(a,f,g,l),Ku(null,a,f,!0,s,l);case 19:return pm(s,a,l);case 22:return lm(s,a,l)}throw Error(n(156,a.tag))};function Fm(s,a){return ya(s,a)}function Iv(s,a,l,f){this.tag=s,this.key=l,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=f,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Un(s,a,l,f){return new Iv(s,a,l,f)}function hd(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Mv(s){if(typeof s=="function")return hd(s)?1:0;if(s!=null){if(s=s.$$typeof,s===Z)return 11;if(s===z)return 14}return 2}function xr(s,a){var l=s.alternate;return l===null?(l=Un(s.tag,a,s.key,s.mode),l.elementType=s.elementType,l.type=s.type,l.stateNode=s.stateNode,l.alternate=s,s.alternate=l):(l.pendingProps=a,l.type=s.type,l.flags=0,l.subtreeFlags=0,l.deletions=null),l.flags=s.flags&14680064,l.childLanes=s.childLanes,l.lanes=s.lanes,l.child=s.child,l.memoizedProps=s.memoizedProps,l.memoizedState=s.memoizedState,l.updateQueue=s.updateQueue,a=s.dependencies,l.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},l.sibling=s.sibling,l.index=s.index,l.ref=s.ref,l}function Hl(s,a,l,f,g,w){var k=2;if(f=s,typeof s=="function")hd(s)&&(k=1);else if(typeof s=="string")k=5;else e:switch(s){case F:return ra(l.children,g,w,a);case L:k=8,g|=8;break;case J:return s=Un(12,l,a,g|2),s.elementType=J,s.lanes=w,s;case R:return s=Un(13,l,a,g),s.elementType=R,s.lanes=w,s;case q:return s=Un(19,l,a,g),s.elementType=q,s.lanes=w,s;case G:return Kl(l,g,w,a);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case V:k=10;break e;case O:k=9;break e;case Z:k=11;break e;case z:k=14;break e;case se:k=16,f=null;break e}throw Error(n(130,s==null?s:typeof s,""))}return a=Un(k,l,a,g),a.elementType=s,a.type=f,a.lanes=w,a}function ra(s,a,l,f){return s=Un(7,s,f,a),s.lanes=l,s}function Kl(s,a,l,f){return s=Un(22,s,f,a),s.elementType=G,s.lanes=l,s.stateNode={isHidden:!1},s}function md(s,a,l){return s=Un(6,s,null,a),s.lanes=l,s}function pd(s,a,l){return a=Un(4,s.children!==null?s.children:[],s.key,a),a.lanes=l,a.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},a}function Lv(s,a,l,f,g){this.tag=a,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Dr(0),this.expirationTimes=Dr(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Dr(0),this.identifierPrefix=f,this.onRecoverableError=g,this.mutableSourceEagerHydrationData=null}function gd(s,a,l,f,g,w,k,M,D){return s=new Lv(s,a,l,M,D),a===1?(a=1,w===!0&&(a|=8)):a=0,w=Un(3,null,null,a),s.current=w,w.stateNode=s,w.memoizedState={element:f,isDehydrated:l,cache:null,transitions:null,pendingSuspenseBoundaries:null},$u(w),s}function Ov(s,a,l){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:I,key:f==null?null:""+f,children:s,containerInfo:a,implementation:l}}function zm(s){if(!s)return hr;s=s._reactInternals;e:{if(js(s)!==s||s.tag!==1)throw Error(n(170));var a=s;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(un(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(a!==null);throw Error(n(171))}if(s.tag===1){var l=s.type;if(un(l))return mh(s,l,a)}return a}function Um(s,a,l,f,g,w,k,M,D){return s=gd(l,f,!0,s,g,w,k,M,D),s.context=zm(null),l=s.current,f=sn(),g=_r(l),w=Us(f,g),w.callback=a??null,gr(l,w,g),s.current.lanes=g,nr(s,g,f),hn(s,f),s}function Jl(s,a,l,f){var g=a.current,w=sn(),k=_r(g);return l=zm(l),a.context===null?a.context=l:a.pendingContext=l,a=Us(w,k),a.payload={element:s},f=f===void 0?null:f,f!==null&&(a.callback=f),s=gr(g,a,k),s!==null&&(ns(s,g,k,w),Sl(s,g,k)),k}function Ql(s){if(s=s.current,!s.child)return null;switch(s.child.tag){case 5:return s.child.stateNode;default:return s.child.stateNode}}function Bm(s,a){if(s=s.memoizedState,s!==null&&s.dehydrated!==null){var l=s.retryLane;s.retryLane=l!==0&&l<a?l:a}}function yd(s,a){Bm(s,a),(s=s.alternate)&&Bm(s,a)}function Pv(){return null}var Wm=typeof reportError=="function"?reportError:function(s){console.error(s)};function wd(s){this._internalRoot=s}Yl.prototype.render=wd.prototype.render=function(s){var a=this._internalRoot;if(a===null)throw Error(n(409));Jl(s,a,null,null)},Yl.prototype.unmount=wd.prototype.unmount=function(){var s=this._internalRoot;if(s!==null){this._internalRoot=null;var a=s.containerInfo;ta(function(){Jl(null,s,null,null)}),a[Os]=null}};function Yl(s){this._internalRoot=s}Yl.prototype.unstable_scheduleHydration=function(s){if(s){var a=Kt();s={blockedOn:null,target:s,priority:a};for(var l=0;l<In.length&&a!==0&&a<In[l].priority;l++);In.splice(l,0,s),l===0&&xa(s)}};function vd(s){return!(!s||s.nodeType!==1&&s.nodeType!==9&&s.nodeType!==11)}function Xl(s){return!(!s||s.nodeType!==1&&s.nodeType!==9&&s.nodeType!==11&&(s.nodeType!==8||s.nodeValue!==" react-mount-point-unstable "))}function Vm(){}function Dv(s,a,l,f,g){if(g){if(typeof f=="function"){var w=f;f=function(){var Y=Ql(k);w.call(Y)}}var k=Um(a,f,s,0,null,!1,!1,"",Vm);return s._reactRootContainer=k,s[Os]=k.current,zo(s.nodeType===8?s.parentNode:s),ta(),k}for(;g=s.lastChild;)s.removeChild(g);if(typeof f=="function"){var M=f;f=function(){var Y=Ql(D);M.call(Y)}}var D=gd(s,0,!1,null,null,!1,!1,"",Vm);return s._reactRootContainer=D,s[Os]=D.current,zo(s.nodeType===8?s.parentNode:s),ta(function(){Jl(a,D,l,f)}),D}function ql(s,a,l,f,g){var w=l._reactRootContainer;if(w){var k=w;if(typeof g=="function"){var M=g;g=function(){var D=Ql(k);M.call(D)}}Jl(a,k,s,g)}else k=Dv(l,a,s,g,f);return Ql(k)}$s=function(s){switch(s.tag){case 3:var a=s.stateNode;if(a.current.memoizedState.isDehydrated){var l=ln(a.pendingLanes);l!==0&&(_a(a,l|1),hn(a,lt()),(Xe&6)===0&&(Ja=lt()+500,mr()))}break;case 13:ta(function(){var f=zs(s,1);if(f!==null){var g=sn();ns(f,s,1,g)}}),yd(s,1)}},As=function(s){if(s.tag===13){var a=zs(s,134217728);if(a!==null){var l=sn();ns(a,s,134217728,l)}yd(s,134217728)}},Fr=function(s){if(s.tag===13){var a=_r(s),l=zs(s,a);if(l!==null){var f=sn();ns(l,s,a,f)}yd(s,a)}},Kt=function(){return Ge},zr=function(s,a){var l=Ge;try{return Ge=s,a()}finally{Ge=l}},ls=function(s,a,l){switch(a){case"input":if(ae(s,l),a=l.name,l.type==="radio"&&a!=null){for(l=s;l.parentNode;)l=l.parentNode;for(l=l.querySelectorAll("input[name="+JSON.stringify(""+a)+'][type="radio"]'),a=0;a<l.length;a++){var f=l[a];if(f!==s&&f.form===s.form){var g=pl(f);if(!g)throw Error(n(90));st(f),ae(f,g)}}}break;case"textarea":Pe(s,l);break;case"select":a=l.value,a!=null&&pe(s,!!l.multiple,a,!1)}},ks=ud,Lt=ta;var Fv={usingClientEntryPoint:!1,Events:[Wo,La,pl,wo,Fi,ud]},si={findFiberByHostInstance:Kr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},zv={bundleType:si.bundleType,version:si.version,rendererPackageName:si.rendererPackageName,rendererConfig:si.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:E.ReactCurrentDispatcher,findHostInstanceByFiber:function(s){return s=us(s),s===null?null:s.stateNode},findFiberByHostInstance:si.findFiberByHostInstance||Pv,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 Zl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Zl.isDisabled&&Zl.supportsFiber)try{va=Zl.inject(zv),An=Zl}catch{}}return mn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Fv,mn.createPortal=function(s,a){var l=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!vd(a))throw Error(n(200));return Ov(s,a,null,l)},mn.createRoot=function(s,a){if(!vd(s))throw Error(n(299));var l=!1,f="",g=Wm;return a!=null&&(a.unstable_strictMode===!0&&(l=!0),a.identifierPrefix!==void 0&&(f=a.identifierPrefix),a.onRecoverableError!==void 0&&(g=a.onRecoverableError)),a=gd(s,1,!1,null,null,l,!1,f,g),s[Os]=a.current,zo(s.nodeType===8?s.parentNode:s),new wd(a)},mn.findDOMNode=function(s){if(s==null)return null;if(s.nodeType===1)return s;var a=s._reactInternals;if(a===void 0)throw typeof s.render=="function"?Error(n(188)):(s=Object.keys(s).join(","),Error(n(268,s)));return s=us(a),s=s===null?null:s.stateNode,s},mn.flushSync=function(s){return ta(s)},mn.hydrate=function(s,a,l){if(!Xl(a))throw Error(n(200));return ql(null,s,a,!0,l)},mn.hydrateRoot=function(s,a,l){if(!vd(s))throw Error(n(405));var f=l!=null&&l.hydratedSources||null,g=!1,w="",k=Wm;if(l!=null&&(l.unstable_strictMode===!0&&(g=!0),l.identifierPrefix!==void 0&&(w=l.identifierPrefix),l.onRecoverableError!==void 0&&(k=l.onRecoverableError)),a=Um(a,null,s,1,l??null,g,!1,w,k),s[Os]=a.current,zo(s),f)for(s=0;s<f.length;s++)l=f[s],g=l._getVersion,g=g(l._source),a.mutableSourceEagerHydrationData==null?a.mutableSourceEagerHydrationData=[l,g]:a.mutableSourceEagerHydrationData.push(l,g);return new Yl(a)},mn.render=function(s,a,l){if(!Xl(a))throw Error(n(200));return ql(null,s,a,!1,l)},mn.unmountComponentAtNode=function(s){if(!Xl(s))throw Error(n(40));return s._reactRootContainer?(ta(function(){ql(null,null,s,!1,function(){s._reactRootContainer=null,s[Os]=null})}),!0):!1},mn.unstable_batchedUpdates=ud,mn.unstable_renderSubtreeIntoContainer=function(s,a,l,f){if(!Xl(l))throw Error(n(200));if(s==null||s._reactInternals===void 0)throw Error(n(38));return ql(s,a,l,!1,f)},mn.version="18.3.1-next-f1338f8080-20240426",mn}var qm;function kg(){if(qm)return xd.exports;qm=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(),xd.exports=Qv(),xd.exports}var Zm;function Yv(){if(Zm)return ec;Zm=1;var e=kg();return ec.createRoot=e.createRoot,ec.hydrateRoot=e.hydrateRoot,ec}var Xv=Yv();const qv=xg(Xv),jg=[{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"]}];jg.map(e=>({id:e.id,label:e.label}));function Zv(e){return`theme-${String(e||"").trim()||"dark"}`}function ep(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(Zv(e))}catch{}}const Yd=[{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}],Xd=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function e_(e){const t=String(e).trim();return Yd.find(n=>n.id===t)||Yd[1]}function t_(e){const t=String(e).trim();return Xd.find(n=>n.id===t)||Xd[1]}function tp(e){try{const t=document.documentElement,n=e_(e.font_scale||"md"),r=t_(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(r.density))}catch{}}const $i={md:"(max-width: 1023.98px)",lg:"(max-width: 1439.98px)"};function n_(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function vc(e){const[t,n]=y.useState(()=>n_(e));return y.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 ai=null;function s_(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 r_(){if(ai)return ai;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:c,keyboardInset:u}=s_(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${c}px`),t.style.setProperty("--keyboard-inset",`${u}px`)},i=()=>{n||(n=window.requestAnimationFrame(r))};return r(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("orientationchange",i),ai=()=>{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"),ai=null},ai}var Rc=kg();function Ya(...e){return e.filter(Boolean).join(" ")}function Wn({value:e,options:t,placeholder:n="Select…",disabled:r=!1,loading:i=!1,searchable:c=!0,searchPlaceholder:u="Search…",allowCustom:d=!1,clearable:h=!1,minPopoverWidth:m=240,variant:p="panel",className:v,triggerClassName:_,ariaLabel:b,id:C,includeValueOption:x=!1,onOpen:j,customOptionLabel:N,validateCustomValue:$,onChange:S,renderOption:E,renderValue:A}){const I=y.useRef(null),F=y.useRef(null),L=y.useRef(null),J=y.useRef(j),V=y.useId(),O=C||`af-select-${V.replace(/[^a-zA-Z0-9_-]/g,"")}`,Z=`${O}-listbox`,[R,q]=y.useState(!1),[z,se]=y.useState(""),[G,te]=y.useState(0),[ue,ne]=y.useState("bottom"),[P,B]=y.useState({left:0,top:0,width:0});y.useEffect(()=>{J.current=j},[j]);const W=y.useMemo(()=>{if(!x)return t;const Q=String(e??"").trim();return!Q||t.some(pe=>pe.value===Q)?t:[...t,{value:Q,label:Q}]},[x,t,e]),de=y.useMemo(()=>{const Q=String(e??"");return W.find(pe=>pe.value===Q)||null},[W,e]),ee=y.useMemo(()=>(de==null?void 0:de.label)||String(e||"").trim()||"",[de,e]),le=y.useMemo(()=>{const Q=z.trim().toLowerCase();return Q?W.filter(pe=>pe.label.toLowerCase().includes(Q)||pe.value.toLowerCase().includes(Q)):W},[W,z]),fe=y.useMemo(()=>{if(!d)return null;const Q=z.trim();if(!Q||W.some(Ee=>Ee.value===Q))return null;const be=($==null?void 0:$(Q,{options:W}))||"";return{value:Q,label:N?N(Q):`Use "${Q}"`,disabled:!!be,reason:be}},[d,N,W,z,$]),oe=y.useMemo(()=>{const Q=fe?[fe,...le]:le;if(Q.length>0)return Q;const pe=String(e??"").trim();return i&&pe?[{value:pe,label:ee||pe}]:Q},[fe,le,i,ee,e]),we=y.useCallback(()=>{const Q=I.current;if(!Q)return;const pe=Q.getBoundingClientRect(),be=Math.max(pe.width,m),Ee=Math.max(8,Math.min(pe.left,window.innerWidth-be-8)),Pe=window.innerHeight-pe.bottom,We=pe.top,Be=Pe>=220||Pe>=We?"bottom":"top";ne(Be);const bt=Be==="bottom"?pe.bottom+6:pe.top-6;B({left:Ee,top:bt,width:be})},[m]),Oe=y.useCallback(()=>{q(!1),se("")},[]);y.useEffect(()=>{var Q;R&&((Q=J.current)==null||Q.call(J))},[R]),y.useEffect(()=>{if(!R)return;we();const Q=()=>we();return window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0)}},[R,we]),y.useEffect(()=>{if(!R)return;const Q=pe=>{var Ee,Pe;const be=pe.target;be&&((Ee=I.current)!=null&&Ee.contains(be)||(Pe=F.current)!=null&&Pe.contains(be)||Oe())};return document.addEventListener("mousedown",Q,!0),()=>document.removeEventListener("mousedown",Q,!0)},[R,Oe]),y.useEffect(()=>{if(!R)return;const Q=Math.max(0,oe.findIndex(pe=>pe.value===e));te(Q===-1?0:Q),c&&setTimeout(()=>{var pe;return(pe=L.current)==null?void 0:pe.focus()},0)},[R,c,e,oe]);const Je=Q=>{var be;const pe=oe.find(Ee=>Ee.value===Q);pe!=null&&pe.disabled||(S(Q),Oe(),(be=I.current)==null||be.focus())},st=Q=>{var pe,be;if(Q.key==="Escape")return Q.preventDefault(),Oe(),(pe=I.current)==null||pe.focus(),!0;if(Q.key==="Tab")return Oe(),(be=I.current)==null||be.focus(),!1;if(Q.key==="ArrowDown")return Q.preventDefault(),te(Ee=>Math.min(Ee+1,Math.max(0,oe.length-1))),!0;if(Q.key==="ArrowUp")return Q.preventDefault(),te(Ee=>Math.max(Ee-1,0)),!0;if(Q.key==="Home")return Q.preventDefault(),te(0),!0;if(Q.key==="End")return Q.preventDefault(),te(Math.max(0,oe.length-1)),!0;if(Q.key==="Enter"){Q.preventDefault();const Ee=oe[G];return Ee&&Je(Ee.value),!0}return!1},Ce=Q=>{if(!r){if(R){if(st(Q))return;if(Q.key===" "&&!c){Q.preventDefault();const pe=oe[G];pe&&Je(pe.value)}return}(Q.key==="Enter"||Q.key===" "||Q.key==="ArrowDown"||Q.key==="ArrowUp")&&(Q.preventDefault(),q(!0))}},Ye=!!String(e||"").trim(),he=Ye?ee:n,Ve=fe!=null&&fe.disabled?fe.reason||"Unavailable":"",ae=R&&oe.length>0?`${O}-opt-${G}`:void 0,Te=o.jsx("span",{className:Ya("af-select-value",!Ye&&"af-select-value--placeholder"),children:i&&!Ye?"Loading…":he}),ge=A?A(de,String(e||"")):Te;return o.jsxs("span",{className:Ya("af-select",p==="pin"?"af-select--pin":"af-select--panel",v),children:[o.jsxs("button",{ref:I,id:O,type:"button",className:Ya("af-select-trigger",h&&Ye&&"af-select-trigger--clearable",_),disabled:r,onMouseDown:Q=>Q.stopPropagation(),onClick:Q=>{Q.stopPropagation(),!r&&q(pe=>!pe)},onKeyDown:Ce,role:c?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":R,"aria-controls":R?Z:void 0,"aria-activedescendant":c?void 0:ae,"aria-label":b,children:[ge,o.jsx("span",{className:Ya("af-select-caret",R&&"af-select-caret--open"),children:"▾"})]}),h&&Ye?o.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:r,onMouseDown:Q=>{Q.preventDefault(),Q.stopPropagation()},onClick:Q=>{var pe;Q.preventDefault(),Q.stopPropagation(),S(""),Oe(),(pe=I.current)==null||pe.focus()},title:"Clear",children:"×"}):null,R?Rc.createPortal(o.jsxs("div",{ref:F,className:Ya("af-select-popover",ue==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${P.left}px`,top:`${P.top}px`,width:`${P.width}px`},onMouseDown:Q=>Q.stopPropagation(),onClick:Q=>Q.stopPropagation(),onWheel:Q=>Q.stopPropagation(),onKeyDown:st,tabIndex:-1,children:[c?o.jsxs("div",{className:"af-select-search",children:[o.jsx("input",{ref:L,className:"af-select-search-input",value:z,onChange:Q=>se(Q.target.value),placeholder:u,onKeyDown:st,role:"combobox","aria-expanded":!0,"aria-controls":Z,"aria-activedescendant":ae,"aria-invalid":!!Ve,"aria-describedby":Ve?`${O}-custom-error`:void 0}),Ve?o.jsx("div",{id:`${O}-custom-error`,className:"af-select-custom-error",role:"alert",children:Ve}):null]}):null,o.jsx("div",{className:"af-select-options",role:"listbox",id:Z,"aria-label":b,children:i&&oe.length===0?o.jsx("div",{className:"af-select-empty",children:"Loading…"}):oe.length===0?o.jsx("div",{className:"af-select-empty",children:"No results"}):oe.map((Q,pe)=>{var bt;const be=Q.value===e,Ee=pe===G,Pe=String(Q.group||"").trim(),We=pe>0?String(((bt=oe[pe-1])==null?void 0:bt.group)||"").trim():"",Be=!!Pe&&Pe!==We;return o.jsxs(ct.Fragment,{children:[Be?o.jsx("div",{className:"af-select-group",role:"presentation",children:Pe}):null,o.jsx("div",{id:`${O}-opt-${pe}`,role:"option","aria-selected":be,className:Ya("af-select-option",be&&"af-select-option--selected",Ee&&"af-select-option--highlighted",Q.disabled&&"af-select-option--disabled"),title:Q.disabled?Q.reason||"Unavailable":void 0,onMouseEnter:()=>te(pe),onMouseDown:Nt=>{Nt.preventDefault(),Nt.stopPropagation()},onClick:()=>Je(Q.value),"aria-disabled":Q.disabled?!0:void 0,children:E?E(Q,{selected:be,highlighted:Ee}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"af-select-option-label",children:[o.jsx("span",{children:Q.label}),Q.reason?o.jsx("small",{className:"af-select-option-reason",children:Q.reason}):null]}),be?o.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},Q.value)})})]}),document.body):null]})}function a_(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 o_(e){const t=new Set,n=[];for(const r of e||[]){const i=String(r||"").trim();!i||t.has(i)||(t.add(i),n.push(i))}return n.sort(),n}function i_(e){const t=e.disabled===!0,n=e.layout||"stack",r=e.allowGatewayDefault!==!1,i=String(e.gatewayDefaultLabel||"(gateway default)"),c=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),d=String(e.providerPlaceholder||"(select)"),h=String(e.modelPlaceholder||"(select)"),m=String(e.provider||"").trim(),p=String(e.model||"").trim(),v=a_(e.providers),_=o_(e.models),b=t||!!e.loadingProviders,C=t||!!e.loadingModels,x=[...r?[{value:"",label:i}]:[],...v.map(N=>({value:N.name,label:N.display_name?`${N.display_name} (${N.name})`:N.name}))],j=[...r?[{value:"",label:i}]:[],..._.map(N=>({value:N,label:N}))];return o.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[o.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[o.jsx("label",{children:c}),o.jsx(Wn,{value:m,options:x,placeholder:r?i:d,disabled:b,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:c,onChange:N=>e.onChange({provider:String(N||"").trim(),model:""})}),e.loadingProviders?o.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?o.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),o.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[o.jsx("label",{children:u}),o.jsx(Wn,{value:p,options:j,placeholder:r?i:h,disabled:C,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:r,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:N=>e.onChange({provider:m,model:String(N||"").trim()})}),e.loadingModels?o.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?o.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function Sg(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 l_(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 np(e){const t=Sg(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function c_(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 u_(e){const t=l_(e.capabilities),n=np(e.value),r=(t==null?void 0:t.supported_depths.map(String))||[],i=np(t==null?void 0:t.default),c=e.inheritLabel||"Workflow / Gateway default",u=i?`${c} (${i==="off"?"Off":`depth ${i}`})`:c,d=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 o.jsxs("div",{className:"af-pmp__speculation",children:[o.jsx("label",{children:"MTP depth"}),o.jsx(Wn,{ariaLabel:"MTP depth",value:n,placeholder:u,disabled:e.disabled||e.loading,options:[{value:"",label:u},{value:"off",label:"Off"},...r.map(h=>({value:h,label:`Depth ${h}`})),...n&&n!=="off"&&!r.includes(n)?[{value:n,label:`Depth ${n} (saved; not available)`}]:[]],onChange:h=>e.onChange(c_(h))}),d&&!e.hideNote?o.jsx("div",{role:"status",className:"af-pmp__hint",children:d}):null]})}const d_="Reasoning and MTP choices appear when the gateway can describe the selected model.",f_="Reasoning choices appear when the gateway can describe the selected model.";function Ic(e){var ne,P;const t=e.disabled===!0,n=e.value||{provider:"",model:""},r=!String(n.provider||"").trim()&&!String(n.model||"").trim(),[i,c]=y.useState(!r),u=r&&!i,d=y.useRef(r);y.useEffect(()=>{r&&!d.current&&c(!1),d.current=r},[r]);const[h,m]=y.useState([]),[p,v]=y.useState(!1),[_,b]=y.useState(""),[C,x]=y.useState([]),[j,N]=y.useState(!1),[$,S]=y.useState(""),E=y.useRef(e);E.current=e,y.useEffect(()=>{if(u||t)return;let B=!0;return v(!0),(async()=>{try{const W=await E.current.fetchProviders();if(!B)return;m(Array.isArray(W)?W:[]),b("")}catch(W){if(!B)return;m([]),b(`#FALLBACK provider discovery failed: ${String((W==null?void 0:W.message)||W)}`)}finally{B&&v(!1)}})(),()=>{B=!1}},[u,t]);const A=String(n.provider||"").trim();y.useEffect(()=>{if(!A||t){x([]),S(""),N(!1);return}let B=!0;return x([]),N(!0),S(""),(async()=>{try{const W=await E.current.fetchModels(A);if(!B)return;x(Array.isArray(W)?W:[])}catch(W){if(!B)return;x([]),S(`#FALLBACK model discovery failed: ${String((W==null?void 0:W.message)||W)}`)}finally{B&&N(!1)}})(),()=>{B=!1}},[A,t]);const I=y.useMemo(()=>{const B=[...h];return A&&!B.some(W=>W.name===A)&&B.unshift({name:A}),B},[h,A]),F=String(n.model||"").trim(),L=y.useMemo(()=>{const B=[...C];return F&&!B.includes(F)&&B.unshift(F),B},[C,F]),J=e.defaultModeLabel||"Gateway default",V=e.customModeLabel||"Custom",O=A||((ne=e.effectiveDefault)==null?void 0:ne.provider)||"",Z=F||(A?"":(P=e.effectiveDefault)==null?void 0:P.model)||"",[R,q]=y.useState({levels:[],error:"",loading:!1}),z=!!e.fetchModelCapabilities,[se,G]=y.useState();y.useEffect(()=>{let B=!0;if(G(void 0),q({levels:[],error:"",loading:z&&!!Z}),!(!z||!Z||t))return E.current.fetchModelCapabilities(Z,O).then(W=>{var fe;if(!B)return;if(W!=null&&W.error)throw new Error(String(W.error));G(W);const de=(W==null?void 0:W.capabilities)||W||{},ee=de.reasoning_levels||de.thinking_levels,le=Array.isArray(ee)?[...new Set(ee.filter(oe=>typeof oe=="string"&&!!oe.trim()))]:[];!le.length&&de.thinking_support===!0&&((fe=de.thinking_control)!=null&&fe.prompt_disable_token)&&le.push("off","auto"),q({levels:le,error:"",loading:!1})}).catch(W=>{B&&q({levels:[],error:String((W==null?void 0:W.message)||W),loading:!1})}),()=>{B=!1}},[O,Z,z,t]);const te=e.inheritLabel||"Workflow / Gateway default",ue=!u||e.optionsInDefaultMode!==!1;return o.jsxs("div",{className:`af-pmp${e.className?` ${e.className}`:""}`,children:[o.jsxs("div",{className:"af-pmp__seg",role:"tablist","aria-label":"Provider mode",children:[o.jsx("button",{type:"button",role:"tab","aria-selected":u,className:`af-pmp__seg-btn${u?" is-active":""}`,onClick:()=>{c(!1),e.onChange({...n,provider:"",model:"",...z?{reasoning:""}:{}})},disabled:t,children:J}),o.jsx("button",{type:"button",role:"tab","aria-selected":!u,className:`af-pmp__seg-btn${u?"":" is-active"}`,onClick:()=>{c(!0)},disabled:t,children:V})]}),u?o.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}):o.jsx(i_,{provider:A,model:F,providers:I,models:L,disabled:t,loadingProviders:p,loadingModels:j,providerError:_||void 0,modelError:$||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:!1,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:B=>e.onChange({...n,provider:B.provider,model:B.model,...z?{reasoning:""}:{}})}),ue&&z&&(R.levels.length>0||n.reasoning)?o.jsxs("div",{className:"af-pmp__reasoning",children:[o.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),o.jsx(Wn,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:te,value:n.reasoning||"",options:[{value:"",label:te},...R.levels.map(B=>({value:B,label:B})),...n.reasoning&&!R.levels.includes(n.reasoning)?[{value:n.reasoning,label:`${n.reasoning} (saved; not advertised)`}]:[]],disabled:t||R.loading,onChange:B=>e.onChange({...n,reasoning:B})})]}):null,ue&&e.enableSpeculation?o.jsx(u_,{value:n.speculation,inheritLabel:te,onChange:B=>e.onChange({...n,speculation:B}),capabilities:se,disabled:t,loading:R.loading,hideNote:!!R.error}):null,ue&&R.error?o.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?d_:f_,o.jsxs("details",{className:"af-pmp__details",children:[o.jsx("summary",{children:"Technical details"}),o.jsx("span",{children:R.error})]})]}):null]})}function sp(...e){return e.filter(Boolean).join(" ")}function h_({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:c=!1,gatewayUrl:u="",gatewayUrlPlaceholder:d="http://127.0.0.1:8080",onGatewayUrlChange:h,userId:m,userPlaceholder:p="admin",onUserIdChange:v,token:_,tokenPlaceholder:b="Paste Gateway user token",showToken:C=!1,onTokenChange:x,onShowTokenChange:j,remember:N=!1,rememberLabel:$="Remember this browser",onRememberChange:S,loading:E=!1,submitting:A=!1,submitDisabled:I=!1,submitLabel:F="Sign in",submittingLabel:L="Signing in...",closeLabel:J="Close",signOutLabel:V="Sign out",showClose:O=!1,showSignOut:Z=!1,error:R,message:q,className:z,onSubmit:se,onClose:G,onSignOut:te}){const ue=E||A,ne=ue||I||!String(m||"").trim()||!String(_||"").trim(),P=B=>{B.preventDefault(),!ne&&se()};return o.jsxs("form",{className:sp("af-gateway-signin",z),onSubmit:P,children:[o.jsxs("div",{className:"af-gateway-signin__hero",children:[o.jsxs("div",{children:[o.jsx("div",{className:"af-gateway-signin__kicker",children:e}),o.jsx("h2",{children:t}),n?o.jsx("p",{children:n}):null]}),o.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),o.jsx("div",{className:"af-gateway-signin__status-row",children:o.jsx("span",{className:sp("af-gateway-signin__status",`af-gateway-signin__status--${i}`),children:r})}),o.jsxs("div",{className:"af-gateway-signin__form",children:[c?o.jsxs(o.Fragment,{children:[o.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),o.jsx("input",{id:"gateway-session-url",value:u,onChange:B=>h==null?void 0:h(B.target.value),placeholder:d,autoComplete:"url",disabled:ue})]}):null,o.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),o.jsx("input",{id:"gateway-session-user",value:m,onChange:B=>v(B.target.value),placeholder:p,autoComplete:"username",disabled:ue}),o.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),o.jsxs("div",{className:"af-gateway-signin__token-input",children:[o.jsx("input",{id:"gateway-session-token",type:C?"text":"password",value:_,onChange:B=>x(B.target.value),placeholder:b,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:ue}),o.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>j==null?void 0:j(!C),disabled:ue,children:C?"Hide":"Show"})]}),o.jsxs("label",{className:"af-gateway-signin__checkbox",children:[o.jsx("input",{type:"checkbox",checked:!!N,onChange:B=>S==null?void 0:S(B.target.checked),disabled:ue}),$]})]}),R?o.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:R}):null,!R&&q?o.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:q}):null,o.jsxs("div",{className:"af-gateway-signin__actions",children:[O?o.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:G,disabled:ue,children:J}):null,Z?o.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(te==null?void 0:te()),disabled:ue,children:V}):null,o.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:ne,children:A?L:F})]})]})}function m_(e){return e==="light"?"Light":"Dark"}function p_(e){const t=e.themes&&e.themes.length?e.themes:jg,n=e.showSwatches!==!1,r=e.variant||"panel",i=y.useMemo(()=>{const u={};for(const d of t)u[d.id]=d;return u},[t]),c=y.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:m_(u.group)})),[t]);return o.jsx(Wn,{value:e.value,options:c,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:r,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,d)=>{const h=String(d||"").trim(),m=i[h],p=(m==null?void 0:m.label)||h||e.placeholder||"Select theme…",v=(m==null?void 0:m.swatches)||null,_=!h;return o.jsxs("span",{className:"af-theme-value",children:[o.jsx("span",{className:`af-theme-label ${_?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&v?o.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:v.map((b,C)=>o.jsx("span",{className:"af-theme-swatch",style:{background:b}},`${h}:${C}`))}):null]})},renderOption:(u,d)=>{const h=String(u.value||"").trim(),m=i[h],p=(m==null?void 0:m.swatches)||null;return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"af-theme-option-label",children:u.label}),o.jsxs("span",{className:"af-theme-option-right",children:[n&&p?o.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((v,_)=>o.jsx("span",{className:"af-theme-swatch",style:{background:v}},`${h}:${_}`))}):null,d.selected?o.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function g_(e){const t=e.scales&&e.scales.length?e.scales:Yd,n=e.variant||"panel",r=y.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return o.jsx(Wn,{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 y_(e){const t=e.densities&&e.densities.length?e.densities:Xd,n=e.variant||"panel",r=y.useMemo(()=>t.map(i=>({value:i.id,label:i.label})),[t]);return o.jsx(Wn,{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 w_=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function v_(e){switch(e){case"chat":return o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 5v14"}),o.jsx("path",{d:"M5 12h14"})]});case"history":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"9"}),o.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),o.jsx("path",{d:"M3 3v5h5"}),o.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),o.jsx("path",{d:"M21 21v-5h-5"})]});case"cog":return o.jsxs(o.Fragment,{children:[o.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"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"activity":return o.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2"});case"settings":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M4 6h16"}),o.jsx("circle",{cx:"8",cy:"6",r:"2"}),o.jsx("path",{d:"M4 12h16"}),o.jsx("circle",{cx:"16",cy:"12",r:"2"}),o.jsx("path",{d:"M4 18h16"}),o.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"8",r:"4"}),o.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 2v3"}),o.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),o.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),o.jsx("path",{d:"M9 17h6"})]});case"paperclip":return o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),o.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),o.jsx("path",{d:"M12 18v4"}),o.jsx("path",{d:"M8 22h8"})]});case"speaker":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),o.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),o.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),o.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),o.jsx("path",{d:"M7 9l3 3-3 3"}),o.jsx("path",{d:"M12 15h5"})]});case"edit":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 20h9"}),o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),o.jsx("path",{d:"M7 10l5 5 5-5"}),o.jsx("path",{d:"M12 15V3"})]});case"loader":return o.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 16v-4"}),o.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 3l10 18H2L12 3z"}),o.jsx("path",{d:"M12 9v4"}),o.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M15 9l-6 6"}),o.jsx("path",{d:"M9 9l6 6"})]});case"copy":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return o.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M18 6L6 18"}),o.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return o.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return o.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M3 6h18"}),o.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),o.jsx("path",{d:"M6 6l1 16h10l1-16"}),o.jsx("path",{d:"M10 11v6"}),o.jsx("path",{d:"M14 11v6"})]});case"send":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M22 2L11 13"}),o.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M7 10v11"}),o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M17 14V3"}),o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M7 10v11"}),o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M17 14V3"}),o.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 o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),o.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),o.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),o.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),o.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),o.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),o.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),o.jsx("path",{d:"M8 4.5V2.2"}),o.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),o.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M2.5 4h11"}),o.jsx("path",{d:"M2.5 8h11"}),o.jsx("path",{d:"M2.5 12h7"})]});case"gear":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),o.jsx("path",{d:"M8 1.6v2"}),o.jsx("path",{d:"M8 12.4v2"}),o.jsx("path",{d:"M1.6 8h2"}),o.jsx("path",{d:"M12.4 8h2"}),o.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),o.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),o.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),o.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),o.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 o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"9"}),o.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),o.jsx("path",{d:"M16 17l5-5-5-5"}),o.jsx("path",{d:"M21 12H9"})]});case"play":return o.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 o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return o.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 o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),o.jsx("path",{d:"M14 2v6h6"})]});case"archive":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),o.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),o.jsx("path",{d:"M10 12h4"})]});case"unarchive":return o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),o.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),o.jsx("path",{d:"M12 18v-6"}),o.jsx("path",{d:"m9 14 3-3 3 3"})]});case"clock":return o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 6v6h4"})]});case"book":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2z"}),o.jsx("path",{d:"M22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z"})]});case"compose":return o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),o.jsx("path",{d:"M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"})]});default:return null}}function re({name:e,size:t=16,className:n,title:r,...i}){const c=r?void 0:!0,u=w_.has(e);return o.jsxs("svg",{width:t,height:t,viewBox:u?"0 0 16 16":"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:u?1.4:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":c,role:r?"img":"presentation",...i,children:[r?o.jsx("title",{children:r}):null,v_(e)]})}const Rr="api/gateway",Ri="api/connection/gateway";function ve(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?`${Rr}/${t}`:Rr}function Ze(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 __(e){const t=String(e||""),n=`/${Rr}/`;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 c=i.replace(/%2e/gi,".");if(c==="."||c==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}function b_(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function x_(e){return b_(e)?!e.checked:null}let k_=0;function Mr(e){const{label:t,checked:n,onChange:r,description:i,reasonVisible:c=!0,describedBy:u,hint:d,busy:h=!1,variant:m="inline",ariaLabel:p,className:v,id:_,action:b}=e,C=String(e.unavailableReason||"").trim(),x=!!C,j=u||(_?`${_}-reason`:x?`af-switch-reason-${++k_}`:void 0),N=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",x?"af-switch--unavailable":"",v||""].filter(Boolean).join(" "),$=E=>{const A=x_({checked:n,unavailableReason:C,busy:h});if(A===null){E.preventDefault();return}r==null||r(A)},S=o.jsxs("button",{type:"button",role:"switch",id:_,className:N,"data-action":b,"aria-checked":n?"true":"false","aria-disabled":x?"true":void 0,"aria-describedby":x?j:void 0,"aria-busy":h?"true":void 0,"aria-label":p,"aria-description":i?void 0:d,title:x?d?`${C}
41
+ ${d}`:C:d,onClick:$,children:[o.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:o.jsx("span",{className:"af-switch__thumb"})}),o.jsxs("span",{className:"af-switch__text",children:[o.jsx("span",{className:"af-switch__label",children:t}),i?o.jsx("span",{className:"af-switch__desc",children:i}):null]})]});return!x||u?S:o.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[S,o.jsx("span",{id:j,className:c?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:C})]})}function j_(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=o.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[o.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:c=>{var u;return(u=e.onChange)==null?void 0:u.call(e,c.target.checked)},disabled:!!t,"aria-describedby":r}),o.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:o.jsx("span",{className:"af-switch__thumb"})}),o.jsx("span",{className:"af-switch__text",children:o.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?o.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[i,o.jsx("span",{id:r,className:"af-switch__reason",children:t})]}):i}const S_=150,xf="data-af-tip";function N_(e,t,n,r=6,i=8){let c="top",u=e.top-r-t.height;if(u<i){const m=e.bottom+r;(m+t.height<=n.height-i||n.height-e.bottom>e.top)&&(u=m,c="bottom")}let h=(e.left+e.right)/2-t.width/2;return h=Math.max(i,Math.min(h,n.width-i-t.width)),u=Math.max(i,Math.min(u,n.height-i-t.height)),{top:Math.round(u),left:Math.round(h),side:c}}let rp=0;function Ng(e){return e?String(e.getAttribute(xf)||"").trim():""}function Sd(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const r=n.closest(`[${xf}]`);return!r||!t.contains(r)||!Ng(r)?null:r}function C_(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:S_;rp+=1;const c=n.createElement("div");c.className="af-tooltip",c.setAttribute("role","tooltip");const u=`af-tooltip-${rp}`;c.setAttribute("id",u),c.hidden=!0,(n.body||n.documentElement).appendChild(c);let d=null,h=null,m=null,p=null,v=!1,_=null;const b=()=>{m&&clearTimeout(m),m=null,h=null},C=()=>{p&&clearTimeout(p),p=null},x=()=>{if(!d)return;const z=d.getBoundingClientRect(),se=c.getBoundingClientRect(),G=N_(z,{width:se.width,height:se.height},{width:r.innerWidth,height:r.innerHeight});c.style.top=`${G.top}px`,c.style.left=`${G.left}px`,c.setAttribute("data-side",G.side)},j=()=>{if(b(),C(),!d)return;String(d.getAttribute("aria-describedby")||"").split(/\s+/).includes(u)&&(_?d.setAttribute("aria-describedby",_):d.removeAttribute("aria-describedby")),_=null,d=null,c.hidden=!0,c.textContent=""},N=z=>{b(),C(),d&&d!==z&&j();const se=Ng(z);if(!se||z.isConnected===!1)return;if(d=z,c.textContent=se,c.hidden=!1,String(z.getAttribute("aria-label")||"").trim()!==se){const te=z.getAttribute("aria-describedby");_=te&&te!==u?te:null,z.setAttribute("aria-describedby",_?`${_} ${u}`:u)}x()},$=z=>{C(),d!==z&&h!==z&&(b(),h=z,m=setTimeout(()=>{const se=h;m=null,h=null,se&&N(se)},i))},S=()=>{b(),d&&(C(),p=setTimeout(j,100))},E=z=>{try{if(typeof z.matches=="function")return z.matches(":focus-visible")}catch{}return v},A=z=>{if(z.pointerType==="touch")return;if(c.contains(z.target)){C();return}const G=Sd(z.target,e);G&&$(G)},I=z=>{const G=z.relatedTarget||null;if(!(G&&(c.contains(G)||d&&d.contains(G)||h&&h.contains(G)))){if(h&&!d){b();return}d&&S()}},F=z=>{const se=z.relatedTarget||null;se&&(c.contains(se)||d&&d.contains(se))||S()},L=z=>{const se=Sd(z.target,e);se&&E(se)&&$(se)},J=z=>{const se=Sd(z.target,e);se&&(se===d||se===h)&&j()},V=()=>{v=!1,j()},O=z=>{if(z.key==="Escape"||z.key==="Esc"){d?(z.preventDefault(),j()):b();return}!z.metaKey&&!z.ctrlKey&&!z.altKey&&(v=!0)},Z=()=>j(),R=e;R.addEventListener("pointerover",A),R.addEventListener("pointerout",I),R.addEventListener("focusin",L),R.addEventListener("focusout",J),c.addEventListener("pointerover",A),c.addEventListener("pointerout",F),n.addEventListener("pointerdown",V,!0),r.addEventListener("keydown",O,!0),r.addEventListener("scroll",Z,!0),r.addEventListener("resize",Z);let q=!1;return()=>{q||(q=!0,j(),R.removeEventListener("pointerover",A),R.removeEventListener("pointerout",I),R.removeEventListener("focusin",L),R.removeEventListener("focusout",J),c.removeEventListener("pointerover",A),c.removeEventListener("pointerout",F),n.removeEventListener("pointerdown",V,!0),r.removeEventListener("keydown",O,!0),r.removeEventListener("scroll",Z,!0),r.removeEventListener("resize",Z),c.parentNode&&c.parentNode.removeChild(c))}}const tc=new WeakMap;function E_(e){let t=tc.get(e);t||(t={count:0,release:C_(e)},tc.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const r=tc.get(e);r&&(r.count-=1,r.count<=0&&(r.release(),tc.delete(e)))}}function fo(){y.useEffect(()=>{if(!(typeof document>"u"))return E_(document)},[])}function $_(e){fo();const t=ct.Children.only(e.children),n=String(e.content||"").trim();return n?ct.cloneElement(t,{[xf]:n}):t}function A_(e){if(!e||typeof e!="object")return;const t=e,n=typeof t.label=="string"?t.label.trim():"";if(!n)return;const r=typeof t.tooltip=="string"&&t.tooltip.trim()?t.tooltip.trim():void 0,i=t.tone==="ok"||t.tone==="warn"||t.tone==="danger"?t.tone:void 0;return{label:n,...r?{tooltip:r}:{},...i?{tone:i}:{}}}const T_={autoApprove:["list_files","skim_folders","analyze_code","read_file","skim_files","search_files","open_attachment","web_search","skim_websearch","skim_url","fetch_url","list_email_accounts","list_emails","read_email","list_whatsapp_messages","read_whatsapp_message","send_email","send_whatsapp_message","send_telegram_message","send_telegram_artifact"],requireApproval:["write_file","edit_file","execute_command"]};function R_(e){const t=new Set,n=[];for(const r of e||[]){if(!r)continue;const i=String(r.name||"").trim();!i||t.has(i)||(t.add(i),n.push({name:i,description:typeof r.description=="string"?r.description:void 0,toolset:typeof r.toolset=="string"?r.toolset:void 0,when_to_use:typeof r.when_to_use=="string"?r.when_to_use:void 0,default_approval:r.default_approval==="approve"||r.default_approval==="ask"?r.default_approval:void 0,state:A_(r.state)}))}return n.sort((r,i)=>{const c=String(r.toolset||""),u=String(i.toolset||"");return c!==u?c.localeCompare(u):r.name.localeCompare(i.name)}),n}function I_(e,t){return e.default_approval?e.default_approval:t.requireApproval.includes(e.name)?"ask":t.autoApprove.includes(e.name)?"approve":"ask"}function M_(e,t,n){const r=String(e||"").trim().toLowerCase();if(!r&&!t&&!n)return null;let i;return r==="approval"||r==="local_approval"||r==="local-approval"?i={label:"APPROVAL",detail:"Safe tools auto-run; mutating tools ask for approval.",tone:"safe"}:r==="passthrough"?i={label:"PASSTHROUGH",detail:"All tools require approval before execution.",tone:"warn"}:r==="delegated"||r==="delegate"||r==="job"?i={label:"DELEGATED",detail:"Tool calls wait for external executors.",tone:"info"}:r==="local"||r==="local_all"||r==="local-all"?i={label:"LOCAL",detail:"All tools run locally; client policy may still require approval.",tone:"danger"}:i={label:"UNKNOWN",detail:"#FALLBACK: gateway tool mode not reported.",tone:"warn"},t&&(i={...i,label:t}),n&&(i={...i,detail:n}),i}function L_(e){const t=e.split("_");return t.map((n,r)=>r<t.length-1?o.jsxs(ct.Fragment,{children:[n,"_",o.jsx("wbr",{})]},r):o.jsx(ct.Fragment,{children:n},r))}function O_(e){var J,V;const t=e.defaults||T_,n=e.disabled===!0,r=e.title||"Tools",i=e.subtitle||"Default is all tools. Safe/read-only tools auto-approve; mutating tools ask for approval.",c=String(e.note||"").trim(),u=y.useMemo(()=>M_(e.toolMode,e.toolModeLabel,e.toolModeDetail),[e.toolMode,e.toolModeLabel,e.toolModeDetail]),d=y.useMemo(()=>R_(e.tools),[e.tools]),h=y.useMemo(()=>d.map(O=>O.name),[d]),m=y.useMemo(()=>new Set(h),[h]),[p,v]=y.useState(""),_=y.useMemo(()=>{var q;const O=Array.isArray((q=e.value)==null?void 0:q.selected)?e.value.selected:[],Z=new Set,R=[];for(const z of O){const se=String(z||"").trim();!se||Z.has(se)||(Z.add(se),R.push(se))}return R},[(J=e.value)==null?void 0:J.selected]),b=y.useMemo(()=>_.filter(O=>m.has(O)),[_,m]),C=y.useMemo(()=>_.filter(O=>!m.has(O)),[_,m]),x=((V=e.value)==null?void 0:V.mode)==="custom"?"custom":"all",j=y.useMemo(()=>{const O=p.trim().toLowerCase();return O?d.filter(Z=>{const R=Z.name.toLowerCase(),q=(Z.description||"").toLowerCase();return R.includes(O)||q.includes(O)}):d},[d,p]),N=x==="all"?new Set(h):new Set(b),$=O=>{e.onChange(O)},S=O=>{n||$({...e.value,mode:O,selected:_})},E=(O,Z)=>{if(n)return;const R=new Set(b);Z?R.add(O):R.delete(O),$({...e.value,selected:[...C,...Array.from(R)],mode:"custom"})},A=(O,Z)=>{var q;if(n)return;const R={...((q=e.value)==null?void 0:q.approval)||{}};R[O]=Z,$({...e.value,approval:R})},I=()=>{n||$({...e.value,selected:[...C,...h],mode:"custom"})},F=()=>{n||$({...e.value,selected:[...C],mode:"custom"})},L=N.size;return o.jsxs("div",{className:`af-tool-policy ${e.className||""}`.trim(),children:[o.jsxs("div",{className:"af-tool-policy__header",children:[o.jsx("div",{className:"af-tool-policy__title",children:r}),o.jsx("div",{className:"af-tool-policy__subtitle",children:i}),u?o.jsxs("div",{className:`af-tool-policy__mode is-${u.tone}`,children:[o.jsx("div",{className:"af-tool-policy__mode-badge",children:"Tool mode"}),o.jsx("div",{className:"af-tool-policy__mode-value",children:u.label}),o.jsx("div",{className:"af-tool-policy__mode-detail",children:u.detail})]}):null,c?o.jsx("div",{className:"af-tool-policy__note",children:c}):null]}),o.jsxs("div",{className:"af-tool-policy__controls",children:[o.jsxs("div",{className:"af-tool-policy__segmented",role:"group","aria-label":"Tool allowlist mode",children:[o.jsx("button",{type:"button",className:`af-tool-policy__seg-btn ${x==="all"?"is-active":""}`.trim(),onClick:()=>S("all"),disabled:n,"aria-pressed":x==="all",children:"All tools"}),o.jsx("button",{type:"button",className:`af-tool-policy__seg-btn ${x==="custom"?"is-active":""}`.trim(),onClick:()=>S("custom"),disabled:n,"aria-pressed":x==="custom",children:"Custom allowlist"})]}),o.jsxs("div",{className:"af-tool-policy__count",children:[L," / ",h.length," enabled"]}),o.jsxs("div",{className:"af-tool-policy__bulk",children:[o.jsx("button",{type:"button",onClick:I,disabled:n||x!=="custom",children:"Select all"}),o.jsx("button",{type:"button",onClick:F,disabled:n||x!=="custom",children:"Select none"})]})]}),o.jsx("div",{className:"af-tool-policy__filter",children:o.jsx("input",{type:"text",placeholder:"Filter tools...","aria-label":"Filter tools",value:p,onChange:O=>v(O.target.value),disabled:n})}),o.jsxs("div",{className:"af-tool-policy__list",children:[j.map(O=>{var q,z;const Z=N.has(O.name),R=((z=(q=e.value)==null?void 0:q.approval)==null?void 0:z[O.name])||I_(O,t);return o.jsxs("div",{className:`af-tool-row ${Z?"is-enabled":""}`.trim(),children:[o.jsx("div",{className:"af-tool-row__check",children:o.jsx(Mr,{variant:"sm",action:"tool-enabled",label:"",ariaLabel:O.name,checked:Z,busy:n,unavailableReason:x!=="custom"?"Choose Custom to pick tools one by one.":null,reasonVisible:!1,onChange:se=>E(O.name,se)})}),o.jsxs("div",{className:"af-tool-row__meta",children:[o.jsxs("div",{className:"af-tool-row__title",children:[o.jsx("span",{className:"af-tool-row__name",children:L_(O.name)}),O.toolset?o.jsx("span",{className:"af-tool-row__badge",children:O.toolset}):null]}),O.state?o.jsx("div",{className:"af-tool-row__state-line",children:o.jsx($_,{content:O.state.tooltip||"",children:o.jsx("span",{className:`af-tool-row__state${O.state.tone?` is-${O.state.tone}`:""}`,"data-tool-state":O.name,tabIndex:O.state.tooltip?0:void 0,"aria-label":O.state.tooltip?`${O.state.label}. ${O.state.tooltip}`:void 0,children:O.state.label})})}):null,O.description?o.jsx("div",{className:"af-tool-row__desc",children:O.description}):null,O.when_to_use?o.jsx("div",{className:"af-tool-row__hint",children:O.when_to_use}):null]}),o.jsx("div",{className:"af-tool-row__approval",children:o.jsxs("select",{value:R,disabled:n||!Z,onChange:se=>A(O.name,se.target.value),"aria-label":`Approval mode for ${O.name}`,children:[o.jsx("option",{value:"approve",children:"Approve"}),o.jsx("option",{value:"ask",children:"Ask"})]})})]},O.name)}),j.length?null:o.jsx("div",{className:"af-tool-policy__empty",children:"No tools match the filter."})]})]})}async function qd(e=Ri){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 P_(e,t=Ri){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 Cg(e=Ri){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 Nd(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const c=JSON.parse(t);if(typeof c=="string"&&c!==t){t=c.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 D_(e){var c,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(c=t.principal)==null?void 0:c.user_id,r=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${r?` · runtime ${r}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const i=t.error||t.detail;return typeof i=="string"&&i.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function F_(e){const t=e.connectionPath||Ri,[n,r]=y.useState(!1),[i,c]=y.useState(!1),[u,d]=y.useState(null),[h,m]=y.useState(!1);y.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[p,v]=y.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[_,b]=y.useState("admin"),[C,x]=y.useState(""),[j,N]=y.useState(!1),[$,S]=y.useState(!0),[E,A]=y.useState(""),[I,F]=y.useState(""),L=y.useMemo(()=>D_(u),[u]),J=R=>{var q;d(R),(q=e.onStatusChange)==null||q.call(e,R)},V=y.useRef(!1);if(y.useEffect(()=>{var q;if(!e.isOpen)return;const R=!V.current;if(V.current=!0,R&&e.initialStatus!==void 0&&e.initialStatus!==null){const z=e.initialStatus;J(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&v(Nd(z.gateway_url));const se=(q=z.gateway)==null?void 0:q.principal;se!=null&&se.user_id&&b(se.user_id);return}r(!0),A(""),qd(t).then(z=>{var G;J(z),typeof z.gateway_url=="string"&&z.gateway_url.trim()&&v(Nd(z.gateway_url));const se=(G=z.gateway)==null?void 0:G.principal;se!=null&&se.user_id&&b(se.user_id)}).catch(z=>A(`Failed to load connection status: ${String((z==null?void 0:z.message)||z)}`)).finally(()=>r(!1))},[e.isOpen]),y.useEffect(()=>{if(!e.isOpen)return;const R=q=>{q.key==="Escape"&&!q.defaultPrevented&&!e.blocking&&(q.preventDefault(),e.onClose())};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||h)return null;const O=async()=>{c(!0),A(""),F("");try{const R=Nd(p);v(R);const q=await P_({gateway_url:R,gateway_user_id:_,gateway_token:C,persist:$},t);J(q),x(""),m(!0),e.onClose()}catch(R){A(String((R==null?void 0:R.message)||R))}finally{c(!1)}},Z=async()=>{c(!0),A(""),F("");try{await Cg(t),x("");const R=await qd(t).catch(()=>null);J(R),F("Signed out. This browser no longer holds a gateway session.")}catch(R){A(String((R==null?void 0:R.message)||R))}finally{c(!1)}};return o.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:R=>{!e.blocking&&R.target===R.currentTarget&&e.onClose()},children:o.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:o.jsx(h_,{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:L.label,statusTone:L.tone,showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:R=>v(R),userId:_,onUserIdChange:b,token:C,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:j,onTokenChange:x,onShowTokenChange:N,remember:$,rememberLabel:"Keep this browser signed in",onRememberChange:S,loading:n,submitting:i,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:Z,error:E,message:I,onSubmit:O})})})}function z_(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function U_(e){const t=e||{},n=t.connectionPath||Ri,r=t.variant||"dismissable",i=y.useRef(t.onStatusChange);i.current=t.onStatusChange;const c=y.useRef(r);c.current=r;const u=y.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[d,h]=y.useState(null),[m,p]=y.useState("loading"),[v,_]=y.useState(!1),b=y.useRef(!1),C=y.useRef(!1),x=y.useRef("loading"),j=y.useRef("none"),N=y.useRef(!1),$=y.useRef(0),S=y.useCallback(q=>{var se;$.current+=1,h(q),(se=i.current)==null||se.call(i,q);const z=z_(q);if(z)p("connected"),x.current="connected",b.current=!1,j.current="none",C.current||_(!1);else if(q!==null){const G=x.current;p("disconnected"),x.current="disconnected",G!=="disconnected"&&(j.current=N.current?"signout":G==="connected"?"mid":"boot");const te=c.current==="blocking"||j.current!=="mid"||u.current;!b.current&&te&&_(!0)}q!==null&&(C.current=z)},[]),E=y.useCallback(async()=>{const q=$.current;try{const z=await qd(n);if($.current!==q)return;S(z)}catch{if($.current!==q)return;S(null)}},[n,S]),[A,I]=y.useState(!1),[F,L]=y.useState(null),J=y.useCallback(async()=>{I(!0),L(null),$.current+=1;let q=null;try{await Cg(n)}catch(z){q=String((z==null?void 0:z.message)||z||"Sign-out request failed")}N.current=!0;try{await E()}finally{N.current=!1}L(q),I(!1)},[n,E]),V=y.useRef(!1);y.useEffect(()=>{V.current||(V.current=!0,E())},[E]);const O=y.useCallback(()=>{_(!0)},[]),Z=y.useCallback(()=>{const q=x.current;r==="blocking"&&q==="disconnected"||(q==="disconnected"&&(b.current=!0),_(!1))},[r]),R=y.useMemo(()=>({isOpen:v,onClose:Z,blocking:r==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:d,onStatusChange:S}),[v,Z,r,m,t.appName,n,t.defaultGatewayUrl,d,S]);return{status:d,phase:m,connected:m==="connected",modalOpen:v,signingOut:A,signOutError:F,openModal:O,refresh:E,signOut:J,modalProps:R}}function B_(){return globalThis.crypto}function W_(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 ca(){const e=B_();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return W_(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Mc(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 V_(e){const t=e.closeOnEscape!==!1,n=y.useRef(null);return y.useEffect(()=>{if(!e.open||!t)return;const r=i=>{i.key!=="Escape"||i.defaultPrevented||(i.preventDefault(),e.onClose())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[e.open,t,e.onClose]),y.useEffect(()=>{const r=n.current;r&&(e.open?r.removeAttribute("inert"):r.setAttribute("inert",""))},[e.open]),o.jsxs(o.Fragment,{children:[e.backdrop&&e.open?o.jsx("div",{className:"af-drawer-backdrop","aria-hidden":"true",onClick:e.onClose,style:{top:e.topOffset||0}}):null,o.jsxs("div",{ref:n,className:`af-drawer${e.side==="left"?" af-drawer--left":""}${e.topOffset?" af-drawer--offset":""}${e.open?" af-drawer--open":""}${e.className?` ${e.className}`:""}`,style:{width:e.width||420,top:e.topOffset||0,display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,children:[e.title!==void 0?o.jsxs("div",{className:"af-drawer__header",children:[o.jsx("div",{className:"af-drawer__title",children:e.title}),o.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,o.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,o.jsx("div",{className:"af-drawer__body",children:e.children})]})]})}const G_=["a[href]","area[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])","iframe","summary",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(", ");function H_(e,t,n,r){if(e.length===0)return null;const i=e[0],c=e[e.length-1];return r?n&&t===i?c:!n&&t===c?i:null:n?c:i}function K_(e){for(let t=e.parentElement;t;t=t.parentElement){if(t.tagName.toUpperCase()!=="DETAILS"||t.hasAttribute("open"))continue;if(!(e.tagName.toUpperCase()==="SUMMARY"&&e.parentElement===t))return!0}return!1}function Cd(e){return Array.from(e.querySelectorAll(G_)).filter(n=>!(typeof n.closest=="function"&&n.closest("[hidden], [inert], [aria-hidden='true']")||K_(n)||typeof n.getClientRects=="function"&&n.getClientRects().length===0))}const ap=new WeakMap;function J_(e,t){const n=t.document||e.ownerDocument,r=e.querySelector(".af-modal")||e,i=n.activeElement,c=ap.get(n)||[];ap.set(n,c),c.push(e);const u=t.lockScroll!==!1;u&&n.documentElement.classList.add("af-modal-open");const d=()=>{const x=r.querySelector(".af-modal__body"),j=t.initialFocus||r.querySelector("[data-af-autofocus], [autofocus]")||(x?Cd(x)[0]:void 0)||Cd(r)[0]||r;j===r&&!r.hasAttribute("tabindex")&&r.setAttribute("tabindex","-1"),j.focus({preventScroll:!0})};d();const h=()=>c[c.length-1]===e,m=x=>{if(!h())return;if(x.key==="Escape"||x.key==="Esc"){if(x.defaultPrevented||t.closeOnEscape===!1)return;x.preventDefault(),t.onClose();return}if(x.key!=="Tab")return;const j=Cd(r),N=n.activeElement,$=!!N&&r.contains(N);if(j.length===0){x.preventDefault(),r.focus({preventScroll:!0});return}const S=H_(j,N,x.shiftKey,$&&N!==r);S&&(x.preventDefault(),S.focus({preventScroll:!0}))},p=x=>{if(!h())return;const j=x.target;j&&!r.contains(j)&&d()};let v=!1;const _=x=>{v=x.target===e},b=x=>{const j=x.target===e&&v;v=!1,!(!j||!h()||t.closeOnBackdrop===!1)&&t.onClose()};n.addEventListener("keydown",m,!0),n.addEventListener("focusin",p,!0),e.addEventListener("mousedown",_),e.addEventListener("click",b);let C=!1;return()=>{if(C)return;C=!0,n.removeEventListener("keydown",m,!0),n.removeEventListener("focusin",p,!0),e.removeEventListener("mousedown",_),e.removeEventListener("click",b);const x=c.lastIndexOf(e);x>=0&&c.splice(x,1),u&&c.length===0&&n.documentElement.classList.remove("af-modal-open"),i&&typeof i.focus=="function"&&i.isConnected!==!1&&i.focus({preventScroll:!0})}}function Q_(e){const t=y.useId().replace(/:/g,""),n=e.id||`af-modal-${t}`,r=y.useRef(null),i=y.useRef(e.onClose);if(i.current=e.onClose,y.useEffect(()=>{if(!(!e.open||!r.current))return J_(r.current,{onClose:()=>i.current(),closeOnEscape:e.closeOnEscape!==!1,closeOnBackdrop:e.closeOnBackdrop!==!1,initialFocus:e.initialFocusRef?e.initialFocusRef.current:null})},[e.open]),!e.open)return null;const c=o.jsx("div",{className:"af-modal-backdrop",ref:r,children:o.jsxs("div",{className:`af-modal${e.size==="narrow"?" af-modal--narrow":e.size==="wide"?" af-modal--wide":""}${e.className?` ${e.className}`:""}`,id:n,role:"dialog","aria-modal":"true","aria-labelledby":`${n}-title`,"aria-describedby":e.describedBy,children:[o.jsxs("div",{className:"af-modal__header",children:[o.jsx("h2",{className:"af-modal__title",id:`${n}-title`,children:e.title}),o.jsx("button",{type:"button",className:"af-modal__close","aria-label":e.closeLabel||"Close",onClick:()=>i.current(),children:o.jsx("span",{"aria-hidden":"true",children:"×"})})]}),o.jsx("div",{className:"af-modal__body",children:e.children}),e.footer!==void 0||e.footerNote!==void 0?o.jsxs("div",{className:"af-modal__footer",children:[e.footerNote!==void 0?o.jsx("p",{className:"af-modal__footer-note",children:e.footerNote}):null,e.footer]}):null]})});return e.portal!==!1&&typeof document<"u"&&!!document.body?Rc.createPortal(c,document.body):c}function Y_(e,t,n,r=4,i=8){let c=e.bottom+r,u=!1;if(c+t.height>n.height-i){const m=e.top-r-t.height;(m>=i||e.top>n.height-e.bottom)&&(c=m,u=!0)}let d=e.left,h=!1;return d+t.width>n.width-i&&(d=e.right-t.width,h=!0),d=Math.max(i,Math.min(d,n.width-i-t.width)),c=Math.max(i,c),{top:Math.round(c),left:Math.round(d),up:u,leftward:h}}let op=0;function X_(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")||(op+=1,t.setAttribute("id",`af-menu-${op}`)),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 c=()=>{const S=Array.from(t.querySelectorAll(".af-menu__item")),E=S.filter(A=>!A.hidden&&!A.hasAttribute("disabled"));for(const A of S)A.setAttribute("role","menuitem"),A.setAttribute("tabindex","-1");return E};c();let u=!1;const d=()=>{if(!u)return;const S=e.getBoundingClientRect(),E=t.getBoundingClientRect(),A=Y_(S,{width:E.width,height:E.height},{width:i.innerWidth,height:i.innerHeight});t.style.top=`${A.top}px`,t.style.left=`${A.left}px`,t.setAttribute("data-placement",`${A.up?"top":"bottom"}-${A.leftward?"end":"start"}`)},h=S=>{const E=c();if(!E.length)return;const A=(S%E.length+E.length)%E.length;E[A].focus({preventScroll:!0})},m=S=>{u||(u=!0,t.hidden=!1,e.setAttribute("aria-expanded","true"),d(),h(S),r.addEventListener("pointerdown",v,!0),r.addEventListener("mousedown",v,!0),i.addEventListener("scroll",d,!0),i.addEventListener("resize",_),i.addEventListener("keydown",x,!0),n.onOpen&&n.onOpen())},p=S=>{u&&(u=!1,t.hidden=!0,e.setAttribute("aria-expanded","false"),r.removeEventListener("pointerdown",v,!0),r.removeEventListener("mousedown",v,!0),i.removeEventListener("scroll",d,!0),i.removeEventListener("resize",_),i.removeEventListener("keydown",x,!0),S&&e.focus({preventScroll:!0}),n.onClose&&n.onClose())};function v(S){const E=S.target;E&&(t.contains(E)||e.contains(E))||p(!1)}function _(){p(!1)}const b=S=>{S.preventDefault(),u?p(!0):m(0)},C=S=>{S.key==="ArrowDown"||(S.key==="Enter"||S.key===" ")&&!u?(S.preventDefault(),m(0)):S.key==="ArrowUp"&&(S.preventDefault(),m(-1))},x=S=>{if(!u||S.key!=="Escape"&&S.key!=="Esc")return;const E=S.target;E&&E!==e&&!t.contains(E)&&E!==r.body||(S.preventDefault(),p(!0))},j=S=>{if(!u)return;const A=c().indexOf(r.activeElement);S.key==="ArrowDown"?(S.preventDefault(),h(A+1)):S.key==="ArrowUp"?(S.preventDefault(),h(A<0?-1:A-1)):S.key==="Home"?(S.preventDefault(),h(0)):S.key==="End"?(S.preventDefault(),h(-1)):S.key==="Tab"&&p(!1)},N=S=>{const E=S.target,A=E&&typeof E.closest=="function"?E.closest(".af-menu__item"):null;if(!A||!t.contains(A))return;const I=r.activeElement,F=!I||I===r.body||t.contains(I);p(F)};e.addEventListener("click",b),e.addEventListener("keydown",C),t.addEventListener("keydown",j),t.addEventListener("click",N);let $=!1;return()=>{$||($=!0,p(!1),e.removeEventListener("click",b),e.removeEventListener("keydown",C),t.removeEventListener("keydown",j),t.removeEventListener("click",N))}}function Eg(e){const t=y.useRef(null),n=y.useRef(null),r=e.items.filter(c=>c&&!c.hidden),i=r.length>0;return y.useEffect(()=>{if(!(!i||!t.current||!n.current))return X_(t.current,n.current)},[i]),i?o.jsxs("div",{className:`af-menu${e.className?` ${e.className}`:""}`,children:[o.jsx("button",{type:"button",ref:t,className:`af-menu__button${e.buttonClassName?` ${e.buttonClassName}`:""}`,"aria-label":e.label,title:e.title,"aria-haspopup":"menu","aria-expanded":"false",children:e.buttonContent!==void 0?e.buttonContent:o.jsx("span",{"aria-hidden":"true",children:"⋯"})}),o.jsx("div",{className:"af-menu__list",role:"menu",ref:n,hidden:!0,children:r.map(c=>o.jsx("button",{type:"button",role:"menuitem",tabIndex:-1,"data-menu-id":c.id,className:`af-menu__item${c.danger?" af-menu__item--danger":""}`,onClick:()=>c.onSelect(),children:c.label},c.id))})]}):null}const q_={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"},Z_={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"}},eb={framework:q_,apps:Z_},_c=eb;function $g(){return{..._c.framework}}function tb(){return Object.keys(_c.apps).sort()}function nb(e,t){const n=Object.prototype.hasOwnProperty.call(_c.apps,e)?_c.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${tb().join(", ")})`);return{id:e,name:n.name,version:t,website:n.website,repo:n.repo,docs:n.docs,issues:n.issues,feedback:n.feedback}}function ro(e){return typeof e=="string"?e.trim():""}function ip(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=ro(n.abstractgateway),i=ro(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 sb(e){const t=$g();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 rb(e){const t=e||{},n=ro(t.framework),r=ro(t.gateway);return[["AbstractFramework",n||ro(t.frameworkNote)||"not reported"],["AbstractGateway",r||ro(t.gatewayNote)||"not connected"]]}const ab='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Ag(e,t,n){if(e.key!=="Tab"||!t)return;const r=Array.from(t.querySelectorAll(ab));if(r.length===0){e.preventDefault();return}const i=r[0],c=r[r.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===i||!u)&&(e.preventDefault(),c.focus()):(n===c||!u)&&(e.preventDefault(),i.focus())}function ob(e){const t=$g();return o.jsxs("div",{className:`af-about-card${e.className?` ${e.className}`:""}`,"data-app":e.identity.id,children:[o.jsxs("div",{className:"af-about-card__head",children:[o.jsxs("h2",{className:"af-about-card__name",id:e.titleId,children:[e.identity.name," ",o.jsx("span",{className:"af-about-card__version",children:e.identity.version})]}),e.action]}),o.jsx("dl",{className:"af-about-card__versions",children:rb(e.versions).map(([n,r])=>o.jsxs("div",{className:"af-about-card__fact",children:[o.jsx("dt",{children:n}),o.jsx("dd",{children:r})]},n))}),o.jsx("nav",{className:"af-about-card__links","aria-label":`${e.identity.name} links`,children:sb(e.identity).map(n=>n.href.startsWith("mailto:")?o.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,children:n.label},n.id):o.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))}),o.jsx("p",{className:"af-about-card__legal",children:t.copyright})]})}function ib(e){fo();const t=y.useRef(null),n=y.useRef(null),r=y.useId(),i=y.useRef(e.onClose);return i.current=e.onClose,y.useEffect(()=>{var d;if(!e.open)return;const c=document.activeElement;(d=t.current)==null||d.focus();const u=h=>{if(!h.defaultPrevented){if(h.key==="Escape"){h.preventDefault(),i.current();return}Ag(h,n.current,document.activeElement)}};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u),c&&typeof c.focus=="function"&&c.focus()}},[e.open]),e.open?o.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:o.jsx("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":r,onClick:c=>c.stopPropagation(),children:o.jsx(ob,{identity:e.identity,versions:e.versions,titleId:r,action:o.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:o.jsx(re,{name:"x",size:16})})})})}):null}function lb(e){const{connection:t}=e,n=t.phase,r=t.signingOut===!0,[i,c]=y.useState(!1);fo();const u=e.about,d=r?"Signing out…":n==="connected"?"Disconnect":n==="loading"?"Connecting…":"Connect",h=n==="connected"?"Disconnect from gateway":n==="loading"?"Checking gateway session…":"Connect to gateway";return o.jsxs("div",{className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.docs?o.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:o.jsx(re,{name:"book",size:16})}):null,e.assistant?o.jsx("button",{type:"button",className:`af-topbar__btn${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant","data-af-tip":e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:o.jsx(re,{name:"sparkle",size:16})}):null,e.appearance?o.jsx("button",{type:"button",className:"af-topbar__btn","aria-label":e.appearance.label||"Appearance (theme and typography)","data-af-tip":e.appearance.label||"Appearance (theme and text size)",onClick:e.appearance.onOpen,children:o.jsx(re,{name:"contrast",size:16})}):null,u?o.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":u.label||`About ${u.identity.name}`,"data-af-tip":u.label||`About ${u.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var m;c(!0),(m=u.onOpen)==null||m.call(u)},children:o.jsx(re,{name:"info",size:16})}):null,e.extraActions,o.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?t.onDisconnect:t.onConnect,disabled:r,title:h,"aria-label":h,children:[o.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),o.jsx("span",{className:"af-topbar__pill-label",children:d})]}),u?o.jsx(ib,{open:i,onClose:()=>c(!1),identity:u.identity,versions:u.versions}):null]})}const pc={theme:"dark",font_scale:"md",header_density:"standard"};function cb(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:pc.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:pc.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:pc.header_density}}function ub(e){return`af_appearance_${e}_v1`}function db(e,t){const n=ub(e),r=y.useMemo(()=>({...pc,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[i,c]=y.useState(()=>{let u=r;try{const d=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);d&&(u=cb({...r,...JSON.parse(d)}))}catch{}try{ep(u.theme),tp({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return y.useEffect(()=>{ep(i.theme),tp({font_scale:i.font_scale,header_density:i.header_density});try{localStorage.setItem(n,JSON.stringify(i))}catch{}},[n,i]),[i,c]}function fb(e){return y.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?o.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:o.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[o.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),o.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),o.jsxs("div",{className:"af-appearance__grid",children:[o.jsx("label",{className:"af-appearance__label",children:"Theme"}),o.jsx(p_,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),o.jsx("label",{className:"af-appearance__label",children:"Font size"}),o.jsx(g_,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),o.jsx("label",{className:"af-appearance__label",children:"Header size"}),o.jsx(y_,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),o.jsx("div",{className:"af-appearance__actions",children:o.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}function Zd(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function lp(e,t,n=!1){if(n)return"unknown";if(!e)return"";const r=e[t];return!r||!r.configured?"not set":Zd(r)||"not set"}function hb(e,t){var n;return e.stt_provider?Zd({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?Zd(t.stt):""}function Tg(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function mb(e,t,n){return`Transcribing… ${Tg(e,t)}${n?` · ${n}`:""}`}const Lc=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function ef(e){var i;const t=Mc("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=Lc())!=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 pb(e){const t=Lc();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const r=(await t.enumerateDevices()).filter(u=>u.kind===e),i=r.some(u=>!!u.label);return{devices:r.filter(u=>u.deviceId&&u.deviceId!=="default"&&u.deviceId!=="communications").map((u,d)=>({id:String(u.deviceId),label:String(u.label||`${e==="audioinput"?"Microphone":"Speaker"} ${d+1}`)})),labelled:i}}async function gb(){const e=Lc();if(!(e!=null&&e.getUserMedia))throw new Error(Mc("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Rg(e){const t=Lc();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 Oc(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Ig(){const e=Oc();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function yb(e,t,n=1){const r=Oc();if(!r)return()=>{};const i=new r,c=i.createMediaStreamSource(e),u=i.createAnalyser();u.fftSize=1024,c.connect(u);const d=new Float32Array(u.fftSize);let h=!0;const p=setInterval(()=>{if(!h)return;u.getFloatTimeDomainData(d);let v=0;for(let _=0;_<d.length;_+=1)v+=d[_]*d[_];t(Math.min(1,Math.sqrt(v/d.length)*4*n))},50);return()=>{var v;h=!1,clearInterval(p);try{c.disconnect()}catch{}(v=i.close)==null||v.call(i)}}const wb=.02;async function vb(e){var c;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});const n=await Rg(e.deviceId);let r=0;const i=yb(n,u=>{var d;r=Math.max(r,u),(d=e.onLevel)==null||d.call(e,u)},e.gain??1);try{const u=new t(n),d=[],h=new Promise((p,v)=>{u.ondataavailable=_=>(_==null?void 0:_.data)&&d.push(_.data),u.onstop=()=>p(),u.onerror=_=>v((_==null?void 0:_.error)||new Error("Recording failed."))});u.start(),await new Promise(p=>{var _;const v=setTimeout(p,e.ms??3e3);(_=e.signal)==null||_.addEventListener("abort",()=>{clearTimeout(v),p()},{once:!0})}),u.stop(),await h;const m=String(u.mimeType||"audio/webm");return{blob:new Blob(d,{type:m}),peak:r,mime:m}}finally{i(),n.getTracks().forEach(u=>u.stop()),(c=e.onLevel)==null||c.call(e,0)}}async function _b(e,t={}){var i;const n=Oc();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 c=e instanceof Blob?await e.arrayBuffer():e,u=await r.decodeAudioData(c.slice(0)),d=r.createGain();d.gain.value=kf(t.volume),d.connect(r.destination);const h=r.createBufferSource();h.buffer=u,h.connect(d),await new Promise(m=>{h.onended=()=>m(),h.start()})}finally{(i=r.close)==null||i.call(r)}}async function bb(e={}){var r,i;const t=Oc();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 c=n.createGain();c.connect(n.destination);const u=.3*kf(e.volume),d=n.currentTime+.02;[660,880].forEach((h,m)=>{const p=n.createOscillator(),v=n.createGain();p.frequency.value=h,p.connect(v),v.connect(c);const _=d+m*.22;v.gain.setValueAtTime(0,_),v.gain.linearRampToValueAtTime(u,_+.02),v.gain.exponentialRampToValueAtTime(1e-4,_+.2),p.start(_),p.stop(_+.21)}),await new Promise(h=>setTimeout(h,520))}finally{(i=n.close)==null||i.call(n)}}function kf(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}async function*xb(e){var r,i,c;const t=new AbortController,n=()=>t.abort();(r=e.signal)!=null&&r.aborted?n():(i=e.signal)==null||i.addEventListener("abort",n,{once:!0});try{const u=await fetch(e.path,{method:"POST",headers:{"Content-Type":"application/json",...e.csrfToken?{"x-abstract-csrf":e.csrfToken}:{},...e.headers||{}},body:JSON.stringify(e.body),signal:t.signal});if(!u.ok){const p=await u.json().catch(()=>null),v=p&&typeof p=="object"&&p.detail?String(p.detail):`HTTP ${u.status}`;throw new Error(v)}if(!u.body)throw new Error("TTS stream has no body");const d=u.body.getReader(),h=new TextDecoder;let m="";for(;;){const{done:p,value:v}=await d.read();m+=p?h.decode():h.decode(v,{stream:!0}),p&&m.trim()&&(m+=`
42
+ `);let _;for(;(_=m.indexOf(`
43
+ `))>=0;){const b=m.slice(0,_).trim();if(m=m.slice(_+1),!b)continue;let C=null;try{C=JSON.parse(b)}catch{throw new Error("TTS stream returned invalid JSON.")}if(C&&C.type==="error")throw new Error(String(C.error||"TTS stream error"));const x=C&&typeof C.audio_b64=="string"?C.audio_b64:"";if(x){const j=atob(x),N=new Uint8Array(j.length);for(let $=0;$<j.length;$+=1)N[$]=j.charCodeAt($);yield N.buffer}if(C&&(C.type==="done"||C.type==="cancelled"))return}if(p)throw new Error("TTS stream ended before synthesis completed.")}}finally{(c=e.signal)==null||c.removeEventListener("abort",n),t.abort()}}function oi(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const kb=350;function jb(){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 Sb(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function Nb(){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 Ed(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 c=r(n);if(c&&typeof c.then=="function")return await c}catch{}return await new Promise((c,u)=>{try{r(n,c,u)}catch(d){u(d)}})}function Cb(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=c=>String.fromCharCode(t[c],t[c+1],t[c+2],t[c+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const r=new DataView(e);let i=12;for(;i+8<=t.length;){const c=n(i),u=r.getUint32(i+4,!0);if(c==="data")return t.slice(0,i+8);i+=8+u+u%2}return null}function Eb(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 $b(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const nc=new WeakMap;function Ab(e,t){const n=e;if(!(typeof n.setSinkId!="function"||nc.get(e)===t)){nc.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>nc.delete(e))}catch{nc.delete(e)}}}function Tb(e){const t=y.useRef(e);t.current=e;const n=ae=>{var Te,ge;return(ge=(Te=t.current).on_error)==null?void 0:ge.call(Te,ae)},r=y.useMemo(()=>Sb()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),i=y.useMemo(()=>jb()&&typeof e.transcribe=="function",[e.transcribe]),[c,u]=y.useState({key:"",status:"idle"}),d=y.useRef(c),h=y.useCallback(ae=>{d.current=ae,u(Te=>Te.key===ae.key&&Te.status===ae.status?Te:ae)},[]),m=y.useRef(""),p=y.useRef(""),v=y.useRef(null),_=y.useRef(null),b=y.useRef(null),C=y.useRef(null),x=y.useRef(0),j=y.useRef(0),N=y.useRef(0),$=y.useRef(null),S=y.useRef([]),E=y.useRef(0),A=y.useRef(!0),I=y.useRef(!1),F=()=>{try{const ae=globalThis,Te=(ae==null?void 0:ae.AudioContext)||(ae==null?void 0:ae.webkitAudioContext);if(!Te)return null;if(!v.current){const pe=new Te,be=pe.createGain();be.gain.value=1,be.connect(pe.destination),v.current=pe,_.current=be}const ge=v.current,Q=_.current;if(!ge||!Q)return null;Ab(ge,t.current.output_device_id||""),Q.gain.value=kf(t.current.volume);try{ge.state==="suspended"&&ge.resume()}catch{}return{ctx:ge,gain:Q}}catch{return null}},L=y.useCallback(()=>{const ae=b.current;if(b.current=null,!!ae){try{ae.onended=null}catch{}try{ae.stop()}catch{}try{ae.disconnect()}catch{}}},[]),J=y.useCallback(()=>{var ae;L(),N.current+=1,(ae=$.current)==null||ae.abort(),$.current=null,S.current=[],E.current=0,A.current=!0,I.current=!1,p.current="",m.current="",C.current=null,x.current=0,j.current=0,h({key:"",status:"idle"})},[L,h]);y.useEffect(()=>()=>{var ae,Te;J();try{(ae=_.current)==null||ae.disconnect()}catch{}try{(Te=v.current)==null||Te.close()}catch{}v.current=null,_.current=null,C.current=null},[]);const V=async(ae,Te,ge)=>{const Q=N.current,pe=F();if(!pe)throw new Error("TTS playback is not supported in this browser");const{ctx:be,gain:Ee}=pe;try{be.state==="suspended"&&await be.resume()}catch{}if(Q!==N.current)return;L();const Pe=be.createBufferSource();Pe.buffer=Te,Pe.connect(Ee);const We=Number.isFinite(Number(Te.duration))?Number(Te.duration):0,Be=Math.max(0,Math.min(Number(ge||0),We>0?Math.max(0,We-.01):0));j.current=be.currentTime-Be,x.current=Be,b.current=Pe,m.current=ae,Pe.onended=()=>{b.current===Pe&&(b.current=null,x.current=0,j.current=0,m.current="",h({key:"",status:"idle"}))},Pe.start(0,Be),h({key:ae,status:"playing"})},O=(ae,Te)=>{if(Te!==N.current)return;const ge=F();if(!ge)return;const Q=S.current,pe=E.current;if(pe>=Q.length){A.current&&(m.current="",x.current=0,j.current=0,h({key:"",status:"idle"}));return}const be=Q[pe],{ctx:Ee,gain:Pe}=ge;L();const We=Ee.createBufferSource();We.buffer=be,We.connect(Pe);const Be=Number.isFinite(Number(be.duration))?Number(be.duration):0,bt=Math.max(0,Math.min(Number(x.current||0),Be>0?Math.max(0,Be-.01):0));j.current=Ee.currentTime-bt,b.current=We,m.current=ae,We.onended=()=>{Te===N.current&&b.current===We&&(b.current=null,E.current=pe+1,x.current=0,O(ae,Te))};try{Ee.state==="suspended"&&Ee.resume()}catch{}We.start(0,bt),h({key:ae,status:"playing"})},Z=async(ae,Te,ge)=>{var Pe;const Q=F();if(!Q){n==null||n("This browser cannot play spoken replies.");return}L();const pe=++N.current;(Pe=$.current)==null||Pe.abort();const be=new AbortController;$.current=be,S.current=[],E.current=0,A.current=!1,I.current=!1,C.current=null,x.current=0,j.current=0,m.current=ae,p.current=ae,h({key:ae,status:"loading"}),n==null||n("");let Ee=null;try{for await(const We of ge(Te,be.signal)){if(pe!==N.current)return;let Be;try{Be=await Ed(Q.ctx,We),Ee||(Ee=Cb(We))}catch{if(!Ee)continue;try{Be=await Ed(Q.ctx,Eb(Ee,We))}catch{continue}}if(pe!==N.current)return;S.current.push(Be),!b.current&&!I.current&&(p.current="",O(ae,pe))}if(pe!==N.current)return;if(A.current=!0,S.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),J();return}!b.current&&!I.current&&O(ae,pe)}catch(We){if(pe!==N.current)return;n==null||n(oi("Reading aloud failed",We)),J()}finally{$.current===be&&($.current=null)}},R=y.useCallback(async(ae,Te)=>{var bt;const ge=String(ae||"").trim(),Q=String(Te||"").trim();if(!ge||!Q)return;const pe=t.current.tts,be=t.current.tts_stream;if(typeof pe!="function"&&typeof be!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Ee=F();if(!Ee){n==null||n("This browser cannot play spoken replies.");return}const Pe=d.current,We=Pe.key===ge;if(We&&Pe.status==="playing"){if(b.current){const Nt=Math.max(0,Ee.ctx.currentTime-Number(j.current||0));x.current=Nt}else x.current=0;I.current=!0,L(),h({key:ge,status:"paused"});return}if(We&&Pe.status==="paused"){if(S.current.length>0){n==null||n(""),I.current=!1,h({key:ge,status:"playing"}),O(ge,N.current);return}const Nt=C.current;if(Nt){n==null||n(""),I.current=!1;try{await V(ge,Nt,x.current)}catch(Vn){n==null||n(oi("Reading aloud failed",Vn)),h({key:"",status:"idle"})}return}}if(We&&Pe.status==="loading")return;if(typeof be=="function"){await Z(ge,Q,be);return}L(),N.current+=1,(bt=$.current)==null||bt.abort(),$.current=null;const Be=N.current;S.current=[],E.current=0,A.current=!0,I.current=!1,C.current=null,x.current=0,j.current=0,m.current=ge,p.current=ge,h({key:ge,status:"loading"}),n==null||n("");try{const Nt=await pe(Q);if(p.current!==ge||N.current!==Be)return;const Vn=await Ed(Ee.ctx,Nt);if(p.current!==ge||N.current!==Be)return;C.current=Vn,x.current=0,await V(ge,Vn,0)}catch(Nt){if(N.current!==Be)return;p.current===ge&&(p.current="",m.current="",h({key:"",status:"idle"})),n==null||n(oi("Reading aloud failed",Nt))}},[]),[q,z]=y.useState(!1),[se,G]=y.useState(!1),te=y.useRef(!1),ue=y.useRef(i);ue.current=i;const ne=y.useCallback(ae=>{te.current=ae,z(Te=>Te===ae?Te:ae)},[]),P=y.useRef(!1),B=y.useRef(null),W=y.useRef(null),de=y.useRef([]),ee=y.useRef(""),le=y.useRef(0),fe=y.useRef(!1),[oe,we]=y.useState(0),Oe=y.useRef(0),Je=y.useRef(null);function st(){var Te,ge;try{(ge=(Te=B.current)==null?void 0:Te.getTracks)==null||ge.call(Te).forEach(Q=>{try{Q.stop()}catch{}})}catch{}B.current=null;const ae=Je.current;Je.current=null;try{ae==null||ae.close()}catch{}}const Ce=y.useCallback(()=>{le.current+=1,fe.current=!1;const ae=W.current;if(ae){ae.onstop=null,ae.ondataavailable=null,ae.onerror=null;try{ae.stop()}catch{}}W.current=null,st(),ne(!1),P.current=!1,G(!1),we(0),de.current=[]},[ne]);y.useEffect(()=>()=>Ce(),[Ce]);async function Ye(ae,Te){var be,Ee;if(n==null||n(""),P.current)return;const ge=Oe.current?Date.now()-Oe.current:1/0;if(!ae||!ae.size||ge<kb){we(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 Q=t.current.transcribe;if(typeof Q!="function"){n==null||n("Speech to text is not available on this gateway.");return}P.current=!0;const pe=le.current;G(!0),we(Date.now());try{const Pe=await Q(ae,Te),We=typeof Pe=="string"||!Pe?{text:String(Pe||"")}:Pe,Be=String(We.text||"").trim();if(pe!==le.current)return;Be?(Ee=(be=t.current).on_transcript)==null||Ee.call(be,Be,{...We,text:Be}):n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(Pe){if(pe===le.current){const We=String((Pe==null?void 0:Pe.message)||Pe||"").trim().replace(/\.$/,"");n==null||n(We?`Transcription failed: ${We}.`:"Transcription failed.")}}finally{pe===le.current&&(P.current=!1,G(!1),we(0))}}const he=y.useCallback(async()=>{if(n==null||n(""),!ue.current){n==null||n(Mc("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(P.current||fe.current||te.current||W.current)return;de.current=[];const ae=le.current;fe.current=!0;try{const Te=await Rg(t.current.input_device_id||"");if(ae!==le.current){Te.getTracks().forEach(Ee=>Ee.stop());return}B.current=Te;const ge=Nb();ee.current=ge;let Q=Te;const pe=Number(t.current.input_gain??1);if(Number.isFinite(pe)&&pe>0&&pe!==1&&Ig()){const Ee=globalThis.AudioContext||globalThis.webkitAudioContext,Pe=new Ee,We=Pe.createGain();We.gain.value=pe;const Be=Pe.createMediaStreamDestination();Pe.createMediaStreamSource(Te).connect(We),We.connect(Be),Je.current=Pe,Q=Be.stream}const be=ge?new MediaRecorder(Q,{mimeType:ge}):new MediaRecorder(Q);W.current=be,be.ondataavailable=Ee=>{if(ae===le.current)try{Ee!=null&&Ee.data&&de.current.push(Ee.data)}catch{}},be.onerror=()=>{ae===le.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},be.onstop=()=>{if(ae===le.current){ne(!1),st(),W.current=null;try{const Ee=new Blob(de.current,{type:ee.current||""});Ye(Ee,ee.current)}catch(Ee){n==null||n(oi("The recording could not be prepared",Ee))}}},be.start(),Oe.current=Date.now(),we(Oe.current),ne(!0)}catch(Te){if(ae!==le.current)return;st(),W.current=null,ne(!1),we(0),n==null||n(ef(Te))}finally{ae===le.current&&(fe.current=!1)}},[]),Ve=y.useCallback(()=>{const ae=W.current;if(!(!te.current||!ae)){ne(!1);try{ae.stop()}catch(Te){n==null||n(oi("The recording could not stop",Te))}}},[]);return y.useEffect(()=>{if(!q||t.current.stop_on_pointerup===!1)return;const ae=()=>Ve();return window.addEventListener("pointerup",ae),window.addEventListener("pointercancel",ae),()=>{window.removeEventListener("pointerup",ae),window.removeEventListener("pointercancel",ae)}},[q]),{tts_supported:r,tts_playback:c,toggle_tts:R,stop_tts:J,voice_ptt_supported:i,voice_ptt_recording:q,voice_ptt_busy:se,start_voice_ptt_recording:he,stop_voice_ptt_recording:Ve,cancel_voice_ptt_recording:Ce,voice_ptt_since:oe}}const sc=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 Rb({value:e,onChange:t,fetchCatalog:n,intro:r,delivery:i=!0,quality:c=!0,showReset:u=!0,defaultHint:d,voiceDefaultLabel:h}){var I,F,L,J;const m=y.useRef(n);m.current=n;const[p,v]=y.useState({}),[_,b]=y.useState(""),[C,x]=y.useState(!1);y.useEffect(()=>{let V=!0;return x(!0),v({}),b(""),m.current(e.provider,e.model).then(O=>{V&&(v(O),b(O.error?String(O.error):""))}).catch(O=>{V&&b(String((O==null?void 0:O.message)||O))}).finally(()=>{V&&x(!1)}),()=>{V=!1}},[e.provider,e.model]);const j=Array.isArray(p.items)?p.items:[...Array.isArray(p.profiles)?p.profiles.map(V=>({...V,voice_kind:"profile"})):[],...Array.isArray(p.voices)?p.voices.map(V=>({...V,voice_kind:"voice"})):[]],N=V=>JSON.stringify([V.provider||"",V.model||"",V.voice_kind==="profile"?"profile":"voice",V.id]),$=j.find(V=>V.id===(e.profile||e.voice)&&V.voice_kind==="profile"==!!e.profile&&(!e.provider||!V.provider||V.provider===e.provider)&&(!e.model||!V.model||V.model===e.model)),S=$?N($):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",E=j.filter(V=>(V==null?void 0:V.id)&&(!e.provider||!V.provider||V.provider===e.provider)).map(V=>({value:N(V),label:`${V.label||V.name||V.id}${!e.provider&&V.provider?` · ${V.provider}`:""}`}));S&&!E.some(V=>V.value===S)&&E.unshift({value:S,label:`${e.profile||e.voice} (saved)`});const A=V=>t({...e,...V});return o.jsxs("div",{className:"af-voice-settings",children:[r===void 0?o.jsx("p",{children:"Speech is generated by your authenticated Gateway. Leave routing and voice unset to use its defaults."}):r,o.jsx(Ic,{defaultHint:d,value:{provider:e.provider||"",model:e.model||""},onChange:V=>t({...e,...V,voice:"",profile:""}),fetchProviders:async()=>{const V=await m.current();if(V.error&&!sc(V.tts_providers||V.providers).length)throw new Error(V.error);return sc(V.tts_providers||V.providers).map(O=>({name:O}))},fetchModels:async V=>{var Z;const O=await m.current(V);return sc(((Z=O.tts_models_by_provider)==null?void 0:Z[V])||O.tts_models||O.models)},providerLabel:"Speech provider",modelLabel:"Speech model"}),o.jsxs("label",{children:["Voice / profile",o.jsx(Wn,{ariaLabel:"AI voice",placeholder:h||"Gateway / provider default",value:S,disabled:C,options:[{value:"",label:h||"Gateway / provider default"},...E],onChange:V=>{if(!V){A({voice:"",profile:""});return}const[O,Z,R,q]=JSON.parse(V);A({provider:O||e.provider||"",model:Z||(O&&O!==e.provider?"":e.model)||"",voice:R==="voice"?q:"",profile:R==="profile"?q:""})}})]}),C?o.jsx("p",{role:"status",children:"Loading available voices…"}):null,_?o.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",_,". Your saved choice is preserved."]}):null,i?o.jsxs(o.Fragment,{children:[o.jsxs("label",{children:["Speaking speed",o.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:V=>A({speed:V.target.value?Number(V.target.value):void 0}),children:[o.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(V=>o.jsxs("option",{value:V,children:[V,"×"]},V))]})]}),c&&((F=(I=p.controls)==null?void 0:I.quality_preset)!=null&&F.supported)?o.jsxs("label",{children:["Quality",o.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:V=>A({quality_preset:V.target.value}),children:[o.jsx("option",{value:"",children:"Gateway default"}),sc(p.controls.quality_preset.values).map(V=>o.jsx("option",{value:V,children:V},V))]})]}):null,(J=(L=p.controls)==null?void 0:L.instructions)!=null&&J.supported?o.jsxs("label",{children:["Delivery instructions",o.jsx("textarea",{"aria-label":"Voice delivery instructions",rows:3,placeholder:"For example: calm, clear, and conversational",value:e.instructions||"",onChange:V=>A({instructions:V.target.value})})]}):null]}):null,u?o.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const $d=ve("automations"),Ib=ve("trigger-sources"),Mb=ve("me/email");class cp 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 Lb(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 Ad(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 Ob(){return ca()}function Pb(e){const t=e.newId??Ob,n=i=>`${$d}/${encodeURIComponent(i)}`;async function r(i,c,u){const d={accept:"application/json",...e.headers?e.headers():{}},h={method:i,headers:d};u!==void 0&&(d["content-type"]="application/json",h.body=JSON.stringify(u));const m=await e.fetch(Ze(e.baseUrl,c),h),p=await m.text();let v,_=!1;if(p)try{v=JSON.parse(p),_=!0}catch{_=!1}if(!m.ok)throw new cp(Lb(m.status,v));if(!_||v===null||typeof v!="object")throw new cp({status:m.status,code:"invalid_response",message:`The gateway answered ${i} ${c} with a body that is not a JSON object.`});return v}return{listAutomations:(i={})=>r("GET",`${$d}${Ad({status:i.status,cursor:i.cursor,limit:i.limit})}`),getAutomation:i=>r("GET",n(i)),createAutomation:i=>r("POST",$d,i),reviseAutomation:(i,c)=>r("PATCH",n(i),{command_id:c.command_id??t(),...c.expected_revision!==void 0?{expected_revision:c.expected_revision}:{},changes:c.changes}),sendAutomationCommand:(i,c)=>r("POST",`${n(i)}/commands`,{command_id:c.command_id??t(),type:c.type,...c.payload!==void 0?{payload:c.payload}:{}}),listOccurrences:(i,c={})=>r("GET",`${n(i)}/occurrences${Ad({cursor:c.cursor,limit:c.limit})}`),discuss:(i,c)=>r("POST",`${n(i)}/discuss`,{request_id:c.request_id??t(),occurrence_index:c.occurrence_index,prompt:c.prompt}),markSeen:(i,c)=>r("POST",`${n(i)}/seen`,{attention_cursor:c}),listAttention:(i,c={})=>r("GET",`${n(i)}/attention${Ad({cursor:c.cursor,limit:c.limit})}`),listTriggerSources:()=>r("GET",Ib),getMyEmail:()=>r("GET",Mb)}}function Ii(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 Pc(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 Db(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 c of["allowed_tools","provider","model","thinking","speculation","stream"])c in r&&(i[c]=r[c]);Object.keys(i).length&&(n._runtime=i)}return n}function tf(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const Fb={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},zb={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.`},Ub="Next scheduled run: {time}.",Bb="Growing context: later runs see this run in their history.",Wb={run_now:{name:"playCircle"}},Vb={trigger_label:"When an email arrives",not_set_up:"Connect a mailbox first — open My email",open_my_email:"open My email",filters_legend:"Only mail that matches (all optional)",from_in:"From these addresses",from_domain_in:"From these domains",to_in:"Sent to these addresses",subject_contains:"Subject contains",has_attachment:"Attachments",has_attachment_any:"any",has_attachment_yes:"only with attachments",has_attachment_no:"only without attachments",list_hint:"Separate entries with commas or new lines. Exact addresses and domains only (no patterns).",every_label:"Check for new mail every",interval_rule:"An automation that runs a model on new mail checks once an hour by default; one that needs no model checks every 60 s. The shortest interval is 60 s.",max_batch_label:"At most this many emails per run",max_batch_hint:"The rest wait for the next run. Each email is read once by this automation; mail that arrived before it was created, or while it is paused, is not processed.",untrusted_hint:"Incoming mail is data, never instructions: the automation acts only on its task. Link-opening tools (fetch_url, browser_probe) always ask for your approval.",notify_label:"Email result",notify_hint:"Email each completed run’s result to the selected recipients.",recipients_legend:"Recipients",recipients_self:"Only me (default)",recipients_list:"Me and these addresses",recipients_hint:"Separate multiple addresses with commas."},Mg={labels:Fb,hints:zb,run_now_next_run_line:Ub,run_now_growing_line:Bb,icons:Wb,email:Vb},Gb=/^([1-9][0-9]*)([smhd])$/,Hb={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function ho(e){if(typeof e!="string")return null;const t=Gb.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function Lg(e){const t=ho(e);if(!t)return`every ${e}`;const[n,r]=Hb[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${r}`}function Ir(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 Og(e){const t=e;if(typeof t.every!="string")return t.start_at?`once at ${Ir(t.start_at)}`:"once, now";const n=[`${Lg(t.every)} (UTC)`];return typeof t.count=="number"&&n.push(`${t.count} ${t.count===1?"run":"runs"} max`),typeof t.until=="string"&&n.push(`until ${Ir(t.until)}`),n.join(" · ")}function Pg(e){return e.source_id==="schedule"&&e.source_version===1?Og(e.config):e.source_id==="manual"&&e.source_version===1?"manual runs only":Mi(e)?Gg(e.config):`${e.source_id}@${e.source_version}`}function Dg(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const Kb={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},He=Mg.email,Fg="email.received",zg=1,Jb="1h",Qb="60s",Ug=60,jf=100,nf=1e3,up=200,dp=200,fp=50;function Mi(e){return!!e&&e.source_id===Fg&&e.source_version===zg}function Sf(e){return!!e&&e.effective_enabled===!0}function Bg(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 Yb=/[\s<>,;:"()[\]]/;function sf(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!Yb.test(t)}function Xb(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const Nf={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function Cf(e){return e?Jb:Qb}function Wg(e){const t=ho(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function Td(e,t,n,r,i){const c=Bg(e);if(!c.length)return null;const u=c.filter(d=>!n(d));return u.length&&i.push(`${t}: ${u.join(", ")} ${u.length===1?"is not":"are not"} ${r}.`),c.length>up&&i.push(`${t}: at most ${up} entries.`),c}function Vg(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=Cf(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&&(Wg(n.every)??0)<Ug&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=jf:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>nf?t.push(`At most this many emails per run: a whole number from 1 to ${nf}.`):n.max_batch=e.maxBatch;const r={},i=Td(e.fromIn,He.from_in,sf,"an email address",t);i&&(r.from_in=i);const c=Td(e.fromDomainIn,He.from_domain_in,Xb,"a domain like example.com",t);c&&(r.from_domain_in=c);const u=Td(e.toIn,He.to_in,sf,"an email address",t);u&&(r.to_in=u);const d=e.subjectContains.trim();return d&&(d.length>dp||/[\r\n]/.test(d)?t.push(`${He.subject_contains}: one line of at most ${dp} characters.`):r.subject_contains=d),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 Gg(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 c=typeof t.every=="string"?t.every:Cf(t.uses_model!==!1);r.push(`checked ${Lg(c)}`);const u=typeof t.max_batch=="number"?t.max_batch:jf;return r.push(`up to ${u} per run`),r.join(" · ")}const Si={mode:"self",addresses:""};function rf(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=Bg(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=>!sf(i));return r.length&&t.push(`${He.recipients_list}: ${r.join(", ")} ${r.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>fp&&t.push(`At most ${fp-1} addresses.`),{recipients:["self",...n],errors:t}}function qb(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function Zb(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function Hg(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function Kg(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function ex(e){return Kg(e)?"In the console and by email":"In the console"}const _t={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},tx=new Set(["running","waiting","backoff"]);function nx(e,t=[]){return e.current_occurrence!=null}function sx(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 rx(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 lo(e,t=[],n=!1){const r=new Set(e.capabilities),i=e.status,c=nx(e,t),u=(p,v,_)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:r.has(p)?i==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:v?{enabled:!0}:{enabled:!1,reason:_}:{enabled:!1,reason:"Not permitted for this automation."},d=i==="active"||i==="paused",h=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."}:d?r.has(h)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",i==="active",i==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",i==="paused",i==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",d&&!c,c?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",c,"Nothing is running."),revise:u("revise",!0,""),archive:u("archive",!0,""),unarchive:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:i!=="archived"?{enabled:!1,reason:"Not archived."}:r.has("unarchive")?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."},discuss:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: discussion is not available."}:r.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function Jg(e){return e.status==="active"?_t.pause:_t.resume}function ax(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 ox(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=ax(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,c=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:c,canDiscuss:!tx.has(t.status)}})}function ix(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function lx(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 cx={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 mo(e){return{title:cx[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function Li(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 Qg(e,t){var c,u,d;const n=e.trigger,r=n.source_id==="schedule"||Mi(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,context:e.context_mode,growingMaxTokens:Number(((u=(c=t==null?void 0:t.context)==null?void 0:c.growing)==null?void 0:u.max_tokens)??e.growing_max_tokens??Ai),prompt:typeof i=="string"?i:null,toolApproval:t?t.policy.tool_approval:null,tools:Ii(t==null?void 0:t.target.input_data),notifyEmail:t?Kg(t.notify):null,emailRecipients:t?qb((d=t.notify)==null?void 0:d.recipients):null}}function Yg(e,t,n){var h;const r=[],i={},c=t.title.trim();c?c.length>120?r.push("Title is at most 120 characters."):c!==e.title&&(i.title=c):r.push("Title is required.");const u=Qg(e,n);if(t.every!==u.every&&t.every!==null){const m=Mi(e.trigger);if(!ho(t.every))r.push("Interval must be a whole number of minutes, hours or days.");else if(m&&(Wg(t.every)??0)<Ug)r.push("The check interval is at least 60 seconds.");else{const p={...e.trigger.config,every:t.every};m&&delete p.start_at,i.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:p}}}const d=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(Zg(d)||r.push(qg),(t.context!==e.context_mode||d!==u.growingMaxTokens)&&(i.context=ey(t.context,d)),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const m=t.prompt.trim();m?i.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:m}}:r.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(u.tools)){const m=i.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};i.target={...m,input_data:Pc(m.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(i.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const m=rf(t.notifyEmail?t.emailRecipients??Si:u.emailRecipients??Si),p=rf(u.emailRecipients??Si).recipients;m.errors.length?r.push(...m.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(m.recipients)!==JSON.stringify(p))&&(i.notify=Hg(t.notifyEmail,m.recipients))}if(r.length)return{errors:r};if(n&&t.target&&tf(t.target)!==tf(n.target)){const m=((h=i.target)==null?void 0:h.input_data)||n.target.input_data;i.target={...t.target,input_data:Db(m)}}return Object.keys(i).length?i:null}const Ai=5e4,Xg="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.",qg="Max growing context must be a positive whole number of tokens.";function Zg(e){return Number.isSafeInteger(e)&&e>0}function ey(e,t){return{mode:e,...t!==Ai?{growing:{max_tokens:t}}:{}}}const ux=[{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 Rd(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 dx(e){const t=e.trim().split(`
56
+ `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}function ty(e){const t=[],n={};if(e.when.kind==="once"){const i=Rd(e.when.at);return i?n.start_at=i:t.push("Pick the date and time (UTC) to run once."),{config:n,errors:t}}const r=e.when.amount;if(!Number.isInteger(r)||r<1?t.push("The interval must be a whole number of at least 1."):n.every=`${r}${e.when.unit}`,e.startAt){const i=Rd(e.startAt);i?n.start_at=i:t.push("First run must be a date and time (UTC).")}if(e.count!==void 0&&(!Number.isInteger(e.count)||e.count<1?t.push("Maximum runs must be a whole number of at least 1."):n.count=e.count),e.until){const i=Rd(e.until);i?n.until=i:t.push("Stop at must be a date and time (UTC).")}return{config:n,errors:t}}function fx(e){if(e.trigger==="email"){const i=Vg(e.email??Nf);return i.errors.length?"":Gg(i.config)}const{config:t,errors:n}=ty(e);if(n.length)return"";const r=Og(t);return e.when.kind==="once"?r:`${r}, first run ${t.start_at?`at ${Ir(t.start_at)}`:"now"}`}function hx(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()||dx(r);i.length>120&&n.push("Title is at most 120 characters.");const c=e.trigger==="email",u=c?Vg(e.email??Nf):ty(e);n.push(...u.errors);const d=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?rf(e.emailRecipients):null;d&&n.push(...d.errors);const h=e.growingMaxTokens??Ai;if(e.context==="growing"&&!Zg(h)&&n.push(qg),n.length||!t.target)return{ok:!1,errors:n};const m={...t.target,input_data:{...t.target.input_data??{},prompt:r}},p={request_id:t.requestId,title:i,target:m,trigger:c?{source_id:Fg,source_version:zg,config:u.config}:{source_id:"schedule",source_version:1,config:u.config},context:ey(e.context,e.context==="growing"?h:Ai),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(p.notify=Hg(!0,d==null?void 0:d.recipients)),{ok:!0,body:p}}const mx="Tools run without asking (you approve them now by creating this automation)";function px(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 gx(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 ny={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class sy{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||yx(n.error))&&this.open.delete(t)}}function yx(e){return Li(e)&&e.status>0&&e.code!=="invalid_response"}function ry(){return ca()}class wx{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 hp(e,t){if(!e)return null;for(const n of t){const r=e.querySelector(n);if(r&&r.disabled!==!0&&typeof r.focus=="function")return r}return null}function mp(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 vx(e){const t=e.disabled===!0,n=y.useMemo(()=>mp([...e.options||[],...e.value||[]]),[e.options,e.value]),r=y.useMemo(()=>mp(e.value||[]),[e.value]),[i,c]=y.useState(!1),[u,d]=y.useState(""),h=y.useMemo(()=>{const v=u.trim().toLowerCase();return v?n.filter(_=>_.toLowerCase().includes(v)):n},[n,u]),m=y.useMemo(()=>new Set(r),[r]),p=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return o.jsxs("div",{className:"af_multi_select",children:[o.jsxs("div",{className:"af_multi_select_row",children:[o.jsxs("button",{className:"btn",type:"button",onClick:()=>c(v=>!v),disabled:t||!n.length,"aria-expanded":i,children:[i?"Hide":"Select"," • ",r.length>0?`${r.length} of ${n.length}`:e.placeholder||"(none)"]}),o.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||r.length===n.length,title:"Select all",children:"All"}),o.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||r.length===0,title:"Clear selection",children:"Clear"})]}),r.length>0?o.jsx("div",{className:"af_multi_select_chips",children:r.map(v=>o.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${v}`,className:"af_multi_select_chip",title:v,onClick:()=>{if(t)return;const _=new Set(m);_.delete(v),e.onChange(Array.from(_.values()))},children:[v,t?null:o.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},v))}):null,i?o.jsxs("div",{className:"af_multi_select_panel",children:[o.jsx("input",{className:"mono",value:u,onChange:v=>d(String(v.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),o.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${p}px`},children:[h.map(v=>{const _=m.has(v);return o.jsxs("label",{className:`af_multi_select_item mono ${_?"checked":""}`,children:[o.jsx("input",{type:"checkbox",checked:_,disabled:t,onChange:b=>{const C=new Set(m);b.target.checked?C.add(v):C.delete(v),e.onChange(Array.from(C.values()))}}),o.jsx("span",{children:v})]},v)}),h.length?null:o.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function ay(e){return o.jsxs("div",{className:"af-auto__field","data-field":"tool-selection",children:[o.jsxs("label",{children:[o.jsx("input",{type:"checkbox",checked:e.value===null,disabled:e.disabled,onChange:t=>e.onChange(t.target.checked?null:[])})," Use workflow default tools"]}),e.value!==null?o.jsx(vx,{options:e.availableTools,value:e.value,disabled:e.disabled,placeholder:"No tools enabled",onChange:e.onChange}):null,o.jsx("p",{className:"af-auto__hint",children:"Choose which tools this automation can use. An empty selection disables tools. Gateway restrictions always apply."})]})}const Dc="@default",oy="No workflows available for this app — ask your admin.",iy={shared:"Shared",mine:"Mine"};class jr extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function ly(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 _x(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function bx(e,t={}){return e===null?_x(t):ly(e,t)}function Ks(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function zt(e){return typeof e=="string"?e.trim():""}const rc="update the gateway";function xx(e,t){var d,h;const n=Ks(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const r=Ks(n[t]);if(!r)return{status:"unavailable",reason:zt((h=Ks((d=Ks(e.default_agent_workflows_unavailable))==null?void 0:d[t]))==null?void 0:h.reason)||`no default workflow for ${t}`};const i=zt(r.bundle_id),c=zt(r.flow_id);if(!i||!c)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=zt(r.bundle_version);return{status:"ok",name:zt(r.name)||c,bundleId:i,bundleVersion:u,flowId:c,workflowId:zt(r.workflow_id)||`${i}${u?`@${u}`:""}:${c}`}}function kx(e,t){return cy(e,t)}function cy(e,t,n={}){var d;const r=Ks(e);if(!r)throw new jr("The gateway's workflow list is not a JSON object.");const i=zt(r.executable_for);if(t===null){if(i)throw new jr(`Asked for every workflow, the gateway listed only ${i}.`)}else if(i!==t)throw new jr(i?`The gateway listed workflows for ${i}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${rc}.`);if(!Array.isArray(r.items))throw new jr("The gateway's workflow list has no items.");const c=[];for(const h of r.items){const m=Ks(h),p=zt(m==null?void 0:m.bundle_id);if(!m||!p)throw new jr("The gateway listed a workflow without a bundle id.");const v=Ks(m.owner),_=zt(v==null?void 0:v.kind);if(_!=="gateway"&&_!=="user")throw new jr(`The gateway did not say who owns ${p} (owner missing): ${rc}.`);if(typeof m.shipped!="boolean")throw new jr(`The gateway did not say whether ${p} ships with it (shipped missing): ${rc}.`);const b=zt(m.bundle_version),C=Array.isArray(m.entrypoints)?m.entrypoints:[];for(const x of C){const j=Ks(x),N=zt(j==null?void 0:j.flow_id);if(!j||!N)continue;const $=Array.isArray(j.interfaces)?j.interfaces.map(zt).filter(Boolean):[];if(t===null){if(!$.length)continue}else if(!$.includes(t))throw new jr(`The gateway offered ${p}:${N}, which does not declare ${t}: ${rc}.`);c.push({value:zt(j.workflow_id)||`${p}${b?`@${b}`:""}:${N}`,bundleId:p,bundleVersion:b,flowId:N,name:zt(j.name)||zt((d=Ks(m.metadata))==null?void 0:d.name)||p,description:zt(j.description)||zt(m.description),registryScope:zt(m.registry_scope)||"private",group:_==="user"?"mine":"shared",shipped:m.shipped,interfaces:$,...t===null?{showInterfaces:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:c,gatewayDefault:u?xx(r,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function jx(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:iy[n],entries:e.filter(r=>r.group===n).sort(t)})).filter(n=>n.entries.length>0)}const Sx={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function Nx(e){return Sx[e]??e}function Cx(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?[[...new Set(e.interfaces.map(Nx))].join(", "),n].filter(Boolean).join(" · "):n}function Ex(e){return e.value}function $x(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function Ax(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 Tx(e,t=!0){const n=(e==null?void 0:e.entries)??[],r=[];t&&r.push({key:"default",value:Dc,name:"Gateway default",detail:$x((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const i of jx(n))for(const c of i.entries)r.push({key:c.value,value:c.value,name:c.name,detail:Cx(c,n),title:Ex(c),group:i.id,entry:c});return r}async function Rx(e,t,n){var c;const r=await fetch(Ze(e,ve(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),i=await r.json().catch(()=>null);if(!r.ok){const u=((c=i==null?void 0:i.detail)==null?void 0:c.message)||(i==null?void 0:i.message)||(typeof(i==null?void 0:i.detail)=="string"?i.detail:"");throw new Error(u||`The gateway answered ${r.status}.`)}return i}function Ix(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 Mx(e){const{interfaceId:t,defaultInterface:n,allVersions:r=!1,enabled:i=!0,gatewayBaseUrl:c,reloadKey:u}=e,d=y.useRef(e.request);d.current=e.request;const[h,m]=y.useState(0),[p,v]=y.useState({status:"idle",data:null,error:""});y.useEffect(()=>{if(!i){v({status:"idle",data:null,error:""});return}const b=new AbortController;v(j=>({...j,status:"loading",error:""}));const C=bx(t,{allVersions:r});return(d.current?d.current(C,{signal:b.signal}):Rx(c,C,b.signal)).then(j=>{b.signal.aborted||v({status:"ready",data:cy(j,t,{defaultInterface:n}),error:""})}).catch(j=>{b.signal.aborted||v({status:"error",data:null,error:Ix(j)})}),()=>b.abort()},[t,n,r,i,c,u,h]);const _=y.useCallback(()=>m(b=>b+1),[]);return{...p,reload:_}}function Lx(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),c=Math.max(16,Math.min(t.left,n-16-i)),u=r-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:c,width:i,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:c,width:i,bottom:r-t.top+4,maxHeight:Math.max(160,t.top-16)}}function uy(...e){return e.filter(Boolean).join(" ")}function dy(e){const t=Mx({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=y.useId().replace(/:/g,""),c=`${i}-list`,[u,d]=y.useState(!1),[h,m]=y.useState(-1),p=y.useRef(null),v=y.useRef(null),[_,b]=y.useState({}),C=y.useMemo(()=>Tx(n.data,r),[n.data,r]),x=C.find(F=>F.value===e.value),j=x?{name:x.name,detail:x.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading workflows…",detail:""}:{name:e.value===Dc?"Gateway default":"Choose a workflow",detail:""},N=String(e.unavailableReason||"").trim(),$=!N&&n.status==="ready",S=y.useCallback(()=>{d(!1),m(-1)},[]),E=y.useCallback(()=>{if(!$)return;b(Lx(v.current)),d(!0);const F=C.findIndex(L=>L.value===e.value);m(F>=0?F:0)},[$,C,e.value]),A=y.useCallback(F=>{var L;S(),F.value!==e.value&&e.onChange(F.value,F.entry),(L=v.current)==null||L.focus()},[S,e]);y.useEffect(()=>{if(!u)return;const F=J=>{p.current&&!p.current.contains(J.target)&&S()},L=()=>S();return document.addEventListener("mousedown",F),document.addEventListener("touchstart",F),window.addEventListener("resize",L),()=>{document.removeEventListener("mousedown",F),document.removeEventListener("touchstart",F),window.removeEventListener("resize",L)}},[u,S]),y.useEffect(()=>{var L;if(!u||h<0)return;const F=typeof document<"u"?document.getElementById(`${i}-opt-${h}`):null;(L=F==null?void 0:F.scrollIntoView)==null||L.call(F,{block:"nearest"})},[u,h,i]);const I=F=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(F.key)&&(F.preventDefault(),E());return}if(F.key==="Escape"){F.preventDefault(),S();return}if(F.key==="Tab"){S();return}if(F.key==="Enter"||F.key===" "){F.preventDefault(),h>=0&&C[h]&&A(C[h]);return}const L=Ax(F.key,h,C.length);L!==null&&(F.preventDefault(),m(L))};return o.jsxs("div",{ref:p,className:uy("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[o.jsxs("button",{ref:v,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${i}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":c,"aria-activedescendant":u&&h>=0?`${i}-opt-${h}`:void 0,"aria-disabled":$?void 0:!0,title:N||void 0,onClick:()=>u?S():E(),onKeyDown:I,children:[o.jsxs("span",{className:"af-workflow-picker__value",id:`${i}-value`,children:[o.jsx("span",{className:"af-workflow-picker__name",children:j.name}),j.detail?o.jsx("span",{className:"af-workflow-picker__detail",children:j.detail}):null]}),o.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?o.jsx(Ox,{id:c,idBase:i,rows:C,value:e.value,highlight:h,ariaLabel:e.ariaLabel||"Workflow",style:_,onHighlight:m,onChoose:A}):null,n.status==="error"?o.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&C.every(F=>!F.entry)&&!r?o.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:oy}):null]})}function Ox(e){const t=(c,u)=>o.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":c.value===e.value,"data-value":c.value,title:c.title,className:uy("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",c.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:d=>d.preventDefault(),onClick:()=>e.onChoose(c),children:[o.jsx("span",{className:"af-workflow-picker__name",children:c.name}),c.detail?o.jsx("span",{className:"af-workflow-picker__detail",children:c.detail}):null]},c.key),n=e.rows.map((c,u)=>({row:c,index:u})),r=n.filter(c=>c.row.group===null),i=["shared","mine"].map(c=>({g:c,items:n.filter(u=>u.row.group===c)})).filter(c=>c.items.length>0);return o.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[r.map(c=>t(c.row,c.index)),i.map(({g:c,items:u})=>o.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${c}`,"data-group":c,children:[o.jsx("div",{id:`${e.idBase}-g-${c}`,className:"af-workflow-picker__group",role:"presentation",children:iy[c]}),u.map(d=>t(d.row,d.index))]},c)),i.length===0?o.jsx("p",{className:"af-workflow-picker__empty",children:oy}):null]})}function fy(e){const t=tf(e.target);return o.jsxs("div",{className:"af-auto__field",children:[o.jsx("span",{children:"Workflow"}),o.jsx(dy,{...e.options,ariaLabel:"Automation workflow",value:t,currentLabel:{name:t},onChange:(n,r)=>e.onChange(n==="@default"?{flow_id:"@default",interface:e.options.interfaceId||e.options.defaultInterface||"abstractcode.agent.v1"}:{bundle_ref:`${r.bundleId}@${r.bundleVersion}`,flow_id:r.flowId})})]})}async function Px(e,t){var _,b;const n=e.flow_id==="@default"?(b=(_=t.workflows)==null?void 0:_.data)==null?void 0:b.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 c=r.lastIndexOf("@"),u=c<0?r:r.slice(0,c),d=c<0?"":r.slice(c+1),h=await t.request(`bundles/${encodeURIComponent(u)}/flows/${encodeURIComponent(i)}/input_schema${d?`?bundle_version=${encodeURIComponent(d)}`:""}`,{signal:new AbortController().signal}),m=(h==null?void 0:h.input_data_schema)||h;if(!m||typeof m!="object"||!m.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const p={...h.defaults||{}};for(const[C,x]of Object.entries(m.properties))x&&"default"in x&&(p[C]=x.default);Object.assign(p,e.input_data||{});const v=(Array.isArray(m.required)?m.required:[]).filter(C=>p[C]===void 0);if(v.length)throw new Error(`This workflow needs additional inputs: ${v.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:p}}function af(e){if(Sf(e.status))return null;const t=He.not_set_up,n=He.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 o.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[r,e.onOpenMyEmail?o.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,i?o.jsxs("span",{className:"af-email__cause",children:[" (",i,")"]}):null]})}function Dx(e){const t=e.value,n=d=>e.onChange({...t,...d}),r=d=>`${e.idBase}-email-${d}`,i=ho(Cf(t.usesModel)),c=t.every??(i&&i.unit==="s"?{amount:Math.max(1,Math.round(i.amount/60)),unit:"m"}:{amount:i?i.amount:1,unit:i?i.unit:"h"}),u=e.disabled===!0;return o.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[o.jsxs("div",{className:"af-auto__row",children:[o.jsx("span",{children:He.every_label}),o.jsx("input",{type:"number",min:1,step:1,value:String(c.amount),disabled:u,"aria-label":"Check interval amount",name:"email_every_amount",onChange:d=>n({every:{amount:Number(d.target.value),unit:c.unit}})}),o.jsxs("select",{value:c.unit,disabled:u,"aria-label":"Check interval unit",name:"email_every_unit",onChange:d=>n({every:{amount:c.amount,unit:d.target.value}}),children:[o.jsx("option",{value:"m",children:"minutes"}),o.jsx("option",{value:"h",children:"hours"}),o.jsx("option",{value:"d",children:"days"})]})]}),o.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:He.interval_rule}),o.jsxs("label",{className:"af-auto__field",htmlFor:r("batch"),children:[o.jsx("span",{children:He.max_batch_label}),o.jsx("input",{id:r("batch"),name:"email_max_batch",type:"number",min:1,max:nf,step:1,disabled:u,value:String(t.maxBatch??jf),onChange:d=>n({maxBatch:d.target.value.trim()===""?null:Number(d.target.value)})})]}),o.jsx("p",{className:"af-auto__hint",children:He.max_batch_hint}),o.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[o.jsx("legend",{children:He.filters_legend}),o.jsxs("label",{className:"af-auto__field",htmlFor:r("from"),children:[o.jsx("span",{children:He.from_in}),o.jsx("input",{id:r("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:d=>n({fromIn:d.target.value})})]}),o.jsxs("label",{className:"af-auto__field",htmlFor:r("domain"),children:[o.jsx("span",{children:He.from_domain_in}),o.jsx("input",{id:r("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:d=>n({fromDomainIn:d.target.value})})]}),o.jsxs("label",{className:"af-auto__field",htmlFor:r("to"),children:[o.jsx("span",{children:He.to_in}),o.jsx("input",{id:r("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:d=>n({toIn:d.target.value})})]}),o.jsxs("label",{className:"af-auto__field",htmlFor:r("subject"),children:[o.jsx("span",{children:He.subject_contains}),o.jsx("input",{id:r("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:d=>n({subjectContains:d.target.value})})]}),o.jsxs("label",{className:"af-auto__field",htmlFor:r("attach"),children:[o.jsx("span",{children:He.has_attachment}),o.jsxs("select",{id:r("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:d=>n({hasAttachment:d.target.value}),children:[o.jsx("option",{value:"any",children:He.has_attachment_any}),o.jsx("option",{value:"yes",children:He.has_attachment_yes}),o.jsx("option",{value:"no",children:He.has_attachment_no})]})]}),o.jsx("p",{className:"af-auto__hint",children:He.list_hint})]})]})}function Fx(e){const t=r=>`${e.idBase}-email-${r}`,n=e.disabled===!0;return o.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[o.jsx(Mr,{variant:"row",action:"notify-email",label:He.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:r=>e.onNotifyEmailChange(r)}),o.jsxs("p",{className:"af-auto__hint",children:[He.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),e.notifyEmail?o.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[o.jsx("legend",{children:He.recipients_legend}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:t("rcpt"),value:"self",checked:e.recipients.mode==="self",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"self"})})," ",He.recipients_self]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:t("rcpt"),value:"list",checked:e.recipients.mode==="list",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"list"})})," ",He.recipients_list]}),e.recipients.mode==="list"?o.jsx("textarea",{name:"email_recipient_list","aria-label":He.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,o.jsx("p",{className:"af-auto__hint",children:He.recipients_hint})]}):null]})}const zx={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function Ux(e){const t=String(e.status),n=zx[t];return o.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[o.jsx("span",{className:"af-auto__status-word",children:Kb[t]??t}),n?o.jsx(re,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const pp="Discuss — fork at this occurrence (own workspace, automation files read-only)",Fc=e=>o.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function Bx(e){return Li(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function gp(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return o.jsx("code",{className:"af-auto__path-text",children:t.map((n,r)=>o.jsxs(ct.Fragment,{children:[n,r<t.length-1?o.jsx("wbr",{}):null]},r))})}function hy(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 Wx(e){const t=e.summary,n=sx(t),r=hy(t,e.triggerSources),i=t.next_fire_at?`${Ir(t.next_fire_at)} (${rx(t.next_fire_at,e.nowMs??Date.now())})`:t.status==="paused"?"none while paused":"none scheduled";return o.jsxs("header",{className:"af-auto__head",children:[o.jsxs("div",{className:"af-auto__titlebar",children:[o.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),o.jsx(Ux,{status:t.status}),t.legacy?o.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),o.jsxs("dl",{className:"af-auto__facts",children:[e.workflowLabel?o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workflow"}),o.jsx("dd",{"data-fact":"workflow",children:e.workflowLabel})]}):null,o.jsx("dt",{children:"When"}),o.jsxs("dd",{"data-fact":"trigger",children:[Pg(t.trigger),r?o.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",r]}):null]}),o.jsx("dt",{children:"Context"}),o.jsx("dd",{"data-fact":"context",children:Dg(t.context_mode)}),n?o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Now"}),o.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,o.jsx("dt",{children:"Next run"}),o.jsx("dd",{"data-fact":"next",children:i}),o.jsx("dt",{children:"Runs"}),o.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root?o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Workspace"}),o.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:e.onOpenWorkspace?o.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
57
+ ${t.workspace_root}`,"aria-label":`Browse the automation's folder ${t.workspace_root}`,onClick:()=>{var c;return(c=e.onOpenWorkspace)==null?void 0:c.call(e,t.automation_id)},children:[o.jsx(re,{name:"folder",size:14,className:"af-auto__path-icon"}),o.jsx(gp,{path:t.workspace_root})]}):o.jsxs("span",{className:"af-auto__path af-auto__path--static",children:[o.jsx(re,{name:"folder",size:14,className:"af-auto__path-icon"}),o.jsx(gp,{path:t.workspace_root})]})})]}):null,o.jsx("dt",{children:"Attention"}),o.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:lx(t)}),t.revision!==null?o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Revision"}),o.jsx("dd",{"data-fact":"revision",children:t.revision})]}):null]})]})}function Vx(e){var u,d;const t=e.definition,n=e.renderText??Fc,r=t.target.input_data.prompt,i=t.policy.retry,c=t.policy.tool_approval;return o.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[o.jsxs("summary",{children:[o.jsx(re,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),o.jsx(re,{name:"file",size:14}),o.jsx("span",{className:"af-auto__definition-title",children:"Definition"}),o.jsxs("span",{className:"af-auto__definition-meta",children:["revision ",t.revision]})]}),o.jsxs("dl",{className:"af-auto__facts",children:[o.jsx("dt",{children:"Target"}),o.jsx("dd",{"data-def":"target",children:o.jsx("code",{children:t.target.workflow_id})}),typeof r=="string"&&r?o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Task"}),o.jsx("dd",{"data-def":"prompt",children:n(r)})]}):null,o.jsx("dt",{children:"Trigger"}),o.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",Pg(t.trigger),o.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),o.jsx("dt",{children:"Context"}),o.jsxs("dd",{"data-def":"context",children:[Dg(t.context.mode),t.context.mode==="growing"?` · ${Number(((u=t.context.growing)==null?void 0:u.max_tokens)??5e4).toLocaleString()} tokens`:""]}),o.jsx("dt",{children:"Tools"}),o.jsx("dd",{"data-def":"tool_approval",children:c==="ask"?"Ask before each tool call (ask)":c==="auto"?"Run without asking (auto)":String(c)}),o.jsx("dt",{children:"Notify"}),o.jsx("dd",{"data-def":"notify",children:ex(t.notify)}),(d=t.notify)!=null&&d.channels.includes("email")?o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Recipients"}),o.jsx("dd",{"data-def":"email_recipients",children:Zb(t.notify.recipients)})]}):null,o.jsx("dt",{children:"Retries"}),o.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]}),o.jsx("dt",{children:"Revision"}),o.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const Oi=Mg,of=Oi.labels,my={active:"play",pause:"pause",resume:"play",run_now:Oi.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},lf=Oi.hints,Gx=Oi.run_now_next_run_line,Hx=Oi.run_now_growing_line;function Ti(e,t){const n=[lf[e]];return e==="run_now"&&t&&(t.next_fire_at&&n.push(Gx.replace("{time}",Ir(t.next_fire_at))),t.context_mode==="growing"&&n.push(Hx)),n.join(`
58
+ `)}function Kx(e,t,n){const r=new Map;for(const u of t){const d=e[u];if(d.enabled)continue;const h=d.reason??"Not available now.";r.set(h,[...r.get(h)??[],u])}const i=[],c={};return[...r.entries()].forEach(([u,d],h)=>{const m=`${n}-why-${h}`;i.push({id:m,text:`${d.map(p=>of[p]).join(", ")}: ${u}`});for(const p of d)c[p]=m}),{lines:i,describedBy:c}}function Zt(e){return o.jsxs(o.Fragment,{children:[o.jsx(re,{name:e.icon,size:14,className:"af-auto__btn-icon"}),o.jsx("span",{children:e.label})]})}function Jx(e){const t=lo(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",i=Kx(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),c=(u,d,h)=>{const m=Ti(u,e.summary);return o.jsx("button",{type:"button",className:`af-auto__btn${h!=null&&h.danger?" af-auto__btn--danger":""}`,"data-action":(h==null?void 0:h.action)??u,disabled:!t[u].enabled,title:t[u].enabled?m:`${t[u].reason}
59
+ ${m}`,"aria-description":m,"aria-describedby":i.describedBy[u],"aria-pressed":h==null?void 0:h.pressed,onClick:d,children:o.jsx(Zt,{icon:my[u],label:(h==null?void 0:h.label)??of[u]})},u)};return o.jsxs("div",{className:"af-auto__controls-wrap",children:[o.jsxs("div",{className:"af-auto__actionbar",children:[o.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[o.jsx(Mr,{className:"af-auto__switch",action:"active",label:of.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:Ti("active",e.summary),onChange:()=>e.onCommand(Jg(e.summary))},"active"),c("run_now",()=>e.onCommand(_t.run_now)),c("stop_current",()=>e.onCommand(_t.stop_current)),c("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?c("unarchive",()=>e.onCommand(_t.unarchive)):c("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),o.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?o.jsxs(o.Fragment,{children:[o.jsx(re,{name:"check",size:13}),o.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?o.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:o.jsx(re,{name:"x",size:12})}):null]}):null})]}),i.lines.length?o.jsxs("p",{className:"af-auto__reasons",children:[o.jsx(re,{name:"info",size:12,className:"af-auto__reasons-icon"}),i.lines.map(u=>o.jsx("span",{id:u.id,children:u.text},u.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?o.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive&&!n?o.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[o.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),o.jsxs("div",{className:"af-auto__row",children:[o.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(_t.archive),children:o.jsx(Zt,{icon:"archive",label:"Archive"})}),o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:o.jsx(Zt,{icon:"x",label:"Keep it"})})]})]}):null]})}const yp=[["m","minutes"],["h","hours"],["d","days"]];function Qx(e,t){const n=j=>{const N=e.elements.namedItem(j);return N&&typeof N.value=="string"?N.value:null},r=n("every_amount"),i=n("every_unit"),c=r!==null&&i!==null?`${r.trim()}${i}`:t.every,u=e.elements.namedItem("context"),d=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,h=n("prompt"),m=e.elements.namedItem("tool_approval"),p=m&&(m.value==="auto"||m.value==="ask")?m.value:t.toolApproval??null,v=e.elements.namedItem("notify_email"),_=v&&typeof v.checked=="boolean"?v.checked:t.notifyEmail??null,b=e.elements.namedItem("email_recipients"),C=n("email_recipient_list"),x=b&&(b.value==="self"||b.value==="list")?{mode:b.value,addresses:C??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:c,context:d,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:h??t.prompt??null,toolApproval:p,notifyEmail:_,emailRecipients:x}}function py(e){const t=Qg(e.summary,e.definition),[n,r]=y.useState(),[i,c]=y.useState(t.tools??null),[u,d]=y.useState(t.context),[h,m]=y.useState(!!t.notifyEmail),p=t.every?ho(t.every):null,v=p&&p.unit==="s"?[["s","seconds"],...yp]:yp,_=`af-auto-revise-${e.summary.automation_id}`,b=Sf(e.emailStatus),C=Mi(e.summary.trigger);return o.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${_}-heading`,onSubmit:x=>{x.preventDefault(),e.onSubmit({...Qx(x.currentTarget,t),...n?{target:n}:{},...e.availableTools!==void 0?{tools:i}:{}})},onKeyDown:x=>{x.key==="Escape"&&e.onCancel&&(x.preventDefault(),e.onCancel())},children:[e.heading===null?o.jsx("span",{id:`${_}-heading`,hidden:!0,children:"Edit automation"}):o.jsxs("h3",{className:"af-auto__form-title",id:`${_}-heading`,children:[o.jsx(re,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?o.jsx(fy,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:r}):null,o.jsxs("label",{className:"af-auto__field",htmlFor:`${_}-title`,children:[o.jsx("span",{children:"Title"}),o.jsx("input",{id:`${_}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?o.jsxs("label",{className:"af-auto__field",htmlFor:`${_}-prompt`,children:[o.jsx("span",{children:"Task"}),o.jsx("textarea",{id:`${_}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
60
+ `).length+1)),required:!0})]}):null,p?o.jsxs("fieldset",{className:"af-auto__field",children:[o.jsx("legend",{children:C?He.every_label:"Repeat every (UTC)"}),o.jsxs("div",{className:"af-auto__row",children:[o.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:p.amount,"aria-label":"Interval amount"}),o.jsx("select",{name:"every_unit",defaultValue:p.unit,"aria-label":"Interval unit",children:v.map(([x,j])=>o.jsx("option",{value:x,children:j},x))})]}),C?o.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:He.interval_rule}):null]}):o.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),o.jsxs("fieldset",{className:"af-auto__field",children:[o.jsx("legend",{children:"Context"}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent",onChange:()=>d("independent")})," Independent — each run starts fresh"]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>d("growing")})," Growing — each run sees the previous runs"]}),o.jsx("div",{hidden:u!=="growing",children:o.jsxs("label",{className:"af-auto__field",children:[o.jsx("span",{children:"Max growing context (tokens)"}),o.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||u!=="growing",defaultValue:t.growingMaxTokens}),o.jsx("span",{className:"af-auto__hint",children:Xg})]})})]}),t.toolApproval?o.jsxs("fieldset",{className:"af-auto__field",children:[o.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?o.jsx(ay,{availableTools:e.availableTools,value:i,onChange:c,disabled:e.busy}):null,o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),o.jsxs("label",{children:[o.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?o.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[o.jsx("legend",{children:"Mailbox"}),b?null:o.jsx(af,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),o.jsx(j_,{variant:"row",action:"notify-email",name:"notify_email",label:He.notify_label,defaultChecked:!!t.notifyEmail,onChange:m,unavailableReason:!b&&!t.notifyEmail?"Connect a mailbox first.":null}),o.jsxs("p",{className:"af-auto__hint",children:[He.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),o.jsx("div",{hidden:!h,children:o.jsxs("fieldset",{className:"af-auto__field",disabled:!h,"data-field":"email-recipients",children:[o.jsx("legend",{children:He.recipients_legend}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",He.recipients_self]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!b&&t.emailRecipients.mode!=="list"})," ",He.recipients_list]}),o.jsx("textarea",{name:"email_recipient_list","aria-label":He.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!b&&t.emailRecipients.mode!=="list"}),o.jsx("p",{className:"af-auto__hint",children:He.recipients_hint})]})})]}):null,o.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; a new interval never fires past ticks."}),e.errors.length?o.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(x=>o.jsx("li",{children:x},x))}):null,o.jsxs("div",{className:"af-auto__row",children:[o.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:o.jsx(Zt,{icon:"check",label:e.submitLabel??"Save changes"})}),e.onCancel?o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:o.jsx(Zt,{icon:"x",label:"Cancel"})}):null]})]})}function cf(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function Yx(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,r=u=>e.onAnswerWait(t.run_id,t.wait_key,u),i=e.renderText??Fc,c=u=>o.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[o.jsx("span",{className:"af-auto-wait__kind",children:ny[t.kind]??"Waiting"}),t.prompt?i(t.prompt):o.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=px(t);return o.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:[c("A tool call needs your approval."),u&&u.length?o.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((d,h)=>o.jsxs("li",{"data-tool":d.name,children:[o.jsx("code",{className:"af-auto-wait__tool",children:d.name}),o.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(d.arguments,null,2)})]},d.call_id??`${d.name}:${h}`))}):o.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),o.jsxs("div",{className:"af-auto__row",children:[o.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>r({approved:!0}),children:o.jsx(Zt,{icon:"check",label:"Approve"})}),o.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>r({approved:!1}),children:o.jsx(Zt,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?o.jsxs("form",{className:"af-auto-wait af-auto-wait--event","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{var h;u.preventDefault();const d=gx(cf(u.currentTarget,"payload"));d.ok?r({payload:d.payload}):(h=e.onWaitError)==null||h.call(e,d.error)},children:[c("The run waits for an event."),o.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),o.jsx("div",{className:"af-auto__row",children:o.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:o.jsx(Zt,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?o.jsxs("form",{className:"af-auto-wait af-auto-wait--ask_user","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,onSubmit:u=>{u.preventDefault();const d=cf(u.currentTarget,"response");d&&r({response:d})},children:[c("The run is waiting for your input."),t.choices&&t.choices.length?o.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>r({response:u}),children:u},u))}):null,o.jsxs("div",{className:"af-auto__row",children:[o.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),o.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:o.jsx(Zt,{icon:"send",label:"Answer"})})]})]}):o.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[c("The run is waiting."),o.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function Xx(e){const{row:t,tone:n,badge:r,statusText:i}=e.view,c=`af-auto-occ-${t.run_id}`,u=e.renderText??Fc,d=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,h=e.discuss.enabled?e.view.canDiscuss?null:"Available once this occurrence finishes.":e.discuss.reason??"Not available.",m=(_,b)=>e.renderTurn?e.renderTurn({kind:_,role:_==="trigger"?"user":"assistant",text:b,index:t.index,runId:t.run_id}):u(b),p=e.renderTurn?" af-auto-turn--card":"",v=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return o.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${c}-h`,children:[o.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[o.jsxs("div",{className:"af-auto-turn__meta",id:`${c}-h`,children:[o.jsxs("span",{className:"af-auto-turn__index",children:["#",t.index]})," · ",t.trigger.summary," · fired ",Ir(t.fired_at)]}),o.jsx("div",{className:"af-auto-turn__text",children:m("trigger",t.user_turn)})]}),o.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"data-turn":"answer",children:[o.jsxs("div",{className:"af-auto-turn__meta",children:[r?o.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:r}):null,o.jsx("span",{className:"af-auto-turn__status",children:i}),t.finished_at?o.jsxs("span",{children:[" · ",Ir(t.finished_at)]}):null]}),t.notify?o.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[o.jsx("strong",{children:t.notify.title}),t.notify.body?o.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?o.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[o.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",o.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?o.jsx("div",{className:"af-auto-turn__text",children:m("answer",t.answer)}):o.jsx("div",{className:"af-auto-turn__empty",children:v}),t.artifacts.length?o.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(_=>o.jsxs("li",{children:[e.onOpenResource?o.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var b;return(b=e.onOpenResource)==null?void 0:b.call(e,{kind:"artifact",url:_.url,name:_.name,mimeType:_.mime_type,runId:t.run_id})},children:[o.jsx(re,{name:"file",size:13,className:"af-auto__btn-icon"})," ",_.name]}):o.jsx("span",{className:"af-auto-artifact__name",children:_.name})," ",o.jsx("span",{className:"af-auto-turn__muted",children:_.mime_type})]},_.artifact_id))}):null,t.waits.map(_=>o.jsx(Yx,{wait:_,busy:e.busy,idBase:c,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${_.run_id}:${_.wait_key}`))]}),o.jsxs("div",{className:"af-auto-occ__foot",children:[o.jsxs("details",{className:"af-auto-occ__details",children:[o.jsx("summary",{children:"Run details"}),o.jsxs("dl",{className:"af-auto__facts",children:[o.jsx("dt",{children:"Run"}),o.jsx("dd",{children:o.jsx("code",{children:t.run_id})}),o.jsx("dt",{children:"Attempts"}),o.jsx("dd",{children:t.attempts})]}),o.jsxs("div",{className:"af-auto__row",children:[o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:o.jsx(Zt,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var _;return(_=e.onOpenResource)==null?void 0:_.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:o.jsx(Zt,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var _;return(_=e.onOpenWorkspace)==null?void 0:_.call(e,t.run_id)},children:o.jsx(Zt,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?o.jsxs("form",{className:"af-auto-discuss","aria-label":`${pp}, from occurrence ${t.index}`,onSubmit:_=>{_.preventDefault();const b=cf(_.currentTarget,"prompt");b&&e.onDiscussSubmit(t.index,b)},children:[o.jsxs("p",{className:"af-auto__hint",children:["Starts a new session that forks this automation at #",t.index," with its full history (runs 1–",t.index,"). It works in its own writable workspace; the automation's files are mounted read-only for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session."]}),o.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),o.jsxs("div",{className:"af-auto__row",children:[o.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:o.jsx(Zt,{icon:"send",label:"Start discussion"})}),o.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:o.jsx(Zt,{icon:"x",label:"Cancel"})})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!d,title:lf.discuss,"aria-description":lf.discuss,"aria-describedby":h?`${c}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:o.jsx(Zt,{icon:my.discuss,label:pp})}),h?o.jsx("span",{className:"af-auto__reasons",id:`${c}-discuss-why`,children:h}):null]})]})]})}const qx=5e3,Zx={[_t.pause]:"Automation paused.",[_t.resume]:"Automation active.",[_t.run_now]:"Run requested.",[_t.stop_current]:"Stop requested.",[_t.unarchive]:"Unarchived: it is paused until you make it active."};function ek(e){var de;const{summary:t,busy:n}=e,r=e.renderText??Fc,i=y.useId(),c=y.useRef(null),[u,d]=y.useState(!1),h=e.editOpen!==void 0,p=lo(t,e.occurrences,!1).revise.enabled&&(h?e.editOpen===!0:u),v=y.useRef(null);p?(!v.current||v.current.summary.automation_id!==t.automation_id)&&(v.current={summary:t,definition:e.definition}):v.current=null;const _=v.current,b=y.useRef(e.onEditOpenChange);b.current=e.onEditOpenChange;const C=ee=>{var le;h||d(ee),(le=b.current)==null||le.call(b,ee)},[x,j]=y.useState([]),[N,$]=y.useState(!1),[S,E]=y.useState(null),[A,I]=y.useState(null),[F,L]=y.useState(null);y.useEffect(()=>{if(!F)return;const ee=setTimeout(()=>L(null),qx);return()=>clearTimeout(ee)},[F]),y.useEffect(()=>{var le;if(!p)return;j([]);const ee=hp(c.current,['.af-auto__revise [name="title"]']);ee==null||ee.focus(),(le=ee==null?void 0:ee.scrollIntoView)==null||le.call(ee,{block:"nearest"})},[p,t.automation_id]);const[J,V]=y.useState(null);y.useEffect(()=>{var ee;J&&((ee=hp(c.current,[...J,".af-auto__notice",".af-auto__title"]))==null||ee.focus(),V(null))},[J]);const O=y.useRef(null);O.current||(O.current=new sy(e.newId??ry));const Z=O.current,R=ee=>I(Bx(ee)),q=(ee,le,fe)=>{I(null),L(null),le(Z.idFor(ee)).then(oe=>{Z.settle(ee,{ok:!0}),fe(oe)},oe=>{Z.settle(ee,{ok:!1,error:oe}),R(oe)})},z=ix(t),se=y.useRef(e.onSeen);se.current=e.onSeen;const G=y.useRef(null);G.current||(G.current=new wx),y.useEffect(()=>{const ee=G.current,le=z?`${t.automation_id}|${z}`:null;if(!z||!ee.next(le,t))return;const fe=t;se.current(z).then(()=>ee.succeeded(le),oe=>{ee.failed(le,fe),R(oe)})});const te=lo(t,e.occurrences,n),ue=ox(e.occurrences),ne=t.occurrence_count-e.occurrences.length,P=A??e.error??null,B=P?mo(P):null,W=t.attention;return o.jsxs("section",{ref:c,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:o.jsxs(o.Fragment,{children:[o.jsx(Wx,{summary:t,workflowLabel:(de=e.definition)==null?void 0:de.target.workflow_id,triggerSources:e.triggerSources,titleId:i,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace}),o.jsx(Jx,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:N,reviseOpen:p,notice:F,onDismissNotice:()=>L(null),idBase:`${i}-ctl`,onCommand:ee=>q(`command:${ee}`,le=>e.onCommand(ee,void 0,{command_id:le}),()=>{ee===_t.archive?($(!1),L("Archive requested."),V(['[data-action="archive"]'])):L(Zx[ee]??"Command sent.")}),onToggleRevise:()=>{j([]),C(!p)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),V(['[data-action="archive"]'])}})]}),p&&_?o.jsx(py,{summary:_.summary,definition:_.definition,busy:n,errors:x,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,onCancel:()=>{C(!1),V(['[data-action="edit"]'])},onSubmit:ee=>{const le=_.summary,fe=Yg(le,ee,_.definition);if(fe===null){j(["Nothing changed."]);return}if("errors"in fe){j(fe.errors);return}j([]),q(`revise:${le.revision}:${JSON.stringify(fe)}`,async oe=>{const we=ee.target&&fe.target?{...fe,target:await(e.prepareTarget?e.prepareTarget(fe.target):Px(fe.target,e.workflowPickerOptions))}:fe;return e.onRevise(we,le.revision,{command_id:oe})},()=>{L("Saved; applies from the next run."),C(!1),V(['[data-action="edit"]'])})}}):e.definition?o.jsx(Vx,{definition:e.definition,renderText:r}):null,B?o.jsxs("div",{className:"af-auto__error",role:"alert","data-code":P==null?void 0:P.code,children:[o.jsx(re,{name:"error",size:14,className:"af-auto__btn-icon"}),o.jsxs("span",{className:"af-auto__error-text",children:[o.jsx("strong",{children:B.title})," ",o.jsx("span",{children:B.detail})]}),A?o.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>I(null),children:o.jsx(re,{name:"x",size:12})}):null]}):null,W.items.length||W.waits.length?o.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:o.jsxs("ul",{children:[W.items.map(ee=>o.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${ee.kind}`,"data-cursor":ee.cursor,children:[o.jsx("span",{className:`af-auto-badge af-auto-badge--${ee.kind==="failure"?"failed":"notified"}`,children:ee.kind==="failure"?"Failed":"Notified"})," ",o.jsx("strong",{children:ee.title})," ",o.jsxs("span",{className:"af-auto-turn__muted",children:["#",ee.index," · ",Ir(ee.at)]}),ee.body?o.jsx("div",{className:"af-auto__attention-body",children:r(ee.body)}):null]},ee.cursor)),W.waits.map(ee=>o.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[o.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":ee.kind,children:ny[ee.kind]??"Waiting for you"})," ",o.jsxs("span",{className:"af-auto-turn__muted",children:["#",ee.index]}),ee.prompt?o.jsx("div",{className:"af-auto__attention-body",children:r(ee.prompt)}):null]},`${ee.run_id}:${ee.wait_key}`))]})}):null,ne>0?o.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:o.jsx(Zt,{icon:"history",label:`Load earlier occurrences (${ne} more)`})}):null,ue.length?o.jsx("ol",{className:"af-auto__timeline","aria-label":"Occurrences",children:ue.map(ee=>{const le=`[data-index="${ee.row.index}"]`;return o.jsx(Xx,{view:ee,busy:n,discuss:te.discuss,renderText:r,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?fe=>{var oe;I(null);try{Promise.resolve((oe=e.onOpenResource)==null?void 0:oe.call(e,fe)).catch(R)}catch(we){R(we)}}:void 0,discussOpen:S===ee.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(fe,oe,we)=>{I(null),e.onAnswerWait(fe,oe,we).then(()=>L("Answer sent."),R)},onWaitError:fe=>I({status:0,code:"invalid_payload",message:fe}),onDiscussOpen:E,onDiscussCancel:()=>{E(null),V([`${le} [data-action="discuss"]`])},onDiscussSubmit:(fe,oe)=>q(`discuss:${fe}:${oe}`,we=>e.onDiscuss(fe,oe,{request_id:we}),we=>{E(null),L(`Discussion started (session ${we.session_id}).`),V([`${le} [data-action="discuss"]`])})},ee.row.run_id)})}):o.jsx("p",{className:"af-auto__empty",children:"No occurrences yet."})]})}function tk(e){var ae,Te;const t=y.useId(),n=y.useId(),r=y.useRef(null),i=y.useRef(null),c=y.useRef(e.onClose);c.current=e.onClose;const u=e.initialTools??Ii((ae=e.target)==null?void 0:ae.input_data),[d,h]=y.useState({open:e.open,value:u});d.open!==e.open&&h({open:e.open,value:u});const m=d.value,p=ge=>h(Q=>({...Q,value:ge})),[v,_]=y.useState(e.initialPrompt??""),[b,C]=y.useState("every"),[x,j]=y.useState(Nf),[N,$]=y.useState(!1),[S,E]=y.useState(Si),[A,I]=y.useState("24"),[F,L]=y.useState("h"),[J,V]=y.useState(""),[O,Z]=y.useState(String(Ai)),[R,q]=y.useState("independent"),[z,se]=y.useState("auto"),[G,te]=y.useState(e.initialTitle??""),[ue,ne]=y.useState(""),[P,B]=y.useState(""),[W,de]=y.useState(""),[ee,le]=y.useState([]),fe=y.useRef(null);if(fe.current||(fe.current=new sy(()=>(e.newRequestId??ry)())),y.useEffect(()=>{var pe;if(!e.open)return;const ge=document.activeElement;(pe=i.current)==null||pe.focus();const Q=be=>{if(!be.defaultPrevented){if(be.key==="Escape"){be.preventDefault(),c.current();return}Ag(be,r.current,document.activeElement)}};return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q),ge&&typeof ge.focus=="function"&&ge.focus()}},[e.open]),!e.open)return null;const oe=Sf(e.emailStatus),we=b==="email"&&oe,Oe=b==="email"&&!oe?"every":b,Je={prompt:v,when:b==="once"?{kind:"once",at:J}:{kind:"every",amount:Number(A),unit:F},...we?{trigger:"email",email:{...x,usesModel:e.targetUsesModel!==!1}}:{},...oe&&N?{notifyEmail:!0}:{},...oe&&S.mode==="list"?{emailRecipients:S}:{},context:R,growingMaxTokens:Number(O),toolApproval:z,title:G,...Oe==="every"&&ue?{startAt:ue}:{},...Oe==="every"&&P.trim()?{count:Number(P)}:{},...Oe==="every"&&W?{until:W}:{}},st=fx(Je),Ce=e.busy===!0,Ye=e.error?mo(e.error):null,he=ge=>`${n}-${ge}`,Ve=ge=>{ge.preventDefault();const Q=hx(Je,{target:e.target,requestId:""});if(!Q.ok){le(Q.errors);return}le([]);const pe=fe.current,be=e.availableTools===void 0?Q.body:{...Q.body,target:{...Q.body.target,input_data:Pc(Q.body.target.input_data||{},m)}},Ee=JSON.stringify(be),Pe={...be,request_id:pe.idFor(Ee)};Promise.resolve(e.onSubmit(Pe)).then(()=>pe.settle(Ee,{ok:!0}),We=>pe.settle(Ee,{ok:!1,error:We}))};return o.jsx("div",{className:"af-appearance-overlay af-schedule-overlay",onClick:e.onClose,role:"presentation",children:o.jsxs("div",{ref:r,className:"af-appearance af-schedule",role:"dialog","aria-modal":"true","aria-labelledby":t,onClick:ge=>ge.stopPropagation(),children:[o.jsx("div",{className:"af-appearance__title",id:t,children:e.title??"Schedule a task"}),o.jsxs("form",{className:"af-schedule__form",onSubmit:Ve,"aria-busy":Ce,children:[o.jsxs("fieldset",{className:"af-auto__field",children:[o.jsx("legend",{children:"What"}),e.workflowPicker?o.jsx("div",{className:"af-schedule__picker",children:e.workflowPicker}):null,e.target?null:o.jsx("p",{className:"af-auto__hint",children:"Choose what to run."}),o.jsxs("label",{className:"af-auto__field",htmlFor:he("prompt"),children:[o.jsx("span",{children:"Task"}),o.jsx("textarea",{id:he("prompt"),ref:i,rows:3,value:v,onChange:ge=>_(ge.target.value),placeholder:"e.g. Check the price of ACME shares and notify me if it moved more than 2%.",required:!0})]})]}),o.jsxs("fieldset",{className:"af-auto__field",children:[o.jsx("legend",{children:"When (UTC)"}),o.jsxs("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:[o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("kind"),value:"every",checked:Oe==="every",onChange:()=>C("every")})," Repeat"]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("kind"),value:"once",checked:b==="once",onChange:()=>C("once")})," Once at…"]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("kind"),value:"email",checked:we,disabled:!oe,onChange:()=>C("email")})," ",He.trigger_label]})]}),oe?null:o.jsx(af,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),we?o.jsx(Dx,{value:{...x,usesModel:e.targetUsesModel!==!1},onChange:j,idBase:n}):Oe==="every"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"af-auto__row af-schedule__presets",role:"group","aria-label":"Presets",children:ux.map(ge=>ge.when.kind==="every"?o.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","aria-pressed":Number(A)===ge.when.amount&&F===ge.when.unit,onClick:()=>{ge.when.kind==="every"&&(I(String(ge.when.amount)),L(ge.when.unit))},children:ge.label},ge.label):null)}),o.jsxs("div",{className:"af-auto__row",children:[o.jsx("span",{children:"Every"}),o.jsx("input",{type:"number",min:1,step:1,value:A,onChange:ge=>I(ge.target.value),"aria-label":"Interval amount"}),o.jsxs("select",{value:F,onChange:ge=>L(ge.target.value),"aria-label":"Interval unit",children:[o.jsx("option",{value:"m",children:"minutes"}),o.jsx("option",{value:"h",children:"hours"}),o.jsx("option",{value:"d",children:"days"})]})]})]}):o.jsxs("label",{className:"af-auto__field",htmlFor:he("once"),children:[o.jsx("span",{children:"Run once at (UTC)"}),o.jsx("input",{id:he("once"),type:"datetime-local",value:J,onChange:ge=>V(ge.target.value)})]}),o.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":"true",children:st?`Runs ${st}.`:we?"Incomplete email trigger.":"Incomplete schedule."})]}),o.jsxs("fieldset",{className:"af-auto__field",children:[o.jsx("legend",{children:"Context"}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("ctx"),value:"independent",checked:R==="independent",onChange:()=>q("independent")})," Independent — each run starts fresh"]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("ctx"),value:"growing",checked:R==="growing",onChange:()=>q("growing")})," Growing — each run sees the previous runs"]}),R==="growing"?o.jsxs("label",{className:"af-auto__field",children:[o.jsx("span",{children:"Max growing context (tokens)"}),o.jsx("input",{type:"number",min:1,step:1,required:!0,disabled:Ce,value:O,onChange:ge=>Z(ge.target.value)}),o.jsx("span",{className:"af-auto__hint",children:Xg})]}):null]}),o.jsxs("fieldset",{className:"af-auto__field","data-field":"tool-approval",children:[o.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?o.jsx(ay,{availableTools:e.availableTools,value:m,onChange:p,disabled:Ce}):null,o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("tools"),value:"auto",checked:z==="auto",onChange:()=>se("auto")})," Run without asking"]}),o.jsxs("label",{children:[o.jsx("input",{type:"radio",name:he("tools"),value:"ask",checked:z==="ask",onChange:()=>se("ask")})," Ask me before each tool call (the run waits for you)"]}),we?o.jsx("p",{className:"af-auto__hint","data-email-rule":"untrusted",children:He.untrusted_hint}):null,z==="auto"?o.jsxs("p",{className:"af-schedule__consent","data-consent":"true",children:[mx,e.targetTools&&e.targetTools.length?`: ${e.targetTools.join(", ")}.`:"."]}):o.jsx("p",{className:"af-auto__hint",children:"Each tool call waits for your approval in the automation's timeline."})]}),e.workspaces?o.jsx("div",{className:"af-auto__field","data-field":"workspaces",role:"group","aria-label":"Workspaces",children:e.workspaces}):null,o.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[o.jsx("legend",{children:"Mailbox"}),oe?null:o.jsx(af,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),o.jsx(Fx,{notifyEmail:oe&&N,onNotifyEmailChange:$,recipients:oe?S:Si,onRecipientsChange:E,disabled:!oe,idBase:n})]}),o.jsxs("fieldset",{className:"af-auto__field","data-field":"limits",children:[o.jsx("legend",{children:"Title and limits"}),o.jsxs("label",{className:"af-auto__field",htmlFor:he("title"),children:[o.jsx("span",{children:"Title"}),o.jsx("input",{id:he("title"),value:G,maxLength:120,onChange:ge=>te(ge.target.value),placeholder:"Defaults to the task's first line"})]}),Oe==="every"?o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"af-auto__field",htmlFor:he("start"),children:[o.jsx("span",{children:"First run at (UTC; empty = now)"}),o.jsx("input",{id:he("start"),type:"datetime-local",value:ue,onChange:ge=>ne(ge.target.value)})]}),o.jsxs("label",{className:"af-auto__field",htmlFor:he("count"),children:[o.jsx("span",{children:"Stop after this many runs"}),o.jsx("input",{id:he("count"),type:"number",min:1,step:1,value:P,onChange:ge=>B(ge.target.value)})]}),o.jsxs("label",{className:"af-auto__field",htmlFor:he("until"),children:[o.jsx("span",{children:"Stop at (UTC)"}),o.jsx("input",{id:he("until"),type:"datetime-local",value:W,onChange:ge=>de(ge.target.value)})]})]}):null]}),ee.length?o.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:ee.map(ge=>o.jsx("li",{children:ge},ge))}):null,Ye?o.jsxs("div",{className:"af-auto__error",role:"alert","data-code":(Te=e.error)==null?void 0:Te.code,children:[o.jsx("strong",{children:Ye.title})," ",o.jsx("span",{children:Ye.detail})]}):null,o.jsxs("div",{className:"af-appearance__actions af-auto__row",children:[o.jsx("button",{type:"button",className:"af-auto__btn",onClick:e.onClose,children:"Cancel"}),o.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary",disabled:Ce,children:"Create automation"})]})]})]})})}const bc=6e4,uf=60*bc,wp=24*uf;function df(e){const t=Math.abs(e);return Number.isFinite(t)?t<bc?"<1 min":t<uf?`${Math.floor(t/bc)} min`:t<2*wp?`${Math.floor(t/uf)} h`:`${Math.floor(t/wp)} d`:""}const nk={s:["second","s"],m:["minute","min"],h:["hour","h"],d:["day","d"]};function gy(e){if(e.source_id==="schedule"){const t=e.config.every,n=ho(t);if(!n)return typeof t=="string"?`every ${t}`:"once";if(n.unit==="s"&&n.amount%60===0)return gy({...e,config:{every:`${n.amount/60}m`}});const[r,i]=nk[n.unit];return n.amount===1?`every ${r}`:`every ${n.amount} ${i}`}return e.source_id==="manual"?"manual":Mi(e)?"on new email":e.source_id}function gc(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function sk(e,t){var i;if(e.current_occurrence&&(((i=e.attention)==null?void 0:i.pending_waits)??0)>0){const c=e.last_occurrence&&e.last_occurrence.index===e.current_occurrence.index?gc(e.last_occurrence.fired_at):null;return c===null?"":`waiting since ${df(Math.max(0,t-c))}`}if(e.current_occurrence)return"running now";const n=e.last_occurrence,r=gc(n==null?void 0:n.finished_at)??gc(n==null?void 0:n.fired_at);return r===null?"last never":`last ${df(Math.max(0,t-r))} ago`}function rk(e,t){const n=gc(e.next_fire_at);return n===null?null:n-t<bc?"next due now":`next in ${df(n-t)}`}function yy(e,t){const n=gy(e.trigger),r=sk(e,t),i=rk(e,t);return{cadence:n,last:r,next:i,line:[n,r,i].filter(Boolean).join(" · ")}}const rs={min:300,max:960,default:420,step:16,bigStep:64};function ua(e,t=rs.min,n=rs.max,r=rs.default){return Number.isFinite(e)?Math.round(Math.min(n,Math.max(t,e))):Math.min(n,Math.max(t,r))}function ak(e,t,n,r=rs.min,i=rs.max){const c=n?rs.bigStep:rs.step;return t==="ArrowLeft"?ua(e+c,r,i):t==="ArrowRight"?ua(e-c,r,i):t==="Home"?r:t==="End"?i:null}function ok(e,t,n){return e<=0?null:n==="ArrowDown"?(t+1)%e:n==="ArrowUp"?(t-1+e)%e:n==="Home"?0:n==="End"?e-1:null}function ik(e,t){return e===t?null:t}function lk(e,t,n,r){if(!e)return ua(t,n,r);try{const i=Number.parseInt(window.localStorage.getItem(e)||"",10);if(Number.isFinite(i))return ua(i,n,r,t)}catch{}return ua(t,n,r)}function ck(e){const t=e.minWidth??rs.min,n=e.maxWidth??rs.max,r=e.idBase||"af-rail",i=vc($i.md),c=e.overlay??i,[u,d]=y.useState(()=>typeof window>"u"?ua(e.defaultWidth??rs.default,t,n):lk(e.storageKey,e.defaultWidth??rs.default,t,n)),h=y.useRef(u);h.current=u;const[m,p]=y.useState(()=>new Set(e.active?[e.active]:[])),v=y.useRef(null),_=y.useRef(null),b=y.useRef(null),C=y.useRef(null),x=e.items.find(L=>L.id===e.active)||null,{onActiveChange:j}=e;y.useEffect(()=>{e.active&&p(L=>L.has(e.active)?L:new Set([...L,e.active]))},[e.active]);const N=y.useCallback(L=>{if(e.storageKey)try{window.localStorage.setItem(e.storageKey,String(Math.round(L)))}catch{}},[e.storageKey]);y.useEffect(()=>{if(!c||!x)return;const L=J=>{J.key!=="Escape"||J.defaultPrevented||(J.preventDefault(),j(null))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[c,x,j]),y.useEffect(()=>{var L,J;c&&(x?(L=_.current)==null||L.focus({preventScroll:!0}):b.current&&document.activeElement&&((J=_.current)!=null&&J.contains(document.activeElement))&&b.current.focus())},[c,x]);const $=L=>{var Z,R;const J=Array.from(((Z=v.current)==null?void 0:Z.querySelectorAll('[role="tab"]'))||[]),V=J.findIndex(q=>q===document.activeElement),O=ok(J.length,V<0?0:V,L.key);O!==null&&(L.preventDefault(),(R=J[O])==null||R.focus())},S=L=>{const J=ak(h.current,L.key,L.shiftKey,t,n);J!==null&&(L.preventDefault(),d(J),N(J))},E=L=>{var J,V;L.button!==0&&L.pointerType==="mouse"||(C.current={startX:L.clientX,startW:h.current,pointerId:L.pointerId},(V=(J=L.currentTarget).setPointerCapture)==null||V.call(J,L.pointerId),L.preventDefault())},A=L=>{const J=C.current;!J||J.pointerId!==L.pointerId||d(ua(J.startW+(J.startX-L.clientX),t,n))},I=L=>{var V,O;const J=C.current;!J||J.pointerId!==L.pointerId||(C.current=null,(O=(V=L.currentTarget).releasePointerCapture)==null||O.call(V,L.pointerId),N(h.current))},F=!!x;return o.jsxs("div",{className:`af-rail${F?" af-rail--open":" af-rail--collapsed"}${c?" af-rail--overlay":" af-rail--docked"}${e.className?` ${e.className}`:""}`,style:{"--af-rail-panel-width":`${u}px`},"data-active":e.active||"",children:[c&&F?o.jsx("div",{className:"af-rail__backdrop","aria-hidden":"true",onClick:()=>j(null)}):null,o.jsxs("div",{className:"af-rail__panel-wrap",hidden:!F,style:!c&&F?{width:u}:void 0,children:[!c&&F?o.jsx("div",{className:"af-rail__resize",role:"separator","aria-orientation":"vertical","aria-label":`Resize the ${(x==null?void 0:x.label)||""} panel`,"aria-valuemin":t,"aria-valuemax":n,"aria-valuenow":u,tabIndex:0,title:"Drag to resize",onKeyDown:S,onPointerDown:E,onPointerMove:A,onPointerUp:I,onPointerCancel:I}):null,o.jsx("div",{ref:_,className:"af-rail__panel",role:c?"dialog":void 0,"aria-label":c?x==null?void 0:x.label:void 0,tabIndex:c?-1:void 0,children:e.items.map(L=>o.jsxs("section",{id:`${r}-panel-${L.id}`,role:"tabpanel","aria-labelledby":`${r}-tab-${L.id}`,className:"af-rail__section","data-panel":L.id,hidden:L.id!==e.active,children:[o.jsxs("header",{className:"af-rail__head",children:[o.jsx("h2",{className:"af-rail__title",children:L.label}),o.jsxs("span",{className:"af-rail__head-actions",children:[L.headerActions,o.jsx("button",{type:"button",className:"af-rail__icon-btn","data-action":"collapse-panel","aria-label":`Collapse ${L.label}`,title:"Collapse",onClick:()=>j(null),children:o.jsx(re,{name:c?"x":"chevronRight",size:16})})]})]}),o.jsx("div",{className:"af-rail__body",children:m.has(L.id)||L.id===e.active?L.content:null})]},L.id))})]}),o.jsx("div",{ref:v,className:"af-rail__rail",role:"tablist","aria-orientation":"vertical","aria-label":e.ariaLabel,onKeyDown:$,children:e.items.map(L=>{const J=L.id===e.active,V=`${J?`Collapse ${L.label}`:L.label}${L.hint?` · ${L.hint}`:""}`;return o.jsxs("button",{type:"button",role:"tab",id:`${r}-tab-${L.id}`,"aria-selected":J,"aria-controls":`${r}-panel-${L.id}`,"aria-label":L.label,title:V,className:`af-rail__tab${J?" is-active":""}`,"data-rail":L.id,onClick:O=>{b.current=O.currentTarget,j(ik(e.active,L.id))},children:[o.jsx(re,{name:L.icon,size:19}),typeof L.badge=="number"&&L.badge>0?o.jsx("span",{className:"af-rail__badge","aria-hidden":"true",children:L.badge>99?"99+":L.badge}):L.badge===!0?o.jsx("span",{className:"af-rail__dot","aria-hidden":"true"}):null]},L.id)})})]})}const wy=72;function uk(e,t=wy){const n=Math.max(1,Math.floor(t)),r=new Array(n).fill(0),i=e.length;if(!i)return r;const c=i/n;let u=0;for(let d=0;d<n;d+=1){const h=Math.floor(d*c),m=Math.max(h+1,Math.floor((d+1)*c));let p=0;for(let v=h;v<m&&v<i;v+=1){const _=Math.abs(Number(e[v])||0);_>p&&(p=_)}r[d]=p,p>u&&(u=p)}return u<=0?r:r.map(d=>d/u)}function ac(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 dk(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function fk(e,t){const[n,r]=y.useState({peaks:t??null,note:""});return y.useEffect(()=>{if(t){r({peaks:t,note:""});return}let i=!0;r({peaks:null,note:""});const c=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!c||typeof fetch!="function"){r({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let u=null;try{const d=await(await fetch(e)).arrayBuffer();u=new c;const h=await u.decodeAudioData(d);i&&r({peaks:uk(h.getChannelData(0)),note:""})}catch(d){i&&r({peaks:null,note:`Waveform unavailable: ${d instanceof Error?d.message:String(d)}`})}finally{u&&u.close().catch(()=>{})}})(),()=>{i=!1}},[e,t]),n}function vy(e){const t=y.useRef(null),n=y.useRef(null),[r,i]=y.useState(!1),[c,u]=y.useState(0),[d,h]=y.useState(null),[m,p]=y.useState(""),{peaks:v,note:_}=fk(e.src,e.peaks),b=v??new Array(wy).fill(0),C=d&&d>0?Math.min(1,c/d):0,x=e.name?`Audio ${e.name}`:"Audio",j=y.useCallback(()=>{const E=t.current;E&&(E.paused?E.play().catch(A=>p(A instanceof Error?A.message:String(A))):E.pause())},[]),N=y.useCallback(E=>{const A=t.current;!A||!Number.isFinite(E)||(A.currentTime=E,u(E))},[]),$=E=>{var I;const A=(I=n.current)==null?void 0:I.getBoundingClientRect();!A||!d||N(dk(E-A.left,A.width,d))},S=E=>{if(!d)return;const A=E.key==="ArrowRight"||E.key==="ArrowUp"?5:E.key==="ArrowLeft"||E.key==="ArrowDown"?-5:0;A?(E.preventDefault(),N(Math.min(d,Math.max(0,c+A)))):E.key==="Home"?(E.preventDefault(),N(0)):E.key==="End"?(E.preventDefault(),N(d)):(E.key===" "||E.key==="Enter")&&(E.preventDefault(),j())};return o.jsxs("div",{className:`af-audio${e.className?` ${e.className}`:""}`,"data-playing":r?"true":"false",children:[o.jsx("audio",{ref:t,src:e.src,preload:"metadata",onPlay:()=>i(!0),onPause:()=>i(!1),onEnded:()=>i(!1),onTimeUpdate:E=>u(E.currentTarget.currentTime),onLoadedMetadata:E=>h(Number.isFinite(E.currentTarget.duration)?E.currentTarget.duration:null),onDurationChange:E=>h(Number.isFinite(E.currentTarget.duration)?E.currentTarget.duration:null),onError:()=>p("This audio cannot be played in this browser. Use Download to open it.")}),o.jsx("button",{type:"button",className:"af-audio__play","data-action":r?"pause-audio":"play-audio","aria-label":r?`Pause ${x}`:`Play ${x}`,title:r?"Pause":"Play",onClick:j,children:o.jsx(re,{name:r?"pause":"play",size:16})}),o.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${x}`,"aria-valuemin":0,"aria-valuemax":Math.round(d??0),"aria-valuenow":Math.round(c),"aria-valuetext":`${ac(c)} of ${ac(d)}`,title:_||void 0,"data-waveform":v?"decoded":"flat",onKeyDown:S,onPointerDown:E=>{var A,I;(I=(A=E.currentTarget).setPointerCapture)==null||I.call(A,E.pointerId),$(E.clientX)},onPointerMove:E=>{E.buttons&1&&$(E.clientX)},children:o.jsx("svg",{viewBox:`0 0 ${b.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:b.map((E,A)=>{const I=Math.max(1.5,E*30),F=(A+.5)/b.length<=C;return o.jsx("rect",{className:F?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:A*2+.3,y:16-I/2,width:1.4,height:I,rx:.6},A)})})}),o.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[ac(c)," / ",ac(d)]}),m?o.jsx("p",{className:"af-audio__error",role:"alert",children:m}):null]})}const ha=e=>new Set(e.split(/\s+/).filter(Boolean)),hk=ha("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"),mk=ha("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"),pk=ha("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),gk=ha("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"),vp=ha("true false null yes no on off"),yk={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:hk},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:mk},shell:{line:["#"],strings:['"',"'"],keywords:pk},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:gk},data:{line:["#"],strings:['"',"'"],keywords:vp},json:{line:[],strings:['"'],keywords:vp},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:ha("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:ha("")}},wk={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 Ef(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 wk[i]||""}const vk=e=>e>="0"&&e<="9",_k=e=>/[A-Za-z_$]/.test(e),_p=e=>/[A-Za-z0-9_$]/.test(e);function _y(e,t){const n=String(e??""),r=yk[t];if(!r)return n?[{kind:"plain",text:n}]:[];const i=[];let c="";const u=(h,m)=>{if(m){if(h==="plain"){c+=m;return}c&&i.push({kind:"plain",text:c}),c="",i.push({kind:h,text:m})}};let d=0;for(;d<n.length;){const h=n[d];if(r.line.find(p=>n.startsWith(p,d))){const p=n.indexOf(`
61
+ `,d),v=p===-1?n.length:p;u("comment",n.slice(d,v)),d=v;continue}if(r.block&&n.startsWith(r.block[0],d)){const p=n.indexOf(r.block[1],d+r.block[0].length),v=p===-1?n.length:p+r.block[1].length;u("comment",n.slice(d,v)),d=v;continue}if(r.strings.includes(h)){const p=r.triple&&n.startsWith(h.repeat(3),d)?h.repeat(3):"";if(p){const b=n.indexOf(p,d+3),C=b===-1?n.length:b+3;u("string",n.slice(d,C)),d=C;continue}let v=d+1;for(;v<n.length&&n[v]!==h&&(h==="`"||n[v]!==`
62
+ `);)v+=n[v]==="\\"?2:1;const _=Math.min(n.length,v+1);u("string",n.slice(d,_)),d=_;continue}if(vk(h)&&!(d>0&&_p(n[d-1]))){let p=d+1;for(;p<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[p]);)p+=1;u("number",n.slice(d,p)),d=p;continue}if(_k(h)){let p=d+1;for(;p<n.length&&_p(n[p]);)p+=1;const v=n.slice(d,p),_=t==="sql"?r.keywords.has(v.toLowerCase()):r.keywords.has(v);u(_?"keyword":"plain",v),d=p;continue}u("plain",h),d+=1}return c&&i.push({kind:"plain",text:c}),i}function oc({text:e,language:t="",lineNumbers:n=!0,className:r,ariaLabel:i}){const c=Ef(t),u=_y(e,c),d=n?String(e??"").split(`
63
+ `).length:0;return o.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${r?` ${r}`:""}`,"data-language":c||"text","aria-label":i,style:n?{"--af-code-gutter":`${String(d).length+1}ch`}:void 0,children:o.jsx("code",{children:n?bk(u).map((h,m)=>o.jsxs("span",{className:"af-code__line","data-line":m+1,children:[h.map((p,v)=>bp(p,v)),`
64
+ `]},m)):u.map((h,m)=>bp(h,m))})})}function bp(e,t){return e.kind==="plain"?o.jsx(ct.Fragment,{children:e.text},t):o.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function bk(e){const t=[[]];for(const n of e)n.text.split(`
65
+ `).forEach((i,c)=>{c>0&&t.push([]),i&&t[t.length-1].push({kind:n.kind,text:i})});return t}const by=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],yi=6e4,wi=60*yi,ic=24*wi;function Pi(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)?Pi(Number(t)):Date.parse(t)}function xp(e){return e<10?`0${e}`:String(e)}function kp(e,t){const n=Pi(e);if(!Number.isFinite(n))return"";const r=new Date(n),i=r.getFullYear()===new Date(t).getFullYear();return`${by[r.getMonth()]} ${r.getDate()}${i?"":`, ${r.getFullYear()}`}`}function zc(e){const t=Pi(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${by[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${xp(n.getHours())}:${xp(n.getMinutes())}`}function co(e,t){const n=Pi(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const r=t-n;if(r<0){const c=-r;if(c<yi)return"due now";if(c<wi)return`in ${Math.round(c/yi)} min`;if(c<ic)return`in ${Math.round(c/wi)} h`;const u=Math.round(c/ic);return u<7?`in ${u} ${u===1?"day":"days"}`:kp(n,t)}if(r<yi)return"just now";if(r<wi)return`${Math.floor(r/yi)} min ago`;if(r<ic)return`${Math.floor(r/wi)} h ago`;const i=Math.floor(r/ic);return i===1?"yesterday":i<7?`${i} days ago`:kp(n,t)}const xk=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),kk=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),jk=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function Sk(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function xc(e,t=""){const n=Sk(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":xk.has(n)||r.startsWith("image/")&&r!=="image/svg+xml"?"image":kk.has(n)||r.startsWith("audio/")?"audio":Ef(e)?"code":jk.has(n)||r.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(r)?"code":"binary"}function ff(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function Uc(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 Nk(e){const t=e.kind??xc(e.name,e.contentType),n=Uc(e.sizeBytes),r=e.modified!==void 0?co(e.modified,e.nowMs):"";return o.jsxs("section",{className:`af-file-viewer${e.className?` ${e.className}`:""}`,"aria-label":`Preview of ${e.name}`,"data-kind":t,children:[o.jsxs("header",{className:"af-file-viewer__head",children:[o.jsx(re,{name:"file",size:15}),o.jsxs("span",{className:"af-file-viewer__title",children:[o.jsx("strong",{className:"af-file-viewer__name",title:e.path||e.name,children:e.name}),n||r?o.jsxs("span",{className:"af-file-viewer__meta",children:[n?o.jsx("span",{"data-meta":"size",children:n}):null,n&&r?o.jsx("span",{"aria-hidden":"true",children:" · "}):null,r?o.jsx("time",{"data-meta":"modified",title:zc(e.modified),dateTime:new Date(Pi(e.modified)).toISOString(),children:r}):null]}):null]}),e.actions,e.onDownload?o.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:o.jsx(re,{name:"download",size:15})}):null,e.onClose?o.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:o.jsx(re,{name:"x",size:15})}):null]}),o.jsx("div",{className:"af-file-viewer__body",children:e.status==="loading"?o.jsx("p",{className:"af-file-viewer__muted",role:"status",children:"Loading preview…"}):e.status==="error"?o.jsx("p",{className:"af-file-viewer__error",role:"alert",children:e.error||"The preview could not be loaded."}):o.jsxs(o.Fragment,{children:[e.partialNote?o.jsx("p",{className:"af-file-viewer__muted",role:"status",children:e.partialNote}):null,o.jsx(Ck,{kind:t,p:e})]})})]})}function Ck({kind:e,p:t}){const n=t.text??"";switch(e){case"image":return t.url?o.jsx("img",{className:"af-file-viewer__image",src:t.url,alt:t.name}):o.jsx(lc,{});case"audio":return t.url?o.jsx(vy,{src:t.url,name:t.name}):o.jsx(lc,{});case"pdf":return t.url?o.jsx("object",{className:"af-file-viewer__pdf",data:t.url,type:"application/pdf","aria-label":t.name,children:o.jsx("p",{className:"af-file-viewer__muted",children:"This browser cannot show PDFs inline. Use Download to open it."})}):o.jsx(lc,{});case"markdown":return t.renderMarkdown?o.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):o.jsx(oc,{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 o.jsxs(o.Fragment,{children:[i?o.jsx("p",{className:"af-file-viewer__muted",children:i}):null,o.jsx(oc,{text:r,language:"json"})]})}case"code":return o.jsx(oc,{text:n,language:t.name});case"text":return o.jsx(oc,{text:n,language:"",lineNumbers:!1});default:return o.jsx(lc,{})}}function lc(){return o.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function vi(e){const t=y.useId(),n=`${e.id||t}-title`;return o.jsxs("section",{className:`af-settings-group${e.variant==="flat"?" af-settings-group--flat":""}${e.className?` ${e.className}`:""}`,"aria-labelledby":n,id:e.id,children:[o.jsxs("div",{className:"af-settings-group__head",children:[o.jsx("h3",{className:"af-settings-group__title",id:n,children:e.title}),e.aside?o.jsx("span",{className:"af-settings-group__aside",children:e.aside}):null]}),e.help?o.jsx("p",{className:"af-settings-group__help",children:e.help}):null,o.jsx("div",{className:"af-settings-group__rows",children:e.children})]})}function ia(e){const t=e.htmlFor?"label":"span";return o.jsxs("div",{className:`af-setting-row${e.stack?" af-setting-row--stack":""}${e.className?` ${e.className}`:""}`,"data-setting":e.setting,children:[o.jsxs("div",{className:"af-setting-row__label",children:[o.jsx(t,{className:"af-setting-row__name",...e.htmlFor?{htmlFor:e.htmlFor}:{},children:e.label}),e.help?o.jsx("span",{className:"af-setting-row__help",children:e.help}):null]}),e.children!==void 0||e.trailing?o.jsxs("div",{className:"af-setting-row__control",children:[e.children,e.trailing?o.jsx("span",{className:"af-setting-row__trailing",children:e.trailing}):null]}):null]})}function jp(e){const t=!!e.overrideSummary,n=y.useId(),r=t?`${e.overrideSummary}${e.overrideOwner?` — ${e.overrideOwner}`:""}`:`Gateway default${e.defaultSummary?` · ${e.defaultSummary}`:""}`;return o.jsxs("div",{className:"af-override","data-setting":e.setting,"data-overridden":t?"true":"false",children:[o.jsx(ia,{label:e.label,help:e.help,trailing:o.jsxs(o.Fragment,{children:[o.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?o.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:o.jsx("span",{className:"af-override__summary",title:r,children:r})}),o.jsx("div",{className:"af-override__editor",id:n,hidden:!e.open,children:e.open?e.children:null})]})}const et={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."},an=et;function Ek(e){return e==="any_except_denied"?an.postureAnyExceptDenied:an.postureAllowedOnly}function $k(e){return e==="any_except_denied"?an.postureAnyExceptDeniedHelp:an.postureAllowedOnlyHelp}function Sp(e){return e==="ro"?an.accessRead:e==="deny"?an.accessDenied:an.accessReadWrite}function Ak(e){return e==="gateway"?an.gatewayHelp:e==="account"?an.accountHelp:e==="session"?an.sessionHelp:an.runHelp}const Np={deny:0,ro:1,rw:2},Id=["rw","ro","deny"];function Tk(e){if(e===null)return{allowed:[...Id],reasons:{}};const t=e==="deny"?an.capRefused:an.capReadOnly,n=Id.filter(i=>Np[i]<=Np[e]),r={};for(const i of Id)n.includes(i)||(r[i]=t);return{allowed:n,reasons:r}}function Rk(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,c=t.can_edit===!1,u=new Map(((r==null?void 0:r.folders)??[]).map(b=>[b.path,b.cap])),d=r,h=i?d.folders.map(b=>({path:b.path,mode:b.mode})):n.folders,m=i?d.posture:n.posture,p=i?d.default_mode??n.default_mode:n.default_mode,v=!i&&!c,_=h.map(b=>{const C=e==="gateway"?null:u.get(b.path)??null,{allowed:x,reasons:j}=Tk(C);return{path:b.path,mode:b.mode,cap:C,allowed:x,reasons:j,builtin:!1,editable:v}});if(e==="gateway")for(const b of n.builtin_refused??[])_.push({path:b,mode:"deny",cap:null,allowed:[],reasons:{},builtin:!0,editable:!1});return{level:e,posture:m,following:i,rows:_,everythingElse:m==="any_except_denied"?{mode:p,editable:v}:null,canAdd:v,gatewayLine:e==="gateway"?null:`${an.gatewayPrefix} ${d.gateway_summary}`,summary:e==="gateway"?n.summary:d.summary,locked:c}}function Ik(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function Di(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 Mk(e,t,n,r){return Di(e,{...t,folders:t.folders.map(i=>i.path===n?{path:n,mode:r}:i)})}function Lk(e,t,n){return Di(e,{...t,posture:n})}function Ok(e,t,n){return Di(e,{...t,default_mode:n})}function Pk(e,t,n,r){const i=String(n).trim();return Di(e,{...t,folders:[...t.folders,{path:i,mode:Ik(e,t.posture)}]})}function Dk(e,t,n){return Di(e,{...t,folders:t.folders.filter(r=>r.path!==n)})}function Fk(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 xy(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function zk(e,t=Rr){const n=xy(t);if(e.level==="gateway")return`${n}/workspace/policy`;if(e.level==="account")return`${n}/workspace/policy/${encodeURIComponent(e.account||"me")}`;if(!e.session)throw new Error("A session-level workspace chooser needs the session id.");return`${n}/sessions/${encodeURIComponent(e.session)}/workspaces${e.account?`?account=${encodeURIComponent(e.account)}`:""}`}function Uk(e="me",t=Rr){return`${xy(t)}/workspace/effective/${encodeURIComponent(e)}`}const hf=e=>e==="ro"||e==="rw"||e==="deny",ky=e=>e==="ro"||e==="rw",jy=e=>e==="allowed_only"||e==="any_except_denied",Bk=e=>Array.isArray(e)&&e.every(t=>t&&typeof t.path=="string"&&hf(t.mode)),kc="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function Wk(e,t){const n=e&&typeof e=="object"?e:{},r=n.policy&&typeof n.policy=="object"?n.policy:{};if("shared_workspace"in r||"shared_workspace"in n)throw new Error(kc);if(!(jy(r.posture)&&ky(r.default_mode)&&Bk(r.folders)&&(t==="gateway"?typeof r.summary=="string":typeof r.configured=="boolean")&&(r.builtin_refused===void 0||Array.isArray(r.builtin_refused)&&r.builtin_refused.every(c=>typeof c=="string"))))throw new Error(`The gateway answered without a workspace policy (policy.posture, default_mode, folders, ${t==="gateway"?"summary":"configured"}). ${kc}`);return{...typeof r.account=="string"?{account:r.account}:{},...t==="gateway"?{summary:r.summary}:{configured:r.configured},posture:r.posture,default_mode:r.default_mode,folders:r.folders.map(c=>({path:c.path,mode:c.mode})),...Array.isArray(r.builtin_refused)?{builtin_refused:[...r.builtin_refused]}:{}}}function Sy(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(kc);if(!(jy(t.posture)&&(ky(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"&&hf(r.mode)&&hf(r.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${kc}`);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 Cp(e,t){const n=Wk(e,t),r=e;return{policy:n,effective:t==="gateway"?null:Sy(r.effective),...typeof r.can_edit=="boolean"?{can_edit:r.can_edit}:{}}}function Ep(e,t,n=Rr){const r=zk(t,n);return{path:r,load:async()=>Cp(await e(r,{method:"GET"}),t.level),save:async i=>Cp(await e(r,{method:"PUT",body:i}),t.level)}}function mf(e,t="me",n=Rr){const r=Uk(t,n);return async(i,c)=>Sy(await e(r,{method:"POST",body:c?{workspace:i,session:c}:{workspace:i}}))}function $f(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 $p(e){const t=$f(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${an.notSaved}`}const Vk=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function Gk(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 Af(e){fo();const t=e.idPrefix||"af-workspace",[n,r]=y.useState(null),[i,c]=y.useState({}),[u,d]=y.useState(null),[h,m]=y.useState(""),[p,v]=y.useState(null),_=String(e.unavailableReason||"").trim(),b=e.level,C=e.level==="run"?Gk(e.value,e.effective):e.state,x=e.level==="run"?e.effective:e.state,j=p&&p.base===x?p.value:C,N=j?Rk(b,j):null,$=z=>{if(e.level==="run"){const se=e,G=z.configured===!1?null:{posture:z.posture,default_mode:z.default_mode,folders:z.folders};return Promise.resolve(se.onChange(G))}return e.save(z)};async function S(z,se){if(n!==null||_)return!1;r(z),d(null),c(G=>{const te={...G};return delete te[z],te});try{const G=await $(se);return Vk(G)&&v({base:x,value:G}),d(z),!0}catch(G){return c(te=>({...te,[z]:$p(G)})),!1}finally{r(null)}}const E=z=>i[z]?o.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:i[z]}):u===z?o.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:et.saved}):null,A=(z,se)=>o.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":z,"data-af-tip":se,tabIndex:se?0:void 0,children:Sp(z)}),I=(z,se,G,te,ue)=>o.jsx("span",{className:"af-workspace__access",role:"group","aria-label":z,"data-workspace":ue,"data-access":se,children:G.map(ne=>{const P=!!ne.reason||!!_;return o.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":se===ne.value?"true":"false","aria-disabled":P?"true":void 0,"data-af-tip":ne.reason||void 0,"data-action":`${ue}-${ne.value}`,onClick:()=>P||n!==null||ne.value===se?void 0:te(ne.value),children:ne.text},ne.value)})}),F=z=>{if(z.builtin)return A("deny",et.builtinRefused);if(!z.editable||!j)return A(z.mode);const se=j.policy;return o.jsxs(o.Fragment,{children:[I(`${et.accessLabel} ${z.path}`,z.mode,["rw","ro","deny"].map(G=>({value:G,text:Sp(G),reason:z.reasons[G]})),G=>void S(z.path,Mk(b,se,z.path,G)),"workspace-mode"),o.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${et.remove} ${z.path}`,"data-af-tip":`${et.remove} ${z.path}`,"aria-disabled":_||n!==null?"true":void 0,onClick:()=>_||n!==null?void 0:void S(z.path,Dk(b,se,z.path)),children:o.jsx(re,{name:"x",size:16})})]})};async function L(z){if(!j||!N||!N.canAdd)return;const se=z.trim();se&&await S("add",Pk(b,j.policy,se))&&m("")}async function J(){if(!e.choose||n!==null||_)return;let z;try{z=await e.choose()}catch(se){c(G=>({...G,add:$p(se)}));return}z&&await L(z)}const V=N?N.rows.filter(z=>z.mode!=="deny"):[],O=N?N.rows.filter(z=>z.mode==="deny"):[],Z=z=>o.jsxs("li",{className:"af-workspace__row","data-workspace":z.builtin?"builtin":"row","data-path":z.path,"data-mode":z.mode,"data-cap":z.cap??void 0,children:[o.jsx("code",{className:"af-workspace__path",children:z.path}),o.jsx("span",{className:"af-workspace__controls",children:F(z)}),E(z.path)]},`${z.builtin?"builtin:":""}${z.path}`),R=b==="account"?et.followGateway:et.useDefault,q=b==="account"?et.followGatewayHelp:et.useDefaultHelp;return o.jsx(vi,{id:t,className:`af-workspace af-workspace--${b}${e.className?` ${e.className}`:""}`,title:b==="gateway"?et.gatewayTitle:et.title,help:Ak(b),children:e.loadError?o.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!N||!j?o.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:et.loading}):o.jsxs("div",{className:"af-workspace__body","data-level":b,"data-following":N.following?"true":"false",children:[N.gatewayLine?o.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:N.gatewayLine}):null,_?o.jsx("p",{className:"af-workspace__note",id:`${t}-blocked`,"data-workspace":"blocked",children:_}):null,b!=="gateway"?o.jsxs("div",{className:"af-workspace__follow","data-workspace":"follow",children:[o.jsx(Mr,{variant:"row",label:R,description:q,checked:N.following,busy:n==="follow",unavailableReason:_||(N.locked?et.locked:null),reasonVisible:!1,describedBy:_?`${t}-blocked`:void 0,action:b==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:z=>void S("follow",Fk(j,z))}),E("follow")]}):null,o.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":N.posture,children:[N.following||N.locked?o.jsx("span",{className:"af-workspace__badge",children:Ek(N.posture)}):I(et.postureLabel,N.posture,[{value:"allowed_only",text:et.postureAllowedOnly},{value:"any_except_denied",text:et.postureAnyExceptDenied}],z=>void S("posture",Lk(b,j.policy,z)),"workspace-posture"),o.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:$k(N.posture)}),E("posture")]}),o.jsxs("ul",{className:"af-workspace__list","aria-label":et.title,"data-workspace":"list",children:[V.length?o.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:et.allowedTitle}):null,V.map(Z),O.length?o.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:et.deniedTitle}):null,O.map(Z),N.everythingElse?o.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":N.everythingElse.mode,children:[o.jsx("span",{className:"af-workspace__name",children:et.everythingElse}),o.jsx("span",{className:"af-workspace__controls",children:N.everythingElse.editable?I(`${et.accessLabel} ${et.everythingElse}`,N.everythingElse.mode,[{value:"rw",text:et.accessReadWrite},{value:"ro",text:et.accessRead}],z=>void S("everything-else",Ok(b,j.policy,z)),"workspace-default"):A(N.everythingElse.mode)}),E("everything-else")]}):null,N.canAdd?o.jsxs("li",{className:"af-workspace__add","data-workspace":"add",children:[o.jsx("input",{type:"text",className:"af-workspace__input","aria-label":et.addPlaceholder,placeholder:et.addPlaceholder,value:h,disabled:!!_||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:z=>m(z.target.value),onKeyDown:z=>{z.key==="Enter"?(z.preventDefault(),L(h)):z.key==="Escape"&&(z.preventDefault(),m(""),c(se=>{const G={...se};return delete G.add,G}))}}),o.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!_||!h.trim()||n!==null,onClick:()=>void L(h),children:et.add}),e.choose?o.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!_||n!==null,onClick:()=>void J(),children:et.choose}):null,E("add")]}):null]}),N.posture==="allowed_only"&&!V.length?o.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:et.emptyAllowed}):null,b==="session"||b==="run"?o.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:et.privateNote}):null,o.jsx("p",{className:"af-workspace__effective","data-workspace":"effective",children:N.summary}),e.footer?o.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const Hk=["provider","model","voice","profile","speed","quality_preset","instructions"];function Kk(e){const t={};for(const n of Hk){const r=e[n];r!==void 0&&r!==""&&r!==null&&(t[n]=r)}return t}function Jk(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 Qk=[{value:"",label:"Detect automatically"},{value:"en",label:"English"},{value:"fr",label:"French"},{value:"de",label:"German"},{value:"es",label:"Spanish"},{value:"it",label:"Italian"},{value:"pt",label:"Portuguese"},{value:"nl",label:"Dutch"},{value:"zh",label:"Chinese"},{value:"ja",label:"Japanese"},{value:"ko",label:"Korean"}];function Yk(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function Xk(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const qk=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],Ap=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):[],ii=e=>`${Math.round(e*100)} %`;function Zk(e){var Je,st,Ce,Ye;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,r=y.useRef(e.fetchCatalog);r.current=e.fetchCatalog;const i=y.useRef(e.fetchDefaults);i.current=e.fetchDefaults;const[c,u]=y.useState({}),[d,h]=y.useState({value:null,failed:!1}),m=e.defaults!==void 0?{value:e.defaults,failed:!1}:d,p=e.defaults!==void 0,[v,_]=y.useState(""),[b,C]=y.useState({devices:[],labelled:!0}),[x,j]=y.useState({devices:[],labelled:!0}),[N,$]=y.useState(""),[S,E]=y.useState({text:"",tone:"info"}),[A,I]=y.useState({phase:"idle",message:"",tone:"info"}),[F,L]=y.useState(0),J=e.outputSelectable??$b(),V=Ig(),O=e.value,Z=e.nested?"flat":"card",R=he=>e.onChange({...O,...he}),q=O.reply_volume===void 0?1:Math.min(1,Math.max(0,Number(O.reply_volume)||0)),z=O.input_gain===void 0?1:Math.min(1.5,Math.max(.5,Number(O.input_gain)||1));y.useEffect(()=>{if(n)return;let he=!0;return r.current().then(Ve=>he&&u(Ve||{})).catch(()=>he&&u({})),p||i.current().then(Ve=>he&&h({value:Ve||{},failed:!1})).catch(()=>he&&h({value:null,failed:!0})),()=>{he=!1}},[n,p]);const se=e.listDevices||pb,G=()=>{J&&se("audiooutput").then(C).catch(()=>C({devices:[],labelled:!1})),se("audioinput").then(j).catch(()=>j({devices:[],labelled:!1}))};y.useEffect(()=>{n||G()},[J,n]);const te=()=>{$(""),gb().then(G).catch(he=>$(ef(he)))},ue=()=>{E({text:"Playing a short chime…",tone:"info"}),bb({deviceId:J&&O.output_device||"",volume:q}).then(()=>E({text:"Chime played. Heard nothing? Pick another output or raise the volume.",tone:"ok"})).catch(he=>E({text:`The speaker test failed: ${String((he==null?void 0:he.message)||he).replace(/\.$/,"")}.`,tone:"error"}))},ne=()=>{I({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),vb({deviceId:O.input_device||"",ms:3e3,gain:z,onLevel:L}).then(async({blob:he,peak:Ve})=>{if(Ve<wb){I({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}I({phase:"playing",message:"Playing it back…",tone:"info"}),await _b(he,{deviceId:J&&O.output_device||"",volume:q}),I({phase:"idle",message:`The microphone works (peak level ${ii(Ve)}).`,tone:"ok"}),G()}).catch(he=>I({phase:"idle",message:ef(he),tone:"error"}))},P=lp(m.value,"tts",m.failed),B=lp(m.value,"stt",m.failed),W=[(Je=m.value)==null?void 0:Je.tts,(st=m.value)==null?void 0:st.stt].map(he=>he&&!he.configured?he.note:"").filter(Boolean),de=!!((Ye=(Ce=c.controls)==null?void 0:Ce.quality_preset)!=null&&Ye.supported),ee=O.output_device||"",le=[{value:"",label:"System default"},...b.devices.map(he=>({value:he.id,label:he.label})),...ee&&!b.devices.some(he=>he.id===ee)?[{value:ee,label:"Saved speaker (not connected)"}]:[]],fe=O.input_device||"",oe=[{value:"",label:"System default"},...x.devices.map(he=>({value:he.id,label:he.label})),...fe&&!x.devices.some(he=>he.id===fe)?[{value:fe,label:"Saved microphone (not connected)"}]:[]],we=!x.labelled||J&&!b.labelled,Oe=A.phase!=="idle";return o.jsxs("div",{className:`af-voice-section${e.className?` ${e.className}`:""}`,children:[e.unavailableReason?o.jsx("p",{className:"af-settings-group__help",role:"status",children:e.unavailableReason}):null,o.jsxs(vi,{variant:Z,title:"Engines",help:"Which engines speak and listen.",children:[o.jsx(jp,{label:"Text → speech",setting:"tts",defaultSummary:P,overrideSummary:Yk(O),overrideOwner:t,open:v==="tts",onToggle:()=>_(v==="tts"?"":"tts"),onReset:()=>R({provider:"",model:"",voice:"",profile:""}),disabled:n,children:o.jsx(Rb,{value:O,onChange:he=>e.onChange({...O,...he}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default"})}),o.jsx(jp,{label:"Speech → text",setting:"stt",defaultSummary:B,overrideSummary:Xk(O),overrideOwner:t,open:v==="stt",onToggle:()=>_(v==="stt"?"":"stt"),onReset:()=>R({stt_provider:"",stt_model:""}),disabled:n,children:o.jsx(Ic,{value:{provider:O.stt_provider||"",model:O.stt_model||""},onChange:he=>R({stt_provider:he.provider,stt_model:he.model}),fetchProviders:async()=>{const he=await r.current();return Ap(he.stt_providers).map(Ve=>({name:Ve}))},fetchModels:async he=>{var ae;const Ve=await r.current(he);return Ap(((ae=Ve.stt_models_by_provider)==null?void 0:ae[he])||Ve.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}),m.failed?o.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,W.map(he=>o.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:he},he))]}),o.jsxs(vi,{variant:Z,title:"Output",children:[o.jsx(ia,{label:"Output device",setting:"output-device",help:J?void 0:"Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).",trailing:o.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:n,onClick:ue,children:"Test"}),children:o.jsx(Wn,{ariaLabel:"Output device",placeholder:"System default",value:J?ee:"",options:le,disabled:n||!J,searchable:!1,onOpen:G,onChange:he=>R({output_device:he})})}),S.text?o.jsx("p",{className:`af-voice-note af-voice-note--${S.tone}`,role:"status","data-voice-note":"speaker",children:S.text}):null,o.jsxs(ia,{label:"Reply volume",setting:"reply-volume",htmlFor:"af-voice-volume",children:[o.jsx("input",{id:"af-voice-volume",className:"af-voice-range",type:"range",min:0,max:100,step:5,value:Math.round(q*100),disabled:n,"aria-valuetext":ii(q),onChange:he=>R({reply_volume:Number(he.currentTarget.value)/100})}),o.jsx("span",{className:"af-voice-range__value",children:ii(q)})]})]}),o.jsxs(vi,{variant:Z,title:"Microphone",children:[o.jsx(ia,{label:"Input device",setting:"input-device",trailing:o.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:n||Oe,onClick:ne,children:A.phase==="recording"?"Recording…":A.phase==="playing"?"Playing…":"Test"}),children:o.jsx(Wn,{ariaLabel:"Input device",placeholder:"System default",value:fe,options:oe,disabled:n,searchable:!1,onOpen:G,onChange:he=>R({input_device:he})})}),o.jsx("div",{className:"af-voice-meter","data-voice-meter":!0,role:"meter","aria-label":"Microphone level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(F*100),children:o.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(F*100)}%`}})}),A.message?o.jsx("p",{className:`af-voice-note af-voice-note--${A.tone}`,role:"status","data-voice-note":"microphone",children:A.message}):null,we&&!n?o.jsxs("p",{className:"af-voice-note","data-voice-note":"labels",children:["Device names appear once the microphone is allowed."," ",o.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"show-device-names",onClick:te,children:"Show names"})]}):null,N?o.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:N}):null,o.jsx(ia,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:o.jsx(Wn,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:O.stt_language||"",options:Qk,disabled:n,searchable:!1,onChange:he=>R({stt_language:he})})}),V?o.jsxs(ia,{label:"Input level",setting:"input-gain",htmlFor:"af-voice-gain",help:"Raises a quiet microphone.",children:[o.jsx("input",{id:"af-voice-gain",className:"af-voice-range",type:"range",min:50,max:150,step:10,value:Math.round(z*100),disabled:n,"aria-valuetext":ii(z),onChange:he=>R({input_gain:Number(he.currentTarget.value)/100})}),o.jsx("span",{className:"af-voice-range__value",children:ii(z)})]}):null]}),o.jsxs(vi,{variant:Z,title:"Replies",children:[o.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:o.jsx(Mr,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:O.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:he=>R({read_aloud:he})})}),o.jsx(ia,{label:"Voice latency",setting:"latency",help:de?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:o.jsx(Wn,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:de&&O.quality_preset||"",options:qk,disabled:n||!de,searchable:!1,onChange:he=>R({quality_preset:he})})})]})]})}function Ny(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 ej(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function tj(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 nj(e){return e.endsWith(`
66
+ `)?e:`${e}
67
+ `}function sj(e){return String(e||"").trimStart().startsWith("```")}function rj(e,t){const r=[`# ${"Chat".trim()||"Chat"}`,""];for(const i of e){const c=tj(i);r.push(`## ${c}`,"");const u=String(i.content||""),d=Ny(u);d!==null&&!sj(u)?r.push("```json",ej(d).trimEnd(),"```",""):r.push(nj(u).trimEnd(),""),r.push("---","")}for(;r.length&&!r[r.length-1].trim();)r.pop();return r.length&&r[r.length-1]==="---"&&r.pop(),`${r.join(`
68
+ `).trimEnd()}
69
+ `}async function Bc(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 aj(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}),c=URL.createObjectURL(i),u=document.createElement("a");u.href=c,u.download=t,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(c),1e3)}const oj=3,ij=Number.MAX_SAFE_INTEGER;function Cy(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ey(e){return Array.isArray(e)}function lj(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ao({kind:e,children:t}){return o.jsx("span",{className:`pc-json-token ${e}`,children:t})}function cj(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[r,i]=y.useState(!n||e.expansionMode==="unfolded");return y.useEffect(()=>{n&&i(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?o.jsxs("span",{className:`pc-json-string ${r?"open":"collapsed"}`,children:[o.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>i(c=>!c),"aria-label":r?"Collapse string value":"Expand string value","aria-expanded":r,children:r?"▾":"▸"}),r?o.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):o.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>i(!0),"aria-label":"Expand string value",children:[o.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),o.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):o.jsx(ao,{kind:"string",children:t})}function uj(e,t,n){return e===null?o.jsx(ao,{kind:"null",children:"null"}):typeof e=="string"?o.jsx(cj,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?o.jsx(ao,{kind:"number",children:String(e)}):typeof e=="boolean"?o.jsx(ao,{kind:"boolean",children:e?"true":"false"}):o.jsx(ao,{kind:"string",children:JSON.stringify(String(e))})}function dj(e){return Ey(e)?e.length===1?"1 item":`${e.length} items`:Cy(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function $y(e){const{label:t,value:n,depth:r,collapseAfterDepth:i,expansionMode:c,expansionVersion:u,trailingComma:d}=e,h=r*14,m=Cy(n),p=Ey(n),v=m||p,_=r<i,[b,C]=y.useState(_);y.useEffect(()=>{C(_)},[_,u]);const x=t?o.jsxs(o.Fragment,{children:[o.jsx(ao,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!v)return o.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:h},children:[x,uj(n,c,u),d?",":""]});const j=p?"[":"{",N=p?"]":"}",$=dj(n),S=b?`${j}`:`${j}…${N}${$?` (${$})`:""}`,E=p?n.map((A,I)=>({key:String(I),label:void 0,value:A})):Object.entries(n).map(([A,I])=>({key:A,label:A,value:I}));return o.jsxs("details",{className:"pc-json-viewer__details",open:b,onToggle:A=>C(A.currentTarget.open),children:[o.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:h},children:[x,o.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:b?"▾":"▸"}),o.jsx("span",{className:"pc-json-viewer__punct",children:S}),!b&&d?o.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),b?o.jsx("div",{className:"pc-json-viewer__children",children:E.length===0?o.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:h},children:[o.jsx("span",{className:"pc-json-viewer__punct",children:N}),d?",":""]}):o.jsxs(o.Fragment,{children:[E.map((A,I)=>{const F=I===E.length-1;return o.jsx($y,{label:A.label,value:A.value,depth:r+1,collapseAfterDepth:i,expansionMode:c,expansionVersion:u,trailingComma:!F},`${r}:${t||"root"}:${A.key}`)}),o.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:h},children:[o.jsx("span",{className:"pc-json-viewer__punct",children:N}),d?",":""]})]})}):null]})}function fj(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 io(e){const{value:t,className:n,showCopy:r=!0}=e,[i,c]=y.useState({mode:"folded",version:0}),[u,d]=y.useState("idle"),h=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):oj,m=i.mode==="unfolded"?ij:h,p=y.useMemo(()=>typeof t=="string"?fj(t):t,[t]),v=y.useMemo(()=>lj(t),[t]),_=["pc-json-viewer",n].filter(Boolean).join(" ");y.useEffect(()=>{c(C=>({mode:"folded",version:C.version+1}))},[p]);const b=()=>{c(C=>({mode:C.mode==="unfolded"?"folded":"unfolded",version:C.version+1}))};return o.jsxs("div",{className:_,children:[o.jsxs("div",{className:"pc-json-viewer__toolbar",children:[o.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:b,"aria-expanded":i.mode==="unfolded",children:i.mode==="unfolded"?"Fold all":"Unfold all"}),r?o.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void Bc(v).then(C=>{d(C?"copied":"failed"),window.setTimeout(()=>d("idle"),2e3)}),children:u==="copied"?"Copied":u==="failed"?"Copy failed — select and copy":"Copy JSON"}):null]}),o.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:o.jsx($y,{value:p,depth:0,collapseAfterDepth:m,expansionMode:i.mode,expansionVersion:i.version,trailingComma:!1})})]})}function hj({code:e,lang:t}){const[n,r]=y.useState("idle"),i=y.useRef(null);y.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]);const c=_y(e,Ef(t));return o.jsxs("div",{className:"pc-md_codeblock",children:[o.jsx("button",{type:"button",className:`pc-md_copy${n!=="idle"?` pc-md_copy--${n}`:""}`,"aria-label":"Copy code",title:n==="idle"?"Copy":n==="copied"?"Copied":"Copy failed",onClick:async()=>{const u=await Bc(e);r(u?"copied":"failed"),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r("idle"),900)},children:o.jsx(re,{name:n==="copied"?"check":"copy",size:14})}),o.jsx("pre",{className:"pc-md_pre",children:o.jsx("code",{className:t?`language-${t}`:void 0,children:c.map((u,d)=>u.kind==="plain"?o.jsx(ct.Fragment,{children:u.text},d):o.jsx("span",{className:`af-code__${u.kind}`,children:u.text},d))})})]})}function li(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const r=[],i=n.toLowerCase();let c=0;for(;c<n.length;){let u=-1,d="";for(let p=0;p<t.needlesLower.length;p++){const v=t.needlesLower[p];if(!v)continue;const _=i.indexOf(v,c);if(_===-1)continue;const b=t.needles[p]||"";b&&(u===-1||_<u||_===u&&b.length>d.length)&&(u=_,d=b)}if(u===-1||!d){r.push(n.slice(c));break}u>c&&r.push(n.slice(c,u));const h=t.hits===0&&t.id?t.id:void 0,m=n.slice(u,u+d.length);r.push(o.jsx("span",{id:h,className:t.className,children:m},`hl:${t.hits}`)),t.hits+=1,c=u+d.length}return r}function Ay(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const pf="http://same-origin.invalid/";function mj(e){try{const t=new URL(e,pf);return t.protocol==="http:"&&t.origin===new URL(pf).origin}catch{return!1}}function Ty(e){const t=String(e||"").trim();return Ay(t)??(t&&mj(t)?t:void 0)}let da=null;function pj(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??pf;let i,c;try{i=new URL(r).origin,c=new URL(t,r)}catch{return!1}return c.protocol!=="http:"&&c.protocol!=="https:"?!1:c.origin===i}function Ry(e,t,n){return o.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function Tp(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function Hs(e,t){const n=[],r=String(e??"");let i=0,c="";const u=()=>{if(c){for(const d of li(c,t))n.push(d);c=""}};for(;i<r.length;){const d=r[i];if(d==="!"&&r[i+1]==="["){const h=r.indexOf("]",i+2);if(h!==-1&&r[h+1]==="("){const m=r.indexOf(")",h+2);if(m!==-1){const p=r.slice(i+2,h),v=Ty(r.slice(h+2,m));if(v&&da&&!da(v)){u(),n.push(Ry(`img:${i}`,v,p)),i=m+1;continue}if(v){u(),n.push(o.jsxs("span",{className:"pc-md_image_inline",children:[o.jsx("img",{className:"pc-md_img",src:v,alt:p,loading:"lazy"}),p?o.jsx("span",{className:"pc-md_img_caption",children:t?li(p,t):p}):null]},`img:${i}`)),i=m+1;continue}}}}if(d==="["){const h=r.indexOf("]",i+1);if(h!==-1&&r[h+1]==="("){const m=r.indexOf(")",h+2);if(m!==-1){const p=r.slice(i+1,h),v=Ay(r.slice(h+2,m));if(v){u(),n.push(o.jsx("a",{className:"pc-md_link",href:v,target:v.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:Hs(p,t)},`link:${i}`)),i=m+1;continue}}}}if(d==="`"){const h=r.indexOf("`",i+1);if(h!==-1){u();const m=r.slice(i+1,h);n.push(o.jsx("code",{children:t?li(m,t):m},`code:${i}`)),i=h+1;continue}}if(d==="_"&&!Tp(r[i-1])){const h=r[i+1]==="_"?"__":"_",m=h.length;if(r[i+m]&&!/\s/.test(r[i+m])&&r[i+m]!=="_"){let p=r.indexOf(h,i+m);for(;p!==-1&&(/\s/.test(r[p-1]||" ")||Tp(r[p+m])||m===1&&r[p+1]==="_");)p=r.indexOf(h,p+1);if(p!==-1&&p>i+m){u();const v=r.slice(i+m,p),_=Hs(v,t);n.push(m===2?o.jsx("strong",{children:_},`ubold:${i}`):o.jsx("em",{children:_},`uem:${i}`)),i=p+m;continue}}}if(d==="*"&&r[i+1]==="*"){const h=r.indexOf("**",i+2);if(h!==-1){u();const m=r.slice(i+2,h);n.push(o.jsx("strong",{children:t?li(m,t):m},`bold:${i}`)),i=h+2;continue}}if(d==="*"&&r[i+1]!=="*"){const h=r.indexOf("*",i+1);if(h!==-1){u();const m=r.slice(i+1,h);n.push(o.jsx("em",{children:t?li(m,t):m},`em:${i}`)),i=h+1;continue}}c+=d,i+=1}return u(),n}function gj(e){return String(e??"").replace(/\r\n/g,`
70
+ `).replace(/\r/g,`
71
+ `).split(`
72
+ `)}function yc(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 yj(e){const t=[];for(const i of e){const c=yc(i);c?t.push(c):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 c=r.length>0?r[r.length-1]:null;if(c&&i.indent>c.indent){const u=c.node.items,d=u[u.length-1];if(d){const h={ordered:i.ordered,start:i.start,items:[]};d.children.push(h),r.push({indent:i.indent,node:h}),c=r[r.length-1]}}else if(c&&c.node.ordered!==i.ordered){r.pop();const u=r.length>0?r[r.length-1]:null,d={ordered:i.ordered,start:i.start,items:[]};if(u){const h=u.node.items,m=h[h.length-1];m?m.children.push(d):u.node.items.push({content:"",children:[d]})}else n.push(d);r.push({indent:i.indent,node:d}),c=r[r.length-1]}if(!c){const u={ordered:i.ordered,start:i.start,items:[]};n.push(u),r.push({indent:i.indent,node:u}),c=r[r.length-1]}c.node.items.push({content:i.content,children:[]})}return n}function Iy(e,t,n){const r=e.items.map((i,c)=>o.jsxs("li",{children:[Hs(i.content,t),i.children.map((u,d)=>Iy(u,t,`${n}:${c}:${d}`))]},`${n}:li:${c}`));return e.ordered?o.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:r},n):o.jsx("ul",{className:"pc-md_ul",children:r},n)}function wj(e,t,n){return yj(e).map((r,i)=>Iy(r,t,`${n}:${i}`))}function Rp(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 Ip(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 Mp=/^(#{1,5})\s+(.*)$/;function Lp(e){return e.trim().startsWith("```")}function Op(e){return e.trimStart().startsWith(">")}function My(e){const t=da;da=e.images==="link"?e.inlineImage||pj:null;try{return vj(e)}finally{da=t}}function vj({text:e,className:t,highlight:n,highlights:r,highlightClassName:i,highlightId:c}){const u=gj(e),d=[],h=[];Array.isArray(r)&&h.push(...r),typeof n=="string"&&n.trim()&&h.push(n);const m=Array.from(new Set(h.map(b=>String(b??"").trim()).filter(Boolean))).filter(b=>b.length>=4),p=m.length?{needles:m,needlesLower:m.map(b=>b.toLowerCase()),className:i||"pc-md_hl",id:c,hits:0}:null;let v=0;for(;v<u.length;){const b=String(u[v]??"");if(!b.trim()){v+=1;continue}const C=b.trim();if(/^([-_*])(\s*\1){2,}$/.test(C)){d.push(o.jsx("hr",{className:"pc-md_hr"},`hr:${v}`)),v+=1;continue}const x=b.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(x){const $=Ty(x[2]||"");if($&&da&&!da($)){d.push(o.jsx("p",{className:"pc-md_p",children:Ry(`img:${v}`,$,x[1]||"")},`p:${v}`)),v+=1;continue}if($){const S=x[1]||"";d.push(o.jsxs("figure",{className:"pc-md_figure",children:[o.jsx("img",{className:"pc-md_img",src:$,alt:S,loading:"lazy"}),S?o.jsx("figcaption",{children:Hs(S,p)}):null]},`figure:${v}`)),v+=1;continue}}if(Lp(b)){const S=b.trim().replace(/```/g,"").trim(),E=[];for(v+=1;v<u.length&&!String(u[v]??"").trim().startsWith("```");)E.push(String(u[v]??"")),v+=1;v<u.length&&(v+=1);const A=E.join(`
73
+ `);d.push(o.jsx(hj,{code:A,lang:S},`pre:${v}`));continue}const j=b.match(Mp);if(j){const $=j[1].length,S=j[2]||"",E=Hs(S,p);$===1?d.push(o.jsx("h1",{children:E},`h1:${v}`)):$===2?d.push(o.jsx("h2",{children:E},`h2:${v}`)):$===3?d.push(o.jsx("h3",{children:E},`h3:${v}`)):$===4?d.push(o.jsx("h4",{children:E},`h4:${v}`)):d.push(o.jsx("h5",{children:E},`h5:${v}`)),v+=1;continue}if(Op(b)){const $=[];for(;v<u.length&&String(u[v]??"").trimStart().startsWith(">");){const E=String(u[v]??"").trimStart();$.push(E.replace(/^>\s?/,"")),v+=1}d.push(o.jsx("blockquote",{className:"pc-md_quote",children:$.map((S,E)=>o.jsxs(ct.Fragment,{children:[Hs(S,p),E<$.length-1?o.jsx("br",{}):null]},`q:${v}:${E}`))},`quote:${v}`));continue}if(b.includes("|")&&v+1<u.length&&Ip(String(u[v+1]??""))){const $=Rp(b),S=Math.max(1,$.length),E=[];for(v+=2;v<u.length;){const A=String(u[v]??"");if(!A.trim()||!A.includes("|"))break;const I=Rp(A),F=[];for(let L=0;L<S;L++)F.push(I[L]??"");E.push(F),v+=1}d.push(o.jsx("div",{className:"pc-md_table_wrap",children:o.jsxs("table",{className:"pc-md_table",children:[o.jsx("thead",{children:o.jsx("tr",{children:$.slice(0,S).map((A,I)=>o.jsx("th",{children:Hs(A,p)},`th:${v}:${I}`))})}),o.jsx("tbody",{children:E.map((A,I)=>o.jsx("tr",{children:A.map((F,L)=>o.jsx("td",{children:Hs(F,p)},`td:${v}:${I}:${L}`))},`tr:${v}:${I}`))})]})},`table:${v}`));continue}if(yc(b)){const $=[];for(;v<u.length;){const S=String(u[v]??"");if(!S.trim()||S.trimStart().startsWith("```"))break;if(yc(S)||/^\s{2,}\S/.test(S)){$.push(S),v+=1;continue}break}d.push(o.jsx(ct.Fragment,{children:wj($,p,`list:${v}`)},`list:${v}`));continue}const N=[];for(;v<u.length&&String(u[v]??"").trim()&&!(N.length>0&&yc(String(u[v]??"")));){const $=String(u[v]??"");if(N.length>0&&(Mp.test($)||Lp($)||Op($))||N.length>0&&$.includes("|")&&v+1<u.length&&Ip(String(u[v+1]??"")))break;N.push($),v+=1}d.push(o.jsx("p",{className:"pc-md_p",children:N.map(($,S)=>o.jsxs(ct.Fragment,{children:[Hs($,p),S<N.length-1?o.jsx("br",{}):null]},`pl:${v}:${S}`))},`p:${v}`))}const _=["pc-md",t].filter(Boolean).join(" ");return o.jsx("div",{className:_,children:d})}function Ly(e){const t=String(e.text??""),n=y.useMemo(()=>Ny(t),[t]),r=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?o.jsx("div",{className:r,children:o.jsx(io,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?o.jsx("div",{className:r,children:e.renderMarkdown(t)}):o.jsx("div",{className:r,children:o.jsx(My,{text:t,images:e.images,inlineImage:e.inlineImage})})}function _i(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Er(e){return typeof e=="string"?e.trim():""}function _j(e){var i;const t=_i(e);if(!t)return null;const n=_i(t.sandbox);if(n&&Er(n.kind))return n;const r=_i((i=_i(t.output))==null?void 0:i.sandbox);return r&&Er(r.kind)?r:null}function Pp(e){const t=_j(e);if(!t)return null;const n=Er(t.kind),r=Er(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 c=[],u=Er(t.private_workspace);u&&c.push({path:u,mode:"Read & write",private:!0});for(const h of Array.isArray(t.allowed)?t.allowed:[]){const m=_i(h),p=Er(m==null?void 0:m.path);p&&c.push({path:p,mode:Er(m==null?void 0:m.mode)==="ro"?"Read-only":"Read & write"})}for(const h of Array.isArray(t.refused)?t.refused:[]){const m=Er(h);m&&c.push({path:m,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:r,line:`Sandbox: ${r}`,rows:[],builtinRefused:0};const d=c.length;return{state:"sandboxed",kind:n,label:r,line:`Sandbox: ${r} · ${d} ${d===1?"workspace":"workspaces"} enforced`,rows:c,builtinRefused:i}}function bj({sandbox:e,className:t}){return e?o.jsxs("div",{className:`pc-tool-sandbox is-${e.state}${t?` ${t}`:""}`,"data-sandbox-kind":e.kind,children:[o.jsx("div",{className:"pc-tool-sandbox__line",children:e.line}),e.rows.length?o.jsxs("ul",{className:"pc-tool-sandbox__rows","aria-label":"Workspaces the sandbox enforced",children:[e.rows.map((n,r)=>o.jsxs("li",{children:[o.jsx("code",{children:n.path}),o.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?o.jsxs("li",{className:"pc-tool-sandbox__builtin",children:[e.builtinRefused," built-in protected ",e.builtinRefused===1?"folder":"folders"," refused"]}):null]}):null]}):null}function Oy(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Py(e){const t=Oy(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(c=>n.find(([u])=>u===c)).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 Dy({tool:e,showCopy:t=!0}){const[n,r]=y.useState(!1),i=Oy(e.arguments),c=Py(e.arguments),u=["file path","path"].includes(c.label)&&c.value.length>60?`${c.value.split(/[\\/]/).pop()} · ${c.value.slice(0,24)}…`:c.value,d=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,h={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},m=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,p=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i):null;return o.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[o.jsxs("summary",{className:"pc-tool-activity__summary",children:[o.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:o.jsx(re,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),o.jsx("strong",{children:e.name}),o.jsx("span",{className:"pc-tool-activity__preview",title:c.value,children:c.value?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"pc-tool-activity__key",children:c.label}),u]}):"No parameters"}),o.jsx("span",{className:"pc-tool-activity__status",children:h[e.status]}),Number.isFinite(m)&&m>=0?o.jsxs("span",{className:"pc-tool-activity__duration",children:[(m/1e3).toFixed(1),"s"]}):null,o.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:o.jsx(re,{name:"chevronRight",size:13})}),e.error?o.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:d}):null]}),o.jsxs("div",{className:"pc-tool-activity__detail",children:[o.jsx(bj,{sandbox:e.sandbox}),e.error?o.jsxs(o.Fragment,{children:[o.jsx("h4",{children:"Error"}),o.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,o.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[o.jsx("h4",{children:"Parameters"}),t?o.jsxs("button",{type:"button",onClick:async()=>r(await Bc(JSON.stringify(e,null,2))),children:[o.jsx(re,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?o.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([v,_])=>o.jsxs(ct.Fragment,{children:[o.jsx("dt",{children:v}),o.jsx("dd",{children:_&&typeof _=="object"?o.jsx(io,{value:_}):o.jsx("code",{children:typeof _=="string"?_:JSON.stringify(_)})})]},v))}):e.arguments===void 0?o.jsx("p",{children:"Arguments are unavailable in this ledger."}):o.jsx(io,{value:i}),e.output!==void 0?o.jsxs(o.Fragment,{children:[o.jsx("h4",{children:"Result"}),typeof e.output=="string"?o.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):o.jsx("div",{className:"pc-tool-activity__output",children:o.jsx(io,{value:e.output})})]}):null]})]})}function Tf({tools:e,showCopy:t}){const n=r=>e.filter(i=>i.status===r).length;return o.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[o.jsxs("div",{className:"pc-tool-group__heading",children:[o.jsx(re,{name:"terminal",size:14}),o.jsx("strong",{children:"Tools"}),o.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),o.jsx("div",{}),n("running")?o.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?o.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?o.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?o.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(r=>o.jsx(Dy,{tool:r,showCopy:t},r.id))]})}const Vt="not reported",rn=e=>e===void 0?Vt:Math.round(e).toLocaleString(),gn=e=>{if(e===void 0)return Vt;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`},Fy=e=>e===void 0?Vt:`${Math.round(e).toLocaleString()} tok/s`,xj=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",fa=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,kj=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function jj(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 jc(e){const t=[],n=(e.models||[]).map(kj),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 Sj(e){const t=e.modelCalls||[],n=[],r=[{label:"Input",value:rn(e.inputTokens)},{label:"Output",value:rn(e.outputTokens)}];if(e.reasoningTokens!==void 0&&r.push({label:"Reasoning",value:rn(e.reasoningTokens),hint:"part of output"}),r.push({label:"Total",value:rn(e.totalTokens)}),n.push({heading:`Usage · ${fa(e.llmCalls,"model call")}`,rows:r}),e.measuredCacheCalls){const c=e.cachedTokens||0,u=e.fedTokens||0,d=[{label:"Reused from cache",value:`${rn(c)}${c+u?` (${xj(c,c+u)})`:""}`},{label:"Newly processed",value:rn(e.fedTokens)},{label:"Outcome",value:jj(t.map(h=>h.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Vt},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Vt}];e.measuredCacheCalls!==e.llmCalls&&d.push({label:"Measured on",value:`${e.measuredCacheCalls} of ${e.llmCalls} calls`}),n.push({heading:"Prompt cache",rows:d})}else e.llmCalls&&n.push({heading:"Prompt cache",rows:[{label:"Cache reuse",value:Vt}]});const i=t.filter(c=>c.inputTokens!==void 0);return i.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${rn(i[0].inputTokens)} tokens`}]}):i.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${rn(i[0].inputTokens)} → ${rn(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((c,u)=>[String(u+1),rn(c.inputTokens),c.cachedTokens===void 0?"—":rn(c.cachedTokens),c.fedTokens===void 0?"—":rn(c.fedTokens),rn(c.outputTokens),c.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Vt:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:jc(e)}}function cc(e,t,n,r){if(e===void 0)return Vt;const i=[gn(e)];return t!==void 0&&i.push(`${t.toLocaleString()} ${r}${n!==void 0?` at ${Fy(n)}`:""}`),i.join(" · ")}function Nj(e){var m,p,v;const t=e.modelCalls||[],n=[],r=e.durationMs,i=[{label:"Wall clock",value:gn(r)}];if(i.push({label:"Model",value:e.genTimeMs===void 0?Vt:`${gn(e.genTimeMs)} · ${fa(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),i.push({label:"Tools",value:e.toolTimeMs!==void 0?`${gn(e.toolTimeMs)} · ${fa(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Vt:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),r!==void 0&&e.genTimeMs!==void 0){const _=r-e.genTimeMs-(e.toolTimeMs||0);i.push({label:"Orchestration",value:_>=0?gn(_):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:i});const c=[],u=e.ttftCalls||0,d=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?c.push({label:u&&u===d?"Prefill (TTFT)":"Prefill",value:cc(e.promptPhaseMs,e.promptPhaseNewTokens,e.promptPhaseTokensPerSecond,"new tok"),hint:u===d?"measured time to first token":u?`TTFT measured on ${u} of ${d}; rest from provider rate`:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0&&e.prefillNewTokensPerSecond!==void 0?c.push({label:"Prefill",value:cc(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?c.push({label:"Prefill",value:`${gn(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Fy(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):c.push({label:"Prefill",value:Vt}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&c.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),c.push({label:"Generation",value:e.generationPhaseMs!==void 0?cc(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):cc(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&c.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:c});const h=e.speculation;if(h){const _=(h.draftKinds||[]).map(C=>C.toUpperCase()).join(", "),b=[{label:"Mode",value:`${h.used?"on":"off"}${_?` · ${_}`:""}${(m=h.modes)!=null&&m.length?` (${h.modes.join(", ")})`:""}`,hint:h.calls!==e.llmCalls||h.used!==h.calls?`used on ${h.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:h.acceptanceRate===void 0?Vt:`${Math.round(h.acceptanceRate*100)}% · ${rn(h.acceptedTokens)} of ${rn(h.draftedTokens)} drafted`}];((p=h.draftLengths)!=null&&p.length||h.rounds!==void 0)&&b.push({label:"Draft length",value:`${(v=h.draftLengths)!=null&&v.length?`${h.draftLengths.join("/")} tok/round`:Vt}${h.rounds!==void 0?` · ${h.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:b})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${gn(e.toolTimeMs)} · ${fa(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${gn(e.slowestToolBatch.ms)} · ${zy(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((_,b)=>[String(b+1),_.promptMs===void 0?"—":`${gn(_.promptMs)}${_.promptSource==="rate"?"*":""}`,_.promptNewTokensPerSecond===void 0?"—":Math.round(_.promptNewTokensPerSecond).toLocaleString(),_.generationMs===void 0?"—":gn(_.generationMs),_.generationTokensPerSecond===void 0?"—":Math.round(_.generationTokensPerSecond).toLocaleString(),_.cacheOutcome||"—"])},note:t.some(_=>_.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:r===void 0?Vt:`${gn(r)} wall clock`,sections:n,footer:jc(e)}}function zy(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${fa(e.calls,"call")} (${e.tools.join(", ")})`}function Cj(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:jc(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((d,h)=>h[1].calls-d[1].calls||d[0].localeCompare(h[0]));i.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:i.map(([d,h])=>[d,h.calls.toLocaleString(),h.failed.toLocaleString(),h.ms!==void 0?`${gn(h.ms)}${h.sharedBatches?" +shared":""}`:h.sharedBatches?"shared":Vt])},note:i.some(([,d])=>d.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const c=i.filter(([,d])=>d.errors&&Object.keys(d.errors).length);c.length&&t.push({heading:"Failures",rows:c.map(([d,h])=>({label:d,value:Object.entries(h.errors).sort((m,p)=>p[1]-m[1]).map(([m,p])=>p>1?`${m} ×${p}`:m).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Vt:`${gn(e.toolTimeMs)} · ${fa(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${gn(e.slowestToolBatch.ms)} · ${zy(e.slowestToolBatch)}`}),t.push({heading:"Timing",rows:u,note:e.toolTimeIncludesApproval?"Gated calls are timed from request to result, so this includes waiting for your approval.":void 0}),{kind:"tools",title:"Tools",headline:`${fa(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:jc(e)}}function Md(e,t){return e==="tokens"?Sj(t):e==="time"?Nj(t):Cj(t)}function Ej(e){const t=e.detail;return o.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:[o.jsxs("div",{className:"pc-stat-detail-head",children:[o.jsx("span",{className:"pc-stat-detail-title",children:t.title}),o.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var r;return o.jsxs("div",{className:"pc-stat-detail-section",children:[o.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(r=n.rows)!=null&&r.length?o.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(i=>o.jsxs(ct.Fragment,{children:[o.jsx("dt",{children:i.label}),o.jsxs("dd",{children:[o.jsx("span",{className:i.value===Vt?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:i.value}),i.hint?o.jsx("span",{className:"pc-stat-detail-hint",children:i.hint}):null]})]},i.label))}):null,n.table?o.jsxs("table",{className:"pc-stat-detail-table",children:[o.jsx("thead",{children:o.jsx("tr",{children:n.table.columns.map(i=>o.jsx("th",{scope:"col",children:i},i))})}),o.jsx("tbody",{children:n.table.rows.map((i,c)=>o.jsx("tr",{children:i.map((u,d)=>o.jsx("td",{children:u},d))},c))})]}):null,n.note?o.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),o.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>o.jsx("div",{children:n},n))})]})}const Vs=8;function $j(e){const[t,n]=y.useState(!!e.defaultOpen),[r,i]=y.useState(null),c=y.useRef(null),u=y.useRef(null),d=y.useRef(null),h=`pc-stat-${y.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=y.useCallback(()=>{d.current!==null&&window.clearTimeout(d.current),d.current=null},[]),p=y.useCallback(()=>{m(),n(!0)},[m]),v=y.useCallback(()=>{m(),d.current=window.setTimeout(()=>n(!1),120)},[m]);y.useEffect(()=>m,[m]),y.useLayoutEffect(()=>{if(!t){i(null);return}const x=()=>{const j=c.current,N=u.current;if(!j||!N)return;const $=j.getBoundingClientRect(),S=N.offsetWidth,E=N.offsetHeight,A=window.innerWidth,I=window.innerHeight,F=$.top-Vs-E,L=$.bottom+Vs,J=F>=Vs?F:L+E<=I-Vs?L:Math.max(Vs,I-Vs-E),V=Math.min(Math.max(Vs,$.left),Math.max(Vs,A-Vs-S));i({top:J,left:V})};return x(),window.addEventListener("resize",x),window.addEventListener("scroll",x,!0),()=>{window.removeEventListener("resize",x),window.removeEventListener("scroll",x,!0)}},[t]),y.useEffect(()=>{if(!t)return;const x=j=>{j.key==="Escape"&&n(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t]);const _=typeof e.onClick=="function",b=_?"button":"span",C=t?o.jsx(Ej,{detail:e.detail,id:h,panelRef:u,onMouseEnter:m,onMouseLeave:v,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 o.jsxs(o.Fragment,{children:[o.jsxs(b,{ref:c,..._?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",_?"pc-chat-stat--clickable":"",e.className].filter(Boolean).join(" "),"aria-label":`${e.label} — ${e.detail.title.toLowerCase()} details`,"aria-describedby":t?h:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:p,onMouseLeave:v,onFocus:p,onBlur:()=>n(!1),onKeyDown:x=>{x.key==="Escape"&&n(!1)},onClick:_?()=>{var x;return(x=e.onClick)==null?void 0:x.call(e)}:void 0,children:[e.icon?o.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,o.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),C&&typeof document<"u"?Rc.createPortal(C,document.body):C]})}function Aj(e){const t=e.totalTokens!==void 0?Md("tokens",e):null,n=Md("tools",e),r=e.durationMs!==void 0?Md("time",e):null;return[...t?[{label:`${e.totalTokens.toLocaleString()} tokens`,detail:t}]:[],{label:`${e.toolCalls} ${e.toolCalls===1?"tool":"tools"}`,detail:n},...e.changedFiles.length?[{label:`${e.changedFiles.length} ${e.changedFiles.length===1?"file":"files"} changed`,title:e.changedFiles.join(`
74
+ `)}]:[],...r?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:r}]:[]]}function Tj(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 Rj=new Set(["blob:","data:","http:","https:"]);function Dp(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return Rj.has(new URL(t,n).protocol)?t:void 0}catch{return}}function Ij({item:e}){const[t,n]=y.useState(!1),r=Dp(e.src),i=e.href?Dp(e.href):void 0,c=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!c||!r&&!i)return null;const u=c==="image"?"Image":c==="video"?"Video":"Audio",d=String(e.label||"").trim()||`Generated ${u.toLowerCase()}`,h=()=>n(!0);return o.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${c}`,children:[r&&c==="image"?o.jsx("img",{className:"pc-chat-media__image",src:r,alt:d,loading:"lazy",onError:h}):null,r&&c==="video"?o.jsx("video",{className:"pc-chat-media__video",src:r,controls:!0,playsInline:!0,preload:"metadata","aria-label":d,onError:h}):null,r&&c==="audio"?o.jsx(vy,{className:"pc-chat-media__audio",src:r,name:d}):null,t?o.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[u," could not be decoded by this browser",i?"; open the raw file with the link.":"."]}):null,i?o.jsx("figcaption",{className:"pc-chat-media__caption",children:o.jsx("a",{className:"pc-chat-media__link",href:i,target:"_blank",rel:"noopener noreferrer",children:d})}):null]})}function Uy(e){var A;const t=e.message,n=y.useMemo(()=>Tj(t),[t.kind,t.level,t.role,t.title]),r=String(t.ts||"").trim(),i=y.useMemo(()=>{if(!r)return"";const I=new Date(r);return Number.isFinite(I.getTime())?I.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[r]),[c,u]=y.useState("idle"),d=y.useRef(null);y.useEffect(()=>()=>{d.current!==null&&window.clearTimeout(d.current)},[]);const h=t.live,m=!h&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),p=m&&((A=e.getSpeakState)==null?void 0:A.call(e,t))||"idle",v=p==="loading"?"loader":p==="playing"?"pause":"speaker",_=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",b=e.showCopy!==!1,C=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],x=t.statistics,j=t.stats,N=y.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(j)?j:x?Aj(x):[],[e.stats,j,x]),$=Array.isArray(t.media)?t.media:[],S=String(h?h.reasoning||"":t.reasoning||""),E=!!String(t.content||"").trim();return t.toolActivity?o.jsx(Dy,{tool:t.toolActivity,showCopy:e.showCopy}):o.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,h?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...h?{"aria-busy":!0}:{},children:[o.jsxs("div",{className:"pc-chat-header",children:[o.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:o.jsx(re,{name:n.icon,size:14})}),o.jsx("span",{className:"pc-chat-role",children:n.label}),h?o.jsxs("span",{className:"pc-chat-live-indicator",title:h.label?`Pending: ${h.label}`:"The reply is still being written",children:[o.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),h.label||"streaming"]}):null,h!=null&&h.caption?o.jsx("span",{className:"pc-chat-live-caption",children:h.caption}):null,o.jsx("span",{className:"pc-chat-header-spacer"}),i?o.jsx("span",{className:"pc-chat-time",children:i}):null,o.jsxs("div",{className:"pc-chat-header-actions",children:[m?o.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":_,title:_,onClick:()=>{var I;return(I=e.onSpeakToggle)==null?void 0:I.call(e,t)},children:o.jsx(re,{name:v,size:22,className:p==="loading"?"pc-chat-speak-spinner":void 0})}):null,b?o.jsx("button",{className:`pc-chat-icon-btn ${c!=="idle"?`pc-chat-icon-btn--${c}`:""}`.trim(),type:"button","aria-label":"Copy message",title:c==="idle"?"Copy":c==="copied"?"Copied":"Copy failed",onClick:async()=>{const I=await Bc(String(t.content||""));u(I?"copied":"failed"),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>u("idle"),900)},children:o.jsx(re,{name:"copy",size:22})}):null]})]}),S.trim()?o.jsxs("details",{className:"pc-chat-thinking",children:[o.jsx("summary",{children:"Thinking"}),o.jsx("div",{className:"pc-chat-thinking-body",children:S})]}):null,E||!h&&!$.length?o.jsx("div",{className:"pc-chat-body",children:o.jsx(Ly,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,$.length?o.jsx("div",{className:"pc-chat-media",children:$.slice(0,24).map((I,F)=>o.jsx(Ij,{item:I},I.id||`${I.kind}:${I.src}:${F}`))}):null,C.length?o.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:C.slice(0,24).map((I,F)=>{const L=String(I.label||"").trim()||"attachment",J=String(I.target||"").trim(),V=String(I.title||"").trim(),O=!!I.disabled||typeof I.onClick!="function";return o.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:V||L,onClick:O?void 0:I.onClick,disabled:O,children:[o.jsx(re,{name:"paperclip",size:14}),J?o.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${J}`,children:J}):null,o.jsx("span",{className:"pc-chat-attachment-name",children:L})]},I.id||`${L}:${F}`)})}):null,N.length?o.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:N.slice(0,12).map((I,F)=>{const L=String(I.label||"").trim();if(!L)return null;if(I.detail)return o.jsx($j,{label:L,detail:I.detail,icon:I.icon,onClick:I.onClick},I.id||`${L}:${F}`);const J=String(I.title||"").trim(),V=typeof I.onClick=="function",O=V?"button":"span";return o.jsxs(O,{...V?{type:"button"}:{},className:["pc-chat-stat",V?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:J||void 0,onClick:V?()=>{var Z;return(Z=I.onClick)==null?void 0:Z.call(I)}:void 0,children:[I.icon?o.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:I.icon}):null,o.jsx("span",{className:"pc-chat-stat-label",children:L})]},I.id||`${L}:${F}`)})}):null]})}function Mj(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function By(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,r=y.useRef(null),i=y.useRef(null),[c,u]=y.useState(!0),d=y.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),h=y.useMemo(()=>{var v;const p=[];for(const _ of d){const b=p[p.length-1];_.toolActivity&&((v=b==null?void 0:b[0])!=null&&v.toolActivity)&&b[0].runId===_.runId?b.push(_):p.push([_])}return p},[d]);y.useEffect(()=>{if(!n)return;const p=r.current;if(!p)return;const v=()=>{u(Mj(p,t))};return p.addEventListener("scroll",v,{passive:!0}),v(),()=>p.removeEventListener("scroll",v)},[n,t]);const m=y.useMemo(()=>{let p=0;for(const v of d)if(p+=String(v.content??"").length,Array.isArray(v.media))for(const _ of v.media)p+=String((_==null?void 0:_.src)??"").length+1;return`${d.length}:${p}:${String(e.afterKey??"")}`},[d,e.afterKey]);return y.useEffect(()=>{if(!n||!c)return;const p=r.current;p&&(p.scrollTop=p.scrollHeight)},[n,c,m]),y.useEffect(()=>{if(!n)return;const p=r.current;if(!p)return;const v=()=>{c&&(p.scrollTop=p.scrollHeight)};return p.addEventListener("load",v,!0),p.addEventListener("loadedmetadata",v,!0),()=>{p.removeEventListener("load",v,!0),p.removeEventListener("loadedmetadata",v,!0)}},[n,c]),o.jsxs("div",{ref:r,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[d.length?null:e.empty||null,h.map((p,v)=>{var C;const _=p[0],b=String(_.id||"")||String(_.ts||"")+":"+String(_.role||"")+":"+v;return _.toolActivity?o.jsx(Tf,{tools:p.map(x=>x.toolActivity),showCopy:(C=e.messageProps)==null?void 0:C.showCopy},b):o.jsx(Uy,{message:_,...e.messageProps||{}},b)}),e.after,o.jsx("div",{ref:i})]})}const Wy=ct.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,c=!!t.busy,u=!i&&!c&&!!String(t.value||"").trim();return o.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,o.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:d=>t.onChange(d.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:d=>{d.key!=="Enter"||d.shiftKey||d.nativeEvent.isComposing||d.keyCode===229||(d.preventDefault(),u&&t.onSubmit())}}),o.jsxs("div",{className:"pc-composer__row",children:[o.jsx("div",{className:"pc-composer__actions",children:t.actions}),o.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:c?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function bi(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Fp(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 zp(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function Rf(e){const t=[],n=[],r=e==null?void 0:e.items;if(r&&r.length){for(let c=0;c<r.length;c+=1){const u=r[c];if(!u||u.kind!=="file")continue;const d=typeof u.webkitGetAsEntry=="function"?u.webkitGetAsEntry():null,h=typeof u.getAsFile=="function"?u.getAsFile():null;d!=null&&d.isDirectory?n.push(d.name||(h==null?void 0:h.name)||"folder"):h&&t.push(h)}return{files:t,folders:n}}const i=e==null?void 0:e.files;if(i)for(let c=0;c<i.length;c+=1)i[c]&&t.push(i[c]);return{files:t,folders:n}}function Vy(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 Lj={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function ci(e){return String(e).padStart(2,"0")}function Oj(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=Lj[String(t||"").toLowerCase()]||r.split(".").pop()||"bin",c=`${n.getFullYear()}-${ci(n.getMonth()+1)}-${ci(n.getDate())} at ${ci(n.getHours())}.${ci(n.getMinutes())}.${ci(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!r?"Pasted image":"Pasted file"} ${c}.${i}`}function Gy(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}=Rf(e);return r.map(i=>{const c=Oj(i.name,i.type,t);return c===i.name?i:new File([i],c,{type:i.type,lastModified:i.lastModified})})}class Pj{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 xi="llm.delta",no="llm.delta_end";function Dj(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function aa(e){return typeof e=="string"&&e.trim()!==""}function Fj(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Hy(e){return"reason"in e}function Ky(e,t){const n=Dj(e),r=n==null?void 0:n.kind,i=t||(typeof r=="string"&&r?r:n&&"reason"in n?no:xi),c=h=>{throw new Error(`Malformed ${i} event from the gateway: ${h}`)};if(t!==void 0&&t!==xi&&t!==no&&c(`unknown event name ${JSON.stringify(t)}`),!n)return c("the payload is not an object");r!==void 0&&r!==xi&&r!==no&&c(`unknown kind ${JSON.stringify(r)}`),r!==void 0&&t!==void 0&&r!==t&&c(`kind ${JSON.stringify(r)} does not match the event name`),aa(n.run_id)||c("run_id is missing"),aa(n.call_id)||c("call_id is missing"),Fj(n.seq)||c("seq is not a non-negative integer");const u=t||r?(t||r)===no:"reason"in n;n.root_run_id!==void 0&&!aa(n.root_run_id)&&c("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!aa(n.parent_run_id)&&c("parent_run_id is neither a run id nor null");const d={run_id:n.run_id,...aa(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...aa(n.node_id)?{node_id:n.node_id}:{},call_id:n.call_id,seq:n.seq};return u?(["completed","failed","cancelled","unavailable"].includes(String(n.reason))||c(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&c("detail is not a string"),{kind:no,...d,reason:n.reason,...aa(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&c("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&c(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&c("snapshot is not a boolean"),{kind:xi,...d,text:n.text,channel:n.channel,snapshot:n.snapshot})}function Jy(e,t){if(e!==xi&&e!==no)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 Ky(n,e)}function zj(e){if(e==="on")return{stream:!0};if(e==="off")return{stream:!1};if(e==="gateway_default")return{};throw new Error(`Unknown streamReplies mode ${JSON.stringify(e)}; use "gateway_default", "on" or "off"`)}const Uj={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 Bj(e){return`This reply is not streamed: ${e?Uj[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const Sc=1024*1024,Wj="1 MiB",Vj=25*1024*1024,Qy=(e,t)=>`${ve(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function Yy(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 Gj(e,t,n){var m;const r=new TextDecoder;let i="",c=0;const u=(m=e.body)==null?void 0:m.getReader();if(u){for(;c<t;){const{done:p,value:v}=await u.read();if(p)break;const _=v.subarray(0,t-c);c+=_.length,i+=r.decode(_,{stream:!0})}await u.cancel().catch(()=>{})}else i=(await e.text()).slice(0,t),c=i.length;const d=Yy(e)??n,h=d!==void 0?d>c:c>=t;return{text:i,received:c,total:d,partial:h}}function Xy(e){return`Showing the first ${Wj} of ${e!==void 0?Uc(e):"a file of unknown size"}; download for the rest.`}function Hj(e){try{return decodeURIComponent(e)}catch{return e}}function Kj(e,t,n){const r=`${ve(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,i=n.split("/").slice(0,-1),c=h=>{if(/^[a-z][a-z0-9+.-]*:/i.test(h)||h.startsWith("/")||h.startsWith("#"))return null;const m=[...i];for(const p of h.split(/[?#]/,1)[0].split("/"))if(!(!p||p==="."))if(p===".."){if(!m.length)return null;m.pop()}else m.push(Hj(p));return m.length?Qy(t,m.join("/")):null},u=h=>{let m="",p=0;for(;p<h.length;){if(h[p]==="!"&&h[p+1]==="["){const v=h.indexOf("]",p+2);if(v!==-1&&h[v+1]==="("){const _=h.indexOf(")",v+2);if(_!==-1){const b=h.slice(p+2,v),C=h.slice(v+2,_).trim(),x=C.startsWith(r)?C:c(C);m+=x?`![${b}](${x})`:`[image: ${b||C}](${C})`,p=_+1;continue}}}m+=h[p],p+=1}return m};let d=!1;return e.split(`
75
+ `).map(h=>/^\s*(```|~~~)/.test(h)?(d=!d,h):d?h:u(h)).join(`
76
+ `)}function Jj(e,t,n,r){const[i,c]=y.useState({status:"idle"});return y.useEffect(()=>{if(!n||!t){c({status:"idle"});return}const u=new AbortController;let d="";const h=xc(n.name);if(h==="binary"){c({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((h==="image"||h==="audio"||h==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>Vj){c({status:"error",kind:h,message:`Too large to preview (${Uc(n.size_bytes)}); use Download.`});return}c({status:"loading",kind:h});const m=ff(h);return(async()=>{var p;try{const v=await e(Qy(t,n.path),{signal:u.signal,...m?{headers:{Range:`bytes=0-${Sc-1}`}}:{}});if(!v.ok)throw new Error(`Preview failed (HTTP ${v.status}): ${await v.text().catch(()=>"")||v.statusText||"no reason given"}`);const _=v.headers.get("content-type")||"",b=xc(n.name,_);if(ff(b)){const C=await Gj(v,Sc,n.size_bytes);if(u.signal.aborted)return;c({status:"ready",kind:b,contentType:_,text:b==="markdown"?Kj(C.text,t,n.path):C.text,partial:C.partial,total:C.total});return}if(b==="image"||b==="audio"||b==="pdf"){const C=await v.blob();if(u.signal.aborted)return;d=URL.createObjectURL(C.type?C:new Blob([C],{type:b==="pdf"?"application/pdf":_})),c({status:"ready",kind:b,contentType:_,url:d,partial:!1});return}await((p=v.body)==null?void 0:p.cancel().catch(()=>{})),u.signal.aborted||c({status:"ready",kind:"binary",contentType:_,partial:!1})}catch(v){u.signal.aborted||c({status:"error",kind:h,message:String((v==null?void 0:v.message)||v)})}})(),()=>{u.abort(),d&&URL.revokeObjectURL(d)}},[e,t,n==null?void 0:n.path,n==null?void 0:n.name,n==null?void 0:n.size_bytes,r]),i}function qy(e){return o.jsx(Nk,{...e,nowMs:e.nowMs??Date.now(),renderMarkdown:t=>o.jsx(My,{text:t})})}function Qj(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:Xy(e.total)}:{}}}const If=e=>ve(`runs/${encodeURIComponent(e)}/workspace`);function Yj(e){return If(e)}function Xj(e,t){return`${If(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function Zy(e,t){return`${If(e)}/content?${new URLSearchParams({path:t})}`}async function po(e,t){let n="";try{const r=await e.text();try{const i=JSON.parse(r),c=(i==null?void 0:i.detail)??(i==null?void 0:i.error)??(i==null?void 0:i.message);n=typeof c=="string"?c:c&&typeof c.message=="string"?c.message:r}catch{n=r}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function qj(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,r=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return r("not an object");Array.isArray(n.entries)||r("no `entries` list"),typeof n.truncated!="boolean"&&r("no `truncated` flag");const i=n.entries.map((u,d)=>{const h=u&&typeof u=="object"?u:{};return(typeof h.name!="string"||typeof h.path!="string"||h.type!=="file"&&h.type!=="dir")&&r(`entry ${d+1} lacks a name, path or file/dir type`),h}),c=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,...c?{hidden:c}:{}}}async function Zj(e,t,n){const r=await e(Yj(t),{signal:n});if(!r.ok)throw await po(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 eS(e,t,n,r){const i=await e(Xj(t,n),{signal:r});if(!i.ok)throw await po(i,"The folder could not be listed");return qj(await i.json(),n)}async function tS(e,t,n,r){const i=await e(Zy(t,n),{signal:r});if(!i.ok)throw await po(i,"The file could not be read");return await i.blob()}async function nS(e,t,n,r){const i=await Zj(e,t,r);return{where:i,listing:i.exists?await eS(e,t,n,r):null}}function sS(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 rS(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 aS(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function oS(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 iS=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function lS(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return iS.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 ew(e,t,n){const r=n==="open"?lS(e.type):{mode:"download"},i=r.mode==="open"&&r.type!==e.type?new Blob([e],{type:r.type}):e,c=URL.createObjectURL(i);if(r.mode==="open")window.open(c,"_blank","noopener");else{const u=document.createElement("a");u.href=c,u.download=t,document.body.appendChild(u),u.click(),u.remove()}window.setTimeout(()=>URL.revokeObjectURL(c),6e4)}async function cS(e,t,n){const r=await e(__(t),{signal:n.signal});if(!r.ok)throw await po(r,`${n.name} could not be read`);ew(await r.blob(),n.name,n.mode??"open")}function uS(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function dS(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 fS(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function Mf(e){var Z;const{fetchGateway:t,runId:n}=e,[r,i]=y.useState({runId:n,path:""}),c=r.runId===n?r.path:"",[u,d]=y.useState(null),[h,m]=y.useState(""),[p,v]=y.useState(""),[_,b]=y.useState(!!n),[C,x]=y.useState(""),[j,N]=y.useState(!1),[$,S]=y.useState(0),[E,A]=y.useState(null),I=E&&E.runId===n&&!e.onSelectFile?E.entry:null,F=Jj(t,n,I,`${e.refreshKey??""}:${$}`);y.useEffect(()=>{if(!n)return;const R=new AbortController;return b(!0),m(""),(async()=>{try{const q=await nS(t,n,c,R.signal);R.signal.aborted||d({runId:n,...q})}catch(q){R.signal.aborted||m(String((q==null?void 0:q.message)||q))}finally{R.signal.aborted||b(!1)}})(),()=>R.abort()},[t,n,c,$,e.refreshKey]),y.useEffect(()=>v(""),[n]);const L=u&&u.runId===n?u:null,J=y.useCallback(async R=>{x(R.path),m("");try{ew(await tS(t,n,R.path),R.name,"download")}catch(q){m(String((q==null?void 0:q.message)||q))}finally{x("")}},[t,n]),V=(L==null?void 0:L.where.workspace_root)||"",O=e.nowMs??Date.now();return o.jsx(hS,{title:e.title,note:e.note,where:(L==null?void 0:L.where)??null,path:c,listing:(L==null?void 0:L.listing)??null,error:h,notice:p,loading:_,fileBusy:C,selectedPath:e.onSelectFile?e.selectedPath:I==null?void 0:I.path,className:e.className,nowMs:O,openingFolder:j,onNavigate:R=>{A(null),i({runId:n,path:R})},onRefresh:()=>S(R=>R+1),onFile:R=>void J(R),onSelectFile:e.onSelectFile??(R=>A({runId:n,entry:R})),onClose:e.onClose,onCopyPath:V?()=>{(e.copyText||fS)(V).then(R=>v(R?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&dS(L==null?void 0:L.where)?()=>{N(!0),v(""),e.onOpenFolder().then(()=>v("Folder opened on this machine.")).catch(R=>v(`Open folder failed: ${String((R==null?void 0:R.message)||R)}`)).finally(()=>N(!1))}:void 0,preview:I?o.jsx(qy,{name:I.name,path:I.path,sizeBytes:I.size_bytes,modified:I.mtime,nowMs:O,...Qj(F),actions:(Z=e.fileActions)==null?void 0:Z.call(e,I),onDownload:()=>void J(I),onClose:()=>A(null)}):null})}function hS(e){var c,u,d,h;const t=e.listing?oS(e.listing):"",n=(u=(c=e.where)==null?void 0:c.host)==null?void 0:u.hostname,r=((d=e.where)==null?void 0:d.workspace_root)||"",i=e.nowMs??Date.now();return o.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":r||void 0,children:[o.jsxs("header",{className:"pc-ws__head",children:[o.jsxs("span",{className:"pc-ws__title",children:[o.jsx(re,{name:"folder",size:15})," ",e.title]}),o.jsx("span",{className:"pc-ws__spacer"}),o.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:o.jsx(re,{name:"refresh",size:14})}),e.onClose?o.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:o.jsx(re,{name:"x",size:14})}):null]}),e.where?o.jsxs("div",{className:"pc-ws__root",children:[o.jsx("span",{className:"pc-ws__root-name",title:r,"data-root-name":"true",children:uS(r)}),e.onOpenFolder?o.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:o.jsx(re,{name:"folder",size:14})}):null,e.onCopyPath?o.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:o.jsx(re,{name:"copy",size:14})}):null,n&&((h=e.where.host)==null?void 0:h.caller_is_this_machine)!==!0?o.jsxs("span",{className:"pc-ws__muted",children:[" on ",n]}):null]}):null,e.note?o.jsx("div",{className:"pc-ws__muted",children:e.note}):null,e.notice?o.jsx("div",{className:"pc-ws__muted",role:"status",children:e.notice}):null,e.error?o.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.preview?o.jsx("div",{className:"pc-ws__preview",children:e.preview}):o.jsxs(o.Fragment,{children:[o.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:sS(e.path).map((m,p,v)=>p===v.length-1?o.jsx("span",{"aria-current":"page",children:m.label},m.path):o.jsxs(ct.Fragment,{children:[o.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(m.path),children:m.label}),o.jsx("span",{className:"pc-ws__muted",children:" / "})]},m.path))}),e.loading&&!e.listing?o.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?o.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?o.jsx("ul",{className:"pc-ws__entries",children:aS(e.listing.entries).map(m=>o.jsx("li",{className:`pc-ws__entry${e.selectedPath===m.path?" is-selected":""}`,"data-type":m.type,"data-path":m.path,children:m.type==="dir"?o.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(m.path),children:[o.jsx(re,{name:"folder",size:14})," ",o.jsxs("span",{className:"pc-ws__label",children:[m.name,"/"]})]}):o.jsxs(o.Fragment,{children:[e.onSelectFile?o.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"select-file","aria-pressed":e.selectedPath===m.path,title:`Preview ${m.name}`,onClick:()=>{var p;return(p=e.onSelectFile)==null?void 0:p.call(e,m)},children:[o.jsx(re,{name:"file",size:14})," ",o.jsx("span",{className:"pc-ws__label",children:m.name})]}):o.jsxs("span",{className:"pc-ws__name",children:[o.jsx(re,{name:"file",size:14})," ",o.jsx("span",{className:"pc-ws__label",children:m.name})]}),o.jsxs("span",{className:"pc-ws__meta",children:[o.jsx("span",{className:"pc-ws__size",children:rS(m.size_bytes)}),m.mtime!==void 0&&co(m.mtime,i)?o.jsx("time",{className:"pc-ws__time",title:zc(m.mtime),"data-meta":"modified",children:co(m.mtime,i)}):null]}),e.onFile?o.jsx("button",{type:"button",className:"pc-ws__icon-btn pc-ws__icon-btn--bare","data-action":"download-file",disabled:e.fileBusy===m.path,onClick:()=>{var p;return(p=e.onFile)==null?void 0:p.call(e,m,"download")},title:"Download","aria-label":`Download ${m.name}`,children:o.jsx(re,{name:"download",size:14})}):null]})},m.path))}):o.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?o.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})]})}const mS={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},tw="docs";function pS(e){return ve(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Ld(e){return`${String(e||"app")}-docs-assistant:${ca()}`}function gS(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}),{...mS,session_id:e.sessionId,kind:tw,input_data:t}}function nw(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 yS(e){const t=e&&typeof e=="object"?e:{},n=d=>typeof d=="number"&&Number.isFinite(d)&&d>0?Math.trunc(d):0,r=n(t.dropped_messages);if(!r)return"";const i=n(t.replayed_messages),c=n(t.dropped_tokens),u=n(t.max_tokens);return`Earlier messages not replayed: ${r.toLocaleString("en-US")}${c?` (~${c.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${i.toLocaleString("en-US")} message${i===1?"":"s"}`+(u?` (history window: the most recent ${u.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*wS(e,t){const n=e.getReader(),r=new TextDecoder;let i="";const c=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",c,{once:!0});try{for(;;){const{value:u,done:d}=await n.read();if(d)break;i+=r.decode(u,{stream:!0}).replace(/\r\n/g,`
77
+ `);let h=i.indexOf(`
78
+
79
+ `);for(;h>=0;){const m=i.slice(0,h);i=i.slice(h+2);let p="message";const v=[];for(const _ of m.split(`
80
+ `))_.startsWith("event:")?p=_.slice(6).trim():_.startsWith("data:")&&v.push(_.slice(5).replace(/^ /,""));v.length&&(yield{event:p,data:v.join(`
81
+ `)}),h=i.indexOf(`
82
+
83
+ `)}}}finally{t==null||t.removeEventListener("abort",c)}}function vS(e,t){return new Promise((n,r)=>{if(t.aborted)return r(new DOMException("Aborted","AbortError"));const i=setTimeout(()=>{t.removeEventListener("abort",c),n()},e),c=()=>{clearTimeout(i),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",c,{once:!0})})}async function $r(e,t){if(!e.ok)throw await po(e,t);return e.json()}function _S(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let r=null;return async(i,c)=>{var C;const{fetchGateway:u,source:d}=e;if(r===null){const x=await u(pS(d.app),{signal:c.signal,headers:{Accept:"application/json"}}),j=await $r(x,`The ${d.name} documentation could not be read, so nothing was asked`),N=typeof(j==null?void 0:j.text)=="string"?j.text:"";if(!N.trim())throw new Error(`The gateway returned an empty ${d.name} documentation corpus, so nothing was asked.`);r=N}const h=String(r),m=[];for(const x of c.files||[]){const j=new FormData;j.append("session_id",c.sessionId),j.append("file",x,x.name||"upload.bin"),j.append("filename",x.name||"upload.bin"),x.type&&j.append("content_type",x.type);const N=await $r(await u(ve("attachments/upload"),{method:"POST",body:j,signal:c.signal}),`"${x.name}" could not be attached`),$=N==null?void 0:N.attachment;if(!$||typeof $.$artifact!="string"||!$.$artifact)throw new Error(`"${x.name}" could not be attached: the gateway returned no attachment reference.`);m.push($)}const p=await $r(await u(ve("runs/start"),{method:"POST",signal:c.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(gS({question:i,docs:h,appName:d.name,sessionId:c.sessionId,attachments:m}))}),"The docs-qa workflow could not start"),v=String((p==null?void 0:p.run_id)||"");if(!v)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const _=new AbortController,b=()=>_.abort();c.signal.addEventListener("abort",b,{once:!0}),c.onText&&(async()=>{var x;try{const j=await u(ve(`runs/${encodeURIComponent(v)}/ledger/stream?after=0`),{signal:_.signal,headers:{Accept:"text/event-stream"}});if(!j.ok||!j.body)return;let N="",$="";for await(const S of wS(j.body,_.signal)){const E=Jy(S.event,S.data);!E||Hy(E)||E.channel!=="content"||E.run_id!==v||(E.call_id!==N&&(N=E.call_id,$=""),$=E.snapshot?E.text:$+E.text,(x=c.onText)==null||x.call(c,$))}}catch{}})();try{const x=Date.now()+n;for(;;){await vS(t,c.signal);const j=await $r(await u(ve(`runs/${encodeURIComponent(v)}`),{signal:c.signal}),"The docs-qa run could not be read"),N=String((j==null?void 0:j.status)||"").toLowerCase();if(N==="completed"){(C=c.onHistory)==null||C.call(c,(j==null?void 0:j.session_history)??null);const $=nw(j);if(!$)throw new Error(`The docs-qa run ${v} completed without an answer.`);return $}if(N==="failed"||N==="cancelled"){const $=j==null?void 0:j.error,S=typeof $=="string"?$:typeof($==null?void 0:$.message)=="string"?$.message:"";throw new Error(`The docs-qa run ${N}${S?`: ${S}`:""}.`)}if(N==="waiting")throw new Error(`The docs-qa run ${v} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=x)throw new Error(`The docs-qa run ${v} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{c.signal.removeEventListener("abort",b),_.abort()}}}async function bS(e,t,n={}){const r=new URLSearchParams({root_only:"true",kind:tw,limit:"500",include_ledger_len:"false"}),i=await $r(await e(ve(`runs?${r}`),{signal:n.signal}),"The docs assistant history could not be read"),c=`${String(t||"app")}-docs-assistant:`,u=new Map;for(const h of Array.isArray(i==null?void 0:i.items)?i.items:[]){const m=String((h==null?void 0:h.session_id)||"");if(!m.startsWith(c)||!(h!=null&&h.run_id))continue;const p=u.get(m)||{runs:[],updatedAt:""};p.runs.push({id:String(h.run_id),created:String(h.created_at||"")});const v=String(h.updated_at||h.created_at||"");v>p.updatedAt&&(p.updatedAt=v),u.set(m,p)}const d=[...u.entries()].sort((h,m)=>h[1].updatedAt<m[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(d.map(async([h,m])=>{var _;const p=m.runs.sort((b,C)=>b.created<C.created?-1:1).map(b=>b.id);let v="";try{const b=await $r(await e(ve(`runs/${encodeURIComponent(p[0])}/input_data`),{signal:n.signal}),"");v=String(((_=b==null?void 0:b.input_data)==null?void 0:_.prompt)||"").trim()}catch{v=""}return{sessionId:h,title:v||"Untitled question",updatedAt:m.updatedAt,runIds:p}}))}async function xS(e,t,n,r){var c;const i=[];for(const u of t.runIds){const[d,h]=await Promise.all([$r(await e(ve(`runs/${encodeURIComponent(u)}/input_data`),{signal:r}),"A past question could not be read"),$r(await e(ve(`runs/${encodeURIComponent(u)}`),{signal:r}),"A past answer could not be read")]),m=String(((c=d==null?void 0:d.input_data)==null?void 0:c.prompt)||"").trim();m&&i.push({id:`u-${u}`,role:"user",content:m,ts:String((h==null?void 0:h.created_at)||"")||void 0});const p=nw(h),v=String((h==null?void 0:h.status)||"").toLowerCase();i.push(p?{id:`a-${u}`,role:"assistant",title:n,content:p,ts:String((h==null?void 0:h.updated_at)||"")||void 0}:{id:`a-${u}`,role:"assistant",title:n,level:"warn",content:v==="completed"?"This answer was empty.":`No answer: the run is ${v||"unknown"}.`})}return i}function kS(e){const[t,n]=y.useState(null);return e.state==="loading"?o.jsx("div",{className:"pc-docs-history__note",role:"status",children:"Loading past conversations…"}):e.state==="error"?o.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?o.jsx("ul",{className:"pc-docs-history","aria-label":"Past conversations",children:e.items.map(r=>o.jsx("li",{className:`pc-docs-history__row${r.sessionId===e.activeSessionId?" is-active":""}`,children:t===r.sessionId?o.jsxs("div",{className:"pc-docs-history__confirm",children:[o.jsx("span",{children:"Archive this conversation? It stays in the gateway; it leaves this list."}),o.jsx("button",{type:"button",className:"pc-docs-history__btn pc-docs-history__btn--danger",onClick:()=>{n(null),e.onArchive(r)},children:"Archive"}),o.jsx("button",{type:"button",className:"pc-docs-history__btn",onClick:()=>n(null),children:"Cancel"})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"pc-docs-history__open",onClick:()=>e.onOpen(r),title:r.title,children:[o.jsx("span",{className:"pc-docs-history__title",children:r.title}),o.jsxs("span",{className:"pc-docs-history__meta",children:[co(r.updatedAt,e.nowMs),r.runIds.length>1?` · ${r.runIds.length} questions`:""]})]}),o.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:o.jsx(re,{name:"archive",size:16})})]})},r.sessionId))}):o.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const jS=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function SS(e){const t=y.useRef(null),[n,r]=y.useState(!1),i=!!e.blockedNotice,c=!!e.busy,u=e.files||[],d=typeof e.onAddFiles=="function"&&!i,h=o.jsxs("div",{className:"pc-docs-assistant__empty",children:[o.jsxs("p",{className:"pc-docs-assistant__empty-text",children:["Ask anything about ",e.source.name,"."]}),e.suggestions&&e.suggestions.length?o.jsx("div",{className:"pc-docs-assistant__suggestions",children:e.suggestions.map(m=>o.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:c||i,onClick:()=>{var p;return(p=e.onSuggestion)==null?void 0:p.call(e,m)},children:m},m))}):null]});return o.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:m=>{var p;!d||!bi((p=m.dataTransfer)==null?void 0:p.types)||(m.preventDefault(),r(!0))},onDragLeave:()=>r(!1),onDrop:m=>{var v,_;if(!d)return;m.preventDefault(),r(!1);const p=Rf(m.dataTransfer);p.files.length&&((v=e.onAddFiles)==null||v.call(e,p.files)),p.folders.length&&((_=e.onNotice)==null||_.call(e,Vy(p.folders)))},children:[o.jsx(By,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:h,messageProps:{showCopy:!0}}),i?o.jsx("div",{className:"pc-docs-assistant__blocked",role:"status",children:e.blockedNotice}):null,e.notice?o.jsx("div",{className:"pc-docs-assistant__notice",role:"status",children:e.notice}):null,o.jsx("div",{className:"pc-docs-assistant__composer",children:o.jsx(Wy,{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:c,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:m=>{var v;if(!d)return;const p=Gy(m.clipboardData);p.length&&(m.preventDefault(),(v=e.onAddFiles)==null||v.call(e,p))},leading:u.length?o.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:u.map(m=>o.jsxs("span",{role:"listitem",className:"pc-chat-attachment-chip",children:[o.jsx(re,{name:"paperclip",size:14}),o.jsx("span",{className:"pc-chat-attachment-name",children:m.name}),e.onRemoveFile&&!c?o.jsx("button",{type:"button",className:"pc-docs-assistant__file-remove","aria-label":`Remove ${m.name}`,"data-af-tip":`Remove ${m.name}`,onClick:()=>{var p;return(p=e.onRemoveFile)==null?void 0:p.call(e,m.id)},children:o.jsx(re,{name:"x",size:12})}):null]},m.id))}):null,actions:o.jsxs(o.Fragment,{children:[d?o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Attach files","data-af-tip":"Attach files to your question",disabled:c,onClick:()=>{var m;return(m=t.current)==null?void 0:m.click()},children:o.jsx(re,{name:"paperclip",size:16})}),o.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:m=>{var v;const p=Array.from(m.currentTarget.files||[]);m.currentTarget.value="",p.length&&((v=e.onAddFiles)==null||v.call(e,p))}})]}):null,c&&e.onStop?o.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Stop","data-af-tip":"Stop the answer",onClick:e.onStop,children:o.jsx(re,{name:"stop",size:14})}):null]})})}),o.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 uc(){return new Date().toISOString()}function NS(e){fo();const{source:t}=e,n=y.useRef(e.fetchGateway);n.current=e.fetchGateway;const r=y.useMemo(()=>e.ask||_S({fetchGateway:(O,Z)=>n.current(O,Z),source:t}),[e.ask,t.app,t.name]),i=y.useRef(Ld(t.app)),[c,u]=y.useState([]),d=y.useRef(c);d.current=c;const[h,m]=y.useState(""),[p,v]=y.useState([]),[_,b]=y.useState(!1),[C,x]=y.useState(""),j=y.useRef(null),[N,$]=y.useState(!1),[S,E]=y.useState({state:"loading",items:[]});y.useEffect(()=>()=>{var O;return(O=j.current)==null?void 0:O.abort()},[]);const A=y.useCallback(async()=>{E(O=>({...O,state:"loading"}));try{const O=await bS((Z,R)=>n.current(Z,R),t.app);E({state:"ready",items:O})}catch(O){E({state:"error",items:[],error:String((O==null?void 0:O.message)||O)})}},[t.app]),I=y.useCallback(async O=>{var Z;(Z=j.current)==null||Z.abort(),E(R=>({...R,state:"loading"}));try{const R=await xS((q,z)=>n.current(q,z),O,t.name);i.current=O.sessionId,u(R),x(""),$(!1),E(q=>({...q,state:"ready"}))}catch(R){E(q=>({...q,state:"error",error:String((R==null?void 0:R.message)||R)}))}},[t.name]),F=y.useCallback(async O=>{try{const Z=await n.current(ve(`sessions/${encodeURIComponent(O.sessionId)}/archive`),{method:"POST"});if(!Z.ok)throw await po(Z,"The conversation could not be archived");i.current===O.sessionId&&(i.current=Ld(t.app),u([])),E(R=>({...R,items:R.items.filter(q=>q.sessionId!==O.sessionId)}))}catch(Z){E(R=>({...R,state:"error",error:String((Z==null?void 0:Z.message)||Z)}))}},[t.app]);y.useEffect(()=>{var O;e.connected||(O=j.current)==null||O.abort()},[e.connected]),y.useEffect(()=>()=>{for(const O of p)O.preview&&URL.revokeObjectURL(O.preview)},[]);const L=y.useCallback(O=>{x(""),v(Z=>[...Z,...O.map(R=>({id:ca(),file:R,preview:jS.test(R.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(R):void 0}))])},[]),J=y.useCallback(async O=>{const Z=String(O||"").trim();if(!Z||_||!e.connected)return;const R=p;m(""),v([]),x("");const q=R.filter(B=>B.preview).map(B=>({kind:"image",src:B.preview,label:B.file.name})),z=R.map(B=>({id:B.id,label:B.file.name,title:B.file.name,disabled:!0})),se={id:`u-${ca()}`,role:"user",content:Z,ts:uc(),...q.length?{media:q}:{},...z.length?{attachments:z}:{}},G=`a-${ca()}`,te=[...d.current,se],ue={id:G,role:"assistant",title:t.name,content:"",ts:uc(),live:{callId:G,reasoning:"",label:"answering"}};u([...te,ue]),b(!0);const ne=new AbortController;j.current=ne;const P=B=>u([...te,B]);try{const B=await r(Z,{signal:ne.signal,sessionId:i.current,files:R.map(W=>W.file),onText:W=>{ne.signal.aborted||P({...ue,content:W,live:{callId:G,reasoning:"",label:"streaming"}})},onHistory:W=>x(yS(W))});ne.signal.aborted||P({id:G,role:"assistant",title:t.name,content:B,ts:uc()})}catch(B){const W=ne.signal.aborted;P({id:G,role:"assistant",title:t.name,level:W?"warn":"error",content:W?"Stopped. Nothing more will be shown for this question.":String((B==null?void 0:B.message)||B||"The docs assistant failed."),ts:uc()})}finally{j.current===ne&&(j.current=null),b(!1)}},[r,_,p,e.connected,t.name]),V=()=>{var O;(O=j.current)==null||O.abort(),i.current=Ld(t.app),u([]),v([]),m(""),x("")};return o.jsxs(V_,{open:e.open,onClose:e.onClose,label:"Docs assistant",title:o.jsxs("span",{className:"pc-docs-assistant__title",children:[o.jsx(re,{name:"book",size:16}),"Docs assistant"]}),width:e.width||420,topOffset:e.topOffset,className:`pc-docs-assistant-drawer${e.className?` ${e.className}`:""}`,headerActions:o.jsxs(o.Fragment,{children:[o.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||_,onClick:()=>{const O=!N;$(O),O&&A()},children:o.jsx(re,{name:"history",size:16})}),o.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"New conversation","data-af-tip":"Start a new conversation",disabled:!c.length&&!h&&!p.length&&!N,onClick:()=>{V(),$(!1)},children:o.jsx(re,{name:"compose",size:16})})]}),children:[N?o.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:o.jsx(kS,{items:S.items,state:S.state,error:S.error,nowMs:Date.now(),activeSessionId:i.current,onOpen:O=>void I(O),onArchive:O=>void F(O)})}):null,o.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:o.jsx(SS,{source:t,messages:c,draft:h,onDraftChange:m,onSend:()=>void J(h),onStop:()=>{var O;return(O=j.current)==null?void 0:O.abort()},busy:_,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:p.map(O=>({id:O.id,name:O.file.name})),onAddFiles:L,onNotice:x,onRemoveFile:O=>v(Z=>{const R=Z.find(q=>q.id===O);return R!=null&&R.preview&&URL.revokeObjectURL(R.preview),Z.filter(q=>q.id!==O)}),notice:C,suggestions:e.suggestions,onSuggestion:O=>void J(O),placeholder:e.placeholder})})]})}const rt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},wc=e=>Array.isArray(e)?e.map(rt):[],Qe=e=>typeof e=="string"?e:"",ui=e=>Qe(e.runtime_call_id||e.call_uid),di=e=>Qe(e.call_id||e.id);function sw(e,t){const n=t.record,r=rt(n.effect);if(r.type!=="tool_calls")return[];const i=rt(n.result),c=wc(rt(r.payload).tool_calls),u=c.length||n.status!=="waiting"?c:wc(rt(rt(i.wait).details).tool_calls),d=wc(i.results),h=u.length?u:d,m=[];return h.forEach((p,v)=>{let _=ui(p)?d.filter(I=>ui(I)===ui(p)):[];!_.length&&di(p)&&u.filter(I=>di(I)===di(p)).length===1&&(_=d.filter(I=>di(I)===di(p)));const b=u.length?_.length===1?_[0]:u.length===d.length?d[v]:{}:p,C=ui(p)||ui(b)||`${Qe(n.idempotency_key)||Qe(n.step_id)||t.cursor}:${v}`,x=`${t.runId}:${C}`,j=e.get(x),N=Qe(p.name||b.name)||(j==null?void 0:j.name);if(!N)return;const $=n.status==="completed"||n.status==="failed",S=n.status==="failed"||b.success===!1||!!b.error,E=p.arguments??b.arguments??(j==null?void 0:j.arguments),A={...j,id:x,runId:t.runId,name:N,arguments:E,status:$?S?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof b.success=="boolean"?{success:b.success}:{},...b.output!==void 0||b.result!==void 0?{output:b.output??b.result}:{},...b.error?{error:String(b.error)}:{},...Pp(b)?{sandbox:Pp(b)}:{},startedAt:(j==null?void 0:j.startedAt)||Qe(n.started_at)||void 0,endedAt:$&&Qe(n.ended_at)||(j==null?void 0:j.endedAt)};j&&["completed","failed"].includes(j.status)&&!$||(e.set(x,A),m.push(A))}),m}function so(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function bs(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 rw(e){if(typeof e=="string")try{return rt(JSON.parse(e))}catch{return{}}return rt(e)}function Xa(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function CS(e){return bs(e,["reasoning_tokens","thinking_tokens"])??bs(rt(e.completion_tokens_details),["reasoning_tokens"])??bs(rt(e.output_tokens_details),["reasoning_tokens"])}function ES(e){const t=rt(typeof e=="string"&&e.trim().startsWith("{")?rw(e):e);return Qe(t.error_class)}function $S(e){const t=new Map;for(const n of e){const r=n.record;if(rt(r.effect).type!=="emit_event")continue;const i=rt(r.result);if(Qe(i.name)!=="abstract.progress")continue;const c=rt(i.payload);if(Qe(c.kind)!=="llm"||!Qe(c.step_id))continue;const u=`${Qe(c.run_id)||n.runId}:${Qe(c.step_id)}`,d=t.get(u)||{},h=so(c.ttft_s);h!==void 0&&(d.ttftS=h),d.provider=d.provider||Qe(c.provider)||void 0,d.model=d.model||Qe(c.model)||void 0,t.set(u,d)}return t}function Ni(e){var x,j,N,$;const t=new Map,n=new Set,r=new Set,i={llmCalls:0,toolCalls:0,changedFiles:[]};let c=1/0,u=-1/0,d=!1,h=0,m=0,p=0;const v=$S(e),_=[],b=new Set;for(const S of e){const E=S.record,A=`${S.runId}:${E.step_id||S.cursor}:${E.status}`;if(n.has(A))continue;n.add(A);for(const oe of[E.started_at,E.ended_at]){const we=Date.parse(Qe(oe));Number.isFinite(we)&&(c=Math.min(c,we),u=Math.max(u,we))}for(const oe of sw(t,S))oe.status==="waiting"&&b.add(oe.id);if(rt(E.effect).type!=="llm_call"||E.status!=="completed")continue;i.llmCalls+=1;const I=rt(E.result),F=rt(I.output),L=rt(I.usage||I.token_usage||I.tokens||F.usage||F.token_usage||F.tokens),J=bs(L,["input_tokens","prompt_tokens","prompt","input","in"]),V=bs(L,["output_tokens","completion_tokens","completion","output","out"]),O=bs(L,["total_tokens","total"])??(J!==void 0||V!==void 0?(J||0)+(V||0):void 0);O!==void 0&&(J===void 0||V===void 0||J+V!==O)&&(d=!0),J!==void 0&&(i.inputTokens=(i.inputTokens||0)+J),V!==void 0&&(i.outputTokens=(i.outputTokens||0)+V),O!==void 0&&(i.totalTokens=(i.totalTokens||0)+O);const Z=so(I.gen_time??F.gen_time);Z!==void 0&&(i.genTimeMs=(i.genTimeMs||0)+Z,i.timedCalls=(i.timedCalls||0)+1);const R=rt(I.metadata||F.metadata),q=rt(R.performance),z=so(q.prompt_tokens_per_second),se=so(q.generation_tokens_per_second),G=rt(R.prompt_cache),te=so(G.cached_tokens),ue=so(G.fed_tokens);if(z!==void 0||se!==void 0){if(i.measuredSpeedCalls=(i.measuredSpeedCalls||0)+1,z!==void 0&&z>0&&(i.promptTokensPerSecond=(i.promptTokensPerSecond||0)+z,J!==void 0)){const oe=J/z*1e3;i.prefillMs=(i.prefillMs||0)+oe,ue!==void 0&&(h+=ue,m+=oe)}se!==void 0&&se>0&&(i.generationTokensPerSecond=(i.generationTokensPerSecond||0)+se,V!==void 0&&(i.decodeMs=(i.decodeMs||0)+V/se*1e3))}if(te!==void 0||ue!==void 0){i.measuredCacheCalls=(i.measuredCacheCalls||0)+1,i.cachedTokens=(i.cachedTokens||0)+(te||0),i.fedTokens=(i.fedTokens||0)+(ue||0);const oe=Qe(G.outcome);if(oe){const we=i.cacheOutcomes||[];we.includes(oe)||we.push(oe),i.cacheOutcomes=we}}const ne=Qe(E.step_id)||void 0,P=ne&&v.get(`${S.runId}:${ne}`)||{},B=rt(I.route),W={runId:S.runId};ne&&(W.stepId=ne),Qe(E.started_at)&&(W.startedAt=Qe(E.started_at));const de=Qe(I.model||F.model)||Qe(B.model)||P.model,ee=Qe(B.provider)||Qe(rt(R._provider_request).provider)||P.provider||Qe(I.provider);de&&(W.model=de),ee&&(W.provider=ee),de&&(i.models=Xa(i.models,de)),ee&&(i.providers=Xa(i.providers,ee)),(O===void 0||J!==void 0&&V!==void 0&&J+V===O)&&(J!==void 0&&(W.inputTokens=J),V!==void 0&&(W.outputTokens=V)),O!==void 0&&(W.totalTokens=O);const le=CS(L);le!==void 0&&(W.reasoningTokens=le,i.reasoningTokens=(i.reasoningTokens||0)+le),te!==void 0&&(W.cachedTokens=te),ue!==void 0&&(W.fedTokens=ue),Qe(G.outcome)&&(W.cacheOutcome=Qe(G.outcome)),Qe(G.backend)&&(W.cacheBackend=Qe(G.backend),i.cacheBackends=Xa(i.cacheBackends,W.cacheBackend)),Z!==void 0&&(W.genTimeMs=Z),z!==void 0&&z>0&&(W.promptTokensPerSecond=z),se!==void 0&&se>0&&(W.generationTokensPerSecond=se),P.ttftS!==void 0?(W.ttftMs=P.ttftS*1e3,W.promptMs=W.ttftMs,W.promptSource="ttft",i.ttftMs=(i.ttftMs||0)+W.ttftMs,i.ttftCalls=(i.ttftCalls||0)+1):W.promptTokensPerSecond!==void 0&&J!==void 0&&(W.promptMs=J/W.promptTokensPerSecond*1e3,W.promptSource="rate"),W.promptMs!==void 0&&(i.promptPhaseMs=(i.promptPhaseMs||0)+W.promptMs,i.promptPhaseCalls=(i.promptPhaseCalls||0)+1,ue!==void 0&&W.promptMs>0&&(W.promptNewTokensPerSecond=ue/(W.promptMs/1e3),i.promptPhaseNewTokens=(i.promptPhaseNewTokens||0)+ue,p+=W.promptMs)),W.ttftMs!==void 0&&Z!==void 0&&Z>=W.ttftMs?W.generationMs=Z-W.ttftMs:W.generationTokensPerSecond!==void 0&&V!==void 0&&(W.generationMs=V/W.generationTokensPerSecond*1e3),W.generationMs!==void 0&&V!==void 0&&(i.generationPhaseMs=(i.generationPhaseMs||0)+W.generationMs,i.generationPhaseTokens=(i.generationPhaseTokens||0)+V);const fe=rt(R.speculation);if(Object.keys(fe).length){const oe={};Qe(fe.mode)&&(oe.mode=Qe(fe.mode)),typeof fe.used=="boolean"&&(oe.used=fe.used),Qe(fe.draft_kind)&&(oe.draftKind=Qe(fe.draft_kind));const we=bs(fe,["accepted_tokens"]),Oe=bs(fe,["drafted_tokens"]),Je=bs(fe,["rounds"]),st=bs(fe,["num_draft_tokens"]);we!==void 0&&(oe.acceptedTokens=we),Oe!==void 0&&(oe.draftedTokens=Oe),we!==void 0&&Oe&&(oe.acceptanceRate=we/Oe),Je!==void 0&&(oe.rounds=Je),st!==void 0&&(oe.draftLength=st),W.speculation=oe;const Ce=i.speculation||(i.speculation={calls:0,used:0});Ce.calls+=1,oe.used&&(Ce.used+=1),oe.mode&&(Ce.modes=Xa(Ce.modes,oe.mode)),oe.draftKind&&(Ce.draftKinds=Xa(Ce.draftKinds,oe.draftKind)),we!==void 0&&Oe!==void 0&&(Ce.acceptedTokens=(Ce.acceptedTokens||0)+we,Ce.draftedTokens=(Ce.draftedTokens||0)+Oe),Je!==void 0&&(Ce.rounds=(Ce.rounds||0)+Je),st!==void 0&&(Ce.draftLengths=Xa(Ce.draftLengths,st))}_.push(W)}_.length&&(_.every(S=>S.startedAt)&&_.sort((S,E)=>Date.parse(S.startedAt)-Date.parse(E.startedAt)),i.modelCalls=_),p>0&&i.promptPhaseNewTokens!==void 0&&(i.promptPhaseTokensPerSecond=i.promptPhaseNewTokens/(p/1e3)),i.generationPhaseMs&&i.generationPhaseTokens!==void 0&&(i.generationPhaseTokensPerSecond=i.generationPhaseTokens/(i.generationPhaseMs/1e3)),(x=i.speculation)!=null&&x.draftedTokens&&(i.speculation.acceptanceRate=(i.speculation.acceptedTokens||0)/i.speculation.draftedTokens),i.measuredSpeedCalls&&(i.promptTokensPerSecond!==void 0&&(i.promptTokensPerSecond/=i.measuredSpeedCalls),i.generationTokensPerSecond!==void 0&&(i.generationTokensPerSecond/=i.measuredSpeedCalls)),m>0&&(i.prefillNewTokens=h,i.prefillNewTokensPerSecond=h/(m/1e3));const C=new Map;for(const S of t.values()){if(S.status==="waiting"){i.toolsWaiting=(i.toolsWaiting||0)+1;continue}if(S.status==="running"){i.toolsRunning=(i.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(S.status))continue;i.toolCalls+=1;const E=S.status==="failed";E&&(i.toolsFailed=(i.toolsFailed||0)+1);const A=i.toolBreakdown||(i.toolBreakdown={}),I=A[S.name]||(A[S.name]={calls:0,failed:0});if(I.calls+=1,E){I.failed+=1;const O=ES(S.output);O&&((I.errors||(I.errors={}))[O]=(((j=I.errors)==null?void 0:j[O])||0)+1)}const F=Date.parse(Qe(S.startedAt)),L=Date.parse(Qe(S.endedAt));if(Number.isFinite(F)&&Number.isFinite(L)&&L>=F){const O=`${S.runId}|${S.startedAt}|${S.endedAt}`,Z=C.get(O)||{ms:L-F,calls:0,names:new Map,waited:!1};Z.calls+=1,Z.names.set(S.name,(Z.names.get(S.name)||0)+1),b.has(S.id)&&(Z.waited=!0),C.set(O,Z)}if(S.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(S.name))continue;const J=rw(S.arguments),V=Qe(J.destination||J.destination_path||J.file_path||J.path||J.filename);V&&r.add(V)}for(const S of C.values()){i.toolBatches=(i.toolBatches||0)+1,i.toolTimeMs=(i.toolTimeMs||0)+S.ms,S.waited&&(i.toolTimeIncludesApproval=!0);const E=[...S.names.keys()].sort();(!i.slowestToolBatch||S.ms>i.slowestToolBatch.ms)&&(i.slowestToolBatch={ms:S.ms,calls:S.calls,tools:E});const A=(N=i.toolBreakdown)==null?void 0:N[E[0]];if(E.length===1&&A)A.ms=(A.ms||0)+S.ms;else for(const I of E){const F=($=i.toolBreakdown)==null?void 0:$[I];F&&(F.sharedBatches=(F.sharedBatches||0)+1)}}return i.changedFiles=[...r],d&&(delete i.inputTokens,delete i.outputTokens),Number.isFinite(c)&&Number.isFinite(u)&&(i.durationMs=Math.max(0,u-c)),{tools:[...t.values()],statistics:i}}function AS(e){const t=rt(rt(e).ledgers);return Object.entries(t).flatMap(([n,r])=>wc(rt(r).items).map((i,c)=>({runId:n,cursor:Number(i.cursor)||c+1,record:Object.keys(rt(i.record)).length?rt(i.record):i})))}const Od=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};function TS(e){var x,j,N,$;const{tools:t,statistics:n}=Ni(e.records),r={toolCalls:n.toolCalls,totalTokens:n.totalTokens,startedAt:String(((x=e.run)==null?void 0:x.created_at)||"")||void 0},i=(S,E,A)=>({...r,label:S,detail:E,tone:A});if(e.loading)return i("Loading conversation","Restoring saved activity","neutral");if(["completed","failed","cancelled"].includes(e.status))return i(e.status==="completed"?"Completed":e.status==="failed"?"Run failed":"Stopped","",e.status==="failed"?"error":e.status==="completed"?"success":"neutral");if((e.connection==="reconnecting"||e.connection==="disconnected")&&(!((j=e.records)!=null&&j.length)||!!e.error))return i(e.connection==="reconnecting"?"Reconnecting":"Disconnected",String(e.error||"Live activity is unavailable"),"waiting");if(e.status==="paused"||((N=e.run)==null?void 0:N.paused)===!0)return i("Paused","Resume when you’re ready","waiting");const c=Od(($=e.interaction)==null?void 0:$.wait),u=Od(c.details),d=u.kind==="tool_approval"||u.mode==="approval_required",h=d&&e.toolApprovalGranted===!0;if(d&&!h)return i("Approval needed","Review the tool requests below","waiting");if(!d&&["user","ask_user"].includes(c.reason))return i("Your answer is needed",String(c.prompt||"The workflow has a question for you"),"waiting");if(!d&&(c.reason==="event"||String(c.wait_key||"").startsWith("evt:")))return i("Waiting for an event",String(c.prompt||"Listening for the workflow’s trigger"),"waiting");const m=t.filter(S=>{var E;return S.status==="running"||h&&S.status==="waiting"&&S.runId===((E=e.interaction)==null?void 0:E.runId)});if(m.length)return i(m.length===1?"Running a tool":`Running ${m.length} tools`,[...new Set(m.map(S=>S.name))].join(" · "),"working");const p=new Map;for(const S of e.records){const E=`${S.runId}:${S.record.step_id||S.record.idempotency_key||S.cursor}`,A=p.get(E);A&&["completed","failed"].includes(String(A.record.status))||p.set(E,S)}if([...p.values()].reverse().find(S=>Od(S.record.effect).type==="llm_call"&&["started","running"].includes(String(S.record.status))))return i("Thinking","Generating the next response","working");const _=e.displayStatus.trim(),b=!/^(completed|complete|done|finished|ready|success|succeeded|failed|running|working|waiting|thinking|idle|paused|stopped|cancelled)$/i.test(_)&&!_.startsWith("{")?_:"",C=t[t.length-1];return i(e.status==="idle"?"Ready":"Working",b||(C?`Last tool: ${C.name} · ${C.status==="failed"?"failed":C.status==="completed"?"done":"waiting"}`:"Following the workflow"),e.status==="idle"?"neutral":"working")}function RS(e,t){if(e.kind==="ask-user"){if(t.kind==="choice"||t.kind==="free-text")return e.onSubmit(t.answer);throw new Error("Invalid submission for ask-user interaction")}if(e.kind==="tool-approval"){if(t.kind==="approve")return e.onApprove();if(t.kind==="deny")return e.onDeny();if(t.kind==="approve-all"&&e.onApproveAll)return e.onApproveAll();throw new Error("Invalid submission for tool-approval interaction")}if(t.kind==="event")return e.onSend(t.payload);throw new Error("Invalid submission for event-wait interaction")}function IS(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function MS(e){return o.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[o.jsxs("span",{children:["Could not complete that action: ",e.message]}),o.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}function LS(e){var F;const t=e.interaction,[n,r]=y.useState(""),[i,c]=y.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[u,d]=y.useState(null),[h,m]=y.useState(!1),[p,v]=y.useState(""),[_,b]=y.useState(null),C=`${t.kind}:${t.id}`,x=y.useRef(C),j=y.useRef(!1),N=y.useRef(!1),$=y.useRef(!0),S=y.useRef(0);x.current!==C&&(x.current=C,j.current=!1,N.current=!1,S.current+=1);const E=!!e.disabled||u!==null||h||j.current||N.current,A=async(L,J)=>{var Z;if(e.disabled||j.current||N.current)return;const V=C,O=++S.current;j.current=!0,b(null),v(""),d(L);try{if(await J(),!$.current||x.current!==V||S.current!==O)return;N.current=!0,m(!0),v("Response sent. Waiting for the workflow to continue.")}catch(R){if(!$.current||x.current!==V||S.current!==O)return;b({submission:L,message:IS(R)}),v("The action failed. You can try again."),(Z=e.onError)==null||Z.call(e,R)}finally{if(!$.current||x.current!==V||S.current!==O)return;j.current=!1,d(null)}};y.useEffect(()=>{r(""),c(t.kind==="event-wait"&&t.initialPayload||""),b(null),d(null),m(!1),v("")},[C]),y.useEffect(()=>($.current=!0,()=>{$.current=!1,S.current+=1,j.current=!1}),[]);const I=()=>{_&&A(_.submission,()=>RS(t,_.submission))};return o.jsxs("section",{className:"pc-workflow-interaction","aria-labelledby":`pc-workflow-interaction-${C}`,children:[o.jsxs("div",{className:"pc-workflow-interaction__heading",children:[o.jsx(re,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:16}),o.jsxs("div",{children:[o.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${C}`,children:t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required")}),t.description?o.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),t.kind==="ask-user"?o.jsxs("div",{className:"pc-workflow-interaction__body",children:[o.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(F=t.choices)!=null&&F.length?o.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(L=>o.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice",disabled:E||L.disabled,onClick:()=>void A({kind:"choice",answer:L.id},()=>t.onSubmit(L.id)),children:[o.jsx("span",{children:L.label}),L.description?o.jsx("small",{children:L.description}):null]},L.id))}):null,t.allowFreeText!==!1?o.jsxs("div",{className:"pc-workflow-interaction__entry",children:[o.jsx("textarea",{"aria-label":"Response",value:n,onChange:L=>r(L.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:2,disabled:E,onKeyDown:L=>{L.key!=="Enter"||L.shiftKey||L.nativeEvent.isComposing||L.keyCode===229||(L.preventDefault(),n.trim()&&A({kind:"free-text",answer:n},()=>t.onSubmit(n)))}},`${C}:text`),o.jsx("button",{type:"button",className:"pc-btn",disabled:E||!n.trim(),onClick:()=>void A({kind:"free-text",answer:n},()=>t.onSubmit(n)),children:(u==null?void 0:u.kind)==="free-text"?"Sending…":t.submitLabel||"Submit"})]}):null]}):t.kind==="tool-approval"?o.jsxs("div",{className:"pc-workflow-interaction__body",children:[o.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",o.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?o.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,o.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[o.jsx("button",{type:"button",className:"pc-workflow-interaction__deny",disabled:E,onClick:()=>void A({kind:"deny"},t.onDeny),children:(u==null?void 0:u.kind)==="deny"?"Denying…":t.denyLabel||"Deny"}),o.jsx("button",{type:"button",className:"pc-btn",disabled:E,onClick:()=>void A({kind:"approve"},t.onApprove),children:(u==null?void 0:u.kind)==="approve"?"Approving…":t.approveLabel||"Approve"}),t.onApproveAll?o.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all",disabled:E,onClick:()=>void A({kind:"approve-all"},t.onApproveAll),children:(u==null?void 0:u.kind)==="approve-all"?"Approving…":t.approveAllLabel||"Allow all"}):null]}),t.onApproveAll&&t.approveAllDescription?o.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]}):o.jsxs("div",{className:"pc-workflow-interaction__body",children:[o.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),o.jsxs("label",{className:"pc-workflow-interaction__entry",children:[o.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),o.jsx("textarea",{value:i,onChange:L=>c(L.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:E},`${C}:payload`)]}),o.jsx("div",{className:"pc-workflow-interaction__buttons",children:o.jsx("button",{type:"button",className:"pc-btn",disabled:E,onClick:()=>void A({kind:"event",payload:i},()=>t.onSend(i)),children:(u==null?void 0:u.kind)==="event"?"Sending…":t.sendLabel||"Send event"})})]}),_?o.jsx(MS,{message:_.message,onRetry:I,disabled:E}):null,o.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:p})]})}function dc(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function OS(e){fo();const[t,n]=y.useState(!1),[r,i]=y.useState(!1),[c,u]=y.useState(!1),[d,h]=y.useState(null),m=y.useRef(!0),p=y.useRef(!1),v=y.useRef(!1),_=y.useRef(!1),b=y.useRef(0),C=y.useRef(0),x=y.useRef(0);y.useEffect(()=>(m.current=!0,()=>{m.current=!1,b.current+=1,C.current+=1,x.current+=1,p.current=!1,v.current=!1,_.current=!1}),[]);const j=!!e.blockedNotice,N=!!e.disabled||j,$=!!e.busy||t,S=t||!!e.busy&&!e.sendWhileBusy,E=e.stopState||null,A=(E==null?void 0:E.phase)==="stopping",I=typeof e.onFiles=="function",F=y.useRef(null),[L,J]=y.useState(null),[V,O]=y.useState(""),Z=y.useRef(e.onFiles);Z.current=e.onFiles;const R=y.useRef(N);R.current=N;const q=async(W,de)=>{const ee=Z.current;if(ee){if(R.current){h({action:"attach",message:"attachments are unavailable right now."});return}if(de.length)h({action:"attach",message:Vy(de)});else if(W.length)h(null);else{h({action:"attach",message:"the drop contained no files."});return}if(W.length){O(`Attaching ${W.length} ${W.length===1?"file":"files"}…`);try{await ee(W)}catch(le){m.current&&h({action:"attach",message:dc(le)})}}}},z=y.useRef(q);z.current=q,y.useEffect(()=>{if(!I||typeof window>"u")return;const W=new Pj;let de=0;const ee=Ce=>!!(F.current&&Ce instanceof Node&&F.current.contains(Ce)),le=()=>{W.reset(),de&&window.clearInterval(de),de=0,J(null)},fe=()=>{de||(de=window.setInterval(()=>{W.active(Date.now())||le()},250))},oe=Ce=>{var Ve;if(!bi((Ve=Ce.dataTransfer)==null?void 0:Ve.types))return;W.enter(Date.now());const Ye=ee(Ce.target),he=Fp(Ce.dataTransfer);J(ae=>ae&&ae.over===Ye&&ae.count===(he??ae.count)?ae:{count:he??(ae==null?void 0:ae.count)??null,over:Ye}),fe()},we=Ce=>{var he;if(!bi((he=Ce.dataTransfer)==null?void 0:he.types))return;Ce.preventDefault(),W.over(Date.now());const Ye=ee(Ce.target);Ce.dataTransfer&&(Ce.dataTransfer.dropEffect=Ye&&!R.current?"copy":"none"),J(Ve=>Ve&&Ve.over===Ye?Ve:{count:(Ve==null?void 0:Ve.count)??Fp(Ce.dataTransfer),over:Ye}),fe()},Oe=Ce=>{var Ye;bi((Ye=Ce.dataTransfer)==null?void 0:Ye.types)&&(W.leave(Date.now())||le())},Je=Ce=>{var Te;if(!bi((Te=Ce.dataTransfer)==null?void 0:Te.types))return;const Ye=ee(Ce.target),he=Ce.defaultPrevented&&!Ye;if(Ce.preventDefault(),le(),he)return;if(!Ye){h({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:Ve,folders:ae}=Rf(Ce.dataTransfer);z.current(Ve,ae)},st=Ce=>{Ce.key==="Escape"&&W.depth>0&&le()};return window.addEventListener("dragenter",oe),window.addEventListener("dragover",we),window.addEventListener("dragleave",Oe),window.addEventListener("drop",Je),window.addEventListener("dragend",le),window.addEventListener("blur",le),window.addEventListener("keydown",st),()=>{window.removeEventListener("dragenter",oe),window.removeEventListener("dragover",we),window.removeEventListener("dragleave",Oe),window.removeEventListener("drop",Je),window.removeEventListener("dragend",le),window.removeEventListener("blur",le),window.removeEventListener("keydown",st),de&&window.clearInterval(de)}},[I]);const se=W=>{if(!I||N)return;const de=Gy(W.clipboardData);de.length&&(W.preventDefault(),q(de,[]))},G=L?o.jsxs("div",{className:["pc-workflow-chat__dropzone",L.over?"is-over":"",N?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[o.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:o.jsx(re,{name:"paperclip",size:18})}),o.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[o.jsx("strong",{children:N?"Attachments are unavailable right now":zp(L.count)}),N?null:o.jsx("span",{children:L.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,te=L?N?"Attachments are unavailable right now":zp(L.count):V,ue=async()=>{const W=String(e.draft||"");if(N||p.current||!e.sendWhileBusy&&e.busy||!W.trim())return;const de=++b.current;p.current=!0,h(null),n(!0);try{await e.onSend(W)}catch(ee){m.current&&b.current===de&&h({action:"send",message:dc(ee)})}finally{m.current&&b.current===de&&(p.current=!1,n(!1))}},ne=async()=>{if(N||v.current||!e.onCancel)return;const W=++C.current;v.current=!0,h(null),i(!0);try{await e.onCancel()}catch(de){m.current&&C.current===W&&h({action:"cancel",message:dc(de)})}finally{m.current&&C.current===W&&(v.current=!1,i(!1))}},P=async()=>{if(N||_.current||!e.onAttach)return;const W=++x.current;_.current=!0,h(null),u(!0);try{await e.onAttach()}catch(de){m.current&&x.current===W&&h({action:"attach",message:dc(de)})}finally{m.current&&x.current===W&&(_.current=!1,u(!1))}},B=()=>{d&&(d.action==="send"&&ue(),d.action==="cancel"&&ne(),d.action==="attach"&&P())};return o.jsxs("section",{ref:F,className:["pc-workflow-chat",L?"pc-workflow-chat--dragging":"",L!=null&&L.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?o.jsx("header",{className:"pc-workflow-chat__header",children:e.header}):null,o.jsx("div",{className:"pc-workflow-chat__transcript",children:o.jsx(By,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:o.jsxs(o.Fragment,{children:[e.interaction?o.jsx(LS,{interaction:e.interaction,disabled:N}):null,j?o.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${j?"blocked":""}`})}),d?o.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[o.jsxs("span",{children:["Could not ",d.action==="send"?"send this message":d.action==="attach"?"attach a file":"stop the run",": ",d.message]}),o.jsx("button",{type:"button",onClick:B,disabled:N,children:"Try again"})]}):null,o.jsxs("div",{className:"pc-workflow-chat__composer",children:[o.jsx(Wy,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void ue(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:N,busy:S,sendLabel:e.sendLabel,busyLabel:e.busyLabel,rows:2,leading:e.attachments?o.jsx("div",{className:"pc-workflow-chat__attachments",children:e.attachments}):null,overlay:G,onPaste:I?se:void 0,actions:o.jsxs(o.Fragment,{children:[e.onAttach?o.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file","data-af-tip":"Attach a file",disabled:N||c,onClick:()=>void P(),children:[o.jsx(re,{name:"paperclip",size:16}),o.jsx("span",{children:c?"Attaching…":"Attach"})]}):null,e.composerExtras,$&&e.onCancel?o.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:N||r||A,onClick:()=>void ne(),children:[o.jsx(re,{name:"x",size:14}),o.jsx("span",{children:r||A?"Stopping…":"Stop"})]}):E?o.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${E.phase}`,role:"status","aria-live":"polite",children:E.label}):null]})}),I?o.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:te}):null]}),e.footer?o.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function PS(e){return e.toolApprovalGranted?null:e.interaction}const Up={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Fe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Le(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function ki(e){return Array.isArray(e)?e:[]}function pn(e){return Le(e==null?void 0:e.status).toLowerCase()||"unknown"}function Mt(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Sr(e){const t=Fe(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function DS(e){const t=Fe(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Pd(e){const t=n=>{if(Array.isArray(n))return n.map(t);const r=Fe(n);if(!r)return n;const i={};for(const c of Object.keys(r).sort())i[c]=t(r[c]);return i};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function gf(e){if(typeof e=="string")return e.trim();const t=Fe(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 qa(e){const t=gf(e);if(t)return t;if(!Fe(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Bp(e){if(!e)return"";for(const r of["prompt","request","task","message","query","input"]){const i=Le(e[r]);if(i)return i}const t=Fe(e.context);for(const r of["task","message"]){const i=Le(t==null?void 0:t[r]);if(i)return i}const n=ki(t==null?void 0:t.messages);for(let r=n.length-1;r>=0;r-=1){const i=Fe(n[r]);if(Le(i==null?void 0:i.role).toLowerCase()!=="user")continue;const c=Le(i==null?void 0:i.content);if(c)return c}return""}function aw(e){const t=Fe(e.result);return Fe(t==null?void 0:t.wait)}function Dd(e){return e?Le(e.reason)==="subworkflow"||Le(e.wait_key).startsWith("subworkflow:"):!1}function Wp(e,t){return!!(e&&e.runId===t.runId&&Le(e.wait.wait_key)===Le(t.wait.wait_key))}function yf(e){return Fe(e.effect)||{}}function FS(e,t){return Le(e.run_id)||t}function Vp(e){return Le(e.ended_at)||Le(e.started_at)||void 0}function Gp(e){const t=new Set,n=m=>{const p=Le(m);p&&t.add(p)},r=Fe(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=yf(e),c=Fe(i.payload);Le(i.type)==="start_subworkflow"&&(n(c==null?void 0:c.sub_run_id),n(c==null?void 0:c.subRunId),n(c==null?void 0:c.child_run_id));const u=aw(e),d=Fe(u==null?void 0:u.details);n(d==null?void 0:d.sub_run_id),n(d==null?void 0:d.subRunId),n(d==null?void 0:d.child_run_id);const h=Le(u==null?void 0:u.wait_key);return h.startsWith("subworkflow:")&&n(h.slice(12)),[...t]}class zS{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Up},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0;const r=n.liveRenderIntervalMs??60;if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=r}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}getSnapshot(){return this.snapshot}reset(){var t;this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.approvalEpoch+=1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps.clear(),this.forcedStop=null,this.generation+=1,(t=this.controller)==null||t.abort(),this.controller=null,this.rootRunId="",this.cursors.clear(),this.seenRecords.clear(),this.seenMessages.clear(),this.watchedRuns.clear(),this.childCatchUpAttempts.clear(),this.runStates.clear(),this.historicalRuns.clear(),this.historicalRunFailures.clear(),this.commandIds.clear(),this.toolActivities.clear(),this.historicalEvidence.clear(),this.approvedWaits.clear(),this.grantedToolWaits.clear(),this.resolvedWaits.clear(),this.liveReplies.clear(),this.closedLiveCalls.clear(),this.shownLiveCalls.clear(),this.liveDirty.clear(),this.lastLiveRender=-1/0,this.liveRenderTimer&&(clearTimeout(this.liveRenderTimer),this.liveRenderTimer=null),this.set({...Up})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=Le(t);if(this.reset(),!n)return;const r=++this.generation,i=new AbortController;this.controller=i,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{const[c,u]=await Promise.all([this.transport.getRun(n,i.signal),this.transport.getHistory(n,i.signal)]);if(!this.live(r))return;const d=Fe(c),h=Fe(d==null?void 0:d.waiting),m=pn(d);if(await this.ingestHistory(u,n,r),!this.live(r))return;if(this.set({...this.snapshot,run:d,status:m,loading:!1,...h&&!Mt(m)?{interaction:this.interactionWith({runId:n,wait:h})}:{}}),d&&this.updateRunState(n,d),h)for(const p of Gp({result:{wait:h}}))p!==n&&this.catchUpAndWatch(p,r);await this.catchUpAndWatch(n,r),this.pollRootLifecycle(n,r)}catch(c){!i.signal.aborted&&this.live(r)&&this.fail(c)}}async sendCommand(t,n={}){var p,v;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const r=Le(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 c=t==="resume"&&r&&((p=this.snapshot.interaction)==null?void 0:p.stepId)||"",u=`${i}\0${t}\0${c}\0${Pd(n)}`;let d=this.commandIds.get(u);d||(d=this.newCommandId(),this.commandIds.set(u,d));const h=this.generation,m=(v=this.controller)==null?void 0:v.signal;try{const _=await this.transport.submitCommand({command_id:d,run_id:i,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},m);if(!this.live(h))return _;const b=Fe(_);if(b&&b.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Le(b.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),i===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(i,h),_}catch(_){throw this.live(h)&&this.fail(_,!1),_}}resume(t){const n=this.requireInteraction();return this.sendCommand("resume",{wait_key:Le(n.wait.wait_key),payload:{response:t}})}approve(t,n){const r=this.requireInteraction();if(Mt(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(r.runId!==n.runId||Le(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:Le(r.wait.wait_key),payload:{approved:!!t}}).then(c=>{if(!this.live(i))return c;const u=this.occurrenceKey(r);return this.approvedWaits.add(u),t&&this.isToolApproval(r)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),c})}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||Mt(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||Mt(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){Pd(t)!==Pd(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}:${Le(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&Dd(t.wait)&&!Dd(n.wait)?n:n&&Wp(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const r=Fe(n.waiting);if(!r||pn(n)!=="waiting"||Dd(r)||Mt(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Le(r.wait_key)}`))return;const i=this.interactionWith({runId:t,wait:r}),c=this.snapshot.interaction;c&&Wp(c,i)&&c.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||Mt(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:!!Le(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 c=!1;const u=t.messages.map(d=>{var p;const h=d.toolActivity;if(!h||((p=this.toolActivities.get(h.id))==null?void 0:p.status)!=="waiting")return d;const m=i&&h.runId===(n==null?void 0:n.runId)?"running":"waiting";return h.status===m?d:(c=!0,this.toolMessage({...h,status:m}))});return{...t,toolApprovalGranted:i,...c?{messages:u}:{}}}toolCallsMatch(t,n){var i;const r=ki((i=Fe(t.wait.details))==null?void 0:i.tool_calls);return r.length>0&&r.every(c=>{var d;const u=Le((d=Fe(c))==null?void 0:d.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=Fe(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:Le(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,c=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(i)){if(this.grantedToolWaits.delete(r),c!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(u,!1)}})}emitEvent(t){return this.sendCommand("emit_event",t)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!Le(this.snapshot.interaction.wait.wait_key))throw new Error("The workflow wait has no wait_key");return this.snapshot.interaction}interactionRunId(){var t;return((t=this.snapshot.interaction)==null?void 0:t.runId)||""}live(t){var n;return t===this.generation&&!((n=this.controller)!=null&&n.signal.aborted)}set(t){this.snapshot=this.present(t);for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async catchUpAndWatch(t,n){var r;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const i=Fe(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(Sr(i))throw i;this.fail(i,!1)}if(await this.catchUp(t,n),!this.live(n)||Mt(pn(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(Sr(i)){this.fail(i);return}const c=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,c),this.fail(i,!1),c>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(c-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 c=this.cursors.get(t)||0,u=await this.transport.getLedger(t,c,(r=this.controller)==null?void 0:r.signal);if(!this.live(n))return;const d=Fe(u),h=Array.isArray(u)?u:ki(d==null?void 0:d.items);for(const p of h)this.ingestItem(t,p);const m=Number(d==null?void 0:d.next_after);if(!h.length||!Number.isFinite(m)||m<=c)break;this.cursors.set(t,m)}}async watch(t,n){try{await this.followStream(t,n)}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async followStream(t,n){var i;let r=0;for(;this.live(n)&&!Mt(pn(this.runStates.get(t)||null));){const c=this.cursors.get(t)||0;this.set({...this.snapshot,connection:r?"reconnecting":"connecting"});try{let u=!1;const d=()=>{!this.live(n)||u||(u=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(t),await this.transport.streamLedger(t,c,m=>{this.live(n)&&(d(),this.ingestItem(t,m))},this.controller.signal,d,m=>{this.live(n)&&(d(),this.ingestDelta(t,m))}),!this.live(n)||(await this.catchUp(t,n),!this.live(n)))return;const h=Fe(await this.transport.getRun(t,(i=this.controller)==null?void 0:i.signal));if(!this.live(n))return;h&&this.updateRunState(t,h),r+=1}catch(u){if(!this.live(n))return;if(r+=1,this.fail(u,!1),Sr(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(r>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(r-1)))}if(this.live(n)){if(Mt(pn(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=Fe(t);if(!i)return;const c=Fe(i.session),u=ki(c==null?void 0:c.turns).map(Fe).filter(m=>!!m);if(await this.hydrateHistoricalSessionRuns(u,n,r),!this.live(r))return;for(const m of u){const p=Le(m==null?void 0:m.run_id)||n;this.ingestSessionTurn(m,n,p!==n&&this.historicalRuns.get(p)||null)}const d=`turn:${n}:user`;if(!this.seenMessages.has(d)){const m=Bp(Fe(i.input_data));m&&this.addMessage({id:d,role:"user",content:m})}const h=Fe(i.ledgers);if(h)for(const[m,p]of Object.entries(h)){const v=Fe(p);for(const _ of ki(v==null?void 0:v.items))this.ingestItem(m,_)}}ingestSessionTurn(t,n,r){if(!t)return;const i=Le(t.run_id)||n,c=Fe(t.input_data)||Fe(t.input)||{},u=Le(t.prompt)||Bp(c);u&&this.addMessage({id:`turn:${i}:user`,role:"user",content:u,ts:Le(t.created_at)||void 0});const d=this.historicalRunFailures.get(i);if(d){const v=Le(t.answer)||gf(t.output),_=d.missing?"is unavailable because the run no longer exists":"could not be restored",b=v?` Saved reply (not verified as the final result): ${v}`:"";this.addMessage({id:`history:${i}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${_}.${b}`});return}const m=(r&&Mt(pn(r))?qa(r.output):"")||(r?Le(t.answer)||gf(t.output):""),p=this.historicalEvidence.get(i);for(const v of(p==null?void 0:p.tools)||[])this.upsertTool(v);m&&this.addRunAssistantMessage(i,{id:`final:${i}`,role:"assistant",content:m,runId:i,statistics:p==null?void 0:p.statistics,ts:Le(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,r){const i=[...new Set(t.map(h=>Le(h.run_id)).filter(h=>h&&h!==n&&!this.historicalRuns.has(h)&&!this.historicalRunFailures.has(h)))];if(!i.length||!this.live(r))return;let c=0,u=!1;const d=async()=>{var h,m,p;for(;!u&&this.live(r);){const v=i[c++];if(!v)return;try{const _=Fe(await this.transport.getRun(v,(h=this.controller)==null?void 0:h.signal));if(!this.live(r))return;if(_){this.historicalRuns.set(v,_);try{const b=await this.transport.getHistory(v,(m=this.controller)==null?void 0:m.signal);if(!this.live(r))return;this.historicalEvidence.set(v,Ni(AS(b)))}catch(b){if(!this.live(r))return;if(Sr(b))throw b;this.fail(new Error(`Earlier turn activity could not be restored: ${b instanceof Error?b.message:String(b)}`),!1)}}else this.historicalRuns.set(v,null),this.historicalRunFailures.set(v,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(_){if(!this.live(r))return;const b=DS(_)===404;this.historicalRuns.set(v,null),this.historicalRunFailures.set(v,{missing:b,detail:_ instanceof Error?_.message:Le((p=Fe(_))==null?void 0:p.detail)||"request failed"}),Sr(_)&&(u=!0,this.fail(_))}}};if(await Promise.all(Array.from({length:Math.min(4,i.length)},()=>d())),u&&this.live(r))for(const h of i)!this.historicalRuns.has(h)&&!this.historicalRunFailures.has(h)&&(this.historicalRuns.set(h,null),this.historicalRunFailures.set(h,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const r=Fe(n),i=Fe(r==null?void 0:r.record)||r;if(!i)return;const c=FS(i,t),u=Number(r==null?void 0:r.cursor),d=Number.isFinite(u)&&u>0?u:(this.cursors.get(c)||0)+1,h=`${c}:${d}`;if(!this.seenRecords.has(h)){if(this.seenRecords.add(h),this.cursors.set(c,Math.max(this.cursors.get(c)||0,d)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:d,record:i,runId:c}]}),this.foldRecord(c,i,h),this.snapshot.messages.some(m=>m.id===`final:${this.rootRunId}`)){const m=Ni(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(p=>p.id===`final:${this.rootRunId}`?{...p,statistics:m}:p)})}for(const m of Gp(i))m!==c&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,r){var p,v,_;const i=yf(n),c=Le(i.type).toLowerCase(),u=Fe(n.result),d=Le(n.status).toLowerCase(),h=Vp(n);if(this.foldStopEvidence(t,n,c,d),["llm_call","tool_calls"].includes(c)&&["started","running"].includes(d)){const b=Date.parse(h||"");(!Number.isFinite(b)||b>=this.displayStatusAt)&&(Number.isFinite(b)&&(this.displayStatusAt=b),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(c==="answer_user"&&d==="completed"){const b=qa(u)||qa(Fe(i.payload));b&&this.addRunAssistantMessage(t,{id:`answer:${t}:${r}`,role:"assistant",content:b,ts:h})}if(c==="emit_event"&&d==="completed"){const b=Fe(i.payload)||{},C=Fe(u),x=Le(b.name)||Le(C==null?void 0:C.name),j=b.payload!==void 0?b.payload:C==null?void 0:C.payload;if(["abstract.message","abstractcode.message"].includes(x)){const N=qa(j);if(N){const $=Le((p=Fe(j))==null?void 0:p.level).toLowerCase(),S=$==="error"?"error":["warn","warning"].includes($)?"warn":"info";this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Workflow",content:N,level:S,ts:h})}}if(["abstract.status","abstractcode.status"].includes(x)){const N=Fe(j),$=N?N.status??N.text??N.value:j,S=Date.parse(h||"");!Mt(this.snapshot.status)&&typeof $=="string"&&(!Number.isFinite(S)||S>=this.displayStatusAt)&&(Number.isFinite(S)&&(this.displayStatusAt=S),this.set({...this.snapshot,displayStatus:$.trim()}))}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(x)){const N=qa(j);N&&this.addMessage({id:`event:${t}:${r}`,role:"system",title:"Tool activity",content:N,ts:h})}}const m=aw(n);if(d==="waiting"&&m&&!Mt(this.snapshot.status)&&!Mt(pn(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Le(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...Le(n.step_id)?{stepId:Le(n.step_id)}:{}})})),c==="tool_calls")for(const b of sw(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(b);if(c==="resume"&&(u==null?void 0:u.resumed)===!0){const b=Le((v=Fe(i.payload))==null?void 0:v.wait_key);b&&this.resolvedWaits.add(`${t}:${b}`),((_=this.snapshot.interaction)==null?void 0:_.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,r,i){let c=!1;if(r==="llm_call"){const u=Le(n.step_id);if(u){const d=`${t}:${u}`;i==="started"?(this.openLlmSteps.add(d),c=!0):["completed","failed","cancelled","waiting"].includes(i)&&(c=this.openLlmSteps.delete(d)||c),["completed","failed","cancelled"].includes(i)&&this.closeLiveReply(d)}}if(r==="emit_event"&&i==="completed"){const u=Fe(yf(n).payload)||{},d=Fe(n.result),h=Le(u.name)||Le(d==null?void 0:d.name),m=Fe(u.payload!==void 0?u.payload:d==null?void 0:d.payload);h==="abstract.status"&&Le(m==null?void 0:m.killed_by)==="kill_switch"&&(this.forcedStop=m,c=!0)}c&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:Le(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 c=[this.rootRunId,...[...this.watchedRuns].filter(d=>d!==this.rootRunId)];let u=!1;for(const d of c)try{await this.catchUp(d,t)}catch(h){u=!0,this.live(t)&&(this.fail(h,!1),i=this.snapshot.error)}!u&&i&&this.snapshot.error===i&&(this.set({...this.snapshot,error:null}),i=null),r=Math.min(5e3,r*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=Le(t.id)||`${t.role}:${t.content}:${t.ts||""}`;this.seenMessages.has(n)||(this.seenMessages.add(n),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...t,id:n}]}))}toolMessage(t){return{id:`tool:${t.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:t.runId,toolActivity:t,content:JSON.stringify({tool:t.name,status:t.status,arguments:t.arguments,output:t.output,error:t.error},null,2),ts:t.endedAt||t.startedAt}}upsertTool(t){const n=this.toolMessage(t),r=this.snapshot.messages.findIndex(c=>c.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(c=>c.role==="assistant"&&c.content===n.content&&(c.id===i||String(c.id||"").startsWith(r)))||this.addMessage(n)}ingestDelta(t,n){let r;try{r=Ky(n)}catch(h){this.fail(h,!1);return}const i=`${r.run_id}:${r.call_id}`;if(Hy(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 c=this.liveReplies.get(i)||{runId:r.run_id,callId:r.call_id,nodeId:r.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=r.channel==="reasoning"?"reasoning":"text",d=c.seq[r.channel];if(r.snapshot){if(r.seq<d)return;c[u]=r.text}else{if(r.seq<=d)return;c[u]+=r.text}c.seq[r.channel]=r.seq,c.via=t,this.liveReplies.set(i,c),this.liveDirty.add(i),this.scheduleLiveRender()}runEnded(t){return Mt(pn(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),c=t.findIndex(u=>u.id===i.id);c<0?t.push(i):t[c]=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}`,c=this.snapshot.messages.findIndex(d=>d.id===i);if(c<0)return;const u=[...this.snapshot.messages];if(n==="restarted"){const d=this.restartNote(t);this.seenMessages.add(String(d.id)),u[c]=d}else if(n){const d=`live-end:${r.runId}:${r.callId}`;this.seenMessages.add(d),u[c]={id:d,role:"system",level:"warn",title:"Reply",runId:r.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else u.splice(c,1);this.set({...this.snapshot,messages:u})}restartNote(t){const n=t.slice(0,t.indexOf(":"));return{id:`live-end:${t}`,role:"system",level:"info",title:"Reply",runId:n,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(t){const n=`${t.run_id}:${t.call_id}`;this.closeLiveReply(n),this.addMessage({id:`stream-unavailable:${t.run_id}:${t.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:t.run_id,content:Bj(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,c;Sr(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:Le((c=Fe(t))==null?void 0:c.detail)||String(t),...Sr(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 c;if(this.runStates.set(t,n),Mt(pn(n))&&this.endLiveRepliesOfRun(t,pn(n)),t!==this.rootRunId){Mt(pn(n))&&((c=this.snapshot.interaction)==null?void 0:c.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const r=pn(n),i=Mt(r);if(i){const u=qa(n.output);u&&this.upsertFinal(t,u,Vp(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 c={id:i,role:"assistant",content:n,ts:r,runId:t,statistics:Ni(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(h=>h.id===i||String(h.id||"").startsWith(`answer:${t}:`)&&h.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,c]});return}const d=[...this.snapshot.messages];d[u]=c,this.set({...this.snapshot,messages:d})}async refreshRunState(t,n){var r;try{const i=Fe(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&&!Mt(pn(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||Mt(pn(this.runStates.get(t)||null)))return;try{const i=Fe(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(Sr(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(c=>{const u=setTimeout(h,t),d=()=>{clearTimeout(u),h()};function h(){r.removeEventListener("abort",d),c()}r.addEventListener("abort",d,{once:!0})})}}function US(e){const t=y.useMemo(()=>new zS(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=y.useSyncExternalStore(i=>t.subscribe(i),()=>t.getSnapshot(),()=>t.getSnapshot()),r=String(e.runId||"").trim();return y.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),y.useEffect(()=>{if(e.enabled===!1||!r){t.reset();return}return t.load(r),()=>t.reset()},[t,r,e.enabled]),{controller:t,snapshot:n}}function oa(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function qt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Hp(e){return["session","workflow","run","global"].includes(e)?e:null}function Cr(e){return{scope:qt(e==null?void 0:e.scope).toLowerCase(),name:qt(e==null?void 0:e.name)||qt(e==null?void 0:e.event_name),scopeId:qt(e==null?void 0:e.scope_id)||qt(e==null?void 0:e.scopeId),sessionId:qt(e==null?void 0:e.session_id)||qt(e==null?void 0:e.sessionId),workflowId:qt(e==null?void 0:e.workflow_id)||qt(e==null?void 0:e.workflowId),runId:qt(e==null?void 0:e.run_id)||qt(e==null?void 0:e.runId)}}function BS(e,t){const n=e.wait,r=qt(n.wait_key),i=[Cr(n),Cr(oa(n.details))];for(const c of t){if(c.runId!==e.runId)continue;const u=c.record,d=oa(u.result),h=oa(d==null?void 0:d.wait),m=oa(u.effect),p=oa(m==null?void 0:m.payload);qt(h==null?void 0:h.wait_key)!==r&&qt(p==null?void 0:p.wait_key)!==r||i.push(Cr(u),Cr(p),Cr(oa(p==null?void 0:p.details)),Cr(h),Cr(oa(h==null?void 0:h.details)))}return i}function Fd(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function ow(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function WS(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?ow(t,n,i):null}function VS(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const r=qt(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 c=Hp(i[1]);if(!c)return{target:null,error:"The event wait uses an unsupported scope."};const u=BS(e,Array.isArray(t)?t:[]),d=new Map;for(const _ of u){const b=Hp(_.scope);if(!b||!_.name)continue;if(b!==c)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const C=`evt:${b}:`,x=`:${_.name}`;if(!r.startsWith(C)||!r.endsWith(x)||r.length<=C.length+x.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const j=r.slice(C.length,-x.length),N=Fd(b,_);if(N&&N!==j)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const $=ow(b,j,_.name);d.set(`${$.scope}\0${$.scopeId}\0${$.name}`,$)}if(d.size>1)return{target:null,error:"Multiple event targets match this wait; routing is unavailable."};if(d.size===1)return{target:[...d.values()][0]};const h=new Set;c==="run"&&h.add(e.runId),c==="global"&&h.add("global");for(const _ of u){const b=Fd(c,_);b&&h.add(b)}if(qt(n==null?void 0:n.run_id)===e.runId){const _=Cr(n||null),b=Fd(c,_);b&&h.add(b)}const p=[...h].map(_=>WS(r,c,_)).filter(_=>!!_),v=new Map(p.map(_=>[`${_.scope}\0${_.scopeId}\0${_.name}`,_]));return v.size===1?{target:[...v.values()][0]}:v.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 GS(e){return o.jsx(Ly,{text:e,images:"link"})}const HS={trigger:"Trigger",answer:"Automation"};function iw(e,t){return o.jsx(Uy,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:HS[e.kind],runId:e.runId},images:"link"})}const KS={renderText:GS,renderTurn:iw};function JS(e){const{fetchGateway:t,messageProps:n,...r}=e,i=r.onOpenResource??(t?c=>cS(t,c.url,{name:c.name}):void 0);return o.jsx(ek,{...r,onOpenResource:i,...KS,renderTurn:c=>iw(c,n)})}function QS(e,t,n={}){if(!e)return null;const r=e.wait,i=`${e.runId}:${r.wait_key}:${e.stepId||""}`,c=r.details||{};if(c.mode==="approval_required"||c.kind==="tool_approval"){const d=Array.isArray(c.tool_calls)?c.tool_calls:[],h={runId:e.runId,waitKey:String(r.wait_key||""),stepId:e.stepId},m=[...new Set(d.map(v=>String((v==null?void 0:v.name)||"tool")))],p=n.onPermissionsAll;return{id:i,kind:"tool-approval",title:`${d.length||"Requested"} ${d.length===1?"action needs":"actions need"} permission`,toolName:m.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:o.jsxs("div",{className:"pc-approval-summary",children:[o.jsx(Tf,{tools:d.map((v,_)=>({id:String((v==null?void 0:v.call_id)||(v==null?void 0:v.id)||_),runId:e.runId,name:(v==null?void 0:v.name)||"Tool",arguments:v==null?void 0:v.arguments,status:"waiting"}))}),o.jsxs("details",{children:[o.jsx("summary",{children:"Review full tool arguments (JSON)"}),o.jsx(io,{value:d.length?d:c})]})]}),approveLabel:"Allow once",denyLabel:"Deny",approveAllLabel:p?"Allow all enabled tools":void 0,approveAllDescription:p?"Sets permissions: all for this Gateway account, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.":void 0,onApproveAll:p?async()=>{await t.approveWithPolicyChange(h,()=>{p()})}:void 0,onApprove:async()=>{await t.approve(!0,h)},onDeny:async()=>{await t.approve(!1,h)}}}if(r.reason==="user"||r.reason==="ask_user")return{id:i,kind:"ask-user",title:"A question for you",prompt:String(r.prompt||c.prompt||"How would you like to continue?"),allowFreeText:r.allow_free_text!==!1,choices:(Array.isArray(r.choices)?r.choices:[]).map(d=>typeof d=="object"&&d!==null?{id:String(d.value??d.id??d.label),label:String(d.label??d.text??d.value??d.id),description:d.description}:{id:String(d),label:String(d)}),onSubmit:async d=>{await t.resume(d)}};const u=String(r.wait_key||"");if(r.reason==="event"||u.startsWith("evt:")){const d=VS(e,n.records||[],n.currentRun??null),h=d.target,m=(h==null?void 0:h.name)||"";return{id:i,kind:"event-wait",title:h?"Waiting for an event":"Event routing unavailable",eventName:m,prompt:String(r.prompt||`This workflow will continue when “${m||"its trigger"}” arrives.`),description:h?"You can also send the expected event here.":`This event cannot be sent safely. ${d.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async p=>{if(!h)throw new Error(d.error);const v=JSON.parse(p||"{}"),_={name:h.name,scope:h.scope,payload:v};h.scope==="session"?_.session_id=h.scopeId:h.scope==="workflow"?_.workflow_id=h.scopeId:h.scope==="run"&&(_.run_id=h.scopeId),await t.emitEvent(_)}}}return null}function lw(e,t,n,r){const i=y.useRef(null);y.useEffect(()=>{var d,h;if(!t)return;if(e){i.current=document.activeElement||null;const m=r(),p=window.setTimeout(()=>m==null?void 0:m.focus(),0);return()=>window.clearTimeout(p)}const c=n(),u=document.activeElement;i.current&&(!u||u===document.body||c&&c.contains(u))&&((h=(d=i.current).focus)==null||h.call(d)),i.current=null},[e,t])}function YS(e,t){return t?"drawers":e?"overlay":"docked"}function XS(e,t){return t==="drawers"?e:!1}function qS(e){return e.key!=="Escape"||e.defaultPrevented||e.overlayOpen?null:e.sidebarOpen?"sidebar":null}function ZS(e=typeof document<"u"?document:void 0){return!!(e!=null&&e.querySelector('[role="dialog"], [role="alertdialog"]'))}function e0(e){const t=Number.parseFloat(String(e??"").trim());return Number.isFinite(t)&&t>0}let fi=null;function t0(){var r;if(fi)return fi;if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const e=document.documentElement,t=()=>{const i=e0(getComputedStyle(e).getPropertyValue("--keyboard-inset"));i&&e.dataset.keyboard!=="open"?e.dataset.keyboard="open":!i&&e.dataset.keyboard&&delete e.dataset.keyboard},n=new MutationObserver(t);return n.observe(e,{attributes:!0,attributeFilter:["style"]}),(r=window.visualViewport)==null||r.addEventListener("resize",t),t(),fi=()=>{var i;n.disconnect(),(i=window.visualViewport)==null||i.removeEventListener("resize",t),fi=null},fi}function n0(e){const t=e.querySelector(".code-topbar");if(!t)return null;const r=getComputedStyle(t).display==="contents"?e.querySelector(".code-toolbar"):t,i=r==null?void 0:r.getBoundingClientRect().bottom;return typeof i=="number"&&i>0?Math.round(i):null}function s0(e){const[t,n]=y.useState(e);return y.useEffect(()=>{if(typeof window>"u")return;const r=()=>n(n0(document)??e);r();const i=typeof ResizeObserver<"u"?new ResizeObserver(r):null,c=document.querySelector(".code-topbar"),u=document.querySelector(".code-toolbar");return i&&c&&i.observe(c),i&&u&&i.observe(u),window.addEventListener("resize",r),()=>{i==null||i.disconnect(),window.removeEventListener("resize",r)}},[e]),t}class r0{constructor(){Nn(this,"_buffer","");Nn(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const r=this._buffer.indexOf(`
84
+ `);if(r===-1)return;const i=this._buffer.slice(0,r);this._buffer=this._buffer.slice(r+1);const c=i.endsWith("\r")?i.slice(0,-1):i;if(c.startsWith(":"))continue;if(c===""){if(this._current.data_lines.length>0||this._current.event||this._current.id){const m={id:this._current.id,event:this._current.event,data:this._current.data_lines.join(`
85
+ `)};n(m)}this._current={data_lines:[]};continue}const u=c.indexOf(":"),d=u===-1?c:c.slice(0,u),h=u===-1?"":c.slice(u+1).trimStart();d==="id"?this._current.id=h:d==="event"?this._current.event=h:d==="data"&&this._current.data_lines.push(h)}}}function tt(e){var r;const t=(e||"").trim(),n={};t&&(n.Authorization=`Bearer ${t}`);try{const i=(r=document.cookie.split(";").map(c=>c.trim()).find(c=>c.startsWith("abstractcode_gateway_csrf=")))==null?void 0:r.slice(26);i&&(n["X-AbstractCode-CSRF"]=decodeURIComponent(i))}catch{}return n}function a0(e){const t=e.headers.get("retry-after");if(!t)return;const n=Number(t);if(Number.isFinite(n)&&n>0)return n}async function o0(e){var t;try{if(String(e.headers.get("content-type")||"").toLowerCase().includes("application/json")){const i=await e.json().catch(()=>null);if(i&&typeof i=="object"){const c=i.detail;if(typeof c=="string"&&c.trim())return c.trim();const u=(t=i.error)==null?void 0:t.message;if(typeof u=="string"&&u.trim())return u.trim();try{const d=JSON.stringify(i);if(d&&d!=="{}")return d}catch{}}}const r=await e.text();return r!=null&&r.trim()?r.trim():`${e.status}`}catch{return`${e.status}`}}class cw extends Error{constructor(n,r){super(n);Nn(this,"status");Nn(this,"retry_after_s");Nn(this,"body_text");this.name="GatewayHttpError",this.status=Number.isFinite(Number(r.status))?Number(r.status):0,this.retry_after_s=r.retry_after_s,this.body_text=r.body_text}}async function nt(e,t){const n=await o0(e);throw new cw(`${t}: ${n}`,{status:e.status,retry_after_s:a0(e),body_text:n})}class i0{constructor(t){Nn(this,"_cfg");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(),c=(r==null?void 0:r.session_id)===null||(r==null?void 0:r.session_id)===void 0?"":String(r.session_id||"").trim(),u=String(t||"").trim(),d={input_data:n||{}};i&&(d.bundle_id=i),u&&(d.flow_id=u),c&&(d.session_id=c);const h=await fetch(Ze(this._cfg.base_url.trim(),ve("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(d)});if(!h.ok)return await nt(h,"start_run failed");const m=await h.json(),p=m==null?void 0:m.run_id;if(typeof p!="string"||!p)throw new Error("start_run: missing run_id");return p}async get_run(t){const n=String(t||"").trim();if(!n)throw new Error("get_run: run_id is required");const r=await fetch(Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(n)}`)),{headers:{...tt(this._cfg.auth_token)}});return r.ok?await r.json():await nt(r,"get_run failed")}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 c=Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(r)}/history_bundle?${i.toString()}`)),u=await fetch(c,{headers:{...tt(this._cfg.auth_token)}});return u.ok?await u.json():await nt(u,"get_run_history_bundle failed")}async list_runs(t){const n=new URLSearchParams,r=typeof(t==null?void 0:t.limit)=="number"?t.limit:50;n.set("limit",String(r));const i=String((t==null?void 0:t.status)||"").trim();i&&n.set("status",i);const c=String((t==null?void 0:t.workflow_id)||"").trim();c&&n.set("workflow_id",c);const u=String((t==null?void 0:t.session_id)||"").trim();u&&n.set("session_id",u),(t==null?void 0:t.root_only)===!0&&n.set("root_only","true"),(t==null?void 0:t.include_ledger_len)===!1&&n.set("include_ledger_len","false"),(t==null?void 0:t.include_metrics)===!0&&n.set("include_metrics","true");const d=Ze(this._cfg.base_url.trim(),ve(`runs?${n.toString()}`)),h=await fetch(d,{headers:{...tt(this._cfg.auth_token)}});return h.ok?await h.json():await nt(h,"list_runs failed")}async get_ledger(t,n){const r=String(t||"").trim();if(!r)throw new Error("get_ledger: run_id is required");const i=Number((n==null?void 0:n.after)||0),c=Number((n==null?void 0:n.limit)||0),u=Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(r)}/ledger?after=${encodeURIComponent(String(i))}&limit=${encodeURIComponent(String(c))}`)),d=await fetch(u,{headers:{...tt(this._cfg.auth_token)}});if(!d.ok)return await nt(d,"get_ledger failed");const h=await d.json(),m=Array.isArray(h==null?void 0:h.items)?h.items:[],p=typeof(h==null?void 0:h.next_after)=="number"?h.next_after:i;return{items:m,next_after:p}}async stream_ledger(t,n){var C;const r=String(t||"").trim();if(!r)throw new Error("stream_ledger: run_id is required");if(n.on_delta&&!n.on_delta_error)throw new Error("stream_ledger: on_delta requires on_delta_error (malformed live frames must be reported)");const i=Number((n==null?void 0:n.after)||0),c=n.on_step,u=n.signal,d=Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(r)}/ledger/stream?after=${encodeURIComponent(String(i))}`)),h=await fetch(d,{headers:{Accept:"text/event-stream",...tt(this._cfg.auth_token)},signal:u});if(!h.ok)return await nt(h,"stream_ledger failed");if(!h.body)throw new Error("stream_ledger: response body is missing");(C=n.on_open)==null||C.call(n);const m=h.body.getReader(),p=new TextDecoder("utf-8"),v=new r0,_=n.on_delta,b=n.on_delta_error;for(;;){const{value:x,done:j}=await m.read();if(j)return;const N=p.decode(x,{stream:!0});v.push(N,$=>{if(_&&b){const S=$.event||"message",E=$.data??"";let A;try{A=Jy(S,E)}catch(I){b(I instanceof Error?I:new Error(String(I)),{event:S,data:E});return}if(A){_(A);return}}if(!($.event!=="step"||!$.data))try{const S=JSON.parse($.data);S&&typeof S.cursor=="number"&&S.record&&c(S)}catch{}})}}async list_bundles(){const t=await fetch(Ze(this._cfg.base_url.trim(),ve("bundles")),{headers:{...tt(this._cfg.auth_token)}});return t.ok?await t.json():await nt(t,"list_bundles failed")}async reload_bundles(){const t=await fetch(Ze(this._cfg.base_url.trim(),ve("bundles/reload")),{method:"POST",headers:{...tt(this._cfg.auth_token)}});return t.ok?await t.json():await nt(t,"reload_bundles failed")}async upload_bundle(t,n){const r=(n==null?void 0:n.overwrite)===!0,i=(n==null?void 0:n.reload)!==!1,c=new FormData;c.set("overwrite",r?"true":"false"),c.set("reload",i?"true":"false"),c.set("file",t,t.name||"upload.flow");const u=await fetch(Ze(this._cfg.base_url.trim(),ve("bundles/upload")),{method:"POST",headers:{...tt(this._cfg.auth_token)},body:c});return u.ok?await u.json():await nt(u,"upload_bundle failed")}async discovery_tools(){const t=await fetch(Ze(this._cfg.base_url.trim(),ve("discovery/tools")),{headers:{...tt(this._cfg.auth_token)}});return t.ok?await t.json():await nt(t,"discovery_tools failed")}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,r=Ze(this._cfg.base_url.trim(),ve(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),i=await fetch(r,{headers:{...tt(this._cfg.auth_token)}});return i.ok?await i.json():await nt(i,"discovery_providers failed")}async discovery_provider_models(t){const n=String(t||"").trim();if(!n)throw new Error("discovery_provider_models: provider_name is required");const r=await fetch(Ze(this._cfg.base_url.trim(),ve(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...tt(this._cfg.auth_token)}});return r.ok?await r.json():await nt(r,"discovery_provider_models failed")}async discovery_model_capabilities(t,n=""){const r=String(t||"").trim();if(!r)throw new Error("discovery_model_capabilities: model_name is required");const i=new URLSearchParams({model_name:r});n.trim()&&i.set("provider",n.trim());const c=Ze(this._cfg.base_url.trim(),ve(`discovery/models/capabilities?${i}`)),u=await fetch(c,{headers:{...tt(this._cfg.auth_token)}});return u.ok?await u.json():await nt(u,"discovery_model_capabilities failed")}async workspace_policy(){const t=await fetch(Ze(this._cfg.base_url.trim(),ve("workspace/policy")),{headers:{...tt(this._cfg.auth_token)}});return t.ok?await t.json():await nt(t,"workspace_policy failed")}async files_search(t,n){const r=String(t||"").trim(),i=typeof(n==null?void 0:n.limit)=="number"&&Number.isFinite(n.limit)?Math.max(1,Math.trunc(n.limit)):20,c=new URLSearchParams;c.set("query",r),c.set("limit",String(i));const u=n==null?void 0:n.scope;if(u&&typeof u=="object"){const m=String(u.workspace_root||"").trim();m&&c.set("workspace_root",m)}const d=Ze(this._cfg.base_url.trim(),ve(`files/search?${c.toString()}`)),h=await fetch(d,{headers:{...tt(this._cfg.auth_token)},signal:n==null?void 0:n.signal});return h.ok?await h.json():await nt(h,"files_search failed")}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,c=Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(r)}/artifacts?limit=${encodeURIComponent(String(i))}`)),u=await fetch(c,{headers:{...tt(this._cfg.auth_token)}});return u.ok?await u.json():await nt(u,"list_run_artifacts failed")}async get_run_artifact_blob(t,n,r){const i=String(t||"").trim(),c=String(n||"").trim();if(!i)throw new Error("get_run_artifact_blob: run_id is required");if(!c)throw new Error("get_run_artifact_blob: artifact_id is required");const u=Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(i)}/artifacts/${encodeURIComponent(c)}/content`)),d=await fetch(u,{headers:{...tt(this._cfg.auth_token)}});if(!d.ok)return await nt(d,"get_run_artifact_blob failed");const h=await d.blob(),m=typeof(r==null?void 0:r.max_bytes)=="number"&&Number.isFinite(r.max_bytes)?Math.max(0,Math.trunc(r.max_bytes)):0;if(m>0&&h.size>m)throw new Error(`Artifact too large (${h.size} bytes > ${m} bytes)`);const p=String(d.headers.get("content-type")||"").trim()||"application/octet-stream";return{blob:h,content_type:p}}async get_run_artifact_text(t,n,r){const{blob:i}=await this.get_run_artifact_blob(t,n,r);return await i.text()}async attachments_ingest(t,n,r){const i=String(t||"").trim(),c=String(n||"").trim();if(!i)throw new Error("attachments_ingest: session_id is required");if(!c)throw new Error("attachments_ingest: path is required");const u={session_id:i,path:c},d=r==null?void 0:r.scope;if(d&&typeof d=="object"){const _=String(d.workspace_root||"").trim();_&&(u.workspace_root=_)}const h=await fetch(Ze(this._cfg.base_url.trim(),ve("attachments/ingest")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(u)});if(!h.ok)return await nt(h,"attachments_ingest failed");const m=await h.json(),p=m==null?void 0:m.attachment;if(!p||typeof p!="object")throw new Error("attachments_ingest: missing attachment");if(!String(p.$artifact||"").trim())throw new Error("attachments_ingest: missing attachment.$artifact");return p}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 c=String((r==null?void 0:r.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((r==null?void 0:r.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),d=new FormData;d.append("session_id",i),d.append("file",n,c),d.append("filename",c),u&&d.append("content_type",u);const h=await fetch(Ze(this._cfg.base_url.trim(),ve("attachments/upload")),{method:"POST",headers:{...tt(this._cfg.auth_token)},body:d});if(!h.ok)return await nt(h,"attachments_upload failed");const m=await h.json(),p=m==null?void 0:m.attachment;if(!p||typeof p!="object")throw new Error("attachments_upload: missing attachment");if(!String(p.$artifact||"").trim())throw new Error("attachments_upload: missing attachment.$artifact");return p}async audio_transcribe(t,n){const r=String(t||"").trim();if(!r)throw new Error("audio_transcribe: run_id is required");const i={audio_artifact:n==null?void 0:n.audio_artifact,request_id:(n==null?void 0:n.request_id)||void 0},c=(n==null?void 0:n.language)===null||(n==null?void 0:n.language)===void 0?"":String(n.language||"").trim();c&&(i.language=c),n!=null&&n.provider&&(i.provider=String(n.provider)),n!=null&&n.provider&&(n!=null&&n.model)&&(i.model=String(n.model));const u=await fetch(Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(r)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(i)});return u.ok?await u.json():await nt(u,"audio_transcribe failed")}async voice_tts(t,n){const r=String(t||"").trim();if(!r)throw new Error("voice_tts: run_id is required");const i={text:String((n==null?void 0:n.text)||"")},c=(n==null?void 0:n.voice)===null||(n==null?void 0:n.voice)===void 0?"":String(n.voice||"").trim(),u=(n==null?void 0:n.format)===null||(n==null?void 0:n.format)===void 0?"":String(n.format||"").trim(),d=(n==null?void 0:n.request_id)===null||(n==null?void 0:n.request_id)===void 0?"":String(n.request_id||"").trim();c&&(i.voice=c),u&&(i.format=u),d&&(i.request_id=d);const h=await fetch(Ze(this._cfg.base_url.trim(),ve(`runs/${encodeURIComponent(r)}/voice/tts`)),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(i)});return h.ok?await h.json():await nt(h,"voice_tts failed")}async submit_command(t){const n={command_id:String((t==null?void 0:t.command_id)||"").trim(),run_id:String((t==null?void 0:t.run_id)||"").trim(),type:String((t==null?void 0:t.type)||"").trim(),payload:t!=null&&t.payload&&typeof t.payload=="object"?t.payload:{}},r=String((t==null?void 0:t.ts)||"").trim();r&&(n.ts=r);const i=String((t==null?void 0:t.client_id)||"").trim();i&&(n.client_id=i);const c=await fetch(Ze(this._cfg.base_url.trim(),ve("commands")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(n)});return c.ok?await c.json():await nt(c,"submit_command failed")}async bug_report_create(t){const n={session_id:String((t==null?void 0:t.session_id)||"").trim(),description:String((t==null?void 0:t.description)||"")},r=String((t==null?void 0:t.active_run_id)||"").trim();r&&(n.active_run_id=r);const i=String((t==null?void 0:t.workflow_id)||"").trim();i&&(n.workflow_id=i);const c=String((t==null?void 0:t.client)||"").trim();c&&(n.client=c);const u=String((t==null?void 0:t.client_version)||"").trim();u&&(n.client_version=u);const d=String((t==null?void 0:t.user_agent)||"").trim();d&&(n.user_agent=d);const h=String((t==null?void 0:t.url)||"").trim();h&&(n.url=h);const m=String((t==null?void 0:t.provider)||"").trim();m&&(n.provider=m);const p=String((t==null?void 0:t.model)||"").trim();p&&(n.model=p);const v=String((t==null?void 0:t.template)||"").trim();v&&(n.template=v);const _=t==null?void 0:t.context;_&&typeof _=="object"&&(n.context=_);const b=await fetch(Ze(this._cfg.base_url.trim(),ve("bugs/report")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(n)});return b.ok?await b.json():await nt(b,"bug_report_create failed")}async feature_report_create(t){const n={session_id:String((t==null?void 0:t.session_id)||"").trim(),description:String((t==null?void 0:t.description)||"")},r=String((t==null?void 0:t.active_run_id)||"").trim();r&&(n.active_run_id=r);const i=String((t==null?void 0:t.workflow_id)||"").trim();i&&(n.workflow_id=i);const c=String((t==null?void 0:t.client)||"").trim();c&&(n.client=c);const u=String((t==null?void 0:t.client_version)||"").trim();u&&(n.client_version=u);const d=String((t==null?void 0:t.user_agent)||"").trim();d&&(n.user_agent=d);const h=String((t==null?void 0:t.url)||"").trim();h&&(n.url=h);const m=String((t==null?void 0:t.provider)||"").trim();m&&(n.provider=m);const p=String((t==null?void 0:t.model)||"").trim();p&&(n.model=p);const v=String((t==null?void 0:t.template)||"").trim();v&&(n.template=v);const _=t==null?void 0:t.context;_&&typeof _=="object"&&(n.context=_);const b=await fetch(Ze(this._cfg.base_url.trim(),ve("features/report")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(n)});return b.ok?await b.json():await nt(b,"feature_report_create failed")}async prompt_cache_stats(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r||!i)throw new Error("prompt_cache_stats: provider and model are required");const c=Ze(this._cfg.base_url.trim(),ve(`prompt_cache/stats?provider=${encodeURIComponent(r)}&model=${encodeURIComponent(i)}`)),u=await fetch(c,{headers:{...tt(this._cfg.auth_token)}});return u.ok?await u.json():await nt(u,"prompt_cache_stats failed")}async prompt_cache_capabilities(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r||!i)throw new Error("prompt_cache_capabilities: provider and model are required");const c=Ze(this._cfg.base_url.trim(),ve(`prompt_cache/capabilities?provider=${encodeURIComponent(r)}&model=${encodeURIComponent(i)}`)),u=await fetch(c,{headers:{...tt(this._cfg.auth_token)}});return u.ok?await u.json():await nt(u,"prompt_cache_capabilities failed")}async prompt_cache_saved(t,n){const r=String(t||"").trim(),i=String(n||"").trim();if(!r||!i)throw new Error("prompt_cache_saved: provider and model are required");const c=Ze(this._cfg.base_url.trim(),ve(`prompt_cache/saved?provider=${encodeURIComponent(r)}&model=${encodeURIComponent(i)}`)),u=await fetch(c,{headers:{...tt(this._cfg.auth_token)}});return u.ok?await u.json():await nt(u,"prompt_cache_saved failed")}async prompt_cache_clear(t){const n={provider:String((t==null?void 0:t.provider)||"").trim(),model:String((t==null?void 0:t.model)||"").trim()},r=(t==null?void 0:t.key)===null||(t==null?void 0:t.key)===void 0?"":String(t.key||"").trim();r&&(n.key=r);const i=await fetch(Ze(this._cfg.base_url.trim(),ve("prompt_cache/clear")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(n)});return i.ok?await i.json():await nt(i,"prompt_cache_clear failed")}async prompt_cache_save(t){const n={provider:String((t==null?void 0:t.provider)||"").trim(),model:String((t==null?void 0:t.model)||"").trim(),name:String((t==null?void 0:t.name)||"").trim(),key:String((t==null?void 0:t.key)||"").trim(),q8:!!(t!=null&&t.q8)},r=await fetch(Ze(this._cfg.base_url.trim(),ve("prompt_cache/save")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(n)});return r.ok?await r.json():await nt(r,"prompt_cache_save failed")}async prompt_cache_load(t){const n={provider:String((t==null?void 0:t.provider)||"").trim(),model:String((t==null?void 0:t.model)||"").trim(),name:String((t==null?void 0:t.name)||"").trim(),key:String((t==null?void 0:t.key)||"").trim(),clear_existing:!!(t!=null&&t.clear_existing)},r=await fetch(Ze(this._cfg.base_url.trim(),ve("prompt_cache/load")),{method:"POST",headers:{"Content-Type":"application/json",...tt(this._cfg.auth_token)},body:JSON.stringify(n)});return r.ok?await r.json():await nt(r,"prompt_cache_load failed")}}function Wc(){const e=document.cookie.split(";").map(t=>t.trim()).find(t=>t.startsWith("abstractcode_gateway_csrf="));return e?{"X-AbstractCode-CSRF":decodeURIComponent(e.slice(26))}:{}}async function mt(e,t={}){var i;if(!e.startsWith(`${Rr}/`))throw new Error("Gateway requests must use the app's authenticated proxy (a relative api/gateway/… path).");const n=new Headers(t.headers);n.set("Accept","application/json"),t.body&&!(t.body instanceof FormData)&&n.set("Content-Type","application/json");for(const[c,u]of Object.entries(Wc()))n.set(c,u);const r=await fetch(e,{...t,headers:n,credentials:"same-origin"});if(!r.ok){const c=await r.text();let u=c;try{const d=JSON.parse(c);u=typeof d.detail=="string"?d.detail:typeof((i=d.detail)==null?void 0:i.message)=="string"?d.detail.message:JSON.stringify(d.detail||d)}catch{}throw new cw(u||`Gateway request failed (${r.status})`,{status:r.status,body_text:c})}if(r.status!==204)return r.json()}const En=new i0({base_url:""});function vt(e){return e instanceof Error?e.message:String(e)}function Ar(){return ca()}async function l0(e,t,n){const{blob:r}=await En.get_run_artifact_blob(e,t),i=URL.createObjectURL(r),c=document.createElement("a");c.href=i,c.download=n.replace(/[\\/]/g,"_")||"artifact",c.click(),window.setTimeout(()=>URL.revokeObjectURL(i),1e3)}const c0={app:"code",name:"AbstractCode"},u0=["How do I change the model?","Where are my files and generated outputs?","How do I schedule an automation?"],d0=(e,t={})=>{const n=new Headers(t.headers||{}),r=String(t.method||"GET").toUpperCase();if(r!=="GET"&&r!=="HEAD")for(const[i,c]of Object.entries(Wc()))n.set(i,c);return fetch(e,{...t,headers:n,credentials:"same-origin"})};function f0({open:e,onClose:t,connected:n,topOffset:r}){return lw(e,!0,()=>document.querySelector(".code-app-assistant"),()=>document.querySelector(".code-app-assistant .pc-composer textarea")),o.jsx(NS,{open:e,onClose:t,source:c0,fetchGateway:d0,connected:n,topOffset:r,className:"code-app-assistant",placeholder:"Ask about AbstractCode…",suggestions:u0})}function uo({children:e}){return o.jsxs("p",{className:"code-history-empty code-loading-status",role:"status",children:[o.jsx("span",{className:"code-loading-spinner","aria-hidden":"true"}),e]})}function h0(e){const t=e.isDrawer&&!e.open;return o.jsx("aside",{className:"code-sidebar","aria-label":"Conversations",...t?{inert:""}:{},children:e.children})}const Vc=(e,t)=>mt(e,{method:t.method,...t.body!==void 0?{body:JSON.stringify(t.body)}:{}}),Gc="Connect to your gateway to change workspaces.";function uw(e,t,n,r){const[i,c]=y.useState(null),[u,d]=y.useState(null),h=t?t.level==="session"?`session:${t.session}`:"account":"";y.useEffect(()=>{if(c(null),d(null),!e||!t)return;let p=!0;return Ep(n,t).load().then(v=>p&&c(v)).catch(v=>p&&d(`Could not read the workspaces: ${vt(v)}`)),()=>{p=!1}},[e,h,n,r]);const m=y.useCallback(async p=>{if(!t)throw new Error(Gc);const v=await Ep(n,t).save(p);return c(v),v},[h,n]);return{state:i,error:u,save:m}}function dw(e){return e.automation?o.jsx(y0,{...e,automation:e.automation}):o.jsx(m0,{...e})}function m0({connected:e,sessionId:t,onOpenDefaults:n,refreshKey:r,request:i=Vc}){const c=uw(e,t?{level:"session",session:t}:null,i,r),u=e?t?null:"Open a conversation to choose its workspaces.":Gc;return o.jsxs(o.Fragment,{children:[o.jsx(Af,{level:"session",idPrefix:"code-workspace-session",state:c.state,save:c.save,loadError:u??c.error,unavailableReason:u}),n?o.jsx("p",{className:"code-default-workspaces",children:o.jsx("button",{type:"button",className:"code-text-button","data-action":"open-default-workspaces",onClick:n,disabled:!e,children:"My default workspaces"})}):null]})}function p0({open:e,onClose:t,connected:n,onChanged:r,request:i=Vc}){const c=uw(n&&e,e?{level:"account"}:null,i),u=n?null:Gc,d=y.useCallback(async h=>{const m=await c.save(h);return r==null||r(),m},[c,r]);return o.jsx(Q_,{open:e,onClose:t,title:"My default workspaces",size:"narrow",children:o.jsx(Af,{level:"account",idPrefix:"code-workspace-account",state:c.state,save:d,loadError:u??c.error,unavailableReason:u})})}function g0(e,t,n,r){const[i,c]=y.useState(null),[u,d]=y.useState(null),h=JSON.stringify(t);y.useEffect(()=>{if(d(null),!e){c(null);return}let p=!0;return mf(r)(t).then(v=>p&&c(v)).catch(v=>p&&d(`Could not read the workspaces: ${$f(v)||vt(v)}`)),()=>{p=!1}},[e,h,r]);const m=y.useCallback(async p=>{const v=await mf(r)(p);c(v),n(p)},[r,n]);return{effective:i,error:u,onChange:m}}function y0({connected:e,automation:t,idPrefix:n="code-workspace-automation",request:r=Vc}){const i=g0(e,t.value,t.onChange,r),c=e?null:Gc;return o.jsx(Af,{level:"run",idPrefix:n,value:t.value,effective:i.effective,onChange:i.onChange,loadError:c??i.error,unavailableReason:c})}const fw="abstractcode.sidebar.panels",hi={automations:!0,conversations:!0};function w0(e){try{const t=e==null?void 0:e.getItem(fw);if(!t)return{...hi};const n=JSON.parse(t);if(!n||typeof n!="object")return{...hi};const r=n;return{automations:typeof r.automations=="boolean"?r.automations:hi.automations,conversations:typeof r.conversations=="boolean"?r.conversations:hi.conversations}}catch{return{...hi}}}function v0(e,t){try{t==null||t.setItem(fw,JSON.stringify(e))}catch{}}function _0(e,t){return{...e,[t]:!e[t]}}function Nc(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function b0(){const[e,t]=y.useState(()=>w0(Nc())),n=y.useCallback(r=>{t(i=>{const c=_0(i,r);return v0(c,Nc()),c})},[]);return[e,n]}const Lf=e=>({toggle:`code-panel-${e}-toggle`,region:`code-panel-${e}`});function hw(e){const t=Lf(e.panel);return o.jsxs("div",{className:"code-panel-header",children:[o.jsxs("button",{type:"button",className:"code-panel-toggle",id:t.toggle,"aria-expanded":e.open,"aria-controls":t.region,onClick:e.onToggle,children:[o.jsx(re,{name:"chevronDown",size:14}),o.jsx("span",{children:e.label})]}),e.actions?o.jsx("span",{className:"code-panel-actions",children:e.actions}):null]})}function x0(e){return o.jsx("div",{className:"code-sidebar-lists","data-automations":e.panels.automations?"open":"closed","data-conversations":e.panels.conversations?"open":"closed",children:e.children})}function k0(e){const t=Lf("conversations");return o.jsxs("section",{className:"code-panel code-conversations","data-open":e.open?"true":"false",children:[o.jsx(hw,{panel:"conversations",label:"Conversations",open:e.open,onToggle:e.onToggle,actions:e.actions}),o.jsx("nav",{className:"code-sessions",id:t.region,"aria-labelledby":t.toggle,hidden:!e.open,children:e.children})]})}function j0(e){return e.split("/").filter(Boolean).pop()||"Gateway managed"}const mw="abstractcode.sidebar.archived",Kp={automations:!1,conversations:!1};function S0(e){try{const t=e==null?void 0:e.getItem(mw),n=t?JSON.parse(t):null;return!n||typeof n!="object"?{...Kp}:{automations:n.automations===!0,conversations:n.conversations===!0}}catch{return{...Kp}}}function N0(){const[e,t]=y.useState(()=>S0(Nc())),n=y.useCallback(r=>{t(i=>{var u;const c={...i,[r]:!i[r]};try{(u=Nc())==null||u.setItem(mw,JSON.stringify(c))}catch{}return c})},[]);return[e,n]}function pw(e){const t=y.useRef(null),n=y.useRef(!1);if(y.useEffect(()=>{var i,c;!e.open||!n.current||(n.current=!1,(c=(i=t.current)==null?void 0:i.scrollIntoView)==null||c.call(i,{block:"nearest",behavior:"smooth"}))},[e.open]),!(e.count>0))return null;const r=`code-archived-${e.list}`;return o.jsxs("div",{className:"code-archived","data-list":e.list,"data-open":e.open?"true":"false",children:[o.jsxs("button",{type:"button",className:"code-archived-toggle","aria-expanded":e.open,"aria-controls":r,onClick:()=>{n.current=!0,e.onToggle()},children:[o.jsxs("span",{children:["Archived · ",e.count]}),o.jsx(re,{name:"chevronDown",size:12})]}),e.open?o.jsx("ul",{ref:t,className:"code-archived-list",id:r,"aria-label":`Archived ${e.list}`,children:e.children}):null]})}function gw(e){return o.jsxs("li",{className:"code-archived-row","data-id":e.id,children:[o.jsxs("button",{type:"button",className:"code-archived-name",title:e.title,onClick:e.onOpen,children:[o.jsx("strong",{children:e.title}),e.meta?o.jsx("small",{children:e.meta}):null]}),o.jsxs("button",{type:"button",className:"code-subtle-button code-archived-unarchive","data-action":"unarchive",disabled:e.busy,"aria-busy":e.busy||void 0,onClick:e.onUnarchive,children:[e.busy?o.jsx(re,{name:"loader",size:12}):o.jsx(re,{name:"archive",size:12}),o.jsx("span",{children:"Unarchive"})]}),e.error?o.jsx("p",{className:"code-inline-error",role:"alert",children:e.error}):null]})}const C0="Archive this conversation? It stays searchable and auditable; it just leaves this list.";function E0(e){const t=y.useRef(null);return y.useEffect(()=>{var n;(n=t.current)==null||n.focus({preventScroll:!0})},[]),o.jsxs("div",{className:`code-archive-confirm${e.className?` ${e.className}`:""}`,role:"group","aria-label":"Archive conversation",onKeyDown:n=>{n.key==="Escape"&&!e.busy&&(n.preventDefault(),n.stopPropagation(),e.onCancel())},children:[o.jsx("p",{children:C0}),o.jsxs("span",{className:"code-archive-confirm-actions",children:[o.jsxs("button",{type:"button",ref:t,className:"code-archive-confirm-yes","data-action":"confirm-archive",disabled:e.busy,"aria-busy":e.busy||void 0,onClick:e.onConfirm,children:[e.busy?o.jsx(re,{name:"loader",size:12}):o.jsx(re,{name:"archive",size:12}),o.jsx("span",{children:"Archive"})]}),o.jsx("button",{type:"button",className:"code-subtle-button","data-action":"cancel-archive",disabled:e.busy,onClick:e.onCancel,children:"Cancel"})]}),e.error?o.jsx("p",{className:"code-inline-error",role:"alert",children:e.error}):null]})}const $0="abstractcode.agent.v1";function Of(e){return!!(e!=null&&e.interfaces.some(t=>[$0,"abstractassistant.agent.v1"].includes(t)))}function it(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function wf(e){return Array.isArray(e)?e:[]}function Re(e){return typeof e!="string"?void 0:e.trim()||void 0}function A0(e){return wf(e).flatMap(t=>{const n=Re(t);return n?[n]:[]})}function Ci(e,t=0){if(typeof e!="number"||!Number.isFinite(e))return;const n=Math.trunc(e);return n>=t?n:void 0}function Pf(e,t){if(Array.isArray(e))return e;const n=it(e);if(!n)return[];for(const r of t)if(Array.isArray(n[r]))return n[r];return[]}function yw(e){const t=it(e);return t?{...t}:void 0}function Jp(e){const t=yw(e.input_schema??e.inputSchema??e.inputs_schema);if(t)return t;const n=it(e.inputs);if(n&&("properties"in n||"type"in n||"$schema"in n))return{...n}}function T0(e){const t=Re(e.bundle_version??e.bundleVersion??e.version);if(t)return t;const n=Re(e.bundle_ref??e.bundleRef);if(!n)return;const r=n.lastIndexOf("@");return r>0&&r<n.length-1?n.slice(r+1):void 0}function R0(e,t,n){return e?`${e}${t?`@${t}`:""}:${n}`:n}function Qp(e,t,n){var d;const r=it(e),i=Re((r==null?void 0:r.default_bundle_id)??(r==null?void 0:r.defaultBundleId)),c=Pf(e,["items","bundles"]),u=[];for(const h of c){const m=it(h);if(!m)continue;const p=it(m.actions);if((p==null?void 0:p.can_run)===!1)continue;const v=(d=Re(m.status))==null?void 0:d.toLowerCase();if(m.is_draft===!0||m.is_published===!1||m.version_channel==="draft"||v&&!["published","deprecated"].includes(v)||!n.includeDeprecated&&(v==="deprecated"||v==="deleted"||v==="disabled"))continue;const _=Re(m.bundle_id??m.bundleId??m.id),b=T0(m);if(b&&/(?:^|[.\-])draft(?:[.\-]|$)/i.test(b))continue;const C=Re(m.default_entrypoint??m.defaultEntrypoint),x=t==="private"&&(m.is_default===!0||m.isDefault===!0||!!_&&_===i);for(const j of wf(m.entrypoints)){const N=it(j);if(!N||!n.includeDeprecated&&(N.deprecated===!0||N.enabled===!1))continue;const $=Re(N.flow_id??N.flowId??N.id);if(!$)continue;const S=A0(N.interfaces??N.interface_ids??N.interfaceIds);if(n.interfaceId&&!S.includes(n.interfaceId))continue;const E=Re(N.workflow_id??N.workflowId)??R0(_,b,$),A=C?C===$:wf(m.entrypoints).length===1;u.push({id:`${t}:${E}`,workflowId:E,..._?{bundleId:_}:{},...b?{bundleVersion:b}:{},flowId:$,name:Re(N.name??N.title)??$,description:Re(N.description)??"",interfaces:S,...Jp(N)?{inputSchema:Jp(N)}:{},registryScope:t,isPreferredVersion:t==="tenant_catalog"?m.is_default===!0||m.default_version===b:m.latest_published_version===b,...x&&A?{isDefault:!0}:{}})}}return u}function I0(e,t,n={}){const r=[...Qp(e,"private",n),...Qp(t,"tenant_catalog",n)],i=new Map;for(const c of r)i.set(c.id,c);return[...i.values()].sort((c,u)=>+!!u.isDefault-+!!c.isDefault||c.name.localeCompare(u.name)||c.id.localeCompare(u.id))}function M0(e){const t=it(e);if(!t)return;const n=it(t.workflow_selection??t.workflowSelection);if(n)return n;const r=it(t._runtime),i=it((r==null?void 0:r.workflow_policy)??(r==null?void 0:r.workflowPolicy));if(i)return i;const c=it(t.input_data??t.inputData),u=it(c==null?void 0:c._runtime);return it((u==null?void 0:u.workflow_policy)??(u==null?void 0:u.workflowPolicy))}function L0(e,t){const n=M0(t.inputData);if(n){const c=Re(n.registry_scope??n.registryScope),u=Re(n.bundle_id??n.bundleId),d=Re(n.bundle_version??n.bundleVersion),h=Re(n.flow_id??n.flowId);if((c==="private"||c==="tenant_catalog")&&u&&h){const m=e.filter(p=>(p.registryScope??"private")===c&&p.bundleId===u&&p.flowId===h&&(!d||p.bundleVersion===d));if(m.length===1)return m[0]}return}const r=Re(t.runWorkflowId);if(!r)return;const i=e.filter(c=>(c.registryScope??"private")==="private"&&c.workflowId===r);return i.length===1?i[0]:void 0}function O0(e){const t=it(e)??{},n=it(t.policy)??t,r=Ci(n.max_attachment_bytes??n.maxAttachmentBytes,1);return{raw:{...n},...r!==void 0?{maxAttachmentBytes:r}:{}}}function Yp(e,t){const n=Re(e.sandbox);if(!n||typeof e.sandboxed!="boolean")return;const r=Re(t==null?void 0:t.sentence),i=e.sandboxed?"ok":Re(t==null?void 0:t.state)==="unsandboxed"?"danger":"warn";return{label:n,...r?{tooltip:r}:{},tone:i}}function P0(e){var c;const t=Pf(e,["items","tools"]),n=it((c=it(e))==null?void 0:c.command_sandbox),r=new Set,i=[];for(const u of t){const d=it(u);if(!d)continue;const h=Re(d.name??d.tool_name??d.id);if(!h||r.has(h))continue;r.add(h);const m=d.enabled!==!1&&d.served_disabled!==!0&&d.servedDisabled!==!0,p=Ci(d.risk_rank??d.riskRank),v=yw(d.input_schema??d.inputSchema??d.parameters);i.push({name:h,description:Re(d.description)??"",...Re(d.toolset)?{toolset:Re(d.toolset)}:{},...Re(d.tier)?{tier:Re(d.tier)}:{},...Re(d.approval_default??d.default_approval??d.approvalDefault??d.defaultApproval??d.approval)?{approval:Re(d.approval_default??d.default_approval??d.approvalDefault??d.defaultApproval??d.approval)}:{},...p!==void 0?{riskRank:p}:{},enabled:m,servedDisabled:!m,...Re(d.enable_gate??d.enableGate)?{enableGate:Re(d.enable_gate??d.enableGate)}:{},...Re(d.why_disabled??d.whyDisabled)?{whyDisabled:Re(d.why_disabled??d.whyDisabled)}:{},...v?{inputSchema:v}:{},...Yp(d,n)?{sandboxState:Yp(d,n)}:{},raw:{...d}})}return i.sort((u,d)=>u.name.localeCompare(d.name))}function D0(e){var r;const t=(r=Re(e.status??e.state))==null?void 0:r.toLowerCase();return Re(e.wait_reason??e.waitReason)||e.waiting===!0||t==="waiting"||t==="paused"?"waiting":t==="running"||t==="queued"||t==="pending"||t==="created"?"running":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"failed":t==="completed"||t==="complete"||t==="done"?"done":"unknown"}const Xp={waiting:4,running:3,failed:2,done:1,unknown:0};function Za(e){return Re(e.updated_at??e.updatedAt??e.finished_at??e.finishedAt??e.created_at??e.createdAt)}function eo(e){if(!e)return Number.NEGATIVE_INFINITY;const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function qp(e){var u;const t=Re(e);if(t)return t;const n=it(e);if(!n)return;const r=Re(n.prompt);if(r)return r;const i=it(n.input_data??n.inputData),c=["prompt","request","task","message","query","input"].map(d=>Re(i==null?void 0:i[d])).find(Boolean);return c||Re((u=it(i==null?void 0:i.context))==null?void 0:u.task)}function Cc(e,t={}){const n=it(e),r=(n==null?void 0:n.has_more)===!0||(n==null?void 0:n.hasMore)===!0,i=Pf(e,["items","runs"]),c=new Map;i.forEach((d,h)=>{const m=it(d);if(!m||Re(m.parent_run_id??m.parentRunId))return;const p=Re(m.session_id??m.sessionId),v=Re(m.run_id??m.runId??m.id);if(!p||!v)return;const _=c.get(p)??[];_.push({run:m,index:h}),c.set(p,_)});const u=[];for(const[d,h]of c){const m=[...h].sort((x,j)=>eo(Za(j.run))-eo(Za(x.run))||x.index-j.index),p=[...h].sort((x,j)=>{const N=Re(x.run.created_at??x.run.createdAt)??Za(x.run),$=Re(j.run.created_at??j.run.createdAt)??Za(j.run);return eo(N)-eo($)||x.index-j.index}),v=m.flatMap(({run:x})=>{const j=Re(x.run_id??x.runId??x.id);return j?[j]:[]});if(!v.length)continue;let _="unknown";for(const{run:x}of h){const j=D0(x);Xp[j]>Xp[_]&&(_=j)}let b;for(const{run:x}of p){const j=Re(x.run_id??x.runId??x.id);if(b=(j?qp(t[j]):void 0)??qp(x),b)break}let C=0;for(const{run:x}of h){const j=x.tool_calls;C=typeof j=="number"&&Number.isFinite(j)&&C!==void 0?C+j:void 0}u.push({sessionId:d,state:_,...Za(m[0].run)?{updatedAt:Za(m[0].run)}:{},firstRunId:Re(p[0].run.run_id??p[0].run.runId??p[0].run.id),latestRunId:v[0],runIds:v,turnCount:h.length,...C!==void 0?{toolCalls:C}:{},...b?{prompt:b}:{},truncated:r})}return u.sort((d,h)=>eo(h.updatedAt)-eo(d.updatedAt)||d.sessionId.localeCompare(h.sessionId))}function Ec(e){return e?{...e}:{}}function mi(e){if(e!==void 0)return e.flatMap(t=>{const n=Re(t);return n?[n]:[]})}function F0(e,t,n){var x,j,N,$,S,E,A;const r=(I,F)=>{var L,J;!Of(t.workflow)&&!((J=it((L=t.inputSchema)==null?void 0:L.properties))!=null&&J[I])||F!==void 0&&n&&(e[I]=F)},i=Re((x=t.model)==null?void 0:x.provider),c=Re((j=t.model)==null?void 0:j.model);if(!!i!=!!c)throw new Error("Choose both a provider and a model, or use the workflow / Gateway defaults.");r("provider",i),r("model",c),t.tools!==void 0&&r("tools",mi(t.tools)??[]);const u=mi(t.skills);u!=null&&u.length&&(e.skills=u);const d=Re((N=t.workspace)==null?void 0:N.root);d!==void 0&&(e.workspace_root=d),r("system",Re(t.system));const h=Ec(it(e._runtime)),m=(I,F)=>{F!==void 0&&n&&(h[I]=F)};if(m("provider",i),m("model",c),m("thinking",Re(t.reasoning)),m("speculation",t.speculation),t.streamReplies!==void 0&&m("stream",zj(t.streamReplies).stream),m("system_prompt_extra",Re(t.systemPromptExtra)),t.tools!==void 0){const I=mi(t.tools)??[],F=Array.isArray(h.allowed_tools)?h.allowed_tools:null;h.allowed_tools=F?I.filter(L=>F.includes(L)):I}if(t.review!==void 0&&t.reviewCapable!==!1){m("review_mode",t.review.enabled);const I=t.review.enabled?Ci(t.review.maxRounds,1):void 0;m("review_max_rounds",I)}const p=mi(($=t.toolPolicy)==null?void 0:$.autoApproveTools),v=mi((S=t.toolPolicy)==null?void 0:S.requireApprovalTools);(((p==null?void 0:p.length)??0)>0||((v==null?void 0:v.length)??0)>0)&&m("tool_policy",{...p!=null&&p.length?{auto_approve_tools:p}:{},...v!=null&&v.length?{require_approval_tools:v}:{}}),t.promptCache!==void 0&&m("prompt_cache",t.promptCache),Object.keys(h).length&&(e._runtime=h);const _=Ec(it(e._limits)),b=Ci((E=t.limits)==null?void 0:E.maxIterations,1),C=Ci((A=t.limits)==null?void 0:A.maxTokens,1);b!==void 0&&n&&(_.max_iterations=b),C!==void 0&&n&&(_.max_tokens=C),Object.keys(_).length&&(e._limits=_),r("max_iterations",b),t.gatingMode==="auto"&&r("gating_mode","auto")}function z0(e){var r;const t=Ec(e.schemaInputs),n=Of(e.workflow);if(e.promptProperty){const i=Re(e.promptProperty);i&&((r=e.prompt)!=null&&r.trim())&&(t[i]=e.prompt)}if(n){const i=e.prompt??"";t.prompt=i;const c=Ec(it(t.context));c.task=i,delete c.messages,delete c.media;const u=(e.attachments??[]).map(d=>({...d}));u.length?c.attachments=u:delete c.attachments,t.use_context=!1,delete t.attachments,delete t.media,t.context=c,t.use_session_history=e.useSessionHistory??!0}return F0(t,e,!0),t}const Zp=(e,t,n)=>`${e} ${e===1?t:n}`;function ww(e,t={}){const n=e.updatedAt?new Date(e.updatedAt):null,i=[n&&Number.isFinite(n.getTime())?n.toLocaleDateString(t.locale,{month:"short",day:"numeric",...t.timeZone?{timeZone:t.timeZone}:{}}):"Saved conversation",Zp(e.turnCount,"turn","turns")];return typeof e.toolCalls=="number"&&e.toolCalls>0&&i.push(Zp(e.toolCalls,"tool","tools")),i.join(" · ")}function vw(e){return e.prompt||`Conversation ${e.sessionId.slice(0,8)}`}function U0(e){const{item:t}=e,n=vw(t);return o.jsxs("div",{className:`code-session-item${e.confirm?" is-confirming":""}`,"data-item-id":t.sessionId,children:[o.jsxs("button",{type:"button",className:`code-session code-card${e.selected?" is-selected":""}`,"aria-current":e.selected?"page":void 0,"data-session-id":t.sessionId,onClick:e.onClick,title:n,children:[o.jsxs("span",{children:[o.jsx("strong",{className:"code-card-title",children:n}),o.jsx("small",{className:"code-card-meta","data-field":"meta",children:ww(t)})]}),t.state==="running"||t.state==="waiting"?o.jsx("span",{className:`code-status-dot ${t.state==="running"?"is-working":"is-waiting"}`,title:t.state}):null]}),e.onAskArchive?o.jsx(Eg,{className:"code-card-menu",label:`More actions for ${n}`,title:"More actions",items:[{id:"archive",label:"Archive",danger:!0,onSelect:e.onAskArchive}]}):null,e.confirm]})}function _w(e){return e.attention.pending_waits>0}function bw(){return o.jsx("span",{className:"code-waiting-badge","data-field":"waiting",children:"waiting for you"})}function xw(e){const t=lo(e.summary,[],e.busy).active;return o.jsx(Mr,{className:`${e.className??""}${e.iconOnly?" code-switch-icon-only":""}`.trim()||void 0,variant:e.variant??"sm",action:"active",label:e.iconOnly?o.jsx("span",{className:"code-visually-hidden",children:"Active"}):"Active",ariaLabel:"Active",checked:e.summary.status==="active",unavailableReason:t.enabled||e.busy?null:t.reason??"Not available now.",reasonVisible:!1,busy:e.busy,hint:e.iconOnly?`Active
86
+ ${Ti("active",e.summary)}`:Ti("active",e.summary),onChange:()=>e.onToggle()})}function B0(e,t){const n=yy(e,t);return{first:[n.cadence,n.last].filter(Boolean).join(" · "),second:n.next||"",scheduled:e.trigger.source_id==="schedule"}}function W0(e){const t=e.summary,n=B0(t,e.nowMs),r=_w(t);return o.jsxs("div",{className:`code-card code-auto-card${e.selected?" is-selected":""}`,"data-automation-id":t.automation_id,"data-status":t.status,children:[o.jsxs("button",{type:"button",className:"code-card-main","aria-current":e.selected?"page":void 0,title:`${t.title}
87
+ ${[n.first,n.second].filter(Boolean).join(" · ")}`,onClick:e.onSelect,children:[o.jsx("strong",{className:"code-card-title",children:t.title}),r?o.jsx(bw,{}):null,o.jsxs("small",{className:"code-card-meta","data-field":"timing",children:[n.scheduled?o.jsx(re,{name:"refresh",size:12,className:"code-card-cadence-icon"}):null,o.jsx("span",{className:"code-card-part",children:n.first})]})]}),o.jsxs("div",{className:"code-card-line2",children:[o.jsx("small",{className:"code-card-meta","data-field":"next",children:n.second}),o.jsx(xw,{className:"code-card-switch",iconOnly:!0,summary:t,busy:e.busy,onToggle:e.onToggleActive})]})]})}const V0="runs?root_only=true&archived_only=true&include_ledger_len=false&include_metrics=true&limit=200",G0=e=>`sessions/${encodeURIComponent(e)}/archive`,H0=e=>`sessions/${encodeURIComponent(e)}/unarchive`;async function K0(e,t=mt){return t(ve(G0(e)),{method:"POST",body:"{}"})}function J0(e,t){const n=e.findIndex(i=>i.sessionId===t),r=e.filter(i=>i.sessionId!==t);return r.length?n<0?r[0]:r[Math.min(n,r.length-1)]:null}function eg(e){const t=e==null?void 0:e.archived_sessions;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function Q0(e){const t=e.request??mt,[n,r]=y.useState(null),[i,c]=y.useState(""),[u,d]=y.useState(""),[h,m]=y.useState(null);return y.useEffect(()=>{if(!e.enabled)return;const p=new AbortController;return c(""),t(ve(V0),{signal:p.signal}).then(async v=>{if(p.signal.aborted)return;const _=Cc(v);r(_);const b={};await Promise.all(_.filter(C=>!C.prompt).slice(0,50).map(async C=>{try{b[C.firstRunId]=await t(ve(`runs/${encodeURIComponent(C.firstRunId)}/input_data`),{signal:p.signal})}catch{}})),!p.signal.aborted&&Object.keys(b).length&&r(Cc(v,b))}).catch(v=>!p.signal.aborted&&c(`Archived conversations unavailable: ${vt(v)}`)),()=>p.abort()},[e.enabled,e.revision]),i?o.jsx("li",{className:"code-inline-error",role:"alert",children:i}):n?o.jsx(o.Fragment,{children:n.map(p=>o.jsx(gw,{id:p.sessionId,title:vw(p),meta:ww(p),busy:u===p.sessionId,error:(h==null?void 0:h.id)===p.sessionId?h.message:void 0,onOpen:()=>e.onOpen(p),onUnarchive:()=>{d(p.sessionId),m(null),t(ve(H0(p.sessionId)),{method:"POST",body:"{}"}).then(()=>{r(v=>(v||[]).filter(_=>_.sessionId!==p.sessionId)),e.onUnarchived(p)}).catch(v=>m({id:p.sessionId,message:`Not unarchived: ${vt(v)}`})).finally(()=>d(""))}},p.sessionId))}):o.jsx("li",{children:o.jsx(uo,{children:"Loading archived conversations…"})})}const vn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Y0=["context","messages","attachments","media"];function X0(e){return Y0.includes(e)}function q0(e,t){const n=vn(t);return Object.fromEntries(Object.keys(vn(e.properties)).flatMap(r=>["_runtime","_limits"].includes(r)||X0(r)||!Object.prototype.hasOwnProperty.call(n,r)?[]:[[r,structuredClone(n[r])]]))}function tg(e){if(!e)return;const t=vn(e.input_data_schema||e.input_schema||e.schema||e),n=Object.fromEntries(Object.entries(vn(t.properties)).map(([r,i])=>[r,{...vn(i)}]));for(const r of Array.isArray(e.inputs)?e.inputs:[])r!=null&&r.id&&(n[r.id]={...vn(r.schema),...n[r.id],...r.type?{"x-abstract-type":r.type}:{},...r.label?{title:r.label}:{},...Object.prototype.hasOwnProperty.call(r,"default")?{default:r.default}:{}});for(const[r,i]of Object.entries(vn(e.defaults)))n[r]={...n[r],default:i};return{...t,properties:n}}function Z0(e,t){var m;const n=vn(t).nodes;if(!Array.isArray(n))throw new Error("The workflow input declarations could not be verified. Please retry.");const r=n.find(p=>{var v;return(((v=p==null?void 0:p.data)==null?void 0:v.nodeType)||(p==null?void 0:p.type))==="on_flow_start"});if(!r||!Array.isArray((m=r.data)==null?void 0:m.outputs))throw new Error("The workflow start inputs could not be verified. Please retry.");const i=r.data.outputs.filter(p=>typeof(p==null?void 0:p.id)=="string"&&p.id&&p.type!=="execution"&&!["exec","exec-out"].includes(p.id)),c=new Set(i.map(p=>p.id)),u=new Set((Array.isArray(e.required)?e.required:[]).filter(p=>!c.has(p))),d={...e.properties},h=vn(r.data.pinDefaults);for(const p of i)p.required===!0&&u.add(p.id),d[p.id]={...vn(d[p.id]),...vn(p.schema),...p.type?{"x-abstract-type":p.type}:{},...p.label?{title:p.label}:{},...Object.prototype.hasOwnProperty.call(h,p.id)?{default:structuredClone(h[p.id])}:{}};return{...e,properties:d,required:[...u]}}function Gs(e){return Object.fromEntries(Object.entries((e==null?void 0:e.properties)||{}).flatMap(([t,n])=>Object.prototype.hasOwnProperty.call(vn(n),"default")?[[t,structuredClone(vn(n).default)]]:[]))}function e1(e){const t=Array.isArray(e.type)?e.type.find(r=>r!=="null"):e.type;if(t)return t;const n=e["x-abstract-type"];return["tools","assertions"].includes(n)?"array":["json_schema","memory","assertion"].includes(n)?"object":"string"}function t1(e){const t=(e==null?void 0:e.properties)||{},n=i=>{const c=t[i];return c&&(c.type==="string"||Array.isArray(c.type)&&c.type.includes("string")||!c.type&&c["x-abstract-type"]==="string")},r=Object.keys(t).filter(i=>{var c;return((c=t[i])==null?void 0:c["x-abstract-role"])==="prompt"&&n(i)});return r.length?r.length===1?r[0]:void 0:["prompt","request","task","message","query","input"].find(n)}function zd(e,t){var i,c,u;if(!e)return[];const n={...Gs(e),...t},r=[];for(const d of Array.isArray(e.required)?e.required:[])n[d]===void 0&&r.push(`${((c=(i=e.properties)==null?void 0:i[d])==null?void 0:c.title)||d} is required.`);for(const[d,h]of Object.entries(n)){const m=(u=e.properties)==null?void 0:u[d];if(!m||h===void 0)continue;const p=m.title||d;Array.isArray(m.enum)&&!m.enum.some(C=>JSON.stringify(C)===JSON.stringify(h))&&r.push(`${p} must be one of the available choices.`);const v=Array.isArray(m.type)?m.type:m.type?[m.type]:[];if(h===null&&(v.includes("null")||!v.length))continue;const _=Array.isArray(h)?"array":h===null?"null":typeof h,b=v.includes(_)?_:_==="number"&&v.includes("integer")?"integer":v[0];(b==="number"||b==="integer")&&(typeof h!="number"||!Number.isFinite(h)||b==="integer"&&!Number.isInteger(h))&&r.push(`${p} must be ${b==="integer"?"a whole number":"a number"}.`),typeof h=="number"&&m.minimum!==void 0&&h<m.minimum&&r.push(`${p} must be at least ${m.minimum}.`),typeof h=="number"&&m.maximum!==void 0&&h>m.maximum&&r.push(`${p} must be at most ${m.maximum}.`),b==="string"&&typeof h!="string"&&r.push(`${p} must be text.`),typeof h=="string"&&m.minLength!==void 0&&h.length<m.minLength&&r.push(`${p} must contain at least ${m.minLength} characters.`),b==="boolean"&&typeof h!="boolean"&&r.push(`${p} must be true or false.`),b==="array"&&!Array.isArray(h)&&r.push(`${p} must be a JSON array.`),b==="object"&&(h===null||typeof h!="object"||Array.isArray(h))&&r.push(`${p} must be a JSON object.`)}return r}function kw(e){const t=(e==null?void 0:e.properties)||{},n=[];for(const[r,i]of Object.entries(t)){const c=vn(i);if(!(r==="provider"||r.endsWith("_provider")||String(c["x-abstract-type"]||"").startsWith("provider")))continue;const u=String(c["x-abstract-type"]||""),d=r.replace("provider","model"),h=Object.keys(t).filter(b=>{var C;return((C=t[b])==null?void 0:C["x-abstract-type"])===u.replace(/^provider/,"model")}),m=d!==r&&t[d]?d:h.length===1?h[0]:"";if(!m)continue;const p=r==="provider"?"":r.startsWith("provider_")?r.slice(9):r.endsWith("_provider")?r.slice(0,-9):u.replace(/^provider_?/,""),v=p&&p!=="text"?`${p}_`:"",_=[`${v}reasoning`,`${v}thinking`,`${v}reasoning_effort`,`reasoning_${p}`,`thinking_${p}`].find(b=>t[b]);n.push({provider:r,model:m,reasoning:_,title:v?v.replace(/_/g," ").trim():"Text model"})}return n}const Df={fetchProviders:async()=>{const e=await En.discovery_providers(),t=e.providers||e.items;return Array.isArray(t)?t.map(n=>typeof n=="string"?{name:n}:n):[]},fetchModels:async e=>{const t=await En.discovery_provider_models(e),n=t.models||t.items;return Array.isArray(n)?n.map(r=>typeof r=="string"?r:r.id||r.name).filter(Boolean):[]},fetchModelCapabilities:(e,t="")=>En.discovery_model_capabilities(e,t)};function n1(e){for(const t of["output.text","input.text"]){const n=(Array.isArray(e==null?void 0:e.routes)?e.routes:[]).find(r=>r.key===t&&r.source!=="not_configured"&&r.provider&&r.model);if(n)return{provider:n.provider,model:n.model}}}function s1(e,t){e.startsWith("provider_")?e=`${e.slice(9)}_provider`:t!=null&&t.startsWith("provider_")&&!e.endsWith("_provider")&&(e=`${t.slice(9)}_provider`);const n={image_provider:"text_to_image",image_edit_provider:"image_to_image",image_upscale_provider:"image_upscale",video_provider:"text_to_video",image_to_video_provider:"image_to_video"}[e];if(!n&&!["music_provider","voice_provider"].includes(e))return Df;const r=e==="voice_provider",i=ve(n?`vision/provider_models?task=${n}`:r?"audio/speech/models?compact=true":"audio/music/models?task=text_to_music"),c=n?`${i}&providers_only=true`:ve(r?"voice/voices?providers_only=true&compact=true":"audio/music/providers?task=text_to_music"),u=d=>Array.isArray(d)?d.map(h=>typeof h=="string"?h:h.id||h.name).filter(Boolean):[];return{fetchProviders:async()=>{const d=await mt(c);if(d.error)throw new Error(d.error);return u(d.providers||d.available_providers||d.items).map(h=>({name:h}))},fetchModels:async d=>{var m,p,v;const h=await mt(`${i}&provider=${encodeURIComponent(d)}`);if(h.error)throw new Error(h.error);return u(((m=h.models_by_provider)==null?void 0:m[d])||((p=h.tts_models_by_provider)==null?void 0:p[d])||((v=h.music_models_by_provider)==null?void 0:v[d])||h.models||h.items)}}}const r1=["gateway_default","on","off"],jw={status:"loading"};function a1(e,t){if(t)return{status:"unsupported",reason:`the gateway's capabilities could not be read (${t})`};const n=e==null?void 0:e.capabilities,r=n==null?void 0:n.streaming;return!r||typeof r!="object"||r.deltas!==!0?{status:"unsupported",reason:"not supported by this gateway (it does not advertise live replies)"}:{status:"supported",gatewayDefault:typeof r.default=="boolean"?r.default:null}}function o1(e){return r1.includes(e)?e:"gateway_default"}function i1(e,t){return e==="on"&&t.status!=="supported"?"gateway_default":e}function l1(e,t,n){if(e!=="on"||t.status!=="unsupported"||!n.length)return null;const r=n.find(i=>i.role==="user")||n[0];return{after:r.id?String(r.id):null,message:{id:"stream-replies:unsupported",role:"system",level:"info",title:"Stream replies",content:`Streaming is on in your settings but this gateway does not support live replies: ${t.reason}. Replies appear when they are complete.`}}}function c1(e){try{const t=JSON.parse(e);return typeof(t==null?void 0:t.call_id)=="string"&&t.call_id?t.call_id:""}catch{return""}}function u1(e,t){const n=c1(e.frame.data),r=n?`call:${n}`:`error:${e.error.message}`;return{after:t,message:{id:`stream-replies:malformed:${e.runId}:${r}`,role:"system",level:"warn",title:"Live reply",runId:e.runId,content:`The gateway sent a malformed live reply update (${e.frame.event}): ${e.error.message}. It was skipped; the complete reply still arrives.`}}}function d1(e,t){return e.some(n=>n.message.id===t.message.id)?[...e]:[...e,t]}function f1(e,t){const n=t.filter(d=>!!d);if(!n.length)return[...e];const r=[],i=new Set;for(const d of e){r.push(d);for(const h of n)!i.has(h)&&h.after!==null&&String(d.id)===h.after&&(r.push(h.message),i.add(h))}const c=n.filter(d=>!i.has(d)&&d.after===null),u=n.filter(d=>!i.has(d)&&d.after!==null);return[...c.map(d=>d.message),...r,...u.map(d=>d.message)]}function h1(e){return e.status==="supported"&&e.gatewayDefault!==null?`Gateway default (${e.gatewayDefault?"on":"off"})`:"Gateway default"}const Cn="@default",as="abstractcode.agent.v1";function xs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function yn(e){return typeof e=="string"&&e.trim()?e.trim():void 0}const m1="gateway does not report a default agent workflow";function p1(e,t=as){var p,v;const n=xs(e);if(!n)return{status:"unavailable",reason:"the gateway's workflow list could not be loaded"};const r=xs(n.default_agent_workflows);if(!r)return{status:"unavailable",reason:m1};const i=xs(r[t]);if(!i){const _=yn((v=xs((p=xs(n.default_agent_workflows_unavailable))==null?void 0:p[t]))==null?void 0:v.reason);return{status:"unavailable",reason:_?`no default workflow for ${t}: ${_}`:`gateway reports no default workflow for ${t}`}}const c=yn(i.bundle_id),u=yn(i.flow_id),d=yn(i.registry_scope);if(!c||!u||!d)return{status:"unavailable",reason:`gateway's default workflow for ${t} is missing its bundle, flow or registry scope`};const h=yn(i.bundle_version);return{status:"ok",workflow:{workflowId:yn(i.workflow_id)??`${c}${h?`@${h}`:""}:${u}`,bundleId:c,...h?{bundleVersion:h}:{},flowId:u,registryScope:d,name:yn(i.name)??u,...yn(i.source)?{source:yn(i.source)}:{}}}}function g1(e){if(e.status==="loading")return"Gateway default (loading…)";if(e.status==="unavailable")return`Gateway default — ${e.reason}`;const{name:t,bundleVersion:n}=e.workflow;return`Gateway default → ${t}${n?` @${n}`:""}`}function y1(e,t,n=as){if(e.status!=="ok")return null;const r=e.workflow,i=t.find(c=>(c.registryScope??"private")===r.registryScope&&c.bundleId===r.bundleId&&c.flowId===r.flowId&&(!r.bundleVersion||c.bundleVersion===r.bundleVersion));return i||{id:`${r.registryScope}:${r.workflowId}`,workflowId:r.workflowId,bundleId:r.bundleId,...r.bundleVersion?{bundleVersion:r.bundleVersion}:{},flowId:r.flowId,name:r.name,description:"",interfaces:[n],registryScope:r.registryScope}}function Ud(e,t=as){if(!e||e.interfaces.includes(t))return"";const n=e.interfaces.length?e.interfaces.join(", "):"no interface";return`The gateway default ${e.name} does not declare ${t} (it declares ${n}); it will not run as a coding agent here.`}function w1(e){return((e==null?void 0:e.entries)??[]).map(t=>({id:`${t.registryScope}:${t.value}`,workflowId:t.value,bundleId:t.bundleId,...t.bundleVersion?{bundleVersion:t.bundleVersion}:{},flowId:t.flowId,name:t.name,description:t.description,interfaces:t.interfaces,registryScope:t.registryScope}))}function v1(e,t){return e===Cn?Dc:(t==null?void 0:t.workflowId)??e}function _1(e,t){return e===Dc||!t?Cn:`${t.registryScope}:${t.value}`}function b1(e){const t=n=>n===Cn||e.visible.some(r=>r.id===n)||!!e.runId&&e.workflows.some(r=>r.id===n);return e.selection&&t(e.selection)?e.selection:e.preferred&&t(e.preferred)?e.preferred:Cn}function Ff(e){var n,r;const t=xs((r=xs((n=xs(e))==null?void 0:n.input_data))==null?void 0:r.workflow_selection);return yn(t==null?void 0:t.source)}function x1(e){var t;return Ff(e.restoredInputs)==="gateway_default"?Cn:(t=e.restored)==null?void 0:t.id}function k1(e){return!xs(e)||Ff(e)?"":"This gateway does not record whether this conversation used the gateway default workflow; its next turn uses the workflow its last run used."}function j1(e){return e.selection===Cn?{flow_id:Cn,interface:e.interfaceId??as,session_id:e.sessionId,input_data:e.input}:{bundle_id:e.workflow.bundleId,bundle_version:e.workflow.bundleVersion,registry_scope:e.workflow.registryScope,flow_id:e.workflow.flowId,session_id:e.sessionId,input_data:e.input}}function S1(e){const t=xs(e);if(!t)return{text:"the gateway did not report which workflow it started",missing:!0};const n=yn(t.name)??yn(t.workflow_id)??yn(t.flow_id)??"unnamed workflow",r=yn(t.bundle_version);return{text:`running ${n}${r?` @${r}`:""}${t.source==="gateway_default"?" (gateway default)":""}`,missing:!1}}const Bd=25,N1=4,C1=e=>`runs?root_only=true&include_ledger_len=false&include_metrics=true&limit=${e}`;function E1(e){const t=(e==null?void 0:e.items)??(e==null?void 0:e.runs);return Array.isArray(t)?t.length:0}async function $1(e,t){let n=Math.max(1,t)*N1;for(;;){const r=await e(n);if((r==null?void 0:r.has_more)!==!0||E1(r)<n||Cc(r).length>t)return r;n*=2}}function A1(e,t){return{sessions:e.slice(0,t),hasMore:e.length>t}}const Wd={gatewayDefault:{status:"loading"},executable:{status:"idle",data:null,error:""},workflows:[],policy:null,tools:[],sessions:[],capabilities:{},capabilitiesLoading:!0,streaming:jw,loading:!1,sessionsLoaded:!1,errors:[],hasMore:!1,archivedSessions:0};function T1(e){var n;const t=((n=e==null?void 0:e.capabilities)==null?void 0:n.contracts)??(e==null?void 0:e.contracts)??e;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function R1(e,t){const[n,r]=y.useState(Wd),i=y.useRef(Bd),c=y.useRef(0),u=y.useRef(),d=y.useRef(0),h=y.useRef(),m=y.useRef({identity:"",values:{}}),p=y.useCallback(N=>$1($=>mt(ve(C1($)),{signal:N}),i.current),[]),v=N=>A1(Cc(N,m.current.values),i.current),_=y.useCallback(async(N,$,S)=>{const E=()=>d.current!==$||S.aborted,A=v(N).sessions.filter(I=>!I.prompt&&!(I.firstRunId in m.current.values));for(let I=0;I<A.length;I+=4){if(E()||(await Promise.all(A.slice(I,I+4).map(async F=>{try{const L=await mt(ve(`runs/${encodeURIComponent(F.firstRunId)}/input_data`),{signal:S});E()||(m.current.values[F.firstRunId]=L)}catch(L){!S.aborted&&(L==null?void 0:L.status)===401&&t()}})),E()))return;r(F=>({...F,sessions:v(N).sessions}))}},[t]),b=y.useCallback(async()=>{var S;if(!e)return;const N=++d.current;(S=h.current)==null||S.abort();const $=new AbortController;h.current=$,r(E=>({...E,loading:!0}));try{const E=await p($.signal);if(d.current!==N)return;const A=v(E);r(I=>({...I,loading:!1,sessions:A.sessions,sessionsLoaded:!0,hasMore:A.hasMore,archivedSessions:eg(E),errors:I.errors.filter(F=>!F.startsWith("Conversations: "))})),await _(E,N,$.signal)}catch(E){if($.signal.aborted||d.current!==N)return;(E==null?void 0:E.status)===401&&t(),r(A=>({...A,loading:!1,errors:[...A.errors.filter(I=>!I.startsWith("Conversations: ")),`Conversations: ${vt(E)}`]}))}},[e,p,_,t]),C=y.useCallback(async()=>{var O,Z;const N=++c.current,$=++d.current;(O=h.current)==null||O.abort(),(Z=u.current)==null||Z.abort();const S=new AbortController;if(u.current=S,m.current.identity!==e&&(m.current={identity:e,values:{}}),!e){r(Wd);return}r(R=>({...R,loading:!0,capabilitiesLoading:!0,errors:[],executable:{...R.executable,status:"loading",error:""}}));const E=R=>mt(ve(R),{signal:S.signal}),A=await Promise.allSettled([E("bundles?all_versions=true&include_drafts=false"),E("workspace/policy"),E("discovery/tools"),p(S.signal),E("discovery/capabilities"),E("workflow-catalog?scope=tenant"),E("config/capability-defaults"),E(ly(as))]);if(c.current!==N)return;const I=R=>A[R].status==="fulfilled"?A[R].value:void 0,F=[];A.forEach((R,q)=>{var z,se;R.status==="rejected"&&(((z=R.reason)==null?void 0:z.status)===401&&t(),!(q===5&&[403,404,501].includes((se=R.reason)==null?void 0:se.status))&&q!==7&&F.push(`${["Workflows","Workspace policy","Tools","Conversations","Capabilities","Shared workflows","Gateway defaults"][q]}: ${vt(R.reason)}`))});const L=d.current===$,J=v(I(3));let V;if(A[7].status==="rejected")V={status:"error",data:null,error:`Workflows for this app: ${vt(A[7].reason)}`};else try{V={status:"ready",data:kx(I(7),as),error:""}}catch(R){V={status:"error",data:null,error:String((R==null?void 0:R.message)||R)}}r(R=>({executable:V,workflows:I0(I(0),I(5)),policy:I(1)?O0(I(1)):null,tools:P0(I(2)),sessions:L&&I(3)?J.sessions:R.sessions,sessionsLoaded:R.sessionsLoaded||!!(L&&I(3)),capabilities:T1(I(4)),capabilitiesLoading:!1,streaming:a1(I(4),A[4].status==="rejected"?vt(A[4].reason):void 0),defaultModel:n1(I(6)),gatewayDefault:p1(I(0)),loading:!1,errors:F,hasMore:L&&I(3)?J.hasMore:R.hasMore,archivedSessions:L&&I(3)?eg(I(3)):R.archivedSessions})),L&&I(3)&&await _(I(3),$,S.signal)},[e,t,p,_]);y.useEffect(()=>(i.current=Bd,r(Wd),C(),()=>{var N,$;c.current+=1,d.current+=1,(N=u.current)==null||N.abort(),($=h.current)==null||$.abort()}),[C]);const x=y.useCallback(()=>{i.current+=Bd,b()},[b]),j=y.useCallback(N=>{r($=>({...$,sessions:$.sessions.filter(S=>S.sessionId!==N),archivedSessions:$.archivedSessions+1})),b()},[b]);return{...n,refresh:C,loadMore:x,forgetSession:j}}async function Vd(e){if(e.inputSchema)return tg(e.inputSchema);if(!e.bundleId)return;const t=encodeURIComponent(e.bundleId),n=encodeURIComponent(e.flowId),r=e.registryScope==="tenant_catalog"&&e.bundleVersion?ve(`workflow-catalog/${t}/versions/${encodeURIComponent(e.bundleVersion)}/flows/${n}/input_schema?scope=tenant`):ve(`bundles/${t}/flows/${n}/input_schema${e.bundleVersion?`?bundle_version=${encodeURIComponent(e.bundleVersion)}`:""}`),i=await mt(r),c=tg(i);if(!c||i!=null&&i.native_loop_factory||(i==null?void 0:i.version)!==1||!Array.isArray(i==null?void 0:i.inputs)||!(i!=null&&i.input_data_schema)||!Array.isArray(c.required)||!c.required.length)return c;const u=e.bundleVersion||i.bundle_version;if(!u)throw new Error("The Gateway did not identify the workflow version. Refresh workflows and retry.");const d={bundle_id:e.bundleId,bundle_version:u,flow_id:e.flowId},h=v=>{for(const[_,b]of Object.entries(d))if((v==null?void 0:v[_])!==b)throw new Error("The Gateway returned inputs for a different workflow version. Refresh workflows and retry.");if(e.registryScope==="tenant_catalog"&&(v==null?void 0:v.registry_scope)!=="tenant_catalog")throw new Error("The Gateway returned inputs from a different workflow registry. Refresh workflows and retry.")};h(i);const m=e.registryScope==="tenant_catalog"?ve(`workflow-catalog/${t}/versions/${encodeURIComponent(u)}/flows/${n}?scope=tenant`):ve(`bundles/${t}/flows/${n}?bundle_version=${encodeURIComponent(u)}`),p=await mt(m);return h(p),Z0(c,p.flow)}const Gd=e=>ve(`runs/${encodeURIComponent(e)}`);function I1(e){return{getRun:(t,n)=>mt(Gd(t),{signal:n}),getHistory:(t,n)=>mt(`${Gd(t)}/history_bundle?include_subruns=true&include_session=true&ledger_mode=full`,{signal:n}),getLedger:(t,n,r)=>mt(`${Gd(t)}/ledger?after=${n}&limit=200`,{signal:r}),streamLedger:(t,n,r,i,c,u)=>En.stream_ledger(t,{after:n,on_step:r,signal:i,on_open:c,on_delta:u,on_delta_error:(d,h)=>e.onDeltaError({runId:t,error:d,frame:h})}),submitCommand:(t,n)=>mt(ve("commands"),{method:"POST",body:JSON.stringify(t),signal:n})}}function _s(e){return typeof e=="string"?e.trim():""}function M1(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=(Array.isArray(t.skills)?t.skills:[]).flatMap(d=>{const h=d&&typeof d=="object"&&!Array.isArray(d)?d:null,m=_s(h==null?void 0:h.name);if(!h||!m)return[];const p=h.source&&typeof h.source=="object"&&!Array.isArray(h.source)?h.source:void 0;return[{name:m,description:_s(h.description),trustLevel:_s(h.trust_level)||"unverified",blocked:h.blocked===!0,requiresReview:h.requires_review===!0,reasons:Array.isArray(h.reasons)?h.reasons.map(_s).filter(Boolean):[],source:p?{source:_s(p.source),binding:_s(p.binding),ambiguous:p.ambiguous===!0}:void 0}]}),i=Array.isArray(t.warnings)?t.warnings.map(_s).filter(Boolean):[],c=_s(t.shelf),u=_s(t.shelf_source);return{skills:r.sort((d,h)=>d.name.localeCompare(h.name)),warnings:i,...c?{shelf:c}:{},...u?{shelfSource:u}:{}}}function L1({inventory:e}){return o.jsxs("div",{className:"code-skills-empty",role:"status",children:[o.jsx("p",{children:o.jsx("strong",{children:"This gateway offers no skills."})}),e.warnings.length?e.warnings.map((t,n)=>o.jsx("p",{children:e.shelf?t:`The gateway has no skill shelf: ${t}`},`${t}:${n}`)):o.jsx("p",{children:"The gateway gave no reason for the empty list."}),e.shelf?o.jsxs("p",{className:"code-field-help",children:["Skill shelf: ",o.jsx("code",{children:e.shelf}),e.shelfSource?` (source: ${e.shelfSource})`:""]}):o.jsx("p",{className:"code-field-help",children:"The gateway did not report a skill shelf location."})]})}function O1(e){var r;const t=e.trustLevel.replace(/[_-]+/g," "),n=(r=e.source)!=null&&r.source?`Adopted from ${e.source.source}`:"Source has no adoption record";return`Trust: ${t}. ${n}${e.requiresReview?". Review required":""}.`}function P1({skill:e,checked:t,disabled:n,onChange:r,lockedReasonId:i}){const c=e.reasons.join(" ")||"Blocked by gateway policy.",u=e.blocked?`Blocked by the gateway: ${c}`:n?"Available when a gateway is connected and no run is in progress.":null;return o.jsx("div",{className:"code-field code-skill-row",children:o.jsx(Mr,{variant:"row",action:"skill",label:e.name,description:o.jsxs(o.Fragment,{children:[e.description?o.jsx("span",{className:"code-skill-row__desc",children:e.description}):null,o.jsx("span",{className:"code-skill-row__trust",children:O1(e)})]}),checked:t,unavailableReason:u,describedBy:!e.blocked&&n?i:void 0,onChange:r})})}function D1({value:e,onChange:t,disabled:n,lockedReasonId:r}){const[i,c]=y.useState({skills:[],warnings:[]}),[u,d]=y.useState(""),[h,m]=y.useState(!0),[p,v]=y.useState(""),[_,b]=y.useState(0);y.useEffect(()=>{const N=new AbortController;return m(!0),v(""),mt(ve("skills"),{signal:N.signal}).then($=>{N.signal.aborted||c(M1($))}).catch($=>{N.signal.aborted||v(vt($))}).finally(()=>{N.signal.aborted||m(!1)}),()=>N.abort()},[_]);const C=y.useMemo(()=>new Set(e.map(_s).filter(Boolean)),[e]),x=y.useMemo(()=>{const N=u.trim().toLocaleLowerCase();return N?i.skills.filter($=>`${$.name}
88
+ ${$.description}
89
+ ${$.trustLevel}`.toLocaleLowerCase().includes(N)):i.skills},[i.skills,u]),j=(N,$)=>{const S=$?[...C,N]:[...C].filter(E=>E!==N);t([...new Set(S)])};return o.jsxs("section",{className:"code-settings-section","aria-labelledby":"code-skills-heading",children:[o.jsx("h3",{id:"code-skills-heading",children:"Skills"}),o.jsx("p",{className:"code-muted",children:"Choose curated guidance for the next turn. The gateway evaluates trust and requirements when the run starts; this browser does not load or execute skill scripts."}),o.jsxs("label",{className:"code-field",children:["Find a skill",o.jsx("input",{type:"search",value:u,onChange:N=>d(N.target.value),disabled:n||h,placeholder:"Search names, descriptions, or trust"})]}),h?o.jsx("p",{className:"code-muted",role:"status",children:"Loading skills from the gateway…"}):null,p?o.jsxs("div",{className:"code-inline-error",role:"alert",children:["Skill selection is unavailable: ",p," ",o.jsx("button",{className:"code-text-button",type:"button",onClick:()=>b(N=>N+1),disabled:n,children:"Retry"})]}):null,i.warnings.length&&i.skills.length?o.jsxs("details",{className:"code-disabled-tools",children:[o.jsxs("summary",{children:["Gateway reported ",i.warnings.length," skills warning",i.warnings.length===1?"":"s"]}),i.warnings.map((N,$)=>o.jsx("p",{children:N},`${N}:${$}`))]}):null,!h&&!p&&!i.skills.length?o.jsx(L1,{inventory:i}):null,!h&&!p&&i.skills.length&&!x.length?o.jsx("p",{className:"code-muted",children:"No skills match your search."}):null,x.map(N=>o.jsx(P1,{skill:N,checked:C.has(N.name),disabled:n,lockedReasonId:r,onChange:$=>j(N.name,$)},N.name))]})}function Sw(e,t,n="default"){const r=e.filter(c=>c.enabled&&!c.servedDisabled&&(t.mode==="all"||t.selected.includes(c.name))),i=c=>{const u=t.approval[c.name];if(u==="ask")return!1;if(u==="approve"||n==="all")return!0;const d=["auto","approve"].includes((c.approval||"").trim().toLowerCase());if(n==="default")return d;const h=d?1:["write_file","edit_file"].includes(c.name)?2:3,m=c.riskRank===void 0||c.riskRank===1?1:c.riskRank===2?2:3;return Math.max(h,m)<=(n==="write"?2:1)};return{enabledTools:r.map(c=>c.name),autoApproveTools:r.filter(i).map(c=>c.name),requireApprovalTools:r.filter(c=>!i(c)).map(c=>c.name)}}function F1(e,t){if(!Array.isArray(t))return e;const n=r=>t.includes(r);return{enabledTools:e.enabledTools.filter(n),autoApproveTools:e.autoApproveTools.filter(n),requireApprovalTools:e.requireApprovalTools.filter(n)}}const z1="code-settings-locked",os={provider:"",model:"",reasoning:"",maxIterations:"",maxTokens:"",system:"",workspace:null,tools:{mode:"all",selected:[],approval:{}},toolsCustomized:!1,permissions:"default",skills:[],workflow:"@default",streamReplies:"gateway_default"};function U1({tab:e,value:t,onChange:n,tools:r,disabled:i,defaultModel:c,workflowDefault:u,streaming:d=jw,lockedReasonId:h=z1,workspaceRootFixed:m,hideStreamReplies:p,lockedText:v,connected:_=!1,automationFolders:b=!1,workspaceRequest:C,sessionId:x,onOpenDefaultWorkspaces:j,workspaceRefreshKey:N}){const $=S=>n({...t,...S});return o.jsxs(o.Fragment,{children:[i?o.jsx("p",{className:"code-notice",id:h,children:v||"Settings are unavailable while disconnected or while a run is active. Reconnect, or finish or stop the run, then try again."}):null,e==="model"?o.jsxs(o.Fragment,{children:[o.jsx("section",{className:"code-settings-section","aria-label":"Model",children:o.jsx(Ic,{defaultModeLabel:u?"Workflow default":"Gateway default",value:t,onChange:$,disabled:i,effectiveDefault:c,fetchModelCapabilities:Df.fetchModelCapabilities,enableSpeculation:!0,inheritLabel:"Gateway default",defaultHint:c?`${u?"Workflow":"Gateway"} default: ${c.provider} · ${c.model}.`:void 0,fetchProviders:async()=>{const S=await En.discovery_providers();return Array.isArray(S.providers)?S.providers:Array.isArray(S.items)?S.items:[]},fetchModels:async S=>{const E=await En.discovery_provider_models(S);return(Array.isArray(E.models)?E.models:Array.isArray(E.items)?E.items:[]).map(A=>typeof A=="string"?A:A.id||A.name)}})}),o.jsxs("section",{className:"code-settings-section",children:[o.jsx("h3",{children:"Behavior"}),o.jsxs("div",{className:"code-field-pair",children:[o.jsxs("label",{className:"code-field",children:["Iteration limit",o.jsx("input",{type:"number",min:1,step:1,placeholder:"Workflow default",value:t.maxIterations,disabled:i,onChange:S=>$({maxIterations:S.target.value})})]}),o.jsxs("label",{className:"code-field",children:["Context token limit",o.jsx("input",{type:"number",min:1,step:1,placeholder:"Gateway default",value:t.maxTokens,disabled:i,onChange:S=>$({maxTokens:S.target.value})})]})]}),o.jsxs("label",{className:"code-field",children:["Additional instructions",o.jsx("textarea",{rows:5,value:t.system,placeholder:"Project conventions or guidance for this conversation…",disabled:i,onChange:S=>$({system:S.target.value})})]}),o.jsx("p",{className:"code-field-help",children:"Reasoning and additional instructions depend on the selected workflow and model."}),p?null:o.jsx(B1,{value:t.streamReplies,onChange:S=>$({streamReplies:S}),disabled:i,streaming:d})]})]}):e==="workspace"?o.jsxs("section",{className:"code-settings-section",children:[m?o.jsxs("p",{className:"code-field-help","data-setting":"workspace-root-fixed",children:["Runs work in the automation workspace ",o.jsx("code",{title:m,children:m.split(/[\\/]/).filter(Boolean).pop()||m}),"."]}):null,o.jsx(dw,{connected:_,request:C,sessionId:x,onOpenDefaults:j,refreshKey:N,automation:b?{value:t.workspace,onChange:S=>$({workspace:S})}:void 0})]}):e==="tools"?o.jsxs("section",{className:"code-settings-section",children:[o.jsxs("label",{className:"code-field",children:["Permissions",o.jsxs("select",{"aria-label":"Permissions",value:t.permissions,disabled:i,onChange:S=>$({permissions:S.target.value}),children:[o.jsx("option",{value:"default",children:"Gateway default"}),o.jsx("option",{value:"read",children:"Read"}),o.jsx("option",{value:"write",children:"Write"}),o.jsx("option",{value:"all",children:"All enabled tools"})]})]}),o.jsx("p",{className:"code-field-help",children:"Saved for this Gateway account and future turns. Permissions never enable an unchecked tool. Explicit Ask overrides still ask, even with permissions: all."}),o.jsx(O_,{tools:r.filter(S=>S.enabled).map(S=>({...S,...S.sandboxState?{state:S.sandboxState}:{},default_approval:Sw(r,t.tools,t.permissions).autoApproveTools.includes(S.name)?"approve":"ask"})),value:t.tools,onChange:S=>$({tools:S,toolsCustomized:!0}),disabled:i,subtitle:"Choose available tools and when they should ask you. Gateway restrictions always apply.",note:"An empty custom selection disables every tool. Approvals follow the permissions level and each tool's override."}),r.some(S=>!S.enabled)?o.jsxs("details",{className:"code-disabled-tools",children:[o.jsxs("summary",{children:[r.filter(S=>!S.enabled).length," tools unavailable under gateway policy"]}),r.filter(S=>!S.enabled).map(S=>o.jsxs("p",{children:[o.jsx("strong",{children:S.name}),o.jsx("br",{}),S.whyDisabled||"Disabled by the gateway"]},S.name))]}):null,o.jsx("button",{className:"code-text-button",disabled:i,onClick:()=>$({toolsCustomized:!1,tools:os.tools,permissions:"default"}),children:"Use gateway default"})]}):o.jsx(D1,{value:t.skills,onChange:S=>$({skills:S}),disabled:i,lockedReasonId:h})]})}function B1({value:e,onChange:t,disabled:n,streaming:r}){const i=r.status!=="supported",c=r.status==="unsupported"?`Unavailable: ${r.reason}. Replies appear when they are complete.`:r.status==="loading"?"Checking whether this gateway supports live replies…":"Show the reply while the model writes it. The complete reply replaces the live text when the model call ends.";return o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"code-field",children:["Stream replies",o.jsxs("select",{"aria-label":"Stream replies","aria-describedby":"code-stream-replies-help",value:e,disabled:n||i,onChange:u=>t(u.target.value),children:[o.jsx("option",{value:"gateway_default",children:h1(r)}),o.jsx("option",{value:"on",children:"On"}),o.jsx("option",{value:"off",children:"Off"})]})]}),o.jsx("p",{id:"code-stream-replies-help",className:"code-field-help","data-streaming":r.status,children:c})]})}const ng=Mc("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).";function W1(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function V1(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 G1(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 V1(t)}async function zf(e){const t=String(e??"");return t?G1(t):!1}const H1=3,sg=["KB","MB","GB","TB"];function Ei(e){const t=Math.max(0,Number(e)||0);if(t<1024)return`${t} B`;let n=t/1024,r=0;for(;n>=1024&&r<sg.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${sg[r]}`}function rg(e){return`${Math.round(e).toLocaleString("en-US")} bytes`}function Nw(e,t){if(!t||!(t>0)||e.size<=t)return null;let n=Ei(e.size),r=Ei(t);return n===r&&(n=rg(e.size),r=rg(t)),`${e.name||"This file"} is ${n}; the gateway accepts files up to ${r}.`}function K1(e){return`Upload failed: ${String(e||"").replace(/^attachments_upload failed:?\s*/i,"").trim()||"the gateway did not say why"}`}function J1(e,t,n){return e.map(r=>{const i=Nw(r,t);return{id:n(),file:r,name:r.name||"Untitled file",size:r.size,status:i?"refused":"queued",...i?{message:i}:{}}})}async function Q1(e,t,n){let r=0;const i=Array.from({length:Math.max(1,Math.min(Math.floor(t)||1,e.length))},async()=>{for(;r<e.length;){const c=e[r];r+=1,await n(c)}});await Promise.all(i)}function $c(e){return`${e} ${e===1?"file":"files"}`}function ag(e,t){const n=[];return e&&n.push(`${$c(e)} attached`),t&&n.push(`${$c(t)} could not be attached`),n.join(", ")}function Y1(e){const t=e.filter(i=>i.status==="queued"||i.status==="uploading").length;if(t)return`Wait for ${$c(t)} to finish uploading.`;const n=e.filter(i=>i.status==="failed"||i.status==="refused");if(!n.length)return null;const r=n.some(i=>i.status==="failed");return n.length===1?`"${n[0].name}" was not attached. ${r?"Retry or remove":"Remove"} it before sending.`:`${$c(n.length)} were not attached. ${r?"Retry or remove":"Remove"} them before sending.`}const X1=e=>ve(`runs/${encodeURIComponent(e)}/workspace`),Ac=(e,t)=>fetch(e,{...t,credentials:"same-origin"});async function Cw(e){await mt(`${X1(e)}/open`,{method:"POST"})}function og(e,t){return typeof e.size_bytes!="number"?null:Nw({name:e.name,size:e.size_bytes},t)}function q1(e,t){return t?t.status==="refused"?`Not attached: ${t.message||"refused by the gateway's attachment policy"}`:`${e} is uploading; its chip in the message box shows when it is attached.`:`${e} was not queued for upload.`}async function Z1(e,t,n,r){const i=og(t,n);if(i)return`Not attached: ${i}`;const c=new AbortController,u=await fetch(Zy(e,t.path),{credentials:"same-origin",signal:c.signal});if(!u.ok)throw new Error(`Could not read ${t.name} (${u.status}): ${await u.text()}`);const d=og({...t,size_bytes:Yy(u)},n);if(d)return c.abort(),`Not attached: ${d}`;const h=await u.blob(),[m]=r([new File([h],t.name,{type:h.type})]);return q1(t.name,m)}function eN({runId:e,enabled:t,refreshKey:n,maxAttachmentBytes:r,onAttachFiles:i,heading:c="Conversation files"}){const[u,d]=y.useState(""),[h,m]=y.useState("");return e?o.jsxs(o.Fragment,{children:[u?o.jsx("p",{className:"code-field-help",role:"status",children:u}):null,t?o.jsx(Mf,{fetchGateway:Ac,runId:e,title:c,refreshKey:n,className:"code-workspace-browser",copyText:zf,onOpenFolder:()=>Cw(e),fileActions:p=>o.jsx("button",{type:"button",className:"af-file-viewer__icon-btn","data-action":"attach-file",title:"Attach to the next message","aria-label":`Attach ${p.name} to the next message`,disabled:h===p.path,onClick:()=>{m(p.path),d(""),Z1(e,p,r,i).then(d).catch(v=>d(vt(v))).finally(()=>m(""))},children:o.jsx(re,{name:h===p.path?"loader":"paperclip",size:15})})},e):null]}):o.jsxs("div",{className:"code-pane-empty",children:[o.jsx(re,{name:"folder",size:28}),o.jsx("p",{children:"This conversation's files appear here."}),o.jsx("small",{children:"Start a conversation; the files its workflow creates and edits are listed and previewed here."})]})}const tN=new Set(["abstract.progress","abstractcode.progress"]);function to(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function la(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function nN(e){if(!to(e))return null;const t=to(e.effect)?e.effect:null;if(!t||String(t.type||"")!=="emit_event")return null;const n=to(t.payload)?t.payload:null,r=String((n==null?void 0:n.name)??(n==null?void 0:n.event_name)??"").trim();if(!tN.has(r))return null;const i=to(e.result)?e.result:null,c=to(i==null?void 0:i.payload)?i==null?void 0:i.payload:null,u=to(n==null?void 0:n.payload)?n==null?void 0:n.payload:null,d=c||u;if(!d||String(d.kind||"")!=="llm")return null;const h=String(d.phase||"").trim();return h!=="prefill"&&h!=="generate"&&h!=="complete"?null:d}function sN(e){let t=null;for(const n of e||[]){const r=nN(n);r&&(t=r)}return!t||t.phase==="complete"||t.final===!0?null:t}function oo(e){return Math.round(e).toLocaleString()}function Ew(e){if(!e||e.phase!=="prefill")return null;const t=la(e.prompt_tokens),n=la(e.prefill_processed_tokens);if(t===null||t<=0||n===null||n<0)return null;const r=Math.min(n,t),i=Math.min(99,Math.round(r/t*100));return{processed:r,total:t,percent:i}}function $w(e){return`${oo(e.processed)} / ${oo(e.total)} tokens (${e.percent}%)`}function rN(e){if(!e)return"";if(e.phase==="prefill"){const t=Ew(e);if(t)return`Prefill · ${$w(t)}`;const n=la(e.prompt_tokens);if(n===null||n<=0)return"Prefill";const r=la(e.cached_tokens),i=la(e.fed_tokens),c=[];r!==null&&r>0&&c.push(`${oo(r)} cached`),i!==null&&i>0&&c.push(`${oo(i)} new`);const u=c.length?` (${c.join(", ")})`:"";return`Prefill · ${oo(n)} tokens${u}`}if(e.phase==="generate"){const t=la(e.generated_tokens)??0,n=Math.round(t)===1?"token":"tokens",r=la(e.tokens_per_second),i=r!==null&&r>0?` · ${Math.round(r)} tok/s`:"";return`Generating · ${oo(t)} ${n}${i}`}return""}function aN(e){return rN(sN(e))}const Aw=new Set(["abstract.progress","abstractcode.progress"]),oN=new Set(["abstract.status","abstractcode.status"]);function Ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Uf(e){const t=Ue(e);return!!(t&&t.$slim)}function kt(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function wn(e){return Math.round(e).toLocaleString("en-US")}function Gt(e,t=120){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function ji(e,t=120){var i,c;if(e==null)return"";if(typeof e=="string")return Gt(e,t);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return Gt(e.length===0?"[]":`${e.length} ${e.length===1?"item":"items"}`,t);const n=Ue(e);if(!n)return"";if(Uf(n)){const u=String(((i=n.$slim)==null?void 0:i.field)||""),d=kt((c=n.$slim)==null?void 0:c.bytes);return`${u||"payload"} stored${d?` · ${wn(d)} bytes`:""}`}const r=[];for(const[u,d]of Object.entries(n)){const h=typeof d=="string"?Gt(d,60):typeof d=="number"||typeof d=="boolean"?String(d):Array.isArray(d)?`${d.length} items`:d==null?"":"{…}";if(h&&(r.push(`${u.replace(/_/g," ")} ${h}`),r.join(" · ").length>=t))break}return Gt(r.join(" · "),t)}function Hc(e){return`${e>=100?String(Math.round(e)):e.toFixed(e<1?2:1).replace(/\.0+$/,"")} s`}function Tw(e,t){const n=Date.parse(String(e||"")),r=Date.parse(String(t||""));if(!Number.isFinite(n)||!Number.isFinite(r))return null;const i=(r-n)/1e3;return i>=0?i:null}function iN(e){const t=String(e||""),n=/T(\d{2}:\d{2}:\d{2})/.exec(t);return n?n[1]:""}function Rw(e){const t=String(e||"").trim();if(!t)return"";const n=t.split("/").pop()||t;return n.length>48?`${n.slice(0,47)}…`:n}function Ht(e,t=" · "){return e.filter(n=>!!n).join(t)}const ig="visual_react_agent_";function lN(e){if(!/^[A-Za-z0-9_-]{8,}$/.test(e))return null;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return!/^[ -~]{3,}$/.test(n)||!/[a-z]/i.test(n)?null:n}catch{return null}}function cN(e){const t=String(e||"").trim();if(!t)return{name:"",node:""};const n=/^([^@]+)@([^:]+)(?::(.+))?$/.exec(t);if(n)return{name:n[1],node:n[3]||""};if(t.startsWith(ig)){const r=t.slice(ig.length),i=/^(.*)_(\d+)_(\d+)_(\d+)_([0-9a-f]{6,12})_(.+)$/.exec(r);if(i){let c=i[1];if(c.includes("__")){const u=c.split("__").filter(Boolean);for(let d=u.length-1;d>=0;d-=1){const h=lN(u[d]);if(h&&h.length>3){c=h;break}}}return{name:c,node:i[6]}}return{name:r,node:""}}return{name:t,node:""}}function uN(e){var n;if(!Array.isArray(e)||!e.length)return"";const t=new Map;for(const r of e){const i=String(((n=Ue(r))==null?void 0:n.name)||"").trim()||"tool";t.set(i,(t.get(i)||0)+1)}return[...t.entries()].map(([r,i])=>i>1?`${r} ×${i}`:r).join(", ")}function dN(e){var d;const t=Ue(e);if(!t)return null;const n=Ue(t.effect);if(!n||String(n.type||"")!=="emit_event")return null;const r=Ue(n.payload),i=String((r==null?void 0:r.name)??(r==null?void 0:r.event_name)??"").trim();if(!Aw.has(i))return null;const c=Ue((d=Ue(t.result))==null?void 0:d.payload),u=Ue(r==null?void 0:r.payload);return c||u}function fN(e){if(!e.length)return"";const t=e[e.length-1];let n=null,r=null,i=null,c=null,u=null;for(const p of e)n=kt(p.prompt_tokens)??n,r=kt(p.cached_tokens)??r,i=kt(p.generated_tokens)??i,c=kt(p.tokens_per_second)??c,u=kt(p.elapsed_s)??u;if(t.final===!0||String(t.phase||"")==="complete")return Ht([n!==null?`${wn(n)} tokens in`:null,r!==null&&r>0?`${wn(r)} cached`:null,i!==null?`${wn(i)} out`:null,u!==null?Hc(u):null,c!==null&&c>0?`${Math.round(c)} tok/s`:null]);const h=n!==null?`prefill ${wn(n)} tokens${r!==null&&r>0?` (${wn(r)} cached)`:""}`:"prefill";if(String(t.phase||"")==="prefill"){const p=Ew(t);return p?`prefill ${$w(p)}`:h}const m=Ht([`generating ${wn(i??0)} ${Math.round(i??0)===1?"token":"tokens"}`,c!==null&&c>0?`${Math.round(c)} tok/s`:null]);return`${h} → ${m}`}function hN(e){if(!e.length)return"";const t=e[e.length-1],n=kt(t.step)??kt(t.index),r=kt(t.total)??kt(t.steps),i=kt(t.percent)??kt(t.progress),c=kt(t.frame),u=kt(t.elapsed_s);return Ht([typeof t.label=="string"?Gt(t.label,60):null,typeof t.phase=="string"&&!t.label?Gt(t.phase,40):null,n!==null?`step ${wn(n)}${r!==null?`/${wn(r)}`:""}`:null,c!==null?`frame ${wn(c)}`:null,i!==null?`${Math.round(i<=1?i*100:i)}%`:null,u!==null?Hc(u):null])}function lg(e){return e.length?String(e[e.length-1].kind||"")==="llm"?fN(e):hN(e):""}function mN(e,t,n){var N;const r=String(e.provider||"").trim(),i=Rw(e.model||(t==null?void 0:t.model)),c=Ht(["llm",r,i])||"llm call";if(!t){const $=Ue(e.params)||{};return{title:c,detail:Ht([kt($.temperature)!==null?`temperature ${$.temperature}`:null,$.thinking?`thinking ${$.thinking}`:null,(N=Ue($.speculation))!=null&&N.mode?`speculation ${Ue($.speculation).mode}`:null])}}const u=Ue(t.usage)||{},d=Ue(t.metadata)||{},h=Ue(d.prompt_cache)||{},m=Ue(d.performance)||{},p=kt(u.prompt_tokens)??kt(u.input_tokens),v=kt(u.completion_tokens)??kt(u.output_tokens),_=kt(h.cached_tokens),b=String(h.outcome||"").trim(),C=Tw(n.started_at,n.ended_at),x=kt(m.generation_tokens_per_second),j=Array.isArray(t.tool_calls)?t.tool_calls.length:0;return{title:c,detail:Ht([p!==null?`${wn(p)} tokens in`:null,_!==null&&_>0?`${wn(_)} cached`:b?`${b} cache`:null,v!==null?`${wn(v)} out`:null,C!==null?Hc(C):null,x!==null&&x>0?`${Math.round(x)} tok/s`:null,j?`${j} tool ${j===1?"call":"calls"}`:null])}}function pN(e,t){if(t.length<=60)return Gt(t,60);if(e==="url")try{const n=new URL(t),r=n.pathname.split("/").filter(Boolean).pop()||"";return Gt(`${n.host}${r?` · …/${r}`:""}`,72)}catch{}if(e==="file path"||e==="path"){const n=t.split(/[\\/]/).pop()||t;return Gt(`${n} · ${t.slice(0,24)}…`,60)}return Gt(t,60)}function gN(e,t){const n=Array.isArray(e.tool_calls)?e.tool_calls:[],r=uN(n),i=Ue(n[0]),c=i?Py(i.arguments):{label:"",value:""},u=Array.isArray(t==null?void 0:t.results)?t.results:[],d=u.filter(m=>{var p;return((p=Ue(m))==null?void 0:p.success)===!0}).length,h=u.length-d;return{title:Ht(["tools",r||"tool call"]),detail:Ht([c.value?`${c.label} ${pN(c.label,c.value)}`:null,u.length?`${d} ok`:null,h>0?`${h} failed`:null])}}function yN(e,t){var m,p;const{name:n,node:r}=cN(e.workflow_id),i=Ue(e.vars),c=i&&!Uf(i)?i:null,u=Ue(c==null?void 0:c.context),d=typeof(u==null?void 0:u.task)=="string"?u.task:typeof(c==null?void 0:c.request)=="string"?c.request:"",h=String(((p=Ue((m=Ue(t==null?void 0:t.wait))==null?void 0:m.details))==null?void 0:p.sub_run_id)||"").slice(0,8);return c&&typeof c.state=="string"&&!u?{title:"subflow · status",detail:Ht([Gt(c.state,80),h&&`run ${h}`])}:d?{title:"subflow · agent loop",detail:Ht([n,Gt(d,90),h&&`run ${h}`])}:{title:Ht(["subflow",n||"workflow"]),detail:Ht([r,c?ji(c,80):null,h&&`run ${h}`])}}function wN(e,t){const n=e.until,r=Tw(t.started_at,n),i=iN(n);return{title:r!==null?`wait · delay ${Hc(r)}`:`wait · until ${i}`,detail:Ht([r!==null&&i?`until ${i}`:null,e.resume_to_node?`resumes at ${e.resume_to_node}`:null])}}function cg(e){var d;const t=Ue(e)||{},n=Ue(t.effect),r=String((n==null?void 0:n.type)||"").trim(),i=Ue(n==null?void 0:n.payload)||{},c=Ue(t.result);if(r==="emit_event"){const h=String(i.name??i.event_name??"").trim();if(Aw.has(h))return{kind:"progress",title:"progress",detail:"",isProgress:!0,isStatus:!1,isResume:!1,hidden:!0};if(oN.has(h))return{kind:"event",title:"status",detail:ji(i.payload,80),isProgress:!1,isStatus:!0,isResume:!1,hidden:!0};const m=String(i.scope||"").trim();return{kind:"event",title:`event · ${h||"unnamed"}${m?` (${m})`:""}`,detail:ji(i.payload??(c==null?void 0:c.payload),110),isProgress:!1,isStatus:!1,isResume:!1,hidden:!1}}if(r==="resume")return{kind:"step",title:"resume",detail:String(i.wait_reason||""),isProgress:!1,isStatus:!1,isResume:!0,hidden:!0};const u={isProgress:!1,isStatus:!1,isResume:!1,hidden:!1};if(r==="llm_call")return{kind:"llm",...mN(i,c,t),...u};if(r==="tool_calls")return{kind:"tools",...gN(i,c),...u};if(r==="start_subworkflow")return{kind:"subflow",...yN(i,c),...u};if(r==="wait_until")return{kind:"wait",...wN(i,t),...u};if(r==="wait_event")return{kind:"wait",title:"wait · event",detail:Ht([typeof i.prompt=="string"?Gt(i.prompt,90):null,!i.prompt&&i.wait_key?Gt(String(i.wait_key),70):null]),...u};if(r==="ask_user")return{kind:"ask",title:"ask · your input",detail:Gt(String(i.prompt||((d=Ue(c==null?void 0:c.wait))==null?void 0:d.prompt)||"").split(`
90
+ `)[0],110),...u};if(r==="answer_user")return{kind:"message",title:"message",detail:Gt(String(i.message||""),110),...u};if(!r){if((c==null?void 0:c.completed)===!0){const h=Ue(c.output)||{},m=Ue(h.stop_reason)||{},p=kt(h.iterations),v=Ht([String(m.code||h.outcome||"").replace(/_/g," ")||null,p!==null?`${wn(p)} ${p===1?"iteration":"iterations"}`:null]),_=[h.answer,h.response,h.result].find(b=>typeof b=="string"&&b.trim());return{kind:"run",title:"run finished",detail:v||(typeof _=="string"?Gt(_,110):ji(h,110)),...u}}return{kind:"step",title:String(t.node_id||"workflow step"),detail:"",...u}}return{kind:"step",title:r.replace(/_/g," "),detail:ji(i,110),...u}}function vN(e,t,n){var c,u;const r=Ue(e)||{},i=String(r.status||"").trim();if(r.error)return{status:"failed",statusLabel:"failed"};if(i==="failed")return{status:"failed",statusLabel:"failed"};if(i==="completed")return{status:"completed",statusLabel:"completed"};if(i==="waiting"){if(n)return{status:"completed",statusLabel:"completed"};const d=Ue((c=Ue(r.result))==null?void 0:c.wait);return String(((u=Ue(d==null?void 0:d.details))==null?void 0:u.mode)||"")==="approval_required"?{status:"waiting",statusLabel:"approval needed"}:t==="subflow"?{status:"waiting",statusLabel:"waiting for subflow"}:t==="ask"?{status:"waiting",statusLabel:"waiting for you"}:t==="wait"?{status:"waiting",statusLabel:String((d==null?void 0:d.reason)||"")==="until"?"waiting":"waiting for event"}:{status:"waiting",statusLabel:"waiting"}}return i==="started"?{status:"started",statusLabel:"running"}:{status:i||"started",statusLabel:i||"running"}}function _N(e){var i;const t=Ue(e.record)||{},n=String(((i=Ue(t.effect))==null?void 0:i.type)||"(none)"),r=String(t.idempotency_key||t.step_id||e.cursor);return`${e.runId}|${n}|${r}|${t.attempt??1}`}function bN(e){var h;const t=e.map(m=>Ue(m.record)||{}),n=t[t.length-1]||{},r={};for(const m of t){const p=Ue((h=Ue(m.effect))==null?void 0:h.payload);if(p)for(const[v,_]of Object.entries(p))Uf(_)&&v in r||(r[v]=_)}let i=null,c=null,u=null,d=null;for(const m of t)m.result!==null&&m.result!==void 0&&(i=m.result),m.error!==null&&m.error!==void 0&&(c=m.error),!u&&m.started_at&&(u=m.started_at),m.ended_at&&(d=m.ended_at);return{...n,effect:n.effect?{...n.effect,payload:r}:n.effect,result:i,error:c,started_at:u,ended_at:d}}function xN(e){var n,r;const t=[];for(const i of e){const c=Ue((r=Ue((n=Ue(i.record))==null?void 0:n.result))==null?void 0:r.wait),u=String((c==null?void 0:c.wait_key)||"").trim();u&&t.push(u)}return t}function kN(e,t){return`${e}|${String(t.step_id||t.node_id||"")}`}function jN(e,t){const n=new Map;for(const c of t){const u=dN(c.record);if(!u)continue;const d=kN(c.runId,u),h=n.get(d)||{entries:[],payloads:[]};h.entries.push(c),h.payloads.push(u),n.set(d,h)}if(!n.size)return e.map(c=>({...c}));const r=new Set,i=e.map(c=>{const u=c.stepIds.map(b=>`${c.runId}|${b}`).filter(b=>n.has(b));if(!u.length)return{...c};const d=[],h=[];for(const b of u)r.add(b),d.push(...n.get(b).payloads),h.push(...n.get(b).entries);const m=lg(d),p=d[d.length-1],v=p.final===!0||String(p.phase||"")==="complete",_=!(v&&c.status==="completed"&&c.detail);return{...c,progress:_?m:"",progressFinal:v,progressEvents:h.map(b=>Ue(b.record)||{})}});for(const[c,u]of n.entries()){if(r.has(c))continue;const d=u.payloads,h=d[d.length-1],m=String(h.kind||""),p=u.entries[0];i.push({key:`progress:${c}`,runId:p.runId,cursor:u.entries[u.entries.length-1].cursor,kind:"progress",title:Ht(m==="llm"?["llm",String(h.provider||""),Rw(h.model)]:["progress",m]),detail:"",status:h.final===!0||String(h.phase||"")==="complete"?"completed":"started",statusLabel:h.final===!0||String(h.phase||"")==="complete"?"completed":"running",nodeId:String(h.node_id||""),stepIds:[String(h.step_id||"")],progress:lg(d),progressFinal:h.final===!0||String(h.phase||"")==="complete",entries:u.entries,progressEvents:u.entries.map(v=>Ue(v.record)||{}),merged:Ue(u.entries[u.entries.length-1].record)||{}})}return i}function Bf(e,t){var v,_,b,C;const n=String(t||((v=e==null?void 0:e[0])==null?void 0:v.runId)||""),r=new Map,i=[],c=[],u=new Map,d=new Map,h=[];for(const x of e||[]){const j=cg(x.record);if(j.isProgress){h.push(x);continue}if(j.isStatus)continue;if(j.isResume){const $=String(((C=(b=Ue((_=Ue(x.record))==null?void 0:_.effect))==null?void 0:b.payload)==null?void 0:C.wait_key)||"").trim();$&&c.push($);continue}const N=_N(x);d.set(x,d.size),u.set(x.runId,d.size-1),r.has(N)||(r.set(N,[]),i.push(N)),r.get(N).push(x)}const m=new Set(c),p=i.map(x=>{const j=r.get(x),N=bN(j),$=cg(N),S=j[j.length-1],A=(u.get(S.runId)??-1)>(d.get(S)??1/0)||xN(j).some(F=>m.has(F)),I=vN(N,$.kind,A);return{key:x,runId:j[0].runId,cursor:j[j.length-1].cursor,kind:$.kind,title:$.kind==="run"&&n&&j[0].runId!==n?"subflow finished":$.title,detail:$.detail,status:I.status,statusLabel:I.statusLabel,nodeId:String(N.node_id||""),stepIds:[...new Set(j.map(F=>{var L;return String(((L=Ue(F.record))==null?void 0:L.step_id)||"")}).filter(Boolean))],progress:"",progressFinal:!1,entries:j,progressEvents:[],merged:N}});return jN(p,h)}const SN=["running","waiting","failed","completed"],NN={running:"Running",failed:"Failed",completed:"Done"},CN=new Set(["waiting for you","approval needed"]);function EN(e,t){var i;if(e!=="waiting")return NN[e]||e;const n=t.filter(c=>c.status==="waiting");if(n.some(c=>CN.has(c.statusLabel)))return"Waiting for you";const r=((i=n[n.length-1])==null?void 0:i.statusLabel)||"waiting";return r.charAt(0).toUpperCase()+r.slice(1)}function $N(e){for(const t of SN)if(e.some(n=>n.status===t))return t;return e.length?e[e.length-1].status:"completed"}function AN(e){const t=[];let n=null,r=0;for(const i of e){if(i.kind==="llm"||!n){const c=i.kind==="llm";c&&(r+=1),n={key:`${c?"step":"start"}:${i.key}`,title:c?`Step ${r}`:"Start",detail:c?i.title:"",status:"completed",statusLabel:"Done",rows:[],toolRows:0},t.push(n)}n.rows.push(i),i.kind==="tools"&&(n.toolRows+=1)}for(const i of t)i.status=$N(i.rows),i.statusLabel=EN(i.status,i.rows);return t}function TN(e){return e.length?e[e.length-1].key:""}function RN({policy:e,runId:t,enabled:n,isAdmin:r,refreshKey:i,onAttach:c,onAttachFiles:u,includeArtifacts:d=!0}){const[h,m]=y.useState("session");return o.jsxs(o.Fragment,{children:[r?o.jsxs("div",{className:"code-files-mode",role:"group","aria-label":"Files source",children:[o.jsx("button",{"aria-pressed":h==="session",onClick:()=>m("session"),children:"This conversation"}),o.jsx("button",{"aria-pressed":h==="shared",onClick:()=>m("shared"),children:"Gateway files (admin)"})]}):null,r?o.jsx("div",{hidden:h!=="shared",children:o.jsx(UN,{policy:e,enabled:n&&h==="shared",runId:t,onAttach:c})}):null,o.jsx("div",{hidden:r&&h!=="session",children:o.jsx(eN,{runId:t,enabled:n&&(!r||h==="session"),refreshKey:i,maxAttachmentBytes:e==null?void 0:e.maxAttachmentBytes,onAttachFiles:u})}),d?o.jsxs("section",{className:"code-rail-section","aria-labelledby":"code-artifacts-title",children:[o.jsx("h3",{id:"code-artifacts-title",className:"code-rail-section-title",children:"Generated outputs & attachments"}),o.jsx(GN,{runId:t,enabled:n,refreshKey:i})]}):null]})}function IN({records:e,runId:t}){const n=y.useMemo(()=>Bf(e,t),[e,t]);return n.length?o.jsx(Iw,{rows:n}):o.jsxs("div",{className:"code-pane-empty",children:[o.jsx(re,{name:"activity",size:28}),o.jsx("p",{children:"Follow the work as it happens."}),o.jsx("small",{children:"Model steps, tool calls and approvals appear here, one group per step."})]})}function MN(e,t){const n=Bf(e,t),r=n.filter(u=>u.status==="waiting").length,i=n.filter(u=>u.status==="running").length,c=[r?`${r} waiting`:"",i?`${i} running`:""].filter(Boolean);return{count:r+i,hint:c.join(" · ")}}function Iw({rows:e}){const t=y.useMemo(()=>AN(e),[e]),n=TN(t),[r,i]=y.useState({});return o.jsx("div",{className:"code-activity-groups",children:t.map(c=>{const u=r[c.key]??c.key===n;return o.jsxs("details",{className:`code-activity-group is-${c.status}`,"data-group":c.title,open:u,onToggle:d=>{const h=d.currentTarget.open;h!==u&&i(m=>({...m,[c.key]:h}))},children:[o.jsxs("summary",{children:[o.jsx(re,{name:"chevronRight",size:14,className:"code-activity-group-chevron"}),o.jsx("strong",{children:c.title}),c.detail?o.jsx("span",{className:"code-activity-group-detail",title:c.detail,children:c.detail}):o.jsx("span",{className:"code-activity-group-detail"}),o.jsx("span",{className:`code-step-dot is-${c.status}`,"aria-hidden":"true"}),o.jsx("small",{children:c.statusLabel})]}),u?o.jsx(LN,{group:c}):null]},c.key)})})}function LN({group:e}){const t=y.useMemo(()=>e.rows.flatMap(i=>i.entries.map(c=>({cursor:c.cursor,record:c.record,runId:c.runId}))),[e]),n=y.useMemo(()=>Ni(t).tools,[t]),r=e.rows.filter(i=>i.kind!=="tools");return o.jsxs("div",{className:"code-activity-group-body",children:[r.map(i=>o.jsx(PN,{row:i},i.key)),n.length?o.jsx(Tf,{tools:n}):null]})}const ON={llm:"sparkle",tools:"terminal",subflow:"agent",event:"info",wait:"history",ask:"chat",message:"send",run:"playCircle",progress:"loader",step:"list"};function PN({row:e}){const t=e.merged,n=t.effect||{};return o.jsxs("details",{className:`code-activity-row code-activity-row--${e.kind}`,children:[o.jsxs("summary",{children:[o.jsx("span",{className:"code-activity-icon","aria-hidden":"true",children:o.jsx(re,{name:ON[e.kind],size:14})}),o.jsxs("span",{className:"code-activity-text",children:[o.jsx("span",{className:"code-activity-title",children:e.title}),e.detail?o.jsx("span",{className:"code-activity-sub",children:e.detail}):null,e.progress?o.jsx("span",{className:"code-activity-progress",children:e.progress}):null]}),o.jsx("span",{className:`code-step-dot is-${e.status}`}),o.jsx("small",{children:e.statusLabel})]}),o.jsxs("div",{className:"code-activity-detail",children:[o.jsxs("div",{className:"code-field-help",children:[e.nodeId?`${e.nodeId} · `:"","run ",e.runId.slice(0,8)," · ",e.entries.length," ",e.entries.length===1?"record":"records",e.progressEvents.length?` · ${e.progressEvents.length} progress`:""]}),o.jsx(io,{value:{input:n.payload,result:t.result,error:t.error,records:e.entries.map(r=>r.record),...e.progressEvents.length?{progress:e.progressEvents}:{}},collapseAfterDepth:2})]})]})}async function DN(e,t,n=2e3){var c;const r=[];let i=0;for(;r.length<n;){if(t!=null&&t.aborted)throw new DOMException("aborted","AbortError");const u=await En.get_ledger(e,{after:i,limit:500}),d=Array.isArray(u.items)?u.items:[];for(const h of d){const m=Number(h==null?void 0:h.cursor)||i+r.length+1;r.push({cursor:m,record:(h==null?void 0:h.record)??h,runId:String(((c=h==null?void 0:h.record)==null?void 0:c.run_id)||e)})}if(!d.length||!u.next_after||u.next_after<=i)break;i=u.next_after}return r}function FN({occurrences:e,nowMs:t,loadRecords:n=DN,onOpenRun:r}){var h;const i=y.useMemo(()=>[...e].sort((m,p)=>p.index-m.index),[e]),c=((h=i[0])==null?void 0:h.run_id)||"",[u,d]=y.useState({});return i.length?o.jsx("div",{className:"code-activity-groups","data-scope":"automation",children:i.map(m=>{const p=u[m.run_id]??m.run_id===c,v=m.finished_at||m.fired_at;return o.jsxs("details",{className:`code-activity-group is-${m.status}`,"data-group":`Run #${m.index}`,open:p,onToggle:_=>{const b=_.currentTarget.open;b!==p&&d(C=>({...C,[m.run_id]:b}))},children:[o.jsxs("summary",{children:[o.jsx(re,{name:"chevronRight",size:14,className:"code-activity-group-chevron"}),o.jsxs("strong",{children:["Run #",m.index]}),o.jsx("span",{className:"code-activity-group-detail",children:v?o.jsx("time",{title:zc(v),children:co(v,t)}):null}),o.jsx("span",{className:`code-step-dot is-${m.status}`,"aria-hidden":"true"}),o.jsx("small",{children:m.status})]}),p?o.jsx(zN,{occurrence:m,loadRecords:n,onOpenRun:r}):null]},m.run_id)})}):o.jsxs("div",{className:"code-pane-empty",children:[o.jsx(re,{name:"activity",size:28}),o.jsx("p",{children:"No runs yet."}),o.jsx("small",{children:"Each run of this automation appears here as one group."})]})}function zN({occurrence:e,loadRecords:t,onOpenRun:n}){var u;const[r,i]=y.useState({status:"loading"});y.useEffect(()=>{const d=new AbortController;return i({status:"loading"}),t(e.run_id,d.signal).then(h=>!d.signal.aborted&&i({status:"ready",records:h})).catch(h=>!d.signal.aborted&&i({status:"error",message:`Run activity unavailable: ${vt(h)}`})),()=>d.abort()},[e.run_id,e.status,t]);const c=y.useMemo(()=>r.status==="ready"?Bf(r.records,e.run_id):[],[r,e.run_id]);return o.jsxs("div",{className:"code-activity-group-body",children:[(u=e.failure)!=null&&u.message?o.jsx("p",{className:"code-error-text",role:"alert",children:e.failure.message}):null,r.status==="loading"?o.jsx("p",{className:"code-muted",role:"status",children:"Loading run activity…"}):null,r.status==="error"?o.jsx("p",{className:"code-error-text",role:"alert",children:r.message}):null,r.status==="ready"?c.length?o.jsx(Iw,{rows:c}):o.jsx("p",{className:"code-muted",children:"This run recorded no steps."}):null,n?o.jsxs("button",{type:"button",className:"code-subtle-button",onClick:()=>n(e.run_id),children:[o.jsx(re,{name:"chat",size:13})," ",o.jsx("span",{children:"Open as conversation"})]}):null]})}function UN({policy:e,enabled:t,runId:n,onAttach:r}){const[i,c]=y.useState(""),[u,d]=y.useState(""),[h,m]=y.useState([]),[p,v]=y.useState(!1),[_,b]=y.useState(""),[C,x]=y.useState(""),[j,N]=y.useState(0),[$,S]=y.useState("");return y.useEffect(()=>{const E=new AbortController;if(m([]),b(""),x(""),!t||!e)return;v(!0);const A=window.setTimeout(()=>{const I=new URLSearchParams({limit:"100"});i.trim()?I.set("query",i.trim()):u&&I.set("path",u),mt(ve(`files/${i.trim()?"search":"list"}?${I}`),{signal:E.signal}).then(F=>{if(F.error)throw new Error(String(F.error));m(Array.isArray(F.items)?F.items:[]),(F.truncated||F.has_more)&&x("Showing the first 100 results. Search to narrow the list.")}).catch(F=>{E.signal.aborted||b(vt(F))}).finally(()=>{E.signal.aborted||v(!1)})},i?220:0);return()=>{window.clearTimeout(A),E.abort()}},[t,e,i,u,j,n]),o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"code-pane-intro",children:[o.jsx(re,{name:"terminal",size:17}),o.jsxs("div",{children:[o.jsx("strong",{children:"Gateway files (admin)"}),o.jsx("span",{children:u||"The gateway's files"})]}),o.jsx("button",{className:"code-icon-button","aria-label":"Refresh files",onClick:()=>N(E=>E+1),disabled:!t,children:o.jsx(re,{name:"refresh",size:14})})]}),o.jsx("input",{className:"code-search","aria-label":"Search workspace files",placeholder:"Search files…",value:i,onChange:E=>c(E.target.value),disabled:!t}),u?o.jsx("button",{className:"code-back",onClick:()=>{d(u.split("/").slice(0,-1).join("/")),c("")},children:"← Parent folder"}):null,t?null:o.jsx("p",{className:"code-pane-empty",children:"Connect to browse your workspace."}),p?o.jsx("p",{className:"code-muted",role:"status",children:"Loading files…"}):null,_?o.jsxs("div",{className:"code-inline-error",role:"alert",children:[_,o.jsx("button",{onClick:()=>N(E=>E+1),children:"Retry"})]}):null,C?o.jsx("p",{className:"code-field-help",role:"status",children:C}):null,o.jsx("ul",{className:"code-file-list",children:h.map(E=>{const A=E.kind==="folder"||E.is_dir||E.type==="directory"||E.type==="dir";return o.jsx("li",{children:o.jsxs("button",{title:A?`Show ${E.path}`:`Attach ${E.path} to the conversation`,disabled:!!$,onClick:async()=>{if(A){d(E.path),c("");return}S(E.path),b("");try{await r(E.path),x(`${E.name||E.path} attached.`)}catch(I){b(vt(I))}finally{S("")}},children:[o.jsx(re,{name:A?"folder":"paperclip",size:14}),o.jsx("span",{children:E.name||E.path}),$===E.path?o.jsx(re,{name:"loader",size:13}):o.jsx(re,{name:A?"chevronRight":"plus",size:13,className:"code-file-action"})]})},E.path)})}),!p&&!_&&t&&!h.length?o.jsxs("div",{className:"code-pane-empty",children:[o.jsx(re,{name:"terminal",size:28}),o.jsx("p",{children:i?"No matching files.":"No shared files yet."}),o.jsx("small",{children:i?"Try a shorter name or another folder.":"Browse files exposed by your gateway or attach files from your device."})]}):null]})}function BN(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase(),n=(t.split("/")[1]||"").replace(/^x-/,"").split("+")[0];return t==="application/pdf"?"PDF document":t==="application/json"||t.endsWith("+json")?"JSON file":t.startsWith("image/")?`${n.toUpperCase()} image`:t.startsWith("audio/")?`${n.toUpperCase()} audio`:t.startsWith("video/")?`${n.toUpperCase()} video`:t==="text/markdown"?"Markdown file":t.startsWith("text/")?"Text file":"File"}function WN(e){var r;const t=String(e.artifact_id||e.id||""),n=String(e.content_type||e.mime_type||"");return{id:t,name:String(e.filename||((r=e.metadata)==null?void 0:r.filename)||e.name||BN(n)),contentType:n,...typeof e.size_bytes=="number"?{size:e.size_bytes}:typeof e.size=="number"?{size:e.size}:{},...e.created_at||e.timestamp?{created:String(e.created_at||e.timestamp)}:{}}}function VN(e){return ff(e)?"text":e==="image"||e==="pdf"||e==="audio"?"url":"none"}function GN({runId:e,enabled:t,refreshKey:n}){const[r,i]=y.useState([]),[c,u]=y.useState(""),[d,h]=y.useState(0),[m,p]=y.useState(null),[v,_]=y.useState({status:"loading"}),b=Date.now();y.useEffect(()=>{if(i([]),u(""),p(null),!e||!t)return;const x=new AbortController;return mt(ve(`runs/${encodeURIComponent(e)}/artifacts?limit=200`),{signal:x.signal}).then(j=>i((Array.isArray(j.items)?j.items:Array.isArray(j.artifacts)?j.artifacts:[]).map(WN))).catch(j=>{x.signal.aborted||u(vt(j))}),()=>x.abort()},[e,t,d,n]),y.useEffect(()=>{if(!m)return;let x=!0,j="";return _({status:"loading"}),En.get_run_artifact_blob(e,m.id).then(async({blob:N,content_type:$})=>{const S=VN(xc(m.name,$));if(S==="text"){const E=await N.slice(0,Sc).text();x&&_({status:"ready",text:E,partial:N.size>Sc,total:N.size,contentType:$})}else S==="url"?(j=URL.createObjectURL(N.type?N:new Blob([N],{type:$})),x&&_({status:"ready",url:j,partial:!1,contentType:$})):x&&_({status:"ready",partial:!1,contentType:$})}).catch(N=>x&&_({status:"error",message:`Preview failed: ${vt(N)}`})),()=>{x=!1,j&&URL.revokeObjectURL(j)}},[e,m]);const C=x=>void l0(e,x.id,x.name).catch(j=>u(vt(j)));return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"code-rail-toolbar",children:o.jsx("button",{className:"code-icon-button","aria-label":"Refresh outputs",title:"Refresh",onClick:()=>h(x=>x+1),children:o.jsx(re,{name:"refresh",size:14})})}),c?o.jsx("p",{role:"alert",className:"code-error-text",children:c}):null,m?o.jsx(qy,{name:m.name,sizeBytes:m.size,modified:m.created,nowMs:b,contentType:v.status==="ready"?v.contentType:m.contentType,status:v.status,...v.status==="error"?{error:v.message}:{},...v.status==="ready"?{text:v.text,url:v.url,...v.partial?{partialNote:Xy(v.total)}:{}}:{},onDownload:()=>C(m),onClose:()=>p(null)}):r.length?o.jsx("ul",{className:"code-file-rows",children:r.map(x=>o.jsxs("li",{className:"code-file-row",children:[o.jsxs("button",{className:"code-file-row-name",title:`Preview ${x.name} · ${x.id}`,onClick:()=>p(x),children:[o.jsx(re,{name:"file",size:14}),o.jsx("span",{children:x.name})]}),o.jsxs("span",{className:"code-file-row-meta",children:[x.size!==void 0?o.jsx("span",{children:Uc(x.size)}):null,x.created?o.jsx("time",{title:zc(x.created),children:co(x.created,b)}):null]}),o.jsx("button",{className:"code-icon-button","aria-label":`Download ${x.name}`,title:"Download",onClick:()=>C(x),children:o.jsx(re,{name:"download",size:14})})]},x.id))}):c?null:o.jsx("p",{className:"code-muted",children:"Generated files and attachments appear here."})]})}const Mw=[{id:"activity",label:"Activity",icon:"activity"},{id:"files",label:"Files",icon:"file"},{id:"model",label:"Model",icon:"sparkle"},{id:"workflow",label:"Workflow",icon:"agent"},{id:"workspace",label:"Workspace",icon:"folder"},{id:"tools",label:"Tools",icon:"terminal"},{id:"skills",label:"Skills",icon:"list"},{id:"voice",label:"Voice",icon:"mic"}],ug=Mw.map(e=>e.id),Lw="abstractcode.rail.panel.v2",HN="abstractcode.rail.panel.v1",KN="abstractcode.rail.width.v1";function JN(e){try{const t=e==null?void 0:e.getItem(Lw);if(t!=null)return ug.includes(t)?t:null;const n=e==null?void 0:e.getItem(HN);return n==="settings"?"model":ug.includes(n)?n:null}catch{return null}}function QN(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function YN(){const e=vc($i.md),[t,n]=y.useState(()=>{var i;return typeof window<"u"&&!((i=window.matchMedia)!=null&&i.call(window,$i.md).matches)?JN(QN()):null});y.useEffect(()=>{e&&n(null)},[e]);const r=y.useCallback(i=>{if(n(i),!e)try{window.localStorage.setItem(Lw,i??"")}catch{}},[e]);return[t,r,e]}function XN(e){return o.jsx(ck,{className:"code-rail",ariaLabel:"Workspace panels",idBase:"code-rail",storageKey:KN,defaultWidth:420,minWidth:320,maxWidth:900,active:e.panel,onActiveChange:t=>e.onPanel(t),items:Mw.map(t=>({id:t.id,label:t.label,icon:t.icon,content:e.content[t.id],...t.id==="activity"?{badge:e.activityBadge,hint:e.activityHint}:{}}))})}const Tr=e=>e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},Nr=e=>typeof e=="string"?e:typeof e=="number"?String(e):"",Hd=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!==""):[];function fc(e){const t=Tr(e),n=Tr(t._runtime),r=Tr(t._limits),i=Nr(t.provider)||Nr(n.provider),c=Nr(t.model)||Nr(n.model),u=Ii(t),d=Tr(n.tool_policy),h={};for(const p of Hd(d.auto_approve_tools))h[p]="approve";for(const p of Hd(d.require_approval_tools))h[p]="ask";const m=u!==null||Object.keys(h).length>0;return{...os,provider:i&&c?i:"",model:i&&c?c:"",reasoning:Nr(n.thinking),...n.speculation!==void 0?{speculation:n.speculation}:{},maxIterations:Nr(r.max_iterations),maxTokens:Nr(r.max_tokens),system:Nr(n.system_prompt_extra),workspace:t.workspace&&typeof t.workspace=="object"&&Array.isArray(t.workspace.folders)?t.workspace:null,tools:u===null?{mode:"all",selected:[],approval:h}:{mode:"custom",selected:u,approval:h},toolsCustomized:m,permissions:"default",skills:Hd(t.skills),workflow:os.workflow,streamReplies:"gateway_default"}}function ss(e,t,n){n==null||n===""||Array.isArray(n)&&!n.length?delete e[t]:e[t]=n}function dg(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function qN(e,t){let n=Tr(e);const r=Tr(n._runtime),i=Tr(n._limits),c=!!(t.provider&&t.model);ss(n,"provider",c?t.provider:""),ss(n,"model",c?t.model:""),ss(r,"provider",c?t.provider:""),ss(r,"model",c?t.model:""),ss(r,"thinking",t.reasoning),ss(r,"speculation",t.speculation),ss(r,"system_prompt_extra",t.system.trim()),ss(i,"max_iterations",dg(t.maxIterations)),ss(i,"max_tokens",dg(t.maxTokens));const u=Object.entries(t.tools.approval||{}).filter(([,m])=>m==="approve").map(([m])=>m),d=Object.entries(t.tools.approval||{}).filter(([,m])=>m==="ask").map(([m])=>m),h=t.toolsCustomized&&(u.length||d.length)?{...u.length?{auto_approve_tools:u}:{},...d.length?{require_approval_tools:d}:{}}:void 0;return ss(r,"tool_policy",h),Object.keys(r).length?n._runtime=r:delete n._runtime,Object.keys(i).length?n._limits=i:delete n._limits,delete n.workspace_access_mode,t.workspace===null?(n.workspace&&typeof n.workspace=="object"&&delete n.workspace_allowed_paths,delete n.workspace):(n.workspace={posture:t.workspace.posture,default_mode:t.workspace.default_mode,folders:t.workspace.folders.map(m=>({path:m.path,mode:m.mode}))},delete n.workspace_allowed_paths),ss(n,"skills",t.skills),n=Pc(n,t.toolsCustomized&&t.tools.mode==="custom"?t.tools.selected:null),n}function ZN(e,t){const n=Tr(e.target.input_data),r=qN(n,t);return Tc(n)===Tc(r)?null:{target:{bundle_ref:e.target.bundle_ref,flow_id:e.target.flow_id,input_data:r}}}function Tc(e){if(Array.isArray(e))return`[${e.map(Tc).join(",")}]`;if(e&&typeof e=="object"){const t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Tc(t[n])}`).join(",")}}`}return JSON.stringify(e)}const eC=700;function tC(e){return e.status==="saving"?"Saving…":e.status==="saved"?`Saved as revision ${e.revision}; applies from the next run.`:e.status==="error"?e.message:""}function Ow(e){if(Li(e)){if(e.code==="revision_conflict")return"Not saved: the automation changed elsewhere. The latest revision is shown; make the change again.";const t=mo(e);return`Not saved: ${t.title}${t.detail?` ${t.detail}`:""}`}return`Not saved: ${String((e==null?void 0:e.message)||e)}`}function nC(e,t){const n=(e==null?void 0:e.definition)??null,r=(e==null?void 0:e.summary.automation_id)??"",i=(n==null?void 0:n.revision)??0,[c,u]=y.useState(()=>fc(n==null?void 0:n.target.input_data)),[d,h]=y.useState({status:"idle"}),m=y.useRef(null),p=y.useRef(null),v=y.useRef(n);v.current=n;const _=y.useRef(r);_.current=r;const b=y.useRef(t);b.current=t;const C=y.useRef({id:r,def:n}),x=async()=>{var E;p.current&&window.clearTimeout(p.current),p.current=null;const j=m.current;if(m.current=null,!j)return;const N=j.automationId===_.current?v.current:C.current.id===j.automationId?C.current.def:null;if(!N)return;const $=ZN(N,j.prefs);if(!$)return;const S=()=>j.automationId===_.current;S()&&h({status:"saving"});try{await b.current(j.automationId,$,N.revision),S()&&h({status:"saved",revision:N.revision+1})}catch(A){if(!S())return;h({status:"error",message:Ow(A)}),u(fc((E=v.current)==null?void 0:E.target.input_data))}};return y.useEffect(()=>{m.current&&m.current.automationId!==r&&x(),C.current={id:r,def:n},h({status:"idle"}),u(fc(n==null?void 0:n.target.input_data))},[r]),y.useEffect(()=>{C.current={id:r,def:n},m.current||u(fc(n==null?void 0:n.target.input_data))},[i]),y.useEffect(()=>()=>{p.current&&window.clearTimeout(p.current)},[]),!e||!n?null:{automationId:r,revision:i,draft:c,save:d,setSave:h,onChange:j=>{u(j),m.current={prefs:j,automationId:r},p.current&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>void x(),eC)}}}function sC(e){return o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"code-settings-binding",children:[o.jsx("span",{children:"Automation"})," ",o.jsx("strong",{title:e.summary.title,children:e.summary.title}),o.jsxs("span",{className:"code-settings-revision","data-testid":"automation-revision",children:["Revision ",e.settings.revision]})]}),o.jsx("p",{className:`code-settings-save is-${e.settings.save.status}`,role:"status","aria-live":"polite",children:tC(e.settings.save)||"Changes are saved as a new revision and apply from the next run."})]})}function rC(e){const t=e.definition.revision,[n,r]=y.useState([]),i=e.settings.setSave;return o.jsx("div",{className:"code-automation-definition","data-revision":t,children:o.jsx(py,{summary:e.summary,definition:e.definition,busy:e.busy||e.disabled,errors:n,heading:null,submitLabel:"Save",emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,workflowPickerOptions:e.workflowPickerOptions,onSubmit:c=>{const u=Yg(e.summary,c,e.definition);if(u===null){r(["Nothing changed."]);return}if("errors"in u){r(u.errors);return}r([]),i({status:"saving"}),(async()=>{const h=u;return c.target&&h.target&&e.prepareTarget?{...h,target:await e.prepareTarget(h.target)}:h})().then(h=>e.onRevise(h,t)).then(()=>i({status:"saved",revision:t+1})).catch(h=>{Li(h)?i({status:"error",message:Ow(h)}):(i({status:"idle"}),r([String((h==null?void 0:h.message)||h)]))})}},`${e.summary.automation_id}:${t}`)})}const aC={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function oC(e){return e?e.ok?ip(e.value):ip(null,e.status?`HTTP ${e.status}`:e.message):aC}const iC=3e4,hc=50;function lC(){return Pb({fetch:(e,t)=>fetch(e,{...t,credentials:"same-origin"}),baseUrl:"",headers:Wc})}function cC(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}}function uC(e){var n;const t=(n=e==null?void 0:e.common)==null?void 0:n.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 (0.6.0 or later) to use automations."}}function dC(e,t){return e===Cn?{flow_id:"@default",interface:as}:!(t!=null&&t.bundleId)||!t.flowId?null:{bundle_ref:t.bundleVersion?`${t.bundleId}@${t.bundleVersion}`:t.bundleId,flow_id:t.flowId}}function fC(e){return e.filter(t=>t.status!=="archived")}function hC(e){const t=e==null?void 0:e.archived_automations;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function mC(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}.");return{approved:t.approved}}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)}); open its run to answer it.`)}function pC(e,t,n,r){return{command_id:e,run_id:t,type:"resume",payload:{wait_key:n,payload:r},client_id:"abstractcode-web"}}function Pw(e,t){return`Discussion forked from run #${e}. It works in its own workspace ${t.workspace_root}; the automation's files are mounted read-only at ${t.mounted_workspace} for the file tools (shell commands are not sandboxed), and nothing is written back into the automation's session.`}function Bn(e){return Li(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Kd(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)}const gC={items:[],loaded:!1,loading:!1,listError:null,error:null,archivedCount:0,archived:null,selectedId:"",detail:null,triggerSources:[],busy:!1,notice:"",emailStatus:null,rowError:null};function yC(e){return async(t,n,r)=>{await mt(ve("commands"),{method:"POST",body:JSON.stringify(pC(e(),t,n,r))})}}class wC{constructor(t,n,r=[1500,4e3]){Nn(this,"state",{...gC});Nn(this,"listeners",new Set);Nn(this,"listSeq",0);Nn(this,"detailSeq",0);Nn(this,"sourcesLoaded",!1);this.client=t,this.answerWaitVia=n,this.followupsMs=r}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}set(t){this.state={...this.state,...t};for(const n of this.listeners)n()}async listAll(t){return(await this.listPages(t)).items}async listPages(t){const n=[];let r,i=0;for(let c=0;c<200;c+=1){const u=await this.client.listAutomations({...t?{status:t}:{},...r?{cursor:r}:{},limit:hc});if(r||(i=hC(u)),n.push(...u.items),!u.next_cursor)return{items:n,archivedCount:i};r=u.next_cursor}throw new Error("GET /api/gateway/automations kept returning next_cursor after 200 pages.")}async loadArchived(){try{const{items:t}=await this.listPages("archived");this.set({archived:t})}catch(t){this.set({archived:this.state.archived??[],listError:Bn(t)})}}async loadEmailStatus(){try{const t=await this.client.getMyEmail();this.set({emailStatus:t&&typeof t=="object"?t:null})}catch{this.set({emailStatus:null})}}async refresh(){const t=++this.listSeq;this.set({loading:!0});try{const{items:n,archivedCount:r}=await this.listPages();if(this.loadEmailStatus(),t!==this.listSeq)return;const i=this.state.detail,c=i?n.find(u=>u.automation_id===i.automationId):void 0;this.set({items:n,archivedCount:r,loaded:!0,loading:!1,listError:null,...i&&c?{detail:{...i,summary:c}}:{}}),this.state.archived!==null&&this.loadArchived(),i&&await this.reloadDetail(i.automationId)}catch(n){if(t!==this.listSeq)return;this.set({loading:!1,loaded:!0,listError:Bn(n)})}}async select(t){var i;const n=t.trim(),r=++this.detailSeq;if(!n){this.set({selectedId:"",detail:null});return}this.set({selectedId:n,notice:"",error:null,...((i=this.state.detail)==null?void 0:i.automationId)!==n?{detail:null}:{}});try{const[c,u]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:hc})]);if(r!==this.detailSeq)return;const d=this.state.items.find(h=>h.automation_id===n);if(this.set({detail:{automationId:n,summary:d??c.summary,definition:c.definition,occurrences:Kd([],u.items),nextCursor:u.next_cursor}}),!this.sourcesLoaded){const h=await this.client.listTriggerSources();this.sourcesLoaded=!0,this.set({triggerSources:h.items})}}catch(c){if(r!==this.detailSeq)return;this.set({error:Bn(c)})}}async reloadDetail(t){const[n,r]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:hc})]),i=this.state.detail;if(!i||i.automationId!==t)return;const c=this.state.items.find(u=>u.automation_id===t);this.set({detail:{...i,summary:c??n.summary,definition:n.definition,occurrences:Kd(i.occurrences,r.items),nextCursor:i.occurrences.length>r.items.length?i.nextCursor:r.next_cursor}})}async loadMore(){const t=this.state.detail;if(!(!t||!t.nextCursor))try{const n=await this.client.listOccurrences(t.automationId,{cursor:t.nextCursor,limit:hc}),r=this.state.detail;if(!r||r.automationId!==t.automationId)return;this.set({detail:{...r,occurrences:Kd(r.occurrences,n.items),nextCursor:n.next_cursor}})}catch(n){this.set({error:Bn(n)})}}async afterChange(){await this.refresh();for(const t of this.followupsMs)setTimeout(()=>void this.refresh(),t)}async busyCall(t){this.set({busy:!0});try{const n=await t();return await this.afterChange(),n}catch(n){throw Bn(n)}finally{this.set({busy:!1})}}command(t,n,r){return this.busyCall(()=>this.client.sendAutomationCommand(t,{type:n,...r?{command_id:r}:{}}))}async toggleActive(t,n){this.set({rowError:null});try{return await this.command(t.automation_id,Jg(t),n)}catch(r){const i=Bn(r);throw this.set({rowError:{automationId:t.automation_id,error:i}}),i}}async unarchive(t,n){this.set({rowError:null});try{return await this.command(t,_t.unarchive,n)}catch(r){const i=Bn(r);throw this.set({rowError:{automationId:t,error:i}}),i}}revise(t,n,r,i){return this.busyCall(()=>this.client.reviseAutomation(t,{changes:n,...r!==null?{expected_revision:r}:{},...i?{command_id:i}:{}}))}async create(t){this.set({busy:!0,error:null});try{const n=await this.client.createAutomation(t);this.set({notice:`Automation created: ${n.summary.title}.`}),await this.refresh(),await this.select(n.automation_id);for(const r of this.followupsMs)setTimeout(()=>void this.refresh(),r);return n}catch(n){throw Bn(n)}finally{this.set({busy:!1})}}async discuss(t,n,r,i){this.set({busy:!0});try{const c=await this.client.discuss(t,{occurrence_index:n,prompt:r,...i?{request_id:i}:{}});return this.set({notice:Pw(n,c)}),c}catch(c){throw Bn(c)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(r){throw Bn(r)}}answerWait(t,n,r){return this.busyCall(async()=>{var c;const i=(((c=this.state.detail)==null?void 0:c.occurrences)||[]).flatMap(u=>u.waits).find(u=>u.run_id===t&&u.wait_key===n);if(!i)throw new Error(`No loaded wait ${n} on run ${t}; reload the automation.`);await this.answerWaitVia(t,n,mC(i.kind,r))})}rowControls(t){return lo(t,[],this.state.busy)}reportError(t){this.set({error:Bn(t)})}clearNotice(){this.set({notice:"",error:null})}}const fg={[_t.pause]:"Automation paused.",[_t.resume]:"Automation active.",[_t.run_now]:"Run requested.",[_t.stop_current]:"Stop requested.",[_t.archive]:"Automation archived."},vC=[{id:"run_now",label:"Run now",icon:"playCircle",action:"run_now"},{id:"stop_current",label:"Stop",icon:"stop",action:"stop_current"},{id:"revise",label:"Edit",icon:"edit",action:"edit"},{id:"archive",label:"Archive",icon:"archive",action:"archive"}];function hg(e){const t=e&&typeof e=="object"&&"code"in e?e:null;if(t){const n=mo(t);return{tone:"error",text:n.title,detail:n.detail}}return{tone:"error",text:e instanceof Error?e.message:String(e)}}function _C(e){const t=e.summary,n=lo(t,e.occurrences,e.busy),r=yy(t,e.nowMs??Date.now()),[i,c]=y.useState(!1),[u,d]=y.useState(null),h=y.useRef(null);y.useEffect(()=>{c(!1),d(null)},[t.automation_id]),y.useEffect(()=>{var C;i&&((C=h.current)==null||C.focus())},[i]);const m=(C,x,j)=>{d({tone:"busy",text:C}),x().then(()=>d({tone:"ok",text:j}),N=>d(hg(N)))},p=(C,x)=>m(x,()=>e.onCommand(C),fg[C]??"Done."),v=C=>{C==="run_now"?p(_t.run_now,"Starting a run…"):C==="stop_current"?p(_t.stop_current,"Stopping…"):C==="revise"?e.onEdit():C==="archive"&&c(!0)},_=t.workspace_root||"",b=e.triggerSources.length?hy(t,e.triggerSources):null;return o.jsxs("header",{className:"code-auto-header","data-automation-id":t.automation_id,"aria-busy":e.busy||(u==null?void 0:u.tone)==="busy",children:[o.jsx("h2",{className:"code-auto-header__title",tabIndex:-1,children:t.title}),o.jsxs("div",{className:"code-auto-header__state",children:[o.jsx(xw,{variant:"inline",summary:t,busy:e.busy,onToggle:()=>m(t.status==="active"?"Pausing…":"Activating…",e.onToggleActive,fg[t.status==="active"?_t.pause:_t.resume])}),_w(t)?o.jsx(bw,{}):null,o.jsx("span",{className:"code-auto-header__timing","data-field":"timing",children:r.line})]}),b?o.jsxs("p",{className:"code-auto-header__warn",role:"note","data-field":"trigger-problem",children:[o.jsx(re,{name:"warning",size:13})," ",o.jsx("span",{children:b})]}):null,_?o.jsxs("div",{className:"code-auto-header__workspace","data-field":"workspace",children:[o.jsx("span",{className:"code-auto-header__label",children:"Workspace"}),o.jsx("span",{className:"code-auto-header__folder",title:_,children:j0(_)}),o.jsx("button",{type:"button",className:"code-icon-button","data-action":"open-folder","aria-label":"Open folder",title:"Open folder",onClick:e.onOpenFolder,children:o.jsx(re,{name:"folder",size:15})}),o.jsx("button",{type:"button",className:"code-icon-button","data-action":"copy-path","aria-label":"Copy path",title:"Copy path",onClick:()=>void e.onCopyPath(_).then(C=>d(C?{tone:"ok",text:"Path copied."}:{tone:"error",text:"The browser refused the clipboard."}),C=>d(hg(C))),children:o.jsx(re,{name:"copy",size:15})})]}):null,e.workspaces?o.jsxs("div",{className:"code-auto-header__workspaces-row","data-section":"workspaces",children:[e.workspaces,e.onEditWorkspaces?o.jsx("button",{type:"button",className:"code-icon-button","data-action":"edit-workspaces","aria-label":"Change workspaces",title:"Change workspaces",onClick:e.onEditWorkspaces,children:o.jsx(re,{name:"edit",size:15})}):null]}):null,i?o.jsxs("div",{className:"code-auto-header__confirm",role:"group","aria-label":"Confirm archive",children:[o.jsxs("p",{children:["Archive “",t.title,"”? It will not run again; its history stays readable."]}),o.jsxs("div",{className:"code-auto-header__actions",children:[o.jsxs("button",{ref:h,type:"button",className:"code-subtle-button code-danger-button","data-action":"archive-confirm",disabled:!n.archive.enabled,onClick:()=>{c(!1),p(_t.archive,"Archiving…")},children:[o.jsx(re,{name:"archive",size:14})," ",o.jsx("span",{children:"Archive"})]}),o.jsx("button",{type:"button",className:"code-subtle-button","data-action":"archive-cancel",onClick:()=>c(!1),children:o.jsx("span",{children:"Keep it"})})]})]}):o.jsx("div",{className:"code-auto-header__actions",role:"toolbar","aria-label":"Automation controls",children:vC.map(C=>{const x=n[C.id],j=Ti(C.id,t);return o.jsxs("button",{type:"button",className:`code-subtle-button${C.id==="archive"?" code-danger-button":""}`,"data-action":C.action,disabled:!x.enabled,title:x.enabled?j:`${x.reason??"Not available now."}
91
+ ${j}`,onClick:()=>v(C.id),children:[o.jsx(re,{name:C.icon,size:14})," ",o.jsx("span",{children:C.label})]},C.id)})}),u?o.jsxs("p",{className:`code-auto-header__result is-${u.tone}`,role:u.tone==="error"?"alert":"status","data-field":"result",children:[o.jsx(re,{name:u.tone==="busy"?"loader":u.tone==="ok"?"check":"error",size:13}),o.jsxs("span",{children:[u.text,u.detail?` ${u.detail}`:""]})]}):null]})}const Dw="abstractcode.automation.panels",pi={occurrences:!0,folder:!0};function bC(e){try{const t=e==null?void 0:e.getItem(Dw);if(!t)return{...pi};const n=JSON.parse(t);if(!n||typeof n!="object")return{...pi};const r=n;return{occurrences:typeof r.occurrences=="boolean"?r.occurrences:pi.occurrences,folder:typeof r.folder=="boolean"?r.folder:pi.folder}}catch{return{...pi}}}function xC(e,t){try{t==null||t.setItem(Dw,JSON.stringify(e))}catch{}}function kC(e,t){return{...e,[t]:!e[t]}}function mg(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function jC(){const[e,t]=y.useState(()=>bC(mg())),n=y.useCallback(r=>{t(i=>{const c=kC(i,r);return xC(c,mg()),c})},[]);return[e,n]}const Wf=e=>({toggle:`code-detail-${e}-toggle`,region:`code-detail-${e}`});function Fw(e){const t=Wf(e.panel);return o.jsxs("button",{type:"button",className:"code-detail-toggle",id:t.toggle,"data-panel":e.panel,"aria-expanded":e.open,"aria-controls":t.region,onClick:e.onToggle,children:[o.jsx(re,{name:"chevronDown",size:13}),o.jsx("span",{className:"code-detail-toggle__label",children:e.label}),typeof e.count=="number"?o.jsx("span",{className:"code-detail-toggle__count",children:e.count}):null]})}const SC=".af-auto__timeline",NC=".af-auto__more";function CC(e,t,n){const r=(e==null?void 0:e.querySelector(SC))??null;if(!r||!r.parentNode)return t.parentNode&&t.remove(),!1;r.id!==n&&(r.id=n);const i=(e==null?void 0:e.querySelector(NC))??null,c=i&&i.parentNode===r.parentNode?i:r;return(t.parentNode!==c.parentNode||t.nextSibling!==c)&&c.parentNode.insertBefore(t,c),!0}function EC(e,t){const n=y.useMemo(()=>{if(typeof document>"u")return null;const c=document.createElement("div");return c.className="code-detail-head code-detail-head--occurrences",c},[]),[r,i]=y.useState(!1);return y.useLayoutEffect(()=>{const c=e.current;if(!n||!c||!t){n==null||n.remove(),i(!1);return}const u=Wf("occurrences").region,d=()=>i(CC(c,n,u));d();const h=new MutationObserver(d);return h.observe(c,{childList:!0,subtree:!0}),()=>{h.disconnect(),n.remove()}},[e,n,t]),r?n:null}function zw(){return mt(ve("voice/defaults"))}function $C(e,t){const n=new URLSearchParams({compact:"true"});return e&&n.set("provider",e),t&&n.set("model",t),mt(ve(`voice/voices?${n.toString()}`))}function AC(e){const[t,n]=y.useState({value:null,failed:!1});return y.useEffect(()=>{if(!e)return;let r=!0;return zw().then(i=>r&&n({value:i||{},failed:!1})).catch(()=>r&&n({value:null,failed:!0})),()=>{r=!1}},[e]),t}function TC({value:e,onChange:t,defaults:n,connected:r}){return o.jsx(Zk,{value:e,onChange:t,fetchCatalog:$C,fetchDefaults:zw,defaults:n.value??void 0,overrideOwner:"this app",nested:!0,unavailableReason:r?null:"Connect to a gateway to configure voice."})}const pg=18e4;function Uw({runId:e,sessionId:t,capability:n,scope:r,preferences:i,onTranscript:c,onError:u}){var v,_;const d=y.useRef(!0),h=y.useRef(r);h.current=r,y.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=()=>{if(!d.current||h.current!==r)throw new Error("Voice session changed.")},p=Tb({output_device_id:i.output_device||"",input_device_id:i.input_device||"",input_gain:i.input_gain,volume:i.reply_volume,stop_on_pointerup:!1,tts_stream:((v=n.tts)==null?void 0:v.available)===!0&&e?async function*(b,C){m(),yield*xb({path:ve(`runs/${encodeURIComponent(e)}/voice/tts/stream`),headers:Wc(),signal:C,body:{text:b,request_id:Ar(),...Kk(i)}})}:void 0,transcribe:((_=n.stt)==null?void 0:_.available)===!0&&e?async(b,C)=>{var A;m();const x=Number(((A=n.stt)==null?void 0:A.max_upload_bytes)||0);if(x>0&&b.size>x)throw new Error("Recording exceeds the gateway's upload limit. Try a shorter recording.");const j=C.includes("mp4")?"m4a":C.includes("ogg")?"ogg":C.includes("wav")?"wav":"webm",N=new File([b],`recording.${j}`,{type:C||"audio/webm"}),$=await En.attachments_upload(t,N);m();let S;const E=await Promise.race([En.audio_transcribe(e,{audio_artifact:$,request_id:Ar(),...Jk(i)}),new Promise((I,F)=>{S=setTimeout(()=>F(new Error(`the gateway did not answer within ${pg/1e3} s`)),pg)})]).finally(()=>clearTimeout(S));return m(),{text:String(E.text||""),provider:E.provider??null,model:E.model??null}}:void 0,on_transcript:b=>{d.current&&h.current===r&&c(b)},on_error:b=>{d.current&&h.current===r&&u(b)}});return y.useEffect(()=>{var b;return p.stop_tts(),(b=p.cancel_voice_ptt_recording)==null||b.call(p),()=>{var C;p.stop_tts(),(C=p.cancel_voice_ptt_recording)==null||C.call(p)}},[r,p.stop_tts,p.cancel_voice_ptt_recording]),p}const RC=350;function IC(e){const[t,n]=y.useState(()=>Date.now());return y.useEffect(()=>{if(!e)return;n(Date.now());const r=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(r)},[e]),t}function MC({voice:e,runId:t,capability:n,route:r="",onSettings:i}){var j,N,$,S,E;const c=y.useRef(!1),u=y.useRef(!1),d=y.useRef(0),h=y.useRef(!0);y.useEffect(()=>(h.current=!0,()=>{h.current=!1,c.current=!1,u.current=!1}),[]);const m=()=>{if(u.current){u.current=!1,e.stop_voice_ptt_recording();return}c.current=!0,d.current=Date.now(),e.start_voice_ptt_recording().then(()=>{var A;!c.current&&!u.current&&e.stop_voice_ptt_recording(),h.current||(A=e.cancel_voice_ptt_recording)==null||A.call(e)})},p=()=>{if(c.current){if(c.current=!1,Date.now()-d.current<RC){u.current=!0;return}e.stop_voice_ptt_recording()}},v=()=>{c.current=!1,u.current=!1,e.stop_voice_ptt_recording()};y.useEffect(()=>(window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),window.addEventListener("blur",v),()=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),window.removeEventListener("blur",v)}),[e.stop_voice_ptt_recording]),y.useEffect(()=>{e.voice_ptt_recording||(u.current=!1)},[e.voice_ptt_recording]);const _=e.voice_ptt_since||0,b=IC(!!_);if(!((j=n.tts)!=null&&j.available)&&!((N=n.stt)!=null&&N.available))return null;const C=!W1(),x=e.voice_ptt_recording?`Recording… ${_?Tg(_,b):""}`.trim():e.voice_ptt_busy?mb(_||b,b,r):"";return o.jsxs(o.Fragment,{children:[($=n.stt)!=null&&$.available&&C?o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"code-icon-button","aria-label":"Dictation unavailable","aria-describedby":"code-voice-https-note",title:ng,disabled:!0,children:o.jsx(re,{name:"mic",size:15})}),o.jsx("span",{id:"code-voice-https-note",className:"code-voice-note",role:"note",children:ng})]}):null,(S=n.stt)!=null&&S.available&&!C?o.jsx("button",{className:"code-icon-button","aria-label":e.voice_ptt_recording?"Recording — tap or release to transcribe":"Hold to dictate",title:t?"Hold to dictate, or tap to start and tap again to stop (Space or Enter on keyboard)":"Start a conversation to enable dictation",disabled:!e.voice_ptt_supported||e.voice_ptt_busy,"aria-pressed":e.voice_ptt_recording,onPointerDown:A=>{A.button===0&&m()},onPointerUp:p,onPointerCancel:p,onKeyDown:A=>{[" ","Enter"].includes(A.key)&&!A.repeat&&(A.preventDefault(),m())},onKeyUp:A=>{[" ","Enter"].includes(A.key)&&(A.preventDefault(),p())},onBlur:()=>{u.current||p()},children:o.jsx(re,{name:e.voice_ptt_busy?"loader":"mic",size:15,className:e.voice_ptt_busy?"code-loading-spinner":void 0})}):null,e.tts_playback.status!=="idle"?o.jsx("button",{className:"code-icon-button","aria-label":"Stop spoken reply",onClick:e.stop_tts,children:o.jsx(re,{name:"x",size:14})}):null,i&&((E=n.tts)!=null&&E.available)?o.jsx("button",{className:"code-icon-button","aria-label":"Voice settings",title:"Voice settings",onClick:i,children:o.jsx(re,{name:"cog",size:14})}):null,x?o.jsx("span",{role:"status",className:"code-voice-status","data-voice-status":!0,children:x}):null]})}const LC=et.title;function gg(e){return`${LC}: ${e}`}function OC(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function PC(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 OC(t)?t:null}function DC(e,t){const n={...e||{}};return t===null?(delete n.workspace,n):(delete n.workspace_allowed_paths,delete n.workspace_access_mode,n.workspace={posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(r=>({path:r.path,mode:r.mode}))},n)}const FC=3e4,yg=new WeakMap;function zC(e,t,n=Date.now()){let r=yg.get(e);r||yg.set(e,r=new Map);const i=JSON.stringify(t),c=r.get(i);if(c&&n-c.at<FC)return c.answer;const u=mf(e)(t).then(d=>d.summary);return u.catch(()=>r==null?void 0:r.delete(i)),r.set(i,{at:n,answer:u}),u}function UC(e){const[t,n]=y.useState(null),r=JSON.stringify(e.value);return y.useEffect(()=>{if(!e.connected){n(null);return}let i=!0;return zC(e.request,e.value).then(c=>i&&n(gg(c))).catch(c=>i&&n(gg($f(c)))),()=>{i=!1}},[e.request,e.connected,r,e.refreshKey]),t?o.jsx("span",{className:"code-auto-header__workspaces","data-field":"workspaces",title:t,children:t}):null}function BC(e,t){const n=y.useMemo(()=>new wC(lC(),yC(Ar)),[e]),r=y.useSyncExternalStore(u=>n.subscribe(u),()=>n.state),[i,c]=y.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");return y.useEffect(()=>{const u=()=>c(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",u),()=>document.removeEventListener("visibilitychange",u)},[]),y.useEffect(()=>{if(!e||!t||!i)return;n.refresh();const u=window.setInterval(()=>void n.refresh(),iC);return()=>window.clearInterval(u)},[n,e,t,i]),{ctl:n,state:r}}function vf({error:e}){if(!e)return null;const t=mo(e);return o.jsxs("p",{className:"code-inline-error",role:"alert","data-code":e.code,children:[o.jsx("strong",{children:t.title})," ",t.detail]})}function WC(e){const t=e.open??!0,n=Lf("automations"),r=e.state,i=fC(r.items),c=r.archived??[],u=r.items.reduce((d,h)=>d+h.attention.pending_waits+h.attention.unseen_count,0);return o.jsxs("section",{className:"code-panel code-automations","aria-label":"Automations","data-open":t?"true":"false",children:[o.jsx(hw,{panel:"automations",open:t,onToggle:()=>{var d;return(d=e.onToggle)==null?void 0:d.call(e)},label:o.jsxs(o.Fragment,{children:["Automations",u?o.jsx("span",{className:"code-auto-badge","data-field":"attention-total",children:u}):null]}),actions:o.jsxs("span",{className:"code-auto-actions",children:[o.jsx("button",{className:"code-icon-button","aria-label":"New automation",title:"New automation (choose a workflow and schedule)",disabled:!e.available.available||e.createDisabled,onClick:e.onNew,children:o.jsx(re,{name:"plus",size:13})}),o.jsx("button",{className:"code-icon-button","aria-label":"Refresh automations",disabled:!e.available.available||r.loading,onClick:e.onRefresh,children:o.jsx(re,{name:"refresh",size:13})})]})}),o.jsxs("div",{className:"code-auto-rows",id:n.region,role:"region","aria-labelledby":n.toggle,hidden:!t,children:[!e.discovering&&!e.available.available?o.jsx("p",{className:"code-history-empty",role:"note","data-unavailable":"true",children:e.available.reason}):null,o.jsx(vf,{error:r.listError}),!r.loaded&&(e.discovering||e.available.available&&r.loading)?o.jsx(uo,{children:"Loading automations…"}):null,e.available.available&&r.loaded&&!r.listError&&!r.items.length?o.jsx("p",{className:"code-history-empty",children:"No automations yet. + lets you choose a workflow and schedule."}):null,i.map(d=>{var h;return o.jsxs(ct.Fragment,{children:[o.jsx(W0,{summary:d,selected:e.selectedId===d.automation_id,busy:r.busy,nowMs:e.nowMs??Date.now(),onSelect:()=>e.onSelect(d.automation_id),onToggleActive:()=>{var m;return(m=e.onToggleActive)==null?void 0:m.call(e,d)}}),((h=r.rowError)==null?void 0:h.automationId)===d.automation_id?o.jsx(vf,{error:r.rowError.error}):null]},d.automation_id)}),o.jsxs(pw,{list:"automations",count:r.archivedCount,open:e.archivedOpen===!0,onToggle:()=>{var d;return(d=e.onToggleArchived)==null?void 0:d.call(e)},children:[r.archived===null?o.jsx("li",{children:o.jsx(uo,{children:"Loading archived automations…"})}):null,c.map(d=>{var h;return o.jsx(gw,{id:d.automation_id,title:d.title,busy:r.busy,error:((h=r.rowError)==null?void 0:h.automationId)===d.automation_id?mo(r.rowError.error).title:void 0,onOpen:()=>e.onSelect(d.automation_id),onUnarchive:()=>{var m;return(m=e.onUnarchive)==null?void 0:m.call(e,d)}},d.automation_id)})]})]})]})}function VC(e,t){const n=e.state.detail;if(!n)return null;const r=n.automationId;return{summary:n.summary,...n.definition?{definition:n.definition}:{},occurrences:n.occurrences,triggerSources:e.state.triggerSources,busy:e.state.busy,...e.state.error?{error:e.state.error}:{},onRevise:(i,c,u)=>e.revise(r,i,c,u==null?void 0:u.command_id),onCommand:(i,c,u)=>e.command(r,i,u==null?void 0:u.command_id),onDiscuss:async(i,c,u)=>{const d=await e.discuss(r,i,c,u==null?void 0:u.request_id);return t.openConversation(d.session_id,d.run_id,Pw(i,d)),d},onSeen:i=>e.seen(r,i),onLoadMore:()=>void e.loadMore(),onOpenRun:i=>t.openRun(i),onOpenWorkspace:i=>t.openWorkspace(i),onAnswerWait:(i,c,u)=>e.answerWait(i,c,u),emailStatus:e.state.emailStatus,...t.openMyEmail?{onOpenMyEmail:()=>{var i;return(i=t.openMyEmail)==null?void 0:i.call(t)}}:{}}}function GC(e){const t=e.last_occurrence,n=e.current_occurrence;return[e.occurrence_count,t?`${t.index}:${t.status}:${t.finished_at??""}`:"",n?`${n.index}:${n.status}`:""].join("|")}function wg(e,t,n){if(t===e)return"Automation folder";const r=n.find(i=>i.run_id===t);return r?`Run #${r.index} folder`:"Run folder"}function HC(e){const t=e.panels.folder,n=Wf("folder");return o.jsxs("div",{className:"code-auto-folder-section","data-open":t?"true":"false","data-folder":e.own?"automation":"run",children:[o.jsx("div",{className:"code-detail-head",children:o.jsx(Fw,{panel:"folder",label:e.title,open:t,onToggle:e.onToggle})}),o.jsx("div",{className:"code-detail-region",id:n.region,hidden:!t,children:e.children})]})}function KC(e){const t=e.ctl.state,n=t.detail,[r,i]=y.useState({automationId:"",runId:""}),c=(n==null?void 0:n.automationId)??"",[u,d]=y.useState(""),h=Uw({scope:c,runId:e.enabled?c:"",sessionId:c,capability:e.voiceCapability||{},preferences:e.voicePreferences||{},onTranscript:()=>{},onError:d});y.useEffect(()=>d(""),[c]);const m=r.automationId===c&&r.runId?r.runId:c,p=VC(e.ctl,{...e.host,openWorkspace:x=>i({automationId:c,runId:x})}),[v,_]=jC(),b=y.useRef(null),C=EC(b,!!(n&&n.occurrences.length));return o.jsxs("main",{className:"code-conversation code-automation-main",id:"code-conversation",tabIndex:-1,"aria-label":"Automation",children:[o.jsxs("div",{className:"code-auto-main-head",children:[o.jsxs("button",{className:"code-subtle-button",onClick:e.onClose,children:[o.jsx(re,{name:"chat",size:14})," ",o.jsx("span",{children:"Back to the conversation"})]}),h.tts_playback.status!=="idle"?o.jsx("button",{type:"button",className:"code-subtle-button",onClick:h.stop_tts,children:"Stop audio"}):null,t.notice?o.jsx("p",{className:"code-field-help",role:"status",children:t.notice}):null]}),n?o.jsxs("div",{className:"code-auto-main-body",ref:b,"data-occurrences":v.occurrences?"open":"closed",children:[u?o.jsx("p",{className:"code-inline-error",role:"alert",children:u}):null,o.jsx(_C,{summary:n.summary,occurrences:n.occurrences,triggerSources:t.triggerSources,busy:t.busy,nowMs:e.nowMs,onCommand:x=>e.ctl.command(n.automationId,x),onToggleActive:()=>e.ctl.toggleActive(n.summary),onEdit:()=>e.onEdit(n.automationId),workspaces:n.definition?o.jsx(UC,{request:Vc,connected:e.enabled,value:PC(n.definition),refreshKey:n.summary.revision??""}):null,onEditWorkspaces:e.onEditWorkspaces?()=>{var x;return(x=e.onEditWorkspaces)==null?void 0:x.call(e,n.automationId)}:void 0,onOpenFolder:()=>{i({automationId:c,runId:""}),v.folder||_("folder"),window.requestAnimationFrame(()=>{var x,j;return(j=(x=b.current)==null?void 0:x.querySelector(".code-auto-folder-section"))==null?void 0:j.scrollIntoView({block:"nearest"})})},onCopyPath:zf}),p?o.jsx(JS,{...p,hideHeader:!0,prepareTarget:e.prepareTarget,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,fetchGateway:Ac,messageProps:{...h.tts_supported?{onSpeakToggle:x=>{h.toggle_tts(String(x.id||x.content),x.content)}}:{},getSpeakState:x=>h.tts_playback.key===String(x.id||x.content)?h.tts_playback.status:"idle"}}):null,C?Rc.createPortal(o.jsx(Fw,{panel:"occurrences",label:"Occurrences",count:n.summary.occurrence_count,open:v.occurrences,onToggle:()=>_("occurrences")}),C):null,e.enabled?o.jsx(HC,{panels:v,onToggle:()=>_("folder"),title:wg(n.automationId,m,n.occurrences),own:m===n.automationId,children:o.jsx(Mf,{className:"code-auto-folder",fetchGateway:Ac,runId:m,title:wg(n.automationId,m,n.occurrences),refreshKey:GC(n.summary),onClose:m!==n.automationId?()=>i({automationId:c,runId:""}):void 0})}):null]}):t.error?o.jsx(vf,{error:t.error}):o.jsx(uo,{children:"Loading automation…"})]})}function JC(e){const[t,n]=y.useState(),[r,i]=y.useState(null);y.useEffect(()=>{e.open||i(null)},[e.open]);const[c,u]=y.useState(!1),d=y.useRef(!1),[h,m]=y.useState();return y.useEffect(()=>{e.open||m(void 0)},[e.open]),y.useEffect(()=>{e.open&&(n(void 0),e.ctl.loadEmailStatus())},[e.open]),o.jsx(tk,{open:e.open,onClose:e.onClose,target:h||e.target,availableTools:e.availableTools,initialTools:h?null:e.initialTools,workflowPicker:e.workflowPickerOptions&&(h||e.target)?o.jsx(fy,{target:h||e.target,options:e.workflowPickerOptions,onChange:m}):o.jsx("p",{className:"code-field-help","data-field":"target",children:e.target?`Initially uses ${e.workflowLabel}. Choose the workflow in this form.`:"Choose a workflow in the Workflow panel first."}),initialPrompt:e.initialPrompt,workspaces:o.jsx(dw,{connected:e.connected!==!1,automation:{value:r,onChange:i},idPrefix:"code-new-automation-workspace"}),emailStatus:e.ctl.state.emailStatus,onOpenMyEmail:e.onOpenMyEmail,busy:e.ctl.state.busy||c,error:t,onSubmit:async p=>{var v,_;if(!d.current){d.current=!0,u(!0);try{const b=await((_=e.buildInput)==null?void 0:_.call(e,String(((v=p.target.input_data)==null?void 0:v.prompt)||""),h)),C=b&&e.availableTools!==void 0?Pc(b,Ii(p.target.input_data)):b,x=DC(C||p.target.input_data,r),j=await e.ctl.create({...p,target:{...p.target,input_data:x}});return e.onCreated(j.automation_id),e.onClose(),j}catch(b){throw n(Bn(b)),b}finally{d.current=!1,u(!1)}}}})}function Bw(e){return`abstractcode.workspace.v2:${e}`}function QC(e){try{const{showAllWorkflows:t,...n}=JSON.parse(e||"{}"),r=typeof n.workflow=="string"&&n.workflow.trim()?n.workflow.trim():os.workflow;return{...os,...n,workflow:r,speculation:Sg(n.speculation),streamReplies:o1(n.streamReplies),tools:{...os.tools,...n.tools}}}catch{return os}}function YC(e){try{return QC(localStorage.getItem(Bw(e)))}catch{return os}}function XC(e,t){try{localStorage.setItem(Bw(e),JSON.stringify(t))}catch{}}function qC(e){if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;const t=[...e.currentTarget.querySelectorAll('button[role="tab"]')].filter(i=>!i.disabled),n=t.indexOf(e.target);if(n<0||!t.length)return;e.preventDefault();const r=e.key==="Home"?0:e.key==="End"?t.length-1:(n+(e.key==="ArrowRight"?1:-1)+t.length)%t.length;t[r].focus(),t[r].click()}function ZC(e){var h,m;const t=Object.keys(((h=e.schema)==null?void 0:h.properties)||{}),n=((m=e.schema)==null?void 0:m.required)||[],r=[e.promptProperty||"prompt","context","messages","attachments"],i=["provider","model","tools","skills","max_iterations","use_context","use_session_history"],c=kw(e.schema).map(p=>[p.provider,p.model,p.reasoning].filter(v=>!!v)),u=new Set(t.filter(p=>n.includes(p)&&!r.includes(p)));for(const p of c)p.some(v=>u.has(v))&&p.forEach(v=>u.add(v));const d=new Set(t.filter(p=>!u.has(p)&&!r.includes(p)&&!i.includes(p)));for(const p of c)p.some(v=>d.has(v))&&p.forEach(v=>d.add(v));return o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"code-settings-section","aria-label":"Automatic agent configuration",children:[o.jsx("h3",{children:u.size?"Workflow inputs":"Ready to chat"}),o.jsxs("p",{className:"code-field-help",children:[u.size?"This workflow asks for the inputs below before it can run.":"No setup required. Write a message and press Send."," ","Optional values use workflow and Gateway defaults. Use Settings for model, workspace and tool permission overrides."]})]}),u.size?o.jsx(_f,{...e,omit:t.filter(p=>!u.has(p)),rawObject:!1}):null,d.size?o.jsxs("details",{className:"code-advanced-inputs",children:[o.jsxs("summary",{children:["Advanced workflow inputs"," ",o.jsx("span",{className:"code-muted",children:"Optional"})]}),o.jsx("p",{className:"code-field-help",children:"Leave these unset to use the workflow and Gateway defaults. Only change them when you need a specific override."}),o.jsx(_f,{...e,omit:t.filter(p=>!d.has(p)),rawObject:!1})]}):null]})}function eE(e,t,n){var i;if(!n.length)return t;const r=(i=e==null?void 0:e.properties)==null?void 0:i.attachments;if(!r||r.type&&r.type!=="array")throw new Error("This workflow does not declare an attachments input. Remove the attached files, or choose an agent or workflow that accepts them.");return{...t,attachments:[...Array.isArray(t.attachments)?t.attachments:[],...n]}}function tE(e){if(!e.trim())return{ok:!0,value:{}};let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:"Enter valid JSON."}}return t===null||typeof t!="object"||Array.isArray(t)?{ok:!1,error:"The workflow input payload must be a JSON object."}:{ok:!0,value:t}}function _f({schema:e,values:t,onChange:n,disabled:r=!1,omit:i=[],rawObject:c=!1,onEditorError:u,defaultModel:d}){const[h,m]=ct.useState("fields"),p=Object.entries((e==null?void 0:e.properties)||{}).filter(([x])=>!i.includes(x)),v=kw(e),_=new Set(v.flatMap(x=>[x.provider,x.model,x.reasoning].filter(Boolean))),b=x=>{m(x),u==null||u("")},C=p.length?o.jsx("div",{className:"code-input-fields",children:p.map(([x,j])=>{const N={...j,type:e1(j)},$=v.find(F=>F.provider===x);if($)return o.jsxs("section",{className:"code-settings-section",children:[o.jsx("h3",{children:$.title}),o.jsx(Ic,{value:{provider:String(t[$.provider]||""),model:String(t[$.model]||""),...$.reasoning?{reasoning:String(t[$.reasoning]||"")}:{}},onChange:F=>n({...t,[$.provider]:F.provider,[$.model]:F.model,...$.reasoning?{[$.reasoning]:F.reasoning||""}:{}}),...s1($.provider,N["x-abstract-type"]),fetchModelCapabilities:$.reasoning?Df.fetchModelCapabilities:void 0,effectiveDefault:$.provider==="provider"?d:void 0,defaultHint:$.provider==="provider"&&(d!=null&&d.model)?`Gateway default: ${d.provider} · ${d.model}. Workflow defaults take precedence.`:"Empty routing pins inherit the Gateway defaults. Registered workflow defaults are loaded above any Gateway default.",disabled:r})]},x);if(_.has(x))return null;const S=`workflow-input-${x}`,E=String(N.title||x).replace(/_/g," "),A=Array.isArray(e==null?void 0:e.required)&&e.required.includes(x),I=F=>{const L={...t};F===void 0?delete L[x]:L[x]=F,n(L)};return o.jsxs("div",{className:"code-field",children:[o.jsxs("label",{htmlFor:S,children:[E,A?o.jsx("span",{"aria-label":"required",children:" *"}):null]}),N.enum?o.jsxs("select",{id:S,value:t[x]===void 0?"":JSON.stringify(t[x]),disabled:r,onChange:F=>I(F.target.value?JSON.parse(F.target.value):void 0),children:[o.jsxs("option",{value:"",children:["Choose ",E]}),N.enum.map(F=>o.jsx("option",{value:JSON.stringify(F),children:String(F)},JSON.stringify(F)))]}):N.type==="boolean"?o.jsxs("select",{id:S,value:t[x]===void 0?"":String(t[x]),disabled:r,onChange:F=>I(F.target.value?F.target.value==="true":void 0),children:[o.jsx("option",{value:"",children:"Workflow default"}),o.jsx("option",{value:"true",children:"Yes"}),o.jsx("option",{value:"false",children:"No"})]}):N.type==="number"||N.type==="integer"?o.jsx("input",{id:S,type:"number",value:typeof t[x]=="number"?String(t[x]):"",min:N.minimum,max:N.maximum,step:N.type==="integer"?1:"any",disabled:r,onChange:F=>I(F.target.value===""?void 0:Number(F.target.value))}):N.type==="object"||N.type==="array"?o.jsx(sE,{id:S,value:t[x],disabled:r,onChange:I},x):o.jsx("textarea",{id:S,rows:2,value:String(t[x]??""),disabled:r,onChange:F=>I(F.target.value)}),N.description?o.jsx("p",{className:"code-field-help",id:`${S}-help`,children:N.description}):null]},x)})}):o.jsx("p",{className:"code-muted",children:"This workflow declares no named top-level fields. Use JSON payload mode to provide registered or additional inputs."});return c?o.jsxs("div",{children:[o.jsxs("div",{className:"code-settings-tabs",role:"tablist","aria-label":"Workflow input editor",onKeyDown:qC,children:[o.jsx("button",{type:"button",role:"tab",tabIndex:h==="fields"?0:-1,"aria-selected":h==="fields",onClick:()=>b("fields"),children:"Fields"}),o.jsx("button",{type:"button",role:"tab",tabIndex:h==="json"?0:-1,"aria-selected":h==="json",onClick:()=>b("json"),children:"JSON payload"})]}),h==="json"?o.jsxs(o.Fragment,{children:[o.jsx(nE,{value:t,disabled:r,onChange:n,onError:x=>u==null?void 0:u(x)}),o.jsx("p",{className:"code-field-help",children:"The complete object is sent unchanged. Nested and additional properties are allowed here; the gateway validates it against the registered workflow schema."})]}):C]}):C}function nE({value:e,onChange:t,onError:n,disabled:r}){const[i,c]=ct.useState(JSON.stringify(e,null,2)),[u,d]=ct.useState(""),h=ct.useRef(e);return ct.useEffect(()=>{e!==h.current&&(h.current=e,c(JSON.stringify(e,null,2)),d(""),n(""))},[e,n]),o.jsxs("div",{className:"code-field",children:[o.jsx("label",{htmlFor:"workflow-input-payload",children:"Complete input object"}),o.jsx("textarea",{id:"workflow-input-payload",className:"code-mono",rows:12,value:i,disabled:r,"aria-invalid":!!u,onChange:m=>{c(m.target.value);const p=tE(m.target.value);if(!p.ok){d(p.error),n(p.error);return}h.current=p.value,d(""),n(""),t(p.value)}}),u?o.jsx("span",{role:"alert",className:"code-error-text",children:u}):null]})}function sE({id:e,value:t,onChange:n,disabled:r}){const[i,c]=ct.useState(t===void 0?"":JSON.stringify(t,null,2)),[u,d]=ct.useState(""),h=ct.useRef(t);return ct.useEffect(()=>{t!==h.current&&(h.current=t,c(t===void 0?"":JSON.stringify(t,null,2)),d(""))},[t]),o.jsxs(o.Fragment,{children:[o.jsx("textarea",{id:e,className:"code-mono",rows:4,value:i,disabled:r,"aria-invalid":!!u,onChange:m=>{c(m.target.value);try{const p=m.target.value.trim()?JSON.parse(m.target.value):void 0;h.current=p,n(p),d("")}catch{h.current=m.target.value,n(m.target.value),d("Enter valid JSON.")}}}),u?o.jsx("span",{role:"alert",className:"code-error-text",children:u}):null]})}function rE({attachments:e,uploads:t,sizes:n,onRemoveAttachment:r,onRemoveUpload:i,onRetryUpload:c}){return o.jsxs("div",{className:"code-attachments",role:"list","aria-label":"Attached files",children:[e.map((u,d)=>{const h=u.filename||u.path||"Attachment",m=typeof u.size_bytes=="number"?u.size_bytes:n==null?void 0:n.get(u.$artifact),p=typeof m=="number"?Ei(m):"";return o.jsxs("div",{role:"listitem",tabIndex:0,className:"code-attachment is-attached","aria-label":`${h}${p?`, ${p}`:""}, attached`,children:[o.jsx("span",{className:"code-attachment__icon","aria-hidden":"true",children:o.jsx(re,{name:"paperclip",size:13})}),o.jsxs("span",{className:"code-attachment__body",children:[o.jsx("span",{className:"code-attachment__name",title:h,children:h}),p?o.jsx("span",{className:"code-attachment__meta",children:p}):null]}),o.jsx("button",{type:"button",className:"code-attachment__action","aria-label":`Remove ${h}`,title:`Remove ${h}`,onClick:()=>r(d),children:o.jsx(re,{name:"x",size:12})})]},`${u.$artifact}:${d}`)}),t.map(u=>{const d=u.status==="queued"||u.status==="uploading",h=u.status==="queued"?`Waiting · ${Ei(u.size)}`:u.status==="uploading"?`Uploading · ${Ei(u.size)}`:u.message||"Not attached",m=u.status==="queued"?"waiting to upload":u.status==="uploading"?"uploading":`not attached: ${h}`;return o.jsxs("div",{role:"listitem",tabIndex:0,className:`code-attachment is-${u.status}`,"aria-label":`${u.name}, ${m}`,"aria-busy":d||void 0,children:[o.jsx("span",{className:"code-attachment__icon","aria-hidden":"true",children:d?o.jsx("span",{className:"code-attachment__spinner"}):o.jsx(re,{name:"warning",size:13})}),o.jsxs("span",{className:"code-attachment__body",children:[o.jsx("span",{className:"code-attachment__name",title:u.name,children:u.name}),o.jsx("span",{className:"code-attachment__meta",children:h})]}),u.status==="failed"?o.jsxs("button",{type:"button",className:"code-attachment__action code-attachment__retry","aria-label":`Retry ${u.name}`,title:"Retry upload",onClick:()=>c(u.id),children:[o.jsx(re,{name:"refresh",size:12}),o.jsx("span",{children:"Retry"})]}):null,o.jsx("button",{type:"button",className:"code-attachment__action","aria-label":`Remove ${u.name}`,title:`Remove ${u.name}`,onClick:()=>i(u.id),children:o.jsx(re,{name:"x",size:12})})]},u.id)})]})}function aE({active:e,paused:t,snapshot:n,onRevokeApproval:r,onCommand:i,onActivity:c,onInteraction:u,permissionsAll:d}){const h=y.useMemo(()=>TS(n),[n]),m=y.useMemo(()=>h.tone==="working"?aN(n.records.map(j=>j.record)):"",[h.tone,n.records]),p=m||h.detail,[v,_]=y.useState(Date.now);y.useEffect(()=>{if(!e)return;const j=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(j)},[e]);const b=Date.parse(h.startedAt||""),C=Number.isFinite(b)?Math.max(0,Math.floor((v-b)/1e3)):null,x=C===null?"":C<60?`${C}s`:`${Math.floor(C/60)}m ${C%60}s`;return o.jsxs("div",{className:`code-run-strip code-run-strip--${h.tone}`,children:[o.jsxs("div",{className:"code-run-strip__activity",role:"status","aria-live":"polite",children:[o.jsx("span",{className:"code-run-strip__icon","aria-hidden":"true",children:o.jsx(re,{name:h.tone==="working"?"loader":h.tone==="success"?"check":h.tone==="error"?"error":h.tone==="waiting"?"history":"info",size:15})}),u&&h.tone==="waiting"?o.jsxs("button",{className:"code-run-strip__attention",onClick:u,title:"Go to the pending request",children:[o.jsx("strong",{children:h.label}),o.jsx(re,{name:"chevronRight",size:12})]}):o.jsx("strong",{children:h.label}),o.jsx("span",{className:`code-run-strip__detail${m?" code-run-strip__detail--live":""}`,title:p,children:p})]}),o.jsxs("span",{className:"code-run-strip__metrics","aria-label":"Run activity metrics",children:[e&&x?o.jsx("span",{children:x}):null,h.toolCalls?o.jsxs("span",{children:[h.toolCalls," ",h.toolCalls===1?"tool":"tools"]}):null,h.totalTokens!==void 0?o.jsxs("span",{children:[h.totalTokens.toLocaleString()," tokens"]}):null]}),e?o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>i(t?"resume":"pause"),children:[t?"Resume":"Pause"," "]}),o.jsx("button",{onClick:()=>i("conclude"),children:"Conclude"})]}):null,o.jsxs("button",{onClick:c,children:["View activity ",o.jsx(re,{name:"chevronRight",size:12})]}),d?o.jsxs("div",{className:"code-run-strip__consent",children:[o.jsx(re,{name:"check",size:13}),o.jsx("span",{children:"Permissions: all · enabled tools only"}),o.jsx("button",{onClick:r,children:"Revoke"})]}):null]})}function Jd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function mc(e){return typeof e=="string"?e.trim():""}function oE(e){const t=Jd(e),n=Jd(t==null?void 0:t.gateway),r=Jd(n==null?void 0:n.principal);return JSON.stringify([mc((t==null?void 0:t.gateway_url)??(t==null?void 0:t.gatewayUrl)),mc((r==null?void 0:r.tenant_id)??(r==null?void 0:r.tenantId)),mc((r==null?void 0:r.runtime_id)??(r==null?void 0:r.runtimeId)),mc((r==null?void 0:r.user_id)??(r==null?void 0:r.userId))||"session"])}function vg(e,t){return!!e.sourceRunId&&e.sessionId===t.sessionId&&e.sessionId===t.snapshotSessionId&&e.sourceRunId===t.runId&&e.sourceRunId===t.snapshotRunId&&e.authEpoch===t.authEpoch}function iE(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return["completed","complete","done"].includes(t)?"advance":["failed","error","cancelled","canceled"].includes(t)?"pause":"wait"}function lE(e,t,n){return e.flatMap(r=>r.id===t.id?[]:r.sessionId!==t.sessionId||r.authEpoch!==t.authEpoch||r.sourceRunId!==t.sourceRunId?[r]:[{...r,sourceRunId:n}])}function _g(){return new DOMException("The conversation changed before the run was attached.","AbortError")}const cE=nb("abstractcode","0.11.0"),Qd=e=>["completed","failed","cancelled","canceled"].includes(e);function bg(){const e=new URLSearchParams(window.location.hash.replace(/^#/,""));return{sessionId:e.get("session")||Ar(),runId:e.get("run")||""}}function gi(e,t=""){const n=new URLSearchParams({session:e});t&&n.set("run",t),window.history.replaceState(null,"",`#${n}`)}function uE(){var Ki,Ji,Qi,Yi,$a,Xi,qi,Zi,Lo,el,tl,nl,sl,rl,al,ol,Aa,lr,il,Oo;const e=U_({appName:"AbstractCode",variant:"blocking"}),t=e.connected?oE(e.status):"",n=y.useCallback(()=>{e.refresh()},[e.refresh]),r=R1(t,n),[i,c]=db("abstractcode",{defaults:{theme:"observer-night"}}),[u,d]=y.useState(!1),[h,m]=y.useState(!1),[p,v]=y.useState(!1),[_,b]=y.useState(0),C=y.useCallback(()=>b(T=>T+1),[]),[x,j]=y.useState(),N=y.useCallback(()=>{j(void 0),mt(ve("about")).then(T=>j({ok:!0,value:T})).catch(T=>j({ok:!1,status:T==null?void 0:T.status,message:vt(T)}))},[]),[$,S]=y.useState({});y.useEffect(()=>{try{S(JSON.parse(localStorage.getItem(`abstractcode.voice:${t}`)||"{}"))}catch{S({})}Ys(),d(!1)},[t]);const E=T=>{if(S(T),t)try{localStorage.setItem(`abstractcode.voice:${t}`,JSON.stringify(T))}catch{}},[A,I]=y.useState(os),F=y.useRef(A);F.current=A;const L=i1(A.streamReplies,r.streaming),[J,V]=y.useState(os.workflow),O=y.useMemo(()=>w1(r.executable.data),[r.executable.data]),Z=y.useMemo(()=>y1(r.gatewayDefault,r.workflows),[r.gatewayDefault,r.workflows]),R=J===Cn?Z:r.workflows.find(T=>T.id===J)||O.find(T=>T.id===J)||null,[q,z]=y.useState(null),se=Of(R),[G,te]=y.useState(bg),[ue,ne]=y.useState(""),[P,B]=y.useState(""),[W,de]=y.useState(""),[ee,le]=y.useState(!1),fe=y.useRef(!1),[oe,we]=y.useState([]),[Oe,Je]=y.useState([]),st=y.useRef(new Set),Ce=y.useRef(new Map),[Ye,he]=y.useState(""),Ve=y.useRef(null),[ae,Te]=y.useState(),ge=y.useRef(ae);ge.current=ae;const[Q,pe]=y.useState(!1),[be,Ee]=y.useState(""),[Pe,We]=y.useState(0),[Be,bt]=y.useState({}),[Nt,Vn]=y.useState(""),[at,Js]=y.useState(null),[is,go]=y.useState(""),[_n,Qs,yo]=YN(),ma=_n!==null,Ys=T=>{yo&&Qs(null)},pa=T=>{d(!1),Lt(!1),Qs(T)},ls=T=>{T?pa("workflow"):_n==="workflow"&&Qs(null)},cs=vc($i.md),Xs=vc($i.lg),qs=YS(Xs,cs),wo=y.useRef(qs),Fi=s0(60),[ks,Lt]=y.useState(!1),[Lr,vo]=b0(),[Gn,ga]=N0(),Zs=uC(r.capabilities),{ctl:on,state:pt}=BC(t,e.connected&&Zs.available);y.useEffect(()=>{Gn.automations&&pt.loaded&&pt.archivedCount>0&&pt.archived===null&&on.loadArchived()},[Gn.automations,pt.loaded,pt.archivedCount,pt.archived,on]);const[$t,Hn]=y.useState(!1),[Or,zi]=y.useState(!1),_o=y.useRef(""),[bo,js]=y.useState(""),xo=y.useRef(null),[er,Kc]=y.useState("steer"),[us,Kn]=y.useState([]),[ya,$n]=y.useState(!1),[Ui,ko]=y.useState([]),lt=y.useMemo(()=>Sw(r.tools,A.tools,A.permissions),[r.tools,A.tools,A.permissions]),jo=y.useRef(null),So=y.useMemo(()=>{var je,Ae;const T=((je=jo.current)==null?void 0:je.runId)===G.runId?jo.current.input:null;if(G.runId&&!at&&!T)return{enabledTools:[],autoApproveTools:[]};const X=at?at.input_data:T,_e=F1(lt,(Ae=X==null?void 0:X._runtime)==null?void 0:Ae.allowed_tools);return{..._e,autoApproveTools:A.toolsCustomized||A.permissions!=="default"?_e.autoApproveTools:[]}},[lt,at,G.runId,A.toolsCustomized,A.permissions]),wa=`${t}:${G.sessionId}:${G.runId}`,Pr=y.useRef(wa);Pr.current=wa;const Bi=y.useRef(null),[No,va]=y.useState({scope:"",notes:[]}),An=y.useMemo(()=>I1({onDeltaError:T=>{const X=Pr.current,_e=u1(T,Bi.current);va(je=>({scope:X,notes:d1(je.scope===X?je.notes:[],_e)}))}}),[]),{controller:Ss,snapshot:De}=US({transport:An,runId:G.runId,enabled:e.connected,onAuthError:n,clientId:"abstractcode-web",authScopeKey:t,toolApprovalPolicy:So}),bn=!!G.runId&&!Qd(De.status)&&De.status!=="idle",Co=((Ki=De.run)==null?void 0:Ki.paused)===!0||De.status==="paused",ds=bn||ee,Ns=De.loading&&Ui.length?Ui:De.messages,Cs=Ns[Ns.length-1];Bi.current=Cs!=null&&Cs.id?String(Cs.id):null;const ln=f1(Ns,[l1(A.streamReplies,r.streaming,Ns),...No.scope===wa?No.notes:[]]),tr=((Qi=(Ji=r.capabilities)==null?void 0:Ji.assistant)==null?void 0:Qi.voice)||{},Wi=AC(e.connected),Jn=Uw({scope:`${t}:${G.sessionId}:${G.runId}:${$t}`,runId:t?G.runId:"",sessionId:G.sessionId,capability:tr,preferences:$,onTranscript:T=>ne(X=>X?`${X.trimEnd()}
92
+ ${T}`:T),onError:B}),Qn=[...ln].reverse().find(T=>T.role==="assistant"),Es=Qn?String(Qn.id||Qn.content):"",Dr=y.useRef({scope:"",id:""});y.useEffect(()=>{const T=`${t}:${G.sessionId}`,X=Dr.current;if(X.scope!==T){Dr.current={scope:T,id:Es};return}!Es||Es===X.id||ds||(Dr.current={scope:T,id:Es},$.read_aloud===!0&&Jn.tts_supported&&(Qn!=null&&Qn.content)&&Jn.toggle_tts(Es,Qn.content))},[t,G.sessionId,Es,ds,$.read_aloud,Jn.tts_supported]);const nr=PS(De),Tn=y.useMemo(()=>QS(nr,Ss,{records:De.records,currentRun:De.run,onPermissionsAll:async()=>{I(T=>({...T,permissions:"all"}))}}),[nr,De.records,De.run,Ss]),_a=!!Tn&&er==="steer",Ge=se?"prompt":t1(ae),Eo=se||!!(Ge&&!((Yi=ae==null?void 0:ae.required)!=null&&Yi.some(T=>T!==Ge))),$s=String((($a=at==null?void 0:at.workspace)==null?void 0:$a.workspace_root)||((qi=(Xi=De.run)==null?void 0:Xi.vars)==null?void 0:qi.workspace_root)||""),As=y.useMemo(()=>{var T;return L0(r.workflows,{inputData:at,runWorkflowId:(T=De.run)==null?void 0:T.workflow_id})},[r.workflows,at,(Zi=De.run)==null?void 0:Zi.workflow_id]),Fr=G.runId&&at&&!r.loading&&De.run&&!As&&Ff(at)!=="gateway_default"?"This conversation's exact workflow version is unavailable. Restore it in the gateway, or start a new conversation with an available workflow.":"",Kt=r.sessions.find(T=>T.sessionId===G.sessionId),zr=(Kt==null?void 0:Kt.prompt)||((Lo=ln.find(T=>T.role==="user"))==null?void 0:Lo.content)||"New conversation",ba=cC((el=e.status)==null?void 0:el.gateway_url),sr=ba?()=>{window.open(ba,"_blank","noopener,noreferrer")}:void 0,Rn={...sr?{openMyEmail:sr}:{},openConversation:(T,X,_e)=>{_o.current=_e||"",or(T,X)},openRun:T=>{mt(ve(`runs/${encodeURIComponent(T)}`)).then(X=>{if(!(X!=null&&X.session_id))throw new Error(`The gateway reported no session for run ${T}.`);or(X.session_id,T)}).catch(X=>on.reportError(X))}},Yn=T=>{(!$t||pt.selectedId!==T)&&(Hn(!0),on.select(T)),Lt(!1),d(!1),Qs("workflow")},fs=T=>{Yn(T),Qs("workspace")},rr=async T=>{const X=T.flow_id==="@default"?Z:r.workflows.find(dt=>`${dt.bundleId}@${dt.bundleVersion}`===("bundle_ref"in T?T.bundle_ref:"")&&dt.flowId===T.flow_id);if(!X)throw new Error("The selected workflow is no longer available. Refresh the workflow list.");const _e=await Vd(X);if(!_e)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const je={...Gs(_e),...T.input_data},Ae=zd(_e,je);if(Ae.length)throw new Error(`${Ae.join(" ")} Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...T,input_data:je}},ar=((tl=pt.detail)==null?void 0:tl.summary.title)||"Automation",In=y.useRef(""),Ur=y.useRef(t),Ct=y.useRef(0);Ur.current!==t&&(Ct.current+=1,Ur.current=t);const Ts=y.useRef(!1),Ut=y.useRef(G);Ut.current=G,y.useEffect(()=>{if(fe.current=!1,le(!1),Je([]),B(""),de(""),!t){we([]),ne(""),Kn([]),$n(!1),ko([]),I(os);return}if(In.current&&In.current!==t){const X={sessionId:Ar(),runId:""};te(X),gi(X.sessionId)}In.current=t,Ts.current=!0;const T=YC(t);I(T),V(T.workflow)},[t]),y.useEffect(()=>{if(t){if(Ts.current){Ts.current=!1;return}XC(t,A)}},[A,t]),y.useEffect(()=>{if(r.loading||!r.workflows.length)return;const T=b1({selection:J,preferred:A.workflow,visible:O,workflows:r.workflows,runId:G.runId});T!==J&&V(T)},[r.loading,r.workflows,O,J,A.workflow,G.runId]),y.useEffect(()=>{let T=!0;if(bt({}),Vn(""),Te(void 0),Ee(""),!R){pe(!1);return}return pe(!0),Vd(R).then(X=>{T&&(Te(X),bt(Gs(X)))}).catch(X=>{T&&Ee(vt(X))}).finally(()=>{T&&pe(!1)}),()=>{T=!1}},[R==null?void 0:R.id,Pe]),y.useEffect(()=>{if(Js(null),go(""),!t||!G.runId)return;const T=new AbortController;return mt(ve(`runs/${encodeURIComponent(G.runId)}/input_data`),{signal:T.signal}).then(X=>{Js(X)}).catch(X=>{T.signal.aborted||go(vt(X))}),()=>T.abort()},[G.runId,t]),y.useEffect(()=>{at&&at.flow_id===(R==null?void 0:R.flowId)&&ae&&bt({...Gs(ae),...q0(ae,at.input_data)})},[at,ae,R==null?void 0:R.flowId]),y.useEffect(()=>{!G.runId&&e.connected&&(Kt!=null&&Kt.latestRunId)&&te(T=>({...T,runId:Kt.latestRunId}))},[G.runId,e.connected,Kt==null?void 0:Kt.latestRunId]),y.useEffect(()=>{gi(G.sessionId,G.runId),fe.current=!1,le(!1),Je([]),we([]),bt(Gs(ge.current)),ko([]),de(_o.current),_o.current="",B(""),Kn([]),$n(!1)},[G.sessionId]),y.useEffect(()=>{const T=()=>{const X=bg();fe.current=!1,le(!1),Je([]),Kn([]),$n(!1),ne(""),te(X)};return window.addEventListener("hashchange",T),()=>window.removeEventListener("hashchange",T)},[]),y.useEffect(()=>{!G.runId||!Qd(De.status)||r.refresh()},[G.runId,De.status]),y.useEffect(()=>{if(!G.runId||!at)return;const T=x1({restoredInputs:at,restored:As});T&&V(T)},[G.runId,at,As==null?void 0:As.id]);const xa=G.runId?k1(at):"",hs=y.useCallback(()=>{const T={sessionId:Ar(),runId:""};te(T),V(F.current.workflow),gi(T.sessionId),ne(""),Kn([]),$n(!1),Lt(!1),Hn(!1)},[]),or=y.useCallback((T,X)=>{fe.current=!1,le(!1),Je([]),te({sessionId:T,runId:X}),gi(T,X),Lt(!1),Kn([]),$n(!1),ne(""),Hn(!1)},[]);y.useEffect(()=>{const T=wo.current;wo.current=qs,T!==qs&&Lt(X=>XS(X,qs))},[qs]),lw(ks,cs,()=>document.querySelector(".code-sidebar"),()=>document.querySelector(".code-mobile-close")),y.useEffect(()=>{const T=X=>{var je;if(qS({key:X.key,defaultPrevented:X.defaultPrevented,overlayOpen:ma||u||Or||h||ZS(),sidebarOpen:ks})==="sidebar"){Lt(!1),(je=document.querySelector(".code-mobile-nav"))==null||je.focus();return}(X.metaKey||X.ctrlKey)&&(X.key.toLowerCase()==="k"&&(X.preventDefault(),Ys(),d(!1),Lt(!0),window.setTimeout(()=>{var Ae;return(Ae=xo.current)==null?void 0:Ae.focus()},0)),X.key.toLowerCase()==="n"&&X.shiftKey&&(X.preventDefault(),hs()))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[hs,ks,Or,ma,u,h]);function $o(T,X,_e=[],je=!1,Ae=R,dt=ae){const jt=z0({workflow:Ae||void 0,inputSchema:dt,schemaInputs:X,prompt:T,promptProperty:Ge,model:A,reasoning:A.reasoning||void 0,speculation:A.speculation,streamReplies:L,systemPromptExtra:A.system||void 0,attachments:_e,limits:{maxIterations:A.maxIterations?Number(A.maxIterations):void 0,maxTokens:A.maxTokens?Number(A.maxTokens):void 0},workspace:$s?{root:$s}:void 0,tools:A.toolsCustomized?lt.enabledTools:void 0,toolPolicy:A.toolsCustomized||A.permissions!=="default"?{autoApproveTools:[],requireApprovalTools:lt.enabledTools}:void 0,skills:A.skills.length?A.skills:void 0});return je&&(delete jt.workspace_root,delete jt.workspace_access_mode,delete jt.workspace_allowed_paths,delete jt.workspace,jt._runtime&&typeof jt._runtime=="object"&&delete jt._runtime.tool_policy),jt}async function ms(T){if(fe.current)throw new Error("A turn is already being submitted.");if(!e.connected)throw new Error("Connect to your gateway first.");if(J===Cn&&r.gatewayDefault.status==="unavailable")throw new Error(`Gateway default: ${r.gatewayDefault.reason}. Choose a workflow from the list.`);if(!R)throw new Error("Choose a workflow first.");if(!r.policy)throw new Error("Workspace policy is unavailable. Reconnect or refresh before starting.");if(G.runId&&(!at||is))throw new Error(is||"Wait for the gateway to restore this conversation's workspace.");if(Fr)throw new Error(Fr);if(Q||be)throw new Error(be||"Wait for workflow inputs to load.");if(Nt)throw ls(!0),new Error(Nt);const X=Y1(Oe);if(X)throw new Error(X);if(bn)throw new Error("The current run is still active.");if(!se&&T.trim()&&!Ge)throw ls(!0),new Error("This workflow uses structured inputs. Configure its inputs, then select Run workflow.");const _e={...Gs(ae),...Be,...Ge&&T.trim()?{[Ge]:T.trim()}:{}},je=se?_e:eE(ae,_e,oe);for(const[tn,Ot]of[["Iteration limit",A.maxIterations],["Context token limit",A.maxTokens]])if(Ot&&(!Number.isInteger(Number(Ot))||Number(Ot)<=0))throw new Error(`${tn} must be a positive whole number.`);fe.current=!0,le(!0),B(""),de("");const Ae=G.sessionId,dt=G.runId,jt=t,cr=Ct.current;let Tt="";try{const tn=$o(T,je,oe),Ot=zd(ae,tn);if(Ot.length)throw ls(!0),new Error(Ot.join(" "));const xn=j1({selection:J,workflow:R,sessionId:Ae,input:tn}),ps=await mt(ve("runs/start"),{method:"POST",body:JSON.stringify(xn)});if(!ps.run_id)throw new Error("The gateway did not return a run identifier.");if(Ut.current.sessionId!==Ae||Ut.current.runId!==dt||Ur.current!==jt||Ct.current!==cr)throw _g();return Tt=String(ps.run_id),jo.current={runId:Tt,input:tn},z({runId:Tt,...S1(ps.resolved_workflow)}),ko([...ln,...T.trim()?[{id:`pending:${ps.run_id}`,role:"user",content:T.trim()}]:[]]),te({sessionId:Ae,runId:ps.run_id}),gi(Ae,ps.run_id),ne(""),we([]),ls(!1),ps.runner_warning&&de(String(ps.runner_warning)),r.refresh(),Tt}finally{Ut.current.sessionId===Ae&&(Ut.current.runId===dt||Ut.current.runId===Tt)&&Ur.current===jt&&Ct.current===cr&&(fe.current=!1,le(!1))}}async function Br(T){if(!bn)return ms(T);if(er==="queue")Kn(X=>[...X,{id:Ar(),text:T,sessionId:G.sessionId,sourceRunId:G.runId,authEpoch:Ct.current}]),$n(!0),ne(""),de("Queued for the next turn.");else{if(Tn)throw new Error("Answer the pending workflow request above, or choose Queue next turn.");const X=G.sessionId,_e=G.runId,je=Ct.current;if(await Ss.sendCommand("inject_guidance",{guidance:T}),Ut.current.sessionId!==X||Ut.current.runId!==_e||Ct.current!==je)return;ne(""),de("Guidance queued. The workflow will read it at its next supported boundary.")}}async function Rs(T){var je,Ae;const X=String(((je=De.run)==null?void 0:je.run_id)||"");if(!vg(T,{sessionId:G.sessionId,runId:G.runId,snapshotRunId:X,snapshotSessionId:String(((Ae=De.run)==null?void 0:Ae.session_id)||""),authEpoch:Ct.current}))throw _g();const _e=await ms(T.text);Kn(dt=>lE(dt,T,_e))}y.useEffect(()=>{var _e,je;if(!ya||!us.length||!e.connected||!at||is||fe.current)return;const T=iE(De.status);if(T==="wait")return;if(T==="pause"){$n(!1);const Ae=["failed","error"].includes(De.status.toLowerCase());de(`Queue paused because the run ${Ae?"failed":"was cancelled"}. Review the result, then use Run next to continue explicitly.`);return}const X=us[0];vg(X,{sessionId:G.sessionId,runId:G.runId,snapshotRunId:String(((_e=De.run)==null?void 0:_e.run_id)||""),snapshotSessionId:String(((je=De.run)==null?void 0:je.session_id)||""),authEpoch:Ct.current})&&Rs(X).catch(Ae=>{Ae instanceof DOMException&&Ae.name==="AbortError"||($n(!1),B(vt(Ae)))})},[ya,us,De.status,(nl=De.run)==null?void 0:nl.run_id,(sl=De.run)==null?void 0:sl.session_id,e.connected,at,is,G.sessionId,G.runId]);async function Wr(T){const X=G.sessionId,_e=t,je=Ct.current,Ae=()=>Ut.current.sessionId!==X||Ur.current!==_e||Ct.current!==je,dt=(Tt,tn)=>Je(Ot=>Ot.map(xn=>xn.id===Tt?{...xn,...tn}:xn));let jt=0,cr=0;await Q1(T,H1,async Tt=>{if(!(Ae()||st.current.has(Tt.id))){dt(Tt.id,{status:"uploading",message:void 0});try{const tn=await En.attachments_upload(X,Tt.file);if(Ae()||st.current.has(Tt.id))return;Ce.current.set(tn.$artifact,Tt.size),Je(Ot=>Ot.filter(xn=>xn.id!==Tt.id)),we(Ot=>[...Ot,tn]),jt+=1}catch(tn){if(Ae()||st.current.has(Tt.id))return;dt(Tt.id,{status:"failed",message:K1(vt(tn))}),cr+=1}}}),!Ae()&&(jt||cr)&&he(ag(jt,cr))}function Ao(T){var je;if(!T.length)return[];const X=J1(T,(je=r.policy)==null?void 0:je.maxAttachmentBytes,Ar);Je(Ae=>[...Ae,...X]);const _e=X.filter(Ae=>Ae.status==="refused").length;return _e&&he(ag(0,_e)),Wr(X.filter(Ae=>Ae.status==="queued")),X}function Jc(T){const X=Oe.find(je=>je.id===T);if(!X||X.status!=="failed")return;const _e={...X,status:"queued",message:void 0};Je(je=>je.map(Ae=>Ae.id===T?_e:Ae)),Wr([_e])}function To(T){st.current.add(T),Je(X=>X.filter(_e=>_e.id!==T))}async function ka(){const T=G.sessionId,X=G.runId,_e=Ct.current;await Ss.cancel(),Ut.current.sessionId===T&&Ut.current.runId===X&&Ct.current===_e&&de("")}const Is=T=>{const X=Ct.current,_e=G.sessionId,je=G.runId;B(""),T().catch(Ae=>{Ae instanceof DOMException&&Ae.name==="AbortError"||Ct.current===X&&Ut.current.sessionId===_e&&Ut.current.runId===je&&B(vt(Ae))})},ja=r.sessions.filter(T=>`${T.prompt||""} ${T.sessionId}`.toLowerCase().includes(bo.toLowerCase())),[At,Vr]=y.useState(null),[Gr,Sa]=y.useState(!1),[Na,Ms]=y.useState(""),Ro=(T,X)=>{Ms(""),Vr({sessionId:T,where:X})},en=()=>{Vr(null),Ms("")},ir=async()=>{if(!At||Gr)return;const{sessionId:T}=At;Sa(!0),Ms("");try{await K0(T)}catch(X){Ms(`Not archived: ${vt(X)}`),Sa(!1);return}if(Sa(!1),Vr(null),T===G.sessionId){const X=J0(ja,T);X?or(X.sessionId,X.latestRunId):hs()}r.forgetSession(T)},Ca=o.jsx(E0,{busy:Gr,error:Na,onConfirm:()=>void ir(),onCancel:en}),Hr=(()=>{var T;try{return new URL(((T=e.status)==null?void 0:T.gateway_url)||"").host}catch{return"Your gateway"}})(),Qc=T=>{const X=[];(A.provider||A.model)&&!T.provider&&!T.model&&X.push("provider","model"),A.toolsCustomized&&!T.toolsCustomized&&X.push("tools"),A.maxIterations&&!T.maxIterations&&X.push("max_iterations"),X.length&&bt(_e=>{const je={..._e},Ae=Gs(ae);for(const dt of X)delete je[dt],Object.prototype.hasOwnProperty.call(Ae,dt)&&(je[dt]=Ae[dt]);return je}),I(T)},Mn=(T,X=A,_e=Qc,je)=>o.jsx(U1,{tab:T,lockedReasonId:`code-${T}-locked`,value:X,onChange:_e,tools:r.tools,connected:e.connected,automationFolders:!!je,defaultModel:!je&&Be.provider&&Be.model?{provider:String(Be.provider),model:String(Be.model)}:r.defaultModel,workflowDefault:!je&&!!(Be.provider&&Be.model),streaming:r.streaming,disabled:je?!e.connected:ds||!e.connected,workspaceRootFixed:je==null?void 0:je.root,sessionId:je?void 0:G.sessionId,onOpenDefaultWorkspaces:()=>v(!0),workspaceRefreshKey:_,hideStreamReplies:!!je,lockedText:je?"Connect to a gateway to edit this automation.":void 0}),Ea=o.jsx(TC,{value:$,onChange:T=>{Jn.stop_tts(),E(T)},defaults:Wi,connected:e.connected}),ot=pt.detail,Ln=nC($t&&(ot!=null&&ot.definition)?{summary:ot.summary,definition:ot.definition}:null,(T,X,_e)=>on.revise(T,X,_e)),Ls=(T,X,_e)=>{if($t){if(!(ot!=null&&ot.definition)||!Ln)return pt.selectedId?o.jsx(uo,{children:"Loading automation…"}):o.jsx("p",{className:"code-muted",children:"Select an automation in the sidebar."});const je={root:ot.definition.workspace_root||""};return o.jsxs("div",{className:"code-automation-settings",id:`code-settings-${T}`,"data-revision":Ln.revision,children:[o.jsx(sC,{summary:ot.summary,settings:Ln}),_e(Ln.draft,Ln.onChange,je)]})}return o.jsxs("div",{className:"code-conversation-settings",id:`code-settings-${T}`,children:[o.jsxs("p",{className:"code-settings-binding",children:[o.jsx("span",{children:"Conversation"})," ",o.jsx("strong",{title:zr,children:zr})]}),X()]})},Yc=Ls("model",()=>Mn("model"),(T,X,_e)=>Mn("model",T,X,_e)),Xc=Ls("workflow",()=>o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"code-workflow-select","aria-busy":Q||void 0,children:[o.jsx(re,{name:"agent",size:17}),o.jsx(dy,{id:"code-workflow-picker",className:"code-workflow-picker",interfaceId:as,ariaLabel:"Workflow",workflows:{...r.executable,reload:()=>void r.refresh()},value:v1(J,R),currentLabel:R&&J!==Cn&&!O.some(T=>T.id===R.id)?{name:R.name,detail:G.runId&&R.bundleVersion?`conversation version ${R.bundleVersion}`:R.bundleVersion?`@${R.bundleVersion}`:""}:null,unavailableReason:e.connected?ds?"A run is in progress.":null:"Connect to a gateway first.",onChange:(T,X)=>{const _e=_1(T,X);V(_e),I(je=>({...je,workflow:_e}))}}),J===Cn&&Ud(Z)?o.jsx("span",{className:"code-workflow-resolved is-missing",role:"alert",title:Ud(Z),children:Ud(Z)}):null,xa?o.jsx("span",{className:"code-workflow-resolved is-missing",role:"status",title:xa,children:xa}):null,q&&q.runId===G.runId&&q.missing?o.jsx("span",{className:"code-workflow-resolved is-missing",role:"status",children:q.text}):null]}),o.jsxs("div",{className:"code-settings code-workflow-inputs",children:[o.jsx("h3",{className:"code-settings-heading",children:"Inputs"}),o.jsx("p",{className:"code-muted",children:(R==null?void 0:R.description)||"Configure the values this workflow needs to run."}),Q?o.jsx("p",{role:"status",children:"Loading input schema…"}):be?null:se||Ge?o.jsx(ZC,{schema:ae,promptProperty:Ge,defaultModel:r.defaultModel,values:Be,onChange:bt,disabled:ds,onEditorError:Vn},R==null?void 0:R.id):o.jsx(_f,{schema:ae,defaultModel:r.defaultModel,values:Be,onChange:bt,disabled:ds,rawObject:!0,onEditorError:Vn},R==null?void 0:R.id),be?o.jsx("p",{role:"alert",className:"code-error-text",children:be}):null,Eo?o.jsxs("button",{className:"code-primary-button",onClick:()=>ls(!1),children:["Back to chat ",o.jsx(re,{name:"chat",size:16})]}):o.jsxs("button",{className:"code-primary-button",disabled:ds||Q||!!be||!!Nt||!e.connected,onClick:()=>Is(()=>ms(ue||String(Be[Ge||"prompt"]||""))),children:["Run workflow ",o.jsx(re,{name:"playCircle",size:16})]})]})]}),()=>ot!=null&&ot.definition&&Ln?o.jsx(rC,{summary:ot.summary,definition:ot.definition,settings:Ln,busy:pt.busy,disabled:!e.connected,emailStatus:pt.emailStatus,onOpenMyEmail:Rn.openMyEmail,onRevise:(T,X)=>on.revise(ot.automationId,T,X),prepareTarget:rr,workflowPickerOptions:{interfaceId:as,workflows:{...r.executable,reload:()=>void r.refresh()}}}):null),qc=Ls("workspace",()=>o.jsxs(o.Fragment,{children:[o.jsxs("p",{className:"code-current-workspace",children:["Current workspace ",o.jsx("code",{title:$s||"Gateway workspace",children:$s.split("/").filter(Boolean).pop()||"Gateway workspace"})]}),Mn("workspace")]}),(T,X,_e)=>Mn("workspace",T,X,_e)),Io=Ls("tools",()=>Mn("tools"),(T,X,_e)=>Mn("tools",T,X,_e)),Zc=Ls("skills",()=>Mn("skills"),(T,X,_e)=>Mn("skills",T,X,_e)),eu=Ls("voice",()=>Ea,()=>Ea),Mo=$t?`automation:${pt.selectedId}`:`conversation:${G.sessionId}`,Vi=y.useRef({});y.useEffect(()=>{!_n||_n==="activity"||_n==="files"||Vi.current[_n]===Mo||(Vi.current[_n]=Mo,window.requestAnimationFrame(()=>{const T=document.querySelector(`#code-rail-panel-${_n} .af-rail__body`);T&&(T.scrollTop=0)}))},[Mo,_n]);const Gi=$t?{count:0,hint:""}:MN(De.records,G.runId),Hi=o.jsx(XN,{panel:_n,onPanel:T=>{Qs(T),T&&d(!1)},activityBadge:Gi.count,activityHint:Gi.hint,content:{activity:$t?o.jsx(FN,{occurrences:(ot==null?void 0:ot.occurrences)||[],nowMs:Date.now(),onOpenRun:Rn.openRun}):o.jsx(IN,{records:De.records,runId:G.runId}),files:$t?e.connected&&pt.selectedId?o.jsx(Mf,{fetchGateway:Ac,runId:pt.selectedId,title:"Automation files",refreshKey:ot==null?void 0:ot.summary.updated_at,copyText:zf,onOpenFolder:()=>Cw(pt.selectedId)}):o.jsx("p",{className:"code-muted",children:"Connect to a gateway and select an automation to browse its files."}):o.jsxs(o.Fragment,{children:[o.jsx(RN,{policy:r.policy,runId:G.runId,enabled:e.connected,isAdmin:((ol=(al=(rl=e.status)==null?void 0:rl.gateway)==null?void 0:al.principal)==null?void 0:ol.admin)===!0,refreshKey:De.status,onAttachFiles:Ao,onAttach:async T=>{const X=G.sessionId,_e=G.runId,je=Ct.current,Ae=await En.attachments_ingest(X,T);Ut.current.sessionId===X&&Ut.current.runId===_e&&Ct.current===je&&we(dt=>[...dt,Ae])}}),ln.length?o.jsx("button",{className:"code-subtle-button",onClick:()=>aj({filename:"conversation.md",text:rj(ln)}),children:"Export conversation"}):null]}),model:Yc,workflow:Xc,workspace:qc,tools:Io,skills:Zc,voice:eu}},`rail:${t}`);return o.jsxs("div",{className:`code-app${ks?" code-app--nav-open":""}`,children:[o.jsx("a",{className:"code-skip-link",href:"#code-conversation",children:"Skip to conversation"}),o.jsxs(h0,{isDrawer:cs,open:ks,children:[o.jsxs("div",{className:"code-brand",children:[o.jsxs("span",{className:"code-brand-mark","aria-hidden":"true",children:["a",o.jsx("span",{children:"c"})]}),o.jsxs("div",{children:[o.jsx("strong",{children:"AbstractCode"}),o.jsx("span",{children:"YOUR WORK, IN CONTEXT"})]}),o.jsx("button",{className:"code-mobile-close code-icon-button","aria-label":"Close navigation",onClick:()=>Lt(!1),children:o.jsx(re,{name:"x",size:18})})]}),o.jsxs("div",{className:"code-session-search",children:[o.jsx(re,{name:"history",size:14}),o.jsx("input",{ref:xo,"aria-label":"Search conversations",placeholder:"Search conversations",value:bo,onChange:T=>js(T.target.value)}),o.jsx("kbd",{children:"⌘K"})]}),o.jsxs(x0,{panels:Lr,children:[o.jsx(WC,{state:pt,available:Zs,discovering:r.capabilitiesLoading,createDisabled:Q||!!be||!R,selectedId:$t?pt.selectedId:"",onSelect:T=>{Hn(!0),Lt(!1),on.select(T)},onNew:()=>zi(!0),onRefresh:()=>void on.refresh(),archivedOpen:Gn.automations,onToggleArchived:()=>ga("automations"),onUnarchive:T=>void on.unarchive(T.automation_id).catch(()=>{}),onToggleActive:T=>void on.toggleActive(T).catch(()=>{}),open:Lr.automations,onToggle:()=>vo("automations")}),o.jsxs(k0,{open:Lr.conversations,onToggle:()=>vo("conversations"),actions:o.jsxs("span",{className:"code-auto-actions",children:[o.jsx("button",{className:"code-icon-button code-new-chat","aria-label":"New conversation",title:"New conversation (⇧⌘N)","aria-keyshortcuts":"Shift+Meta+N",onClick:hs,children:o.jsx(re,{name:"plus",size:13})}),o.jsx("button",{className:"code-icon-button","aria-label":"Refresh conversations",disabled:!e.connected||r.loading,onClick:()=>void r.refresh(),children:o.jsx(re,{name:"refresh",size:13})})]}),children:[Kt?null:o.jsx("button",{type:"button",className:"code-session code-card is-selected",onClick:()=>Lt(!1),children:o.jsxs("span",{children:[o.jsx("strong",{className:"code-card-title",children:"New conversation"}),o.jsx("small",{className:"code-card-meta",children:"Ready when you are"})]})}),ja.map(T=>o.jsx(U0,{item:T,selected:T.sessionId===G.sessionId,onClick:()=>or(T.sessionId,T.latestRunId),onAskArchive:e.connected?()=>Ro(T.sessionId,"card"):void 0,confirm:(At==null?void 0:At.where)==="card"&&At.sessionId===T.sessionId?Ca:void 0},T.sessionId)),r.sessionsLoaded&&!ja.length?o.jsx("p",{className:"code-history-empty",children:bo?"No conversations match your search.":"Your conversations will live here. Pick up where you left off, on any device."}):null,r.loading&&!r.sessionsLoaded?o.jsx(uo,{children:"Loading conversations…"}):null,r.hasMore?o.jsx("button",{className:"code-load-more",onClick:r.loadMore,children:"Load more conversations"}):null,o.jsx(pw,{list:"conversations",count:r.archivedSessions,open:Gn.conversations,onToggle:()=>ga("conversations"),children:o.jsx(Q0,{enabled:e.connected&&Gn.conversations,revision:r.archivedSessions,onOpen:T=>{Lt(!1),or(T.sessionId,T.latestRunId)},onUnarchived:()=>void r.refresh()})})]})]}),o.jsx("div",{className:"code-sidebar-bottom",children:o.jsxs("div",{className:"code-gateway-foot",children:[o.jsx("span",{className:`code-status-dot ${e.connected?"is-online":""}`}),o.jsx("span",{children:Hr}),o.jsx("small",{children:((il=(lr=(Aa=e.status)==null?void 0:Aa.gateway)==null?void 0:lr.principal)==null?void 0:il.user_id)||"Signed out"})]})})]}),ks?o.jsx("button",{className:"code-nav-scrim","aria-label":"Close conversation navigation",onClick:()=>Lt(!1)}):null,o.jsxs("div",{className:"code-main-shell",children:[o.jsxs("header",{className:"code-topbar",children:[o.jsx("button",{className:"code-mobile-nav code-icon-button","aria-label":"Open conversation navigation",onClick:()=>{Ys(),d(!1),Lt(!0)},children:o.jsx(re,{name:"list",size:19})}),o.jsxs("div",{className:"code-breadcrumb",children:[o.jsx("span",{children:$t?"Automations":"Conversations"}),o.jsx("span",{"aria-hidden":"true",children:"/"}),o.jsx("strong",{title:$t?ar:zr,children:$t?ar:zr})]}),!$t&&Kt&&e.connected?o.jsx(Eg,{className:"code-conversation-menu",label:"Conversation actions",title:"More actions",items:[{id:"archive",label:"Archive",danger:!0,onSelect:()=>Ro(Kt.sessionId,"header")}]}):null,o.jsx(lb,{docs:{open:u,onToggle:()=>{d(T=>!T),Ys(),Lt(!1)},label:"Docs assistant"},appearance:{onOpen:()=>m(!0)},about:{identity:cE,versions:oC(x),onOpen:N},connection:{phase:e.phase,signingOut:e.signingOut,onConnect:e.openModal,onDisconnect:()=>void e.signOut()}})]}),o.jsxs("div",{className:"code-content",children:[$t?o.jsx(KC,{prepareTarget:rr,workflowPickerOptions:{interfaceId:as,workflows:{...r.executable,reload:()=>void r.refresh()}},ctl:on,availableTools:r.tools.filter(T=>T.enabled).map(T=>T.name),host:Rn,voiceCapability:tr,voicePreferences:$,enabled:e.connected,onClose:()=>Hn(!1),onEdit:Yn,onEditWorkspaces:fs}):o.jsxs("main",{className:"code-conversation",id:"code-conversation",tabIndex:-1,children:[P||De.error||e.signOutError||is?o.jsxs("div",{className:"code-alert",role:"alert",children:[o.jsx(re,{name:"warning",size:16}),o.jsx("span",{children:P||De.error||e.signOutError||is}),De.error||is?o.jsx("button",{onClick:()=>{is?window.location.reload():Is(()=>Ss.load(G.runId))},children:"Reconnect"}):o.jsx("button",{"aria-label":"Dismiss error",onClick:()=>B(""),children:o.jsx(re,{name:"x",size:14})})]}):null,(At==null?void 0:At.where)==="header"&&At.sessionId===G.sessionId?o.jsx("div",{className:"code-archive-confirm-bar",children:Ca}):null,r.errors.length?o.jsx("div",{className:"code-discovery-errors",role:"status",children:o.jsxs("details",{children:[o.jsx("summary",{children:"Some gateway information could not be loaded"}),r.errors.map(T=>o.jsx("p",{children:T},T)),o.jsx("button",{onClick:()=>void r.refresh(),children:"Retry discovery"})]})}):null,Fr?o.jsxs("div",{className:"code-alert",role:"alert",children:[o.jsx("span",{children:Fr}),o.jsx("button",{onClick:hs,children:"New conversation"})]}):null,be?o.jsxs("div",{className:"code-alert",role:"alert",children:[o.jsxs("span",{children:["Workflow inputs: ",be]}),o.jsx("button",{onClick:()=>We(T=>T+1),children:"Retry"})]}):null,W?o.jsxs("div",{className:"code-notice",role:"status",children:[W,o.jsx("button",{"aria-label":"Dismiss notice",onClick:()=>de(""),children:o.jsx(re,{name:"x",size:13})})]}):null,bn||Qd(De.status)?o.jsx(aE,{active:bn,paused:Co,snapshot:De,permissionsAll:A.permissions==="all",onInteraction:Tn&&!Co?()=>{var _e;const T=document.querySelector(".code-conversation .pc-chat-thread"),X=T==null?void 0:T.querySelector(".pc-workflow-interaction");!T||!X||(T.scrollTop+=X.getBoundingClientRect().top-T.getBoundingClientRect().top,(_e=X.querySelector("h3"))==null||_e.focus({preventScroll:!0}))}:void 0,onRevokeApproval:()=>{Ss.revokeToolApproval(),I(T=>({...T,permissions:"default"}))},onCommand:T=>Is(()=>Ss.sendCommand(T,{})),onActivity:()=>{pa("activity")}}):null,o.jsx(OS,{streamReplies:L,messages:(Tn==null?void 0:Tn.kind)==="tool-approval"?ln.filter(T=>{var X,_e;return!(((X=T.toolActivity)==null?void 0:X.status)==="waiting"&&T.toolActivity.runId===((_e=De.interaction)==null?void 0:_e.runId))}):ln,messageProps:{...Jn.tts_supported?{onSpeakToggle:T=>{Jn.toggle_tts(T.id||T.content,T.content)}}:{},getSpeakState:T=>Jn.tts_playback.key===(T.id||T.content)?Jn.tts_playback.status:"idle"},draft:ue,onDraftChange:ne,onSend:Br,busy:ds,busyLabel:_a?"Waiting for you":ee?"Starting…":Co?"Paused":"Working…",sendWhileBusy:bn&&!ee&&!_a,sendLabel:bn?er==="queue"?"Queue":"Steer":"Send",onCancel:ka,stopState:De.stop??null,disabled:!e.connected,interaction:Tn,onAttach:()=>{var T;return(T=Ve.current)==null?void 0:T.click()},onFiles:T=>{Ao(T)},attachments:oe.length||Oe.length?o.jsx(rE,{attachments:oe,uploads:Oe,sizes:Ce.current,onRemoveAttachment:T=>we(X=>X.filter((_e,je)=>je!==T)),onRemoveUpload:To,onRetryUpload:Jc}):null,placeholder:bn?er==="queue"?"Queue the next task after this run…":Tn?"Answer the request above, or choose Queue next turn…":"Guide the current workflow…":"Describe what you want to build, fix, or explore…",emptyState:bn?null:o.jsx(dE,{workflow:R,loading:r.loading||Q,onSuggestion:ne,onInputs:()=>ls(!0),isAgent:Eo,onRun:()=>Is(()=>ms(ue)),connected:e.connected}),composerExtras:o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"code-composer-workspace",title:$s||"Workspace is managed by the gateway",children:[o.jsx(re,{name:"terminal",size:14}),o.jsx("span",{children:$s.split("/").filter(Boolean).pop()||"Gateway workspace"})]}),e.connected?o.jsx(MC,{runId:G.runId,voice:Jn,capability:tr,route:hb($,Wi.value)},`${t}:${G.sessionId}:${G.runId}`):null,bn?o.jsxs("select",{"aria-label":"Message destination",value:er,onChange:T=>Kc(T.target.value),children:[o.jsxs("option",{value:"steer",disabled:!!Tn,children:["Guide this run",Tn?" (answer above)":""]}),o.jsx("option",{value:"queue",children:"Queue next turn"})]}):null]}),footer:o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:["Enter to send ",o.jsx("span",{"aria-hidden":"true",children:"·"})," Shift + Enter for a new line"]}),o.jsxs("span",{children:["Managed workspace",o.jsx("span",{className:"code-small-dot"})]})]})}),us.length?o.jsxs("div",{className:"code-queue",children:[o.jsxs("div",{children:[o.jsxs("strong",{children:[us.length," queued"," ",us.length===1?"turn":"turns"]}),o.jsx(Mr,{className:"code-queue__switch",variant:"sm",action:"queue-running",label:"Run queued turns",hint:"On: each queued turn starts when the current run ends. Off: they wait here.",checked:ya,onChange:$n})]}),us.map(T=>o.jsxs("div",{children:[o.jsx("span",{children:T.text}),bn?null:o.jsx("button",{onClick:()=>Is(()=>Rs(T)),children:"Run next"}),o.jsx("button",{"aria-label":"Remove queued turn",onClick:()=>Kn(X=>X.filter(_e=>_e.id!==T.id)),children:o.jsx(re,{name:"x",size:13})})]},T.id))]}):null]}),Hi]}),o.jsxs("footer",{className:"code-statusbar",children:[o.jsxs("span",{children:[o.jsx("span",{className:`code-status-dot ${e.connected?"is-online":""}`}),e.connected?"Connected":e.phase==="loading"?"Connecting":"Disconnected"]}),o.jsx("span",{children:(R==null?void 0:R.name)||"No workflow selected"}),o.jsx("div",{}),o.jsx("span",{children:G.runId?`Run ${G.runId.slice(0,8)}`:"Ready to start"}),o.jsx("span",{children:i.theme.replace(/-/g," ")})]})]}),o.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:Ye}),o.jsx("input",{ref:Ve,hidden:!0,type:"file",multiple:!0,onChange:T=>{Ao(Array.from(T.target.files||[])),T.target.value=""}}),o.jsx(JC,{connected:e.connected,workflowPickerOptions:{interfaceId:as,workflows:{...r.executable,reload:()=>void r.refresh()}},open:Or,onClose:()=>zi(!1),target:dC(J,R),availableTools:r.tools.filter(T=>T.enabled).map(T=>T.name),initialTools:Ii(A.toolsCustomized?{...Be,tools:lt.enabledTools}:Be),buildInput:async(T,X)=>{if(!X)return $o(T,{...Gs(ae),...Be},[],!0);const _e=X.flow_id==="@default"?Z:r.workflows.find(jt=>`${jt.bundleId}@${jt.bundleVersion}`===("bundle_ref"in X?X.bundle_ref:"")&&jt.flowId===X.flow_id);if(!_e)throw new Error("The selected workflow is no longer available. Refresh the workflow list.");const je=await Vd(_e);if(!je)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const Ae=$o(T,Gs(je),[],!0,_e,je),dt=zd(je,Ae);if(dt.length)throw new Error(dt.join(" "));return Ae},workflowLabel:J===Cn?g1(r.gatewayDefault):(R==null?void 0:R.name)||"the selected workflow",initialPrompt:ue||((Oo=[...ln].reverse().find(T=>T.role==="user"))==null?void 0:Oo.content)||"",ctl:on,onOpenMyEmail:sr,onCreated:()=>{Hn(!0),Lt(!1)}}),o.jsx(F_,{...e.modalProps}),o.jsx(f0,{open:u,onClose:()=>d(!1),connected:e.connected,topOffset:Fi},`assistant:${t}`),o.jsx(fb,{open:h,onClose:()=>m(!1),value:i,onChange:c}),o.jsx(p0,{open:p,onClose:()=>v(!1),connected:e.connected,onChanged:C})]})}function dE({workflow:e,loading:t,onSuggestion:n,onInputs:r,isAgent:i,onRun:c,connected:u}){return o.jsxs("div",{className:"code-welcome",children:[o.jsxs("div",{className:"code-welcome-symbol","aria-hidden":"true",children:[o.jsx("span",{children:"›"}),o.jsx("span",{children:"_"})]}),o.jsx("p",{className:"code-eyebrow",children:"A LITTLE CONTEXT. A LOT OF POSSIBILITY."}),o.jsx("h1",{children:"What are we building?"}),o.jsxs("p",{className:"code-welcome-description",children:["A focused space to think, code, and get things done.",o.jsx("br",{}),"Your workflows. Your tools. One conversation."]}),e&&!i?o.jsxs("div",{className:"code-workflow-welcome",children:[o.jsx(re,{name:"playCircle",size:21}),o.jsxs("div",{children:[o.jsx("strong",{children:e.name}),o.jsx("p",{children:e.description||"Run this workflow with its registered inputs."})]}),o.jsx("button",{onClick:r,children:"Configure inputs"}),o.jsx("button",{onClick:c,disabled:t||!u,children:"Run workflow"})]}):o.jsx("div",{className:"code-suggestions",children:[{icon:"terminal",title:"Explore this project",detail:"Find your bearings in the codebase",prompt:"Explore this project and explain its architecture, key entry points, and how to run its tests."},{icon:"edit",title:"Build something new",detail:"Turn an idea into working code",prompt:"I'd like to build a new feature. Help me clarify the requirements and plan the implementation."},{icon:"warning",title:"Track down a bug",detail:"Understand what went wrong",prompt:"Help me investigate a bug. Start by asking what happened and what I expected."},{icon:"check",title:"Review my changes",detail:"Get a second pair of eyes",prompt:"Review the current changes for correctness, edge cases, and maintainability. Explain any findings before making edits."}].map(d=>o.jsxs("button",{onClick:()=>n(d.prompt),disabled:t,children:[o.jsx(re,{name:d.icon,size:18}),o.jsxs("span",{children:[o.jsx("strong",{children:d.title}),o.jsx("small",{children:d.detail})]}),o.jsx(re,{name:"chevronRight",size:13})]},d.title))}),o.jsx("p",{className:"code-welcome-hint",children:t?"Discovering your workflows…":e?o.jsxs(o.Fragment,{children:["Using ",o.jsx("strong",{children:e.name})," · Choose another in the Workflow panel"]}):u?"Register a workflow with AbstractGateway to get started.":"Connect your gateway to get started."})]})}class fE extends ct.Component{constructor(){super(...arguments);Nn(this,"state",{error:""})}static getDerivedStateFromError(n){return{error:n.message}}render(){return this.state.error?o.jsxs("div",{className:"code-crash",role:"alert",children:[o.jsx("h1",{children:"Something interrupted this view."}),o.jsx("p",{children:this.state.error}),o.jsx("p",{children:"Your runs are stored by the gateway."}),o.jsx("button",{onClick:()=>window.location.reload(),children:"Reload AbstractCode"})]}):this.props.children}}r_();t0();"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("sw.js").catch(()=>{})});qv.createRoot(document.getElementById("root")).render(o.jsx(ct.StrictMode,{children:o.jsx(fE,{children:o.jsx(uE,{})})}));