@abstractframework/code 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,97 +0,0 @@
1
- var Ex=Object.defineProperty;var Ax=(e,t,n)=>t in e?Ex(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var zt=(e,t,n)=>Ax(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();function _w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var df={exports:{}},Ai={},ff={exports:{}},nt={};/**
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 _g;function $x(){if(_g)return nt;_g=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.iterator;function _(T){return T===null||typeof T!="object"?null:(T=g&&T[g]||T["@@iterator"],typeof T=="function"?T:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,x={};function k(T,K,ne){this.props=T,this.context=K,this.refs=x,this.updater=ne||v}k.prototype.isReactComponent={},k.prototype.setState=function(T,K){if(typeof T!="object"&&typeof T!="function"&&T!=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,T,K,"setState")},k.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function S(){}S.prototype=k.prototype;function $(T,K,ne){this.props=T,this.context=K,this.refs=x,this.updater=ne||v}var R=$.prototype=new S;R.constructor=$,C(R,k.prototype),R.isPureReactComponent=!0;var N=Array.isArray,E=Object.prototype.hasOwnProperty,j={current:null},I={key:!0,ref:!0,__self:!0,__source:!0};function L(T,K,ne){var ue,oe={},ve=null,Ne=null;if(K!=null)for(ue in K.ref!==void 0&&(Ne=K.ref),K.key!==void 0&&(ve=""+K.key),K)E.call(K,ue)&&!I.hasOwnProperty(ue)&&(oe[ue]=K[ue]);var q=arguments.length-2;if(q===1)oe.children=ne;else if(1<q){for(var be=Array(q),xe=0;xe<q;xe++)be[xe]=arguments[xe+2];oe.children=be}if(T&&T.defaultProps)for(ue in q=T.defaultProps,q)oe[ue]===void 0&&(oe[ue]=q[ue]);return{$$typeof:e,type:T,key:ve,ref:Ne,props:oe,_owner:j.current}}function z(T,K){return{$$typeof:e,type:T.type,key:K,ref:T.ref,props:T.props,_owner:T._owner}}function V(T){return typeof T=="object"&&T!==null&&T.$$typeof===e}function Z(T){var K={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(ne){return K[ne]})}var ie=/\/+/g;function F(T,K){return typeof T=="object"&&T!==null&&T.key!=null?Z(""+T.key):K.toString(36)}function D(T,K,ne,ue,oe){var ve=typeof T;(ve==="undefined"||ve==="boolean")&&(T=null);var Ne=!1;if(T===null)Ne=!0;else switch(ve){case"string":case"number":Ne=!0;break;case"object":switch(T.$$typeof){case e:case t:Ne=!0}}if(Ne)return Ne=T,oe=oe(Ne),T=ue===""?"."+F(Ne,0):ue,N(oe)?(ne="",T!=null&&(ne=T.replace(ie,"$&/")+"/"),D(oe,K,ne,"",function(xe){return xe})):oe!=null&&(V(oe)&&(oe=z(oe,ne+(!oe.key||Ne&&Ne.key===oe.key?"":(""+oe.key).replace(ie,"$&/")+"/")+T)),K.push(oe)),1;if(Ne=0,ue=ue===""?".":ue+":",N(T))for(var q=0;q<T.length;q++){ve=T[q];var be=ue+F(ve,q);Ne+=D(ve,K,ne,be,oe)}else if(be=_(T),typeof be=="function")for(T=be.call(T),q=0;!(ve=T.next()).done;)ve=ve.value,be=ue+F(ve,q++),Ne+=D(ve,K,ne,be,oe);else if(ve==="object")throw K=String(T),Error("Objects are not valid as a React child (found: "+(K==="[object Object]"?"object with keys {"+Object.keys(T).join(", ")+"}":K)+"). If you meant to render a collection of children, use an array instead.");return Ne}function M(T,K,ne){if(T==null)return T;var ue=[],oe=0;return D(T,ue,"","",function(ve){return K.call(ne,ve,oe++)}),ue}function J(T){if(T._status===-1){var K=T._result;K=K(),K.then(function(ne){(T._status===0||T._status===-1)&&(T._status=1,T._result=ne)},function(ne){(T._status===0||T._status===-1)&&(T._status=2,T._result=ne)}),T._status===-1&&(T._status=0,T._result=K)}if(T._status===1)return T._result.default;throw T._result}var B={current:null},Y={transition:null},te={ReactCurrentDispatcher:B,ReactCurrentBatchConfig:Y,ReactCurrentOwner:j};function W(){throw Error("act(...) is not supported in production builds of React.")}return nt.Children={map:M,forEach:function(T,K,ne){M(T,function(){K.apply(this,arguments)},ne)},count:function(T){var K=0;return M(T,function(){K++}),K},toArray:function(T){return M(T,function(K){return K})||[]},only:function(T){if(!V(T))throw Error("React.Children.only expected to receive a single React element child.");return T}},nt.Component=k,nt.Fragment=n,nt.Profiler=o,nt.PureComponent=$,nt.StrictMode=s,nt.Suspense=f,nt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=te,nt.act=W,nt.cloneElement=function(T,K,ne){if(T==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+T+".");var ue=C({},T.props),oe=T.key,ve=T.ref,Ne=T._owner;if(K!=null){if(K.ref!==void 0&&(ve=K.ref,Ne=j.current),K.key!==void 0&&(oe=""+K.key),T.type&&T.type.defaultProps)var q=T.type.defaultProps;for(be in K)E.call(K,be)&&!I.hasOwnProperty(be)&&(ue[be]=K[be]===void 0&&q!==void 0?q[be]:K[be])}var be=arguments.length-2;if(be===1)ue.children=ne;else if(1<be){q=Array(be);for(var xe=0;xe<be;xe++)q[xe]=arguments[xe+2];ue.children=q}return{$$typeof:e,type:T.type,key:oe,ref:ve,props:ue,_owner:Ne}},nt.createContext=function(T){return T={$$typeof:u,_currentValue:T,_currentValue2:T,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},T.Provider={$$typeof:l,_context:T},T.Consumer=T},nt.createElement=L,nt.createFactory=function(T){var K=L.bind(null,T);return K.type=T,K},nt.createRef=function(){return{current:null}},nt.forwardRef=function(T){return{$$typeof:d,render:T}},nt.isValidElement=V,nt.lazy=function(T){return{$$typeof:p,_payload:{_status:-1,_result:T},_init:J}},nt.memo=function(T,K){return{$$typeof:m,type:T,compare:K===void 0?null:K}},nt.startTransition=function(T){var K=Y.transition;Y.transition={};try{T()}finally{Y.transition=K}},nt.unstable_act=W,nt.useCallback=function(T,K){return B.current.useCallback(T,K)},nt.useContext=function(T){return B.current.useContext(T)},nt.useDebugValue=function(){},nt.useDeferredValue=function(T){return B.current.useDeferredValue(T)},nt.useEffect=function(T,K){return B.current.useEffect(T,K)},nt.useId=function(){return B.current.useId()},nt.useImperativeHandle=function(T,K,ne){return B.current.useImperativeHandle(T,K,ne)},nt.useInsertionEffect=function(T,K){return B.current.useInsertionEffect(T,K)},nt.useLayoutEffect=function(T,K){return B.current.useLayoutEffect(T,K)},nt.useMemo=function(T,K){return B.current.useMemo(T,K)},nt.useReducer=function(T,K,ne){return B.current.useReducer(T,K,ne)},nt.useRef=function(T){return B.current.useRef(T)},nt.useState=function(T){return B.current.useState(T)},nt.useSyncExternalStore=function(T,K,ne){return B.current.useSyncExternalStore(T,K,ne)},nt.useTransition=function(){return B.current.useTransition()},nt.version="18.3.1",nt}var bg;function Dh(){return bg||(bg=1,ff.exports=$x()),ff.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 xg;function Tx(){if(xg)return Ai;xg=1;var e=Dh(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function u(d,f,m){var p,g={},_=null,v=null;m!==void 0&&(_=""+m),f.key!==void 0&&(_=""+f.key),f.ref!==void 0&&(v=f.ref);for(p in f)s.call(f,p)&&!l.hasOwnProperty(p)&&(g[p]=f[p]);if(d&&d.defaultProps)for(p in f=d.defaultProps,f)g[p]===void 0&&(g[p]=f[p]);return{$$typeof:t,type:d,key:_,ref:v,props:g,_owner:o.current}}return Ai.Fragment=n,Ai.jsx=u,Ai.jsxs=u,Ai}var kg;function Rx(){return kg||(kg=1,df.exports=Tx()),df.exports}var a=Rx(),y=Dh();const yt=_w(y);var $c={},hf={exports:{}},Pn={},mf={exports:{}},pf={};/**
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 Sg;function Ix(){return Sg||(Sg=1,(function(e){function t(Y,te){var W=Y.length;Y.push(te);e:for(;0<W;){var T=W-1>>>1,K=Y[T];if(0<o(K,te))Y[T]=te,Y[W]=K,W=T;else break e}}function n(Y){return Y.length===0?null:Y[0]}function s(Y){if(Y.length===0)return null;var te=Y[0],W=Y.pop();if(W!==te){Y[0]=W;e:for(var T=0,K=Y.length,ne=K>>>1;T<ne;){var ue=2*(T+1)-1,oe=Y[ue],ve=ue+1,Ne=Y[ve];if(0>o(oe,W))ve<K&&0>o(Ne,oe)?(Y[T]=Ne,Y[ve]=W,T=ve):(Y[T]=oe,Y[ue]=W,T=ue);else if(ve<K&&0>o(Ne,W))Y[T]=Ne,Y[ve]=W,T=ve;else break e}}return te}function o(Y,te){var W=Y.sortIndex-te.sortIndex;return W!==0?W:Y.id-te.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,d=u.now();e.unstable_now=function(){return u.now()-d}}var f=[],m=[],p=1,g=null,_=3,v=!1,C=!1,x=!1,k=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,$=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(Y){for(var te=n(m);te!==null;){if(te.callback===null)s(m);else if(te.startTime<=Y)s(m),te.sortIndex=te.expirationTime,t(f,te);else break;te=n(m)}}function N(Y){if(x=!1,R(Y),!C)if(n(f)!==null)C=!0,J(E);else{var te=n(m);te!==null&&B(N,te.startTime-Y)}}function E(Y,te){C=!1,x&&(x=!1,S(L),L=-1),v=!0;var W=_;try{for(R(te),g=n(f);g!==null&&(!(g.expirationTime>te)||Y&&!Z());){var T=g.callback;if(typeof T=="function"){g.callback=null,_=g.priorityLevel;var K=T(g.expirationTime<=te);te=e.unstable_now(),typeof K=="function"?g.callback=K:g===n(f)&&s(f),R(te)}else s(f);g=n(f)}if(g!==null)var ne=!0;else{var ue=n(m);ue!==null&&B(N,ue.startTime-te),ne=!1}return ne}finally{g=null,_=W,v=!1}}var j=!1,I=null,L=-1,z=5,V=-1;function Z(){return!(e.unstable_now()-V<z)}function ie(){if(I!==null){var Y=e.unstable_now();V=Y;var te=!0;try{te=I(!0,Y)}finally{te?F():(j=!1,I=null)}}else j=!1}var F;if(typeof $=="function")F=function(){$(ie)};else if(typeof MessageChannel<"u"){var D=new MessageChannel,M=D.port2;D.port1.onmessage=ie,F=function(){M.postMessage(null)}}else F=function(){k(ie,0)};function J(Y){I=Y,j||(j=!0,F())}function B(Y,te){L=k(function(){Y(e.unstable_now())},te)}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(Y){Y.callback=null},e.unstable_continueExecution=function(){C||v||(C=!0,J(E))},e.unstable_forceFrameRate=function(Y){0>Y||125<Y?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):z=0<Y?Math.floor(1e3/Y):5},e.unstable_getCurrentPriorityLevel=function(){return _},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(Y){switch(_){case 1:case 2:case 3:var te=3;break;default:te=_}var W=_;_=te;try{return Y()}finally{_=W}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(Y,te){switch(Y){case 1:case 2:case 3:case 4:case 5:break;default:Y=3}var W=_;_=Y;try{return te()}finally{_=W}},e.unstable_scheduleCallback=function(Y,te,W){var T=e.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?T+W:T):W=T,Y){case 1:var K=-1;break;case 2:K=250;break;case 5:K=1073741823;break;case 4:K=1e4;break;default:K=5e3}return K=W+K,Y={id:p++,callback:te,priorityLevel:Y,startTime:W,expirationTime:K,sortIndex:-1},W>T?(Y.sortIndex=W,t(m,Y),n(f)===null&&Y===n(m)&&(x?(S(L),L=-1):x=!0,B(N,W-T))):(Y.sortIndex=K,t(f,Y),C||v||(C=!0,J(E))),Y},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function(Y){var te=_;return function(){var W=_;_=te;try{return Y.apply(this,arguments)}finally{_=W}}}})(pf)),pf}var jg;function Lx(){return jg||(jg=1,mf.exports=Ix()),mf.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 Ng;function Mx(){if(Ng)return Pn;Ng=1;var e=Dh(),t=Lx();function n(r){for(var i="https://reactjs.org/docs/error-decoder.html?invariant="+r,c=1;c<arguments.length;c++)i+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+r+"; visit "+i+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var s=new Set,o={};function l(r,i){u(r,i),u(r+"Capture",i)}function u(r,i){for(o[r]=i,r=0;r<i.length;r++)s.add(i[r])}var d=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),f=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={},g={};function _(r){return f.call(g,r)?!0:f.call(p,r)?!1:m.test(r)?g[r]=!0:(p[r]=!0,!1)}function v(r,i,c,h){if(c!==null&&c.type===0)return!1;switch(typeof i){case"function":case"symbol":return!0;case"boolean":return h?!1:c!==null?!c.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function C(r,i,c,h){if(i===null||typeof i>"u"||v(r,i,c,h))return!0;if(h)return!1;if(c!==null)switch(c.type){case 3:return!i;case 4:return i===!1;case 5:return isNaN(i);case 6:return isNaN(i)||1>i}return!1}function x(r,i,c,h,w,b,A){this.acceptsBooleans=i===2||i===3||i===4,this.attributeName=h,this.attributeNamespace=w,this.mustUseProperty=c,this.propertyName=r,this.type=i,this.sanitizeURL=b,this.removeEmptyString=A}var k={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){k[r]=new x(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var i=r[0];k[i]=new x(i,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){k[r]=new x(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){k[r]=new x(r,2,!1,r,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(r){k[r]=new x(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){k[r]=new x(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){k[r]=new x(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){k[r]=new x(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){k[r]=new x(r,5,!1,r.toLowerCase(),null,!1,!1)});var S=/[\-:]([a-z])/g;function $(r){return r[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(r){var i=r.replace(S,$);k[i]=new x(i,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var i=r.replace(S,$);k[i]=new x(i,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var i=r.replace(S,$);k[i]=new x(i,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){k[r]=new x(r,1,!1,r.toLowerCase(),null,!1,!1)}),k.xlinkHref=new x("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){k[r]=new x(r,1,!1,r.toLowerCase(),null,!0,!0)});function R(r,i,c,h){var w=k.hasOwnProperty(i)?k[i]:null;(w!==null?w.type!==0:h||!(2<i.length)||i[0]!=="o"&&i[0]!=="O"||i[1]!=="n"&&i[1]!=="N")&&(C(i,c,w,h)&&(c=null),h||w===null?_(i)&&(c===null?r.removeAttribute(i):r.setAttribute(i,""+c)):w.mustUseProperty?r[w.propertyName]=c===null?w.type===3?!1:"":c:(i=w.attributeName,h=w.attributeNamespace,c===null?r.removeAttribute(i):(w=w.type,c=w===3||w===4&&c===!0?"":""+c,h?r.setAttributeNS(h,i,c):r.setAttribute(i,c))))}var N=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,E=Symbol.for("react.element"),j=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),L=Symbol.for("react.strict_mode"),z=Symbol.for("react.profiler"),V=Symbol.for("react.provider"),Z=Symbol.for("react.context"),ie=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),D=Symbol.for("react.suspense_list"),M=Symbol.for("react.memo"),J=Symbol.for("react.lazy"),B=Symbol.for("react.offscreen"),Y=Symbol.iterator;function te(r){return r===null||typeof r!="object"?null:(r=Y&&r[Y]||r["@@iterator"],typeof r=="function"?r:null)}var W=Object.assign,T;function K(r){if(T===void 0)try{throw Error()}catch(c){var i=c.stack.trim().match(/\n( *(at )?)/);T=i&&i[1]||""}return`
34
- `+T+r}var ne=!1;function ue(r,i){if(!r||ne)return"";ne=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(i)if(i=function(){throw Error()},Object.defineProperty(i.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(i,[])}catch(re){var h=re}Reflect.construct(r,[],i)}else{try{i.call()}catch(re){h=re}r.call(i.prototype)}else{try{throw Error()}catch(re){h=re}r()}}catch(re){if(re&&h&&typeof re.stack=="string"){for(var w=re.stack.split(`
35
- `),b=h.stack.split(`
36
- `),A=w.length-1,P=b.length-1;1<=A&&0<=P&&w[A]!==b[P];)P--;for(;1<=A&&0<=P;A--,P--)if(w[A]!==b[P]){if(A!==1||P!==1)do if(A--,P--,0>P||w[A]!==b[P]){var U=`
37
- `+w[A].replace(" at new "," at ");return r.displayName&&U.includes("<anonymous>")&&(U=U.replace("<anonymous>",r.displayName)),U}while(1<=A&&0<=P);break}}}finally{ne=!1,Error.prepareStackTrace=c}return(r=r?r.displayName||r.name:"")?K(r):""}function oe(r){switch(r.tag){case 5:return K(r.type);case 16:return K("Lazy");case 13:return K("Suspense");case 19:return K("SuspenseList");case 0:case 2:case 15:return r=ue(r.type,!1),r;case 11:return r=ue(r.type.render,!1),r;case 1:return r=ue(r.type,!0),r;default:return""}}function ve(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case I:return"Fragment";case j:return"Portal";case z:return"Profiler";case L:return"StrictMode";case F:return"Suspense";case D:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case Z:return(r.displayName||"Context")+".Consumer";case V:return(r._context.displayName||"Context")+".Provider";case ie:var i=r.render;return r=r.displayName,r||(r=i.displayName||i.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case M:return i=r.displayName||null,i!==null?i:ve(r.type)||"Memo";case J:i=r._payload,r=r._init;try{return ve(r(i))}catch{}}return null}function Ne(r){var i=r.type;switch(r.tag){case 24:return"Cache";case 9:return(i.displayName||"Context")+".Consumer";case 10:return(i._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=i.render,r=r.displayName||r.name||"",i.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return i;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ve(i);case 8:return i===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 i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i}return null}function q(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function be(r){var i=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(i==="checkbox"||i==="radio")}function xe(r){var i=be(r)?"checked":"value",c=Object.getOwnPropertyDescriptor(r.constructor.prototype,i),h=""+r[i];if(!r.hasOwnProperty(i)&&typeof c<"u"&&typeof c.get=="function"&&typeof c.set=="function"){var w=c.get,b=c.set;return Object.defineProperty(r,i,{configurable:!0,get:function(){return w.call(this)},set:function(A){h=""+A,b.call(this,A)}}),Object.defineProperty(r,i,{enumerable:c.enumerable}),{getValue:function(){return h},setValue:function(A){h=""+A},stopTracking:function(){r._valueTracker=null,delete r[i]}}}}function Pe(r){r._valueTracker||(r._valueTracker=xe(r))}function Qe(r){if(!r)return!1;var i=r._valueTracker;if(!i)return!0;var c=i.getValue(),h="";return r&&(h=be(r)?r.checked?"true":"false":r.value),r=h,r!==c?(i.setValue(r),!0):!1}function He(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function qe(r,i){var c=i.checked;return W({},i,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:c??r._wrapperState.initialChecked})}function ge(r,i){var c=i.defaultValue==null?"":i.defaultValue,h=i.checked!=null?i.checked:i.defaultChecked;c=q(i.value!=null?i.value:c),r._wrapperState={initialChecked:h,initialValue:c,controlled:i.type==="checkbox"||i.type==="radio"?i.checked!=null:i.value!=null}}function $e(r,i){i=i.checked,i!=null&&R(r,"checked",i,!1)}function st(r,i){$e(r,i);var c=q(i.value),h=i.type;if(c!=null)h==="number"?(c===0&&r.value===""||r.value!=c)&&(r.value=""+c):r.value!==""+c&&(r.value=""+c);else if(h==="submit"||h==="reset"){r.removeAttribute("value");return}i.hasOwnProperty("value")?Lt(r,i.type,c):i.hasOwnProperty("defaultValue")&&Lt(r,i.type,q(i.defaultValue)),i.checked==null&&i.defaultChecked!=null&&(r.defaultChecked=!!i.defaultChecked)}function tt(r,i,c){if(i.hasOwnProperty("value")||i.hasOwnProperty("defaultValue")){var h=i.type;if(!(h!=="submit"&&h!=="reset"||i.value!==void 0&&i.value!==null))return;i=""+r._wrapperState.initialValue,c||i===r.value||(r.value=i),r.defaultValue=i}c=r.name,c!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,c!==""&&(r.name=c)}function Lt(r,i,c){(i!=="number"||He(r.ownerDocument)!==r)&&(c==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+c&&(r.defaultValue=""+c))}var ce=Array.isArray;function fe(r,i,c,h){if(r=r.options,i){i={};for(var w=0;w<c.length;w++)i["$"+c[w]]=!0;for(c=0;c<r.length;c++)w=i.hasOwnProperty("$"+r[c].value),r[c].selected!==w&&(r[c].selected=w),w&&h&&(r[c].defaultSelected=!0)}else{for(c=""+q(c),i=null,w=0;w<r.length;w++){if(r[w].value===c){r[w].selected=!0,h&&(r[w].defaultSelected=!0);return}i!==null||r[w].disabled||(i=r[w])}i!==null&&(i.selected=!0)}}function H(r,i){if(i.dangerouslySetInnerHTML!=null)throw Error(n(91));return W({},i,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function le(r,i){var c=i.value;if(c==null){if(c=i.children,i=i.defaultValue,c!=null){if(i!=null)throw Error(n(92));if(ce(c)){if(1<c.length)throw Error(n(93));c=c[0]}i=c}i==null&&(i=""),c=i}r._wrapperState={initialValue:q(c)}}function he(r,i){var c=q(i.value),h=q(i.defaultValue);c!=null&&(c=""+c,c!==r.value&&(r.value=c),i.defaultValue==null&&r.defaultValue!==c&&(r.defaultValue=c)),h!=null&&(r.defaultValue=""+h)}function Q(r){var i=r.textContent;i===r._wrapperState.initialValue&&i!==""&&i!==null&&(r.value=i)}function _e(r){switch(r){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 ae(r,i){return r==null||r==="http://www.w3.org/1999/xhtml"?_e(i):r==="http://www.w3.org/2000/svg"&&i==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var Se,Oe=(function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(i,c,h,w){MSApp.execUnsafeLocalFunction(function(){return r(i,c,h,w)})}:r})(function(r,i){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=i;else{for(Se=Se||document.createElement("div"),Se.innerHTML="<svg>"+i.valueOf().toString()+"</svg>",i=Se.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;i.firstChild;)r.appendChild(i.firstChild)}});function Fe(r,i){if(i){var c=r.firstChild;if(c&&c===r.lastChild&&c.nodeType===3){c.nodeValue=i;return}}r.textContent=i}var Ze={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},Le=["Webkit","ms","Moz","O"];Object.keys(Ze).forEach(function(r){Le.forEach(function(i){i=i+r.charAt(0).toUpperCase()+r.substring(1),Ze[i]=Ze[r]})});function Ke(r,i,c){return i==null||typeof i=="boolean"||i===""?"":c||typeof i!="number"||i===0||Ze.hasOwnProperty(r)&&Ze[r]?(""+i).trim():i+"px"}function De(r,i){r=r.style;for(var c in i)if(i.hasOwnProperty(c)){var h=c.indexOf("--")===0,w=Ke(c,i[c],h);c==="float"&&(c="cssFloat"),h?r.setProperty(c,w):r[c]=w}}var pt=W({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 St(r,i){if(i){if(pt[r]&&(i.children!=null||i.dangerouslySetInnerHTML!=null))throw Error(n(137,r));if(i.dangerouslySetInnerHTML!=null){if(i.children!=null)throw Error(n(60));if(typeof i.dangerouslySetInnerHTML!="object"||!("__html"in i.dangerouslySetInnerHTML))throw Error(n(61))}if(i.style!=null&&typeof i.style!="object")throw Error(n(62))}}function jt(r,i){if(r.indexOf("-")===-1)return typeof i.is=="string";switch(r){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 Pt=null;function Ss(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Fo=null,Qn=null,Fs=null;function zs(r){if(r=mi(r)){if(typeof Fo!="function")throw Error(n(280));var i=r.stateNode;i&&(i=Gl(i),Fo(r.stateNode,r.type,i))}}function Zt(r){Qn?Fs?Fs.push(r):Fs=[r]:Qn=r}function ja(){if(Qn){var r=Qn,i=Fs;if(Fs=Qn=null,zs(r),i)for(r=0;r<i.length;r++)zs(i[r])}}function zo(r,i){return r(i)}function ir(){}var Na=!1;function Bo(r,i,c){if(Na)return r(i,c);Na=!0;try{return zo(r,i,c)}finally{Na=!1,(Qn!==null||Fs!==null)&&(ir(),ja())}}function js(r,i){var c=r.stateNode;if(c===null)return null;var h=Gl(c);if(h===null)return null;c=h[i];e:switch(i){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(h=!h.disabled)||(r=r.type,h=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!h;break e;default:r=!1}if(r)return null;if(c&&typeof c!="function")throw Error(n(231,i,typeof c));return c}var Ca=!1;if(d)try{var Jt={};Object.defineProperty(Jt,"passive",{get:function(){Ca=!0}}),window.addEventListener("test",Jt,Jt),window.removeEventListener("test",Jt,Jt)}catch{Ca=!1}function Bt(r,i,c,h,w,b,A,P,U){var re=Array.prototype.slice.call(arguments,3);try{i.apply(c,re)}catch(pe){this.onError(pe)}}var Wt=!1,ds=null,lr=!1,Vr=null,Wo={onError:function(r){Wt=!0,ds=r}};function Uo(r,i,c,h,w,b,A,P,U){Wt=!1,ds=null,Bt.apply(Wo,arguments)}function Mu(r,i,c,h,w,b,A,P,U){if(Uo.apply(this,arguments),Wt){if(Wt){var re=ds;Wt=!1,ds=null}else throw Error(n(198));lr||(lr=!0,Vr=re)}}function Ns(r){var i=r,c=r;if(r.alternate)for(;i.return;)i=i.return;else{r=i;do i=r,(i.flags&4098)!==0&&(c=i.return),r=i.return;while(r)}return i.tag===3?c:null}function Cs(r){if(r.tag===13){var i=r.memoizedState;if(i===null&&(r=r.alternate,r!==null&&(i=r.memoizedState)),i!==null)return i.dehydrated}return null}function fs(r){if(Ns(r)!==r)throw Error(n(188))}function Vo(r){var i=r.alternate;if(!i){if(i=Ns(r),i===null)throw Error(n(188));return i!==r?null:r}for(var c=r,h=i;;){var w=c.return;if(w===null)break;var b=w.alternate;if(b===null){if(h=w.return,h!==null){c=h;continue}break}if(w.child===b.child){for(b=w.child;b;){if(b===c)return fs(w),r;if(b===h)return fs(w),i;b=b.sibling}throw Error(n(188))}if(c.return!==h.return)c=w,h=b;else{for(var A=!1,P=w.child;P;){if(P===c){A=!0,c=w,h=b;break}if(P===h){A=!0,h=w,c=b;break}P=P.sibling}if(!A){for(P=b.child;P;){if(P===c){A=!0,c=b,h=w;break}if(P===h){A=!0,h=b,c=w;break}P=P.sibling}if(!A)throw Error(n(189))}}if(c.alternate!==h)throw Error(n(190))}if(c.tag!==3)throw Error(n(188));return c.stateNode.current===c?r:i}function Xn(r){return r=Vo(r),r!==null?Go(r):null}function Go(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var i=Go(r);if(i!==null)return i;r=r.sibling}return null}var Ea=t.unstable_scheduleCallback,Aa=t.unstable_cancelCallback,Ou=t.unstable_shouldYield,Ho=t.unstable_requestPaint,Nt=t.unstable_now,yl=t.unstable_getCurrentPriorityLevel,$a=t.unstable_ImmediatePriority,wl=t.unstable_UserBlockingPriority,Ta=t.unstable_NormalPriority,Zn=t.unstable_LowPriority,Ye=t.unstable_IdlePriority,Es=null,Ut=null;function Ko(r){if(Ut&&typeof Ut.onCommitFiberRoot=="function")try{Ut.onCommitFiberRoot(Es,r,void 0,(r.current.flags&128)===128)}catch{}}var Vt=Math.clz32?Math.clz32:Bs,Ra=Math.log,Ia=Math.LN2;function Bs(r){return r>>>=0,r===0?32:31-(Ra(r)/Ia|0)|0}var cr=64,Gr=4194304;function dn(r){switch(r&-r){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 r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function es(r,i){var c=r.pendingLanes;if(c===0)return 0;var h=0,w=r.suspendedLanes,b=r.pingedLanes,A=c&268435455;if(A!==0){var P=A&~w;P!==0?h=dn(P):(b&=A,b!==0&&(h=dn(b)))}else A=c&~w,A!==0?h=dn(A):b!==0&&(h=dn(b));if(h===0)return 0;if(i!==0&&i!==h&&(i&w)===0&&(w=h&-h,b=i&-i,w>=b||w===16&&(b&4194240)!==0))return i;if((h&4)!==0&&(h|=c&16),i=r.entangledLanes,i!==0)for(r=r.entanglements,i&=h;0<i;)c=31-Vt(i),w=1<<c,h|=r[c],i&=~w;return h}function ur(r,i){switch(r){case 1:case 2:case 4:return i+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 i+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 Jo(r,i){for(var c=r.suspendedLanes,h=r.pingedLanes,w=r.expirationTimes,b=r.pendingLanes;0<b;){var A=31-Vt(b),P=1<<A,U=w[A];U===-1?((P&c)===0||(P&h)!==0)&&(w[A]=ur(P,i)):U<=i&&(r.expiredLanes|=P),b&=~P}}function La(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function $n(){var r=cr;return cr<<=1,(cr&4194240)===0&&(cr=64),r}function Vn(r){for(var i=[],c=0;31>c;c++)i.push(r);return i}function dr(r,i,c){r.pendingLanes|=i,i!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,i=31-Vt(i),r[i]=c}function fr(r,i){var c=r.pendingLanes&~i;r.pendingLanes=i,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=i,r.mutableReadLanes&=i,r.entangledLanes&=i,i=r.entanglements;var h=r.eventTimes;for(r=r.expirationTimes;0<c;){var w=31-Vt(c),b=1<<w;i[w]=0,h[w]=-1,r[w]=-1,c&=~b}}function Ws(r,i){var c=r.entangledLanes|=i;for(r=r.entanglements;c;){var h=31-Vt(c),w=1<<h;w&i|r[h]&i&&(r[h]|=i),c&=~w}}var at=0;function fn(r){return r&=-r,1<r?4<r?(r&268435455)!==0?16:536870912:4:1}var Hr,Ma,Oa,Pa,qo,Yo=!1,Kr=[],hs=null,ts=null,Gn=null,Dt=new Map,Us=new Map,Ct=[],xn="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 Qo(r,i){switch(r){case"focusin":case"focusout":hs=null;break;case"dragenter":case"dragleave":ts=null;break;case"mouseover":case"mouseout":Gn=null;break;case"pointerover":case"pointerout":Dt.delete(i.pointerId);break;case"gotpointercapture":case"lostpointercapture":Us.delete(i.pointerId)}}function Jr(r,i,c,h,w,b){return r===null||r.nativeEvent!==b?(r={blockedOn:i,domEventName:c,eventSystemFlags:h,nativeEvent:b,targetContainers:[w]},i!==null&&(i=mi(i),i!==null&&Ma(i)),r):(r.eventSystemFlags|=h,i=r.targetContainers,w!==null&&i.indexOf(w)===-1&&i.push(w),r)}function Pu(r,i,c,h,w){switch(i){case"focusin":return hs=Jr(hs,r,i,c,h,w),!0;case"dragenter":return ts=Jr(ts,r,i,c,h,w),!0;case"mouseover":return Gn=Jr(Gn,r,i,c,h,w),!0;case"pointerover":var b=w.pointerId;return Dt.set(b,Jr(Dt.get(b)||null,r,i,c,h,w)),!0;case"gotpointercapture":return b=w.pointerId,Us.set(b,Jr(Us.get(b)||null,r,i,c,h,w)),!0}return!1}function Da(r){var i=ta(r.target);if(i!==null){var c=Ns(i);if(c!==null){if(i=c.tag,i===13){if(i=Cs(c),i!==null){r.blockedOn=i,qo(r.priority,function(){Oa(c)});return}}else if(i===3&&c.stateNode.current.memoizedState.isDehydrated){r.blockedOn=c.tag===3?c.stateNode.containerInfo:null;return}}}r.blockedOn=null}function qr(r){if(r.blockedOn!==null)return!1;for(var i=r.targetContainers;0<i.length;){var c=Ba(r.domEventName,r.eventSystemFlags,i[0],r.nativeEvent);if(c===null){c=r.nativeEvent;var h=new c.constructor(c.type,c);Pt=h,c.target.dispatchEvent(h),Pt=null}else return i=mi(c),i!==null&&Ma(i),r.blockedOn=c,!1;i.shift()}return!0}function Fa(r,i,c){qr(r)&&c.delete(i)}function Yr(){Yo=!1,hs!==null&&qr(hs)&&(hs=null),ts!==null&&qr(ts)&&(ts=null),Gn!==null&&qr(Gn)&&(Gn=null),Dt.forEach(Fa),Us.forEach(Fa)}function ms(r,i){r.blockedOn===i&&(r.blockedOn=null,Yo||(Yo=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Yr)))}function Vs(r){function i(w){return ms(w,r)}if(0<Kr.length){ms(Kr[0],r);for(var c=1;c<Kr.length;c++){var h=Kr[c];h.blockedOn===r&&(h.blockedOn=null)}}for(hs!==null&&ms(hs,r),ts!==null&&ms(ts,r),Gn!==null&&ms(Gn,r),Dt.forEach(i),Us.forEach(i),c=0;c<Ct.length;c++)h=Ct[c],h.blockedOn===r&&(h.blockedOn=null);for(;0<Ct.length&&(c=Ct[0],c.blockedOn===null);)Da(c),c.blockedOn===null&&Ct.shift()}var ps=N.ReactCurrentBatchConfig,za=!0;function vl(r,i,c,h){var w=at,b=ps.transition;ps.transition=null;try{at=1,Xo(r,i,c,h)}finally{at=w,ps.transition=b}}function _l(r,i,c,h){var w=at,b=ps.transition;ps.transition=null;try{at=4,Xo(r,i,c,h)}finally{at=w,ps.transition=b}}function Xo(r,i,c,h){if(za){var w=Ba(r,i,c,h);if(w===null)ed(r,i,h,Qr,c),Qo(r,h);else if(Pu(w,r,i,c,h))h.stopPropagation();else if(Qo(r,h),i&4&&-1<xn.indexOf(r)){for(;w!==null;){var b=mi(w);if(b!==null&&Hr(b),b=Ba(r,i,c,h),b===null&&ed(r,i,h,Qr,c),b===w)break;w=b}w!==null&&h.stopPropagation()}else ed(r,i,h,null,c)}}var Qr=null;function Ba(r,i,c,h){if(Qr=null,r=Ss(h),r=ta(r),r!==null)if(i=Ns(r),i===null)r=null;else if(c=i.tag,c===13){if(r=Cs(i),r!==null)return r;r=null}else if(c===3){if(i.stateNode.current.memoizedState.isDehydrated)return i.tag===3?i.stateNode.containerInfo:null;r=null}else i!==r&&(r=null);return Qr=r,null}function bl(r){switch(r){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(yl()){case $a:return 1;case wl:return 4;case Ta:case Zn:return 16;case Ye:return 536870912;default:return 16}default:return 16}}var Tn=null,Xr=null,kn=null;function Wa(){if(kn)return kn;var r,i=Xr,c=i.length,h,w="value"in Tn?Tn.value:Tn.textContent,b=w.length;for(r=0;r<c&&i[r]===w[r];r++);var A=c-r;for(h=1;h<=A&&i[c-h]===w[b-h];h++);return kn=w.slice(r,1<h?1-h:void 0)}function Zr(r){var i=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&i===13&&(r=13)):r=i,r===10&&(r=13),32<=r||r===13?r:0}function hr(){return!0}function xl(){return!1}function en(r){function i(c,h,w,b,A){this._reactName=c,this._targetInst=w,this.type=h,this.nativeEvent=b,this.target=A,this.currentTarget=null;for(var P in r)r.hasOwnProperty(P)&&(c=r[P],this[P]=c?c(b):b[P]);return this.isDefaultPrevented=(b.defaultPrevented!=null?b.defaultPrevented:b.returnValue===!1)?hr:xl,this.isPropagationStopped=xl,this}return W(i.prototype,{preventDefault:function(){this.defaultPrevented=!0;var c=this.nativeEvent;c&&(c.preventDefault?c.preventDefault():typeof c.returnValue!="unknown"&&(c.returnValue=!1),this.isDefaultPrevented=hr)},stopPropagation:function(){var c=this.nativeEvent;c&&(c.stopPropagation?c.stopPropagation():typeof c.cancelBubble!="unknown"&&(c.cancelBubble=!0),this.isPropagationStopped=hr)},persist:function(){},isPersistent:hr}),i}var Gs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Zo=en(Gs),ea=W({},Gs,{view:0,detail:0}),kl=en(ea),ei,ns,mr,wt=W({},ea,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Ua,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==mr&&(mr&&r.type==="mousemove"?(ei=r.screenX-mr.screenX,ns=r.screenY-mr.screenY):ns=ei=0,mr=r),ei)},movementY:function(r){return"movementY"in r?r.movementY:ns}}),As=en(wt),pr=W({},wt,{dataTransfer:0}),Du=en(pr),Fu=W({},ea,{relatedTarget:0}),ti=en(Fu),zu=W({},Gs,{animationName:0,elapsedTime:0,pseudoElement:0}),Bu=en(zu),Wu=W({},Gs,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),ni=en(Wu),Sl=W({},Gs,{data:0}),si=en(Sl),Uu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},jl={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"},Nl={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Cl(r){var i=this.nativeEvent;return i.getModifierState?i.getModifierState(r):(r=Nl[r])?!!i[r]:!1}function Ua(){return Cl}var El=W({},ea,{key:function(r){if(r.key){var i=Uu[r.key]||r.key;if(i!=="Unidentified")return i}return r.type==="keypress"?(r=Zr(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?jl[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Ua,charCode:function(r){return r.type==="keypress"?Zr(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?Zr(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),Al=en(El),$l=W({},wt,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),ri=en($l),Tl=W({},ea,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ua}),Rl=en(Tl),Il=W({},Gs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Ll=en(Il),Ml=W({},wt,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),Ol=en(Ml),Pl=[9,13,27,32],Va=d&&"CompositionEvent"in window,gr=null;d&&"documentMode"in document&&(gr=document.documentMode);var Dl=d&&"TextEvent"in window&&!gr,ai=d&&(!Va||gr&&8<gr&&11>=gr),oi=" ",ii=!1;function O(r,i){switch(r){case"keyup":return Pl.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function se(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var je=!1;function Ie(r,i){switch(r){case"compositionend":return se(i);case"keypress":return i.which!==32?null:(ii=!0,oi);case"textInput":return r=i.data,r===oi&&ii?null:r;default:return null}}function Ve(r,i){if(je)return r==="compositionend"||!Va&&O(r,i)?(r=Wa(),kn=Xr=Tn=null,je=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(i.ctrlKey||i.altKey||i.metaKey)||i.ctrlKey&&i.altKey){if(i.char&&1<i.char.length)return i.char;if(i.which)return String.fromCharCode(i.which)}return null;case"compositionend":return ai&&i.locale!=="ko"?null:i.data;default:return null}}var Gt={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 bt(r){var i=r&&r.nodeName&&r.nodeName.toLowerCase();return i==="input"?!!Gt[r.type]:i==="textarea"}function yr(r,i,c,h){Zt(h),i=Wl(i,"onChange"),0<i.length&&(c=new Zo("onChange","change",null,c,h),r.push({event:c,listeners:i}))}var gs=null,ss=null;function Vu(r){Om(r,0)}function Hn(r){var i=qa(r);if(Qe(i))return r}function Ab(r,i){if(r==="change")return i}var vm=!1;if(d){var Gu;if(d){var Hu="oninput"in document;if(!Hu){var _m=document.createElement("div");_m.setAttribute("oninput","return;"),Hu=typeof _m.oninput=="function"}Gu=Hu}else Gu=!1;vm=Gu&&(!document.documentMode||9<document.documentMode)}function bm(){gs&&(gs.detachEvent("onpropertychange",xm),ss=gs=null)}function xm(r){if(r.propertyName==="value"&&Hn(ss)){var i=[];yr(i,ss,r,Ss(r)),Bo(Vu,i)}}function $b(r,i,c){r==="focusin"?(bm(),gs=i,ss=c,gs.attachEvent("onpropertychange",xm)):r==="focusout"&&bm()}function Tb(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return Hn(ss)}function Rb(r,i){if(r==="click")return Hn(i)}function Ib(r,i){if(r==="input"||r==="change")return Hn(i)}function Lb(r,i){return r===i&&(r!==0||1/r===1/i)||r!==r&&i!==i}var ys=typeof Object.is=="function"?Object.is:Lb;function li(r,i){if(ys(r,i))return!0;if(typeof r!="object"||r===null||typeof i!="object"||i===null)return!1;var c=Object.keys(r),h=Object.keys(i);if(c.length!==h.length)return!1;for(h=0;h<c.length;h++){var w=c[h];if(!f.call(i,w)||!ys(r[w],i[w]))return!1}return!0}function km(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function Sm(r,i){var c=km(r);r=0;for(var h;c;){if(c.nodeType===3){if(h=r+c.textContent.length,r<=i&&h>=i)return{node:c,offset:i-r};r=h}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=km(c)}}function jm(r,i){return r&&i?r===i?!0:r&&r.nodeType===3?!1:i&&i.nodeType===3?jm(r,i.parentNode):"contains"in r?r.contains(i):r.compareDocumentPosition?!!(r.compareDocumentPosition(i)&16):!1:!1}function Nm(){for(var r=window,i=He();i instanceof r.HTMLIFrameElement;){try{var c=typeof i.contentWindow.location.href=="string"}catch{c=!1}if(c)r=i.contentWindow;else break;i=He(r.document)}return i}function Ku(r){var i=r&&r.nodeName&&r.nodeName.toLowerCase();return i&&(i==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||i==="textarea"||r.contentEditable==="true")}function Mb(r){var i=Nm(),c=r.focusedElem,h=r.selectionRange;if(i!==c&&c&&c.ownerDocument&&jm(c.ownerDocument.documentElement,c)){if(h!==null&&Ku(c)){if(i=h.start,r=h.end,r===void 0&&(r=i),"selectionStart"in c)c.selectionStart=i,c.selectionEnd=Math.min(r,c.value.length);else if(r=(i=c.ownerDocument||document)&&i.defaultView||window,r.getSelection){r=r.getSelection();var w=c.textContent.length,b=Math.min(h.start,w);h=h.end===void 0?b:Math.min(h.end,w),!r.extend&&b>h&&(w=h,h=b,b=w),w=Sm(c,b);var A=Sm(c,h);w&&A&&(r.rangeCount!==1||r.anchorNode!==w.node||r.anchorOffset!==w.offset||r.focusNode!==A.node||r.focusOffset!==A.offset)&&(i=i.createRange(),i.setStart(w.node,w.offset),r.removeAllRanges(),b>h?(r.addRange(i),r.extend(A.node,A.offset)):(i.setEnd(A.node,A.offset),r.addRange(i)))}}for(i=[],r=c;r=r.parentNode;)r.nodeType===1&&i.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof c.focus=="function"&&c.focus(),c=0;c<i.length;c++)r=i[c],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var Ob=d&&"documentMode"in document&&11>=document.documentMode,Ga=null,Ju=null,ci=null,qu=!1;function Cm(r,i,c){var h=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;qu||Ga==null||Ga!==He(h)||(h=Ga,"selectionStart"in h&&Ku(h)?h={start:h.selectionStart,end:h.selectionEnd}:(h=(h.ownerDocument&&h.ownerDocument.defaultView||window).getSelection(),h={anchorNode:h.anchorNode,anchorOffset:h.anchorOffset,focusNode:h.focusNode,focusOffset:h.focusOffset}),ci&&li(ci,h)||(ci=h,h=Wl(Ju,"onSelect"),0<h.length&&(i=new Zo("onSelect","select",null,i,c),r.push({event:i,listeners:h}),i.target=Ga)))}function Fl(r,i){var c={};return c[r.toLowerCase()]=i.toLowerCase(),c["Webkit"+r]="webkit"+i,c["Moz"+r]="moz"+i,c}var Ha={animationend:Fl("Animation","AnimationEnd"),animationiteration:Fl("Animation","AnimationIteration"),animationstart:Fl("Animation","AnimationStart"),transitionend:Fl("Transition","TransitionEnd")},Yu={},Em={};d&&(Em=document.createElement("div").style,"AnimationEvent"in window||(delete Ha.animationend.animation,delete Ha.animationiteration.animation,delete Ha.animationstart.animation),"TransitionEvent"in window||delete Ha.transitionend.transition);function zl(r){if(Yu[r])return Yu[r];if(!Ha[r])return r;var i=Ha[r],c;for(c in i)if(i.hasOwnProperty(c)&&c in Em)return Yu[r]=i[c];return r}var Am=zl("animationend"),$m=zl("animationiteration"),Tm=zl("animationstart"),Rm=zl("transitionend"),Im=new Map,Lm="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 wr(r,i){Im.set(r,i),l(i,[r])}for(var Qu=0;Qu<Lm.length;Qu++){var Xu=Lm[Qu],Pb=Xu.toLowerCase(),Db=Xu[0].toUpperCase()+Xu.slice(1);wr(Pb,"on"+Db)}wr(Am,"onAnimationEnd"),wr($m,"onAnimationIteration"),wr(Tm,"onAnimationStart"),wr("dblclick","onDoubleClick"),wr("focusin","onFocus"),wr("focusout","onBlur"),wr(Rm,"onTransitionEnd"),u("onMouseEnter",["mouseout","mouseover"]),u("onMouseLeave",["mouseout","mouseover"]),u("onPointerEnter",["pointerout","pointerover"]),u("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var ui="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(" "),Fb=new Set("cancel close invalid load scroll toggle".split(" ").concat(ui));function Mm(r,i,c){var h=r.type||"unknown-event";r.currentTarget=c,Mu(h,i,void 0,r),r.currentTarget=null}function Om(r,i){i=(i&4)!==0;for(var c=0;c<r.length;c++){var h=r[c],w=h.event;h=h.listeners;e:{var b=void 0;if(i)for(var A=h.length-1;0<=A;A--){var P=h[A],U=P.instance,re=P.currentTarget;if(P=P.listener,U!==b&&w.isPropagationStopped())break e;Mm(w,P,re),b=U}else for(A=0;A<h.length;A++){if(P=h[A],U=P.instance,re=P.currentTarget,P=P.listener,U!==b&&w.isPropagationStopped())break e;Mm(w,P,re),b=U}}}if(lr)throw r=Vr,lr=!1,Vr=null,r}function xt(r,i){var c=i[od];c===void 0&&(c=i[od]=new Set);var h=r+"__bubble";c.has(h)||(Pm(i,r,2,!1),c.add(h))}function Zu(r,i,c){var h=0;i&&(h|=4),Pm(c,r,h,i)}var Bl="_reactListening"+Math.random().toString(36).slice(2);function di(r){if(!r[Bl]){r[Bl]=!0,s.forEach(function(c){c!=="selectionchange"&&(Fb.has(c)||Zu(c,!1,r),Zu(c,!0,r))});var i=r.nodeType===9?r:r.ownerDocument;i===null||i[Bl]||(i[Bl]=!0,Zu("selectionchange",!1,i))}}function Pm(r,i,c,h){switch(bl(i)){case 1:var w=vl;break;case 4:w=_l;break;default:w=Xo}c=w.bind(null,i,c,r),w=void 0,!Ca||i!=="touchstart"&&i!=="touchmove"&&i!=="wheel"||(w=!0),h?w!==void 0?r.addEventListener(i,c,{capture:!0,passive:w}):r.addEventListener(i,c,!0):w!==void 0?r.addEventListener(i,c,{passive:w}):r.addEventListener(i,c,!1)}function ed(r,i,c,h,w){var b=h;if((i&1)===0&&(i&2)===0&&h!==null)e:for(;;){if(h===null)return;var A=h.tag;if(A===3||A===4){var P=h.stateNode.containerInfo;if(P===w||P.nodeType===8&&P.parentNode===w)break;if(A===4)for(A=h.return;A!==null;){var U=A.tag;if((U===3||U===4)&&(U=A.stateNode.containerInfo,U===w||U.nodeType===8&&U.parentNode===w))return;A=A.return}for(;P!==null;){if(A=ta(P),A===null)return;if(U=A.tag,U===5||U===6){h=b=A;continue e}P=P.parentNode}}h=h.return}Bo(function(){var re=b,pe=Ss(c),ye=[];e:{var me=Im.get(r);if(me!==void 0){var Ce=Zo,Ae=r;switch(r){case"keypress":if(Zr(c)===0)break e;case"keydown":case"keyup":Ce=Al;break;case"focusin":Ae="focus",Ce=ti;break;case"focusout":Ae="blur",Ce=ti;break;case"beforeblur":case"afterblur":Ce=ti;break;case"click":if(c.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Ce=As;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Ce=Du;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Ce=Rl;break;case Am:case $m:case Tm:Ce=Bu;break;case Rm:Ce=Ll;break;case"scroll":Ce=kl;break;case"wheel":Ce=Ol;break;case"copy":case"cut":case"paste":Ce=ni;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Ce=ri}var Re=(i&4)!==0,Ft=!Re&&r==="scroll",X=Re?me!==null?me+"Capture":null:me;Re=[];for(var G=re,ee;G!==null;){ee=G;var ke=ee.stateNode;if(ee.tag===5&&ke!==null&&(ee=ke,X!==null&&(ke=js(G,X),ke!=null&&Re.push(fi(G,ke,ee)))),Ft)break;G=G.return}0<Re.length&&(me=new Ce(me,Ae,null,c,pe),ye.push({event:me,listeners:Re}))}}if((i&7)===0){e:{if(me=r==="mouseover"||r==="pointerover",Ce=r==="mouseout"||r==="pointerout",me&&c!==Pt&&(Ae=c.relatedTarget||c.fromElement)&&(ta(Ae)||Ae[Hs]))break e;if((Ce||me)&&(me=pe.window===pe?pe:(me=pe.ownerDocument)?me.defaultView||me.parentWindow:window,Ce?(Ae=c.relatedTarget||c.toElement,Ce=re,Ae=Ae?ta(Ae):null,Ae!==null&&(Ft=Ns(Ae),Ae!==Ft||Ae.tag!==5&&Ae.tag!==6)&&(Ae=null)):(Ce=null,Ae=re),Ce!==Ae)){if(Re=As,ke="onMouseLeave",X="onMouseEnter",G="mouse",(r==="pointerout"||r==="pointerover")&&(Re=ri,ke="onPointerLeave",X="onPointerEnter",G="pointer"),Ft=Ce==null?me:qa(Ce),ee=Ae==null?me:qa(Ae),me=new Re(ke,G+"leave",Ce,c,pe),me.target=Ft,me.relatedTarget=ee,ke=null,ta(pe)===re&&(Re=new Re(X,G+"enter",Ae,c,pe),Re.target=ee,Re.relatedTarget=Ft,ke=Re),Ft=ke,Ce&&Ae)t:{for(Re=Ce,X=Ae,G=0,ee=Re;ee;ee=Ka(ee))G++;for(ee=0,ke=X;ke;ke=Ka(ke))ee++;for(;0<G-ee;)Re=Ka(Re),G--;for(;0<ee-G;)X=Ka(X),ee--;for(;G--;){if(Re===X||X!==null&&Re===X.alternate)break t;Re=Ka(Re),X=Ka(X)}Re=null}else Re=null;Ce!==null&&Dm(ye,me,Ce,Re,!1),Ae!==null&&Ft!==null&&Dm(ye,Ft,Ae,Re,!0)}}e:{if(me=re?qa(re):window,Ce=me.nodeName&&me.nodeName.toLowerCase(),Ce==="select"||Ce==="input"&&me.type==="file")var Me=Ab;else if(bt(me))if(vm)Me=Ib;else{Me=Tb;var Be=$b}else(Ce=me.nodeName)&&Ce.toLowerCase()==="input"&&(me.type==="checkbox"||me.type==="radio")&&(Me=Rb);if(Me&&(Me=Me(r,re))){yr(ye,Me,c,pe);break e}Be&&Be(r,me,re),r==="focusout"&&(Be=me._wrapperState)&&Be.controlled&&me.type==="number"&&Lt(me,"number",me.value)}switch(Be=re?qa(re):window,r){case"focusin":(bt(Be)||Be.contentEditable==="true")&&(Ga=Be,Ju=re,ci=null);break;case"focusout":ci=Ju=Ga=null;break;case"mousedown":qu=!0;break;case"contextmenu":case"mouseup":case"dragend":qu=!1,Cm(ye,c,pe);break;case"selectionchange":if(Ob)break;case"keydown":case"keyup":Cm(ye,c,pe)}var We;if(Va)e:{switch(r){case"compositionstart":var Je="onCompositionStart";break e;case"compositionend":Je="onCompositionEnd";break e;case"compositionupdate":Je="onCompositionUpdate";break e}Je=void 0}else je?O(r,c)&&(Je="onCompositionEnd"):r==="keydown"&&c.keyCode===229&&(Je="onCompositionStart");Je&&(ai&&c.locale!=="ko"&&(je||Je!=="onCompositionStart"?Je==="onCompositionEnd"&&je&&(We=Wa()):(Tn=pe,Xr="value"in Tn?Tn.value:Tn.textContent,je=!0)),Be=Wl(re,Je),0<Be.length&&(Je=new si(Je,r,null,c,pe),ye.push({event:Je,listeners:Be}),We?Je.data=We:(We=se(c),We!==null&&(Je.data=We)))),(We=Dl?Ie(r,c):Ve(r,c))&&(re=Wl(re,"onBeforeInput"),0<re.length&&(pe=new si("onBeforeInput","beforeinput",null,c,pe),ye.push({event:pe,listeners:re}),pe.data=We))}Om(ye,i)})}function fi(r,i,c){return{instance:r,listener:i,currentTarget:c}}function Wl(r,i){for(var c=i+"Capture",h=[];r!==null;){var w=r,b=w.stateNode;w.tag===5&&b!==null&&(w=b,b=js(r,c),b!=null&&h.unshift(fi(r,b,w)),b=js(r,i),b!=null&&h.push(fi(r,b,w))),r=r.return}return h}function Ka(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function Dm(r,i,c,h,w){for(var b=i._reactName,A=[];c!==null&&c!==h;){var P=c,U=P.alternate,re=P.stateNode;if(U!==null&&U===h)break;P.tag===5&&re!==null&&(P=re,w?(U=js(c,b),U!=null&&A.unshift(fi(c,U,P))):w||(U=js(c,b),U!=null&&A.push(fi(c,U,P)))),c=c.return}A.length!==0&&r.push({event:i,listeners:A})}var zb=/\r\n?/g,Bb=/\u0000|\uFFFD/g;function Fm(r){return(typeof r=="string"?r:""+r).replace(zb,`
38
- `).replace(Bb,"")}function Ul(r,i,c){if(i=Fm(i),Fm(r)!==i&&c)throw Error(n(425))}function Vl(){}var td=null,nd=null;function sd(r,i){return r==="textarea"||r==="noscript"||typeof i.children=="string"||typeof i.children=="number"||typeof i.dangerouslySetInnerHTML=="object"&&i.dangerouslySetInnerHTML!==null&&i.dangerouslySetInnerHTML.__html!=null}var rd=typeof setTimeout=="function"?setTimeout:void 0,Wb=typeof clearTimeout=="function"?clearTimeout:void 0,zm=typeof Promise=="function"?Promise:void 0,Ub=typeof queueMicrotask=="function"?queueMicrotask:typeof zm<"u"?function(r){return zm.resolve(null).then(r).catch(Vb)}:rd;function Vb(r){setTimeout(function(){throw r})}function ad(r,i){var c=i,h=0;do{var w=c.nextSibling;if(r.removeChild(c),w&&w.nodeType===8)if(c=w.data,c==="/$"){if(h===0){r.removeChild(w),Vs(i);return}h--}else c!=="$"&&c!=="$?"&&c!=="$!"||h++;c=w}while(c);Vs(i)}function vr(r){for(;r!=null;r=r.nextSibling){var i=r.nodeType;if(i===1||i===3)break;if(i===8){if(i=r.data,i==="$"||i==="$!"||i==="$?")break;if(i==="/$")return null}}return r}function Bm(r){r=r.previousSibling;for(var i=0;r;){if(r.nodeType===8){var c=r.data;if(c==="$"||c==="$!"||c==="$?"){if(i===0)return r;i--}else c==="/$"&&i++}r=r.previousSibling}return null}var Ja=Math.random().toString(36).slice(2),$s="__reactFiber$"+Ja,hi="__reactProps$"+Ja,Hs="__reactContainer$"+Ja,od="__reactEvents$"+Ja,Gb="__reactListeners$"+Ja,Hb="__reactHandles$"+Ja;function ta(r){var i=r[$s];if(i)return i;for(var c=r.parentNode;c;){if(i=c[Hs]||c[$s]){if(c=i.alternate,i.child!==null||c!==null&&c.child!==null)for(r=Bm(r);r!==null;){if(c=r[$s])return c;r=Bm(r)}return i}r=c,c=r.parentNode}return null}function mi(r){return r=r[$s]||r[Hs],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function qa(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(n(33))}function Gl(r){return r[hi]||null}var id=[],Ya=-1;function _r(r){return{current:r}}function kt(r){0>Ya||(r.current=id[Ya],id[Ya]=null,Ya--)}function vt(r,i){Ya++,id[Ya]=r.current,r.current=i}var br={},hn=_r(br),Rn=_r(!1),na=br;function Qa(r,i){var c=r.type.contextTypes;if(!c)return br;var h=r.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===i)return h.__reactInternalMemoizedMaskedChildContext;var w={},b;for(b in c)w[b]=i[b];return h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=w),w}function In(r){return r=r.childContextTypes,r!=null}function Hl(){kt(Rn),kt(hn)}function Wm(r,i,c){if(hn.current!==br)throw Error(n(168));vt(hn,i),vt(Rn,c)}function Um(r,i,c){var h=r.stateNode;if(i=i.childContextTypes,typeof h.getChildContext!="function")return c;h=h.getChildContext();for(var w in h)if(!(w in i))throw Error(n(108,Ne(r)||"Unknown",w));return W({},c,h)}function Kl(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||br,na=hn.current,vt(hn,r),vt(Rn,Rn.current),!0}function Vm(r,i,c){var h=r.stateNode;if(!h)throw Error(n(169));c?(r=Um(r,i,na),h.__reactInternalMemoizedMergedChildContext=r,kt(Rn),kt(hn),vt(hn,r)):kt(Rn),vt(Rn,c)}var Ks=null,Jl=!1,ld=!1;function Gm(r){Ks===null?Ks=[r]:Ks.push(r)}function Kb(r){Jl=!0,Gm(r)}function xr(){if(!ld&&Ks!==null){ld=!0;var r=0,i=at;try{var c=Ks;for(at=1;r<c.length;r++){var h=c[r];do h=h(!0);while(h!==null)}Ks=null,Jl=!1}catch(w){throw Ks!==null&&(Ks=Ks.slice(r+1)),Ea($a,xr),w}finally{at=i,ld=!1}}return null}var Xa=[],Za=0,ql=null,Yl=0,rs=[],as=0,sa=null,Js=1,qs="";function ra(r,i){Xa[Za++]=Yl,Xa[Za++]=ql,ql=r,Yl=i}function Hm(r,i,c){rs[as++]=Js,rs[as++]=qs,rs[as++]=sa,sa=r;var h=Js;r=qs;var w=32-Vt(h)-1;h&=~(1<<w),c+=1;var b=32-Vt(i)+w;if(30<b){var A=w-w%5;b=(h&(1<<A)-1).toString(32),h>>=A,w-=A,Js=1<<32-Vt(i)+w|c<<w|h,qs=b+r}else Js=1<<b|c<<w|h,qs=r}function cd(r){r.return!==null&&(ra(r,1),Hm(r,1,0))}function ud(r){for(;r===ql;)ql=Xa[--Za],Xa[Za]=null,Yl=Xa[--Za],Xa[Za]=null;for(;r===sa;)sa=rs[--as],rs[as]=null,qs=rs[--as],rs[as]=null,Js=rs[--as],rs[as]=null}var Kn=null,Jn=null,Et=!1,ws=null;function Km(r,i){var c=cs(5,null,null,0);c.elementType="DELETED",c.stateNode=i,c.return=r,i=r.deletions,i===null?(r.deletions=[c],r.flags|=16):i.push(c)}function Jm(r,i){switch(r.tag){case 5:var c=r.type;return i=i.nodeType!==1||c.toLowerCase()!==i.nodeName.toLowerCase()?null:i,i!==null?(r.stateNode=i,Kn=r,Jn=vr(i.firstChild),!0):!1;case 6:return i=r.pendingProps===""||i.nodeType!==3?null:i,i!==null?(r.stateNode=i,Kn=r,Jn=null,!0):!1;case 13:return i=i.nodeType!==8?null:i,i!==null?(c=sa!==null?{id:Js,overflow:qs}:null,r.memoizedState={dehydrated:i,treeContext:c,retryLane:1073741824},c=cs(18,null,null,0),c.stateNode=i,c.return=r,r.child=c,Kn=r,Jn=null,!0):!1;default:return!1}}function dd(r){return(r.mode&1)!==0&&(r.flags&128)===0}function fd(r){if(Et){var i=Jn;if(i){var c=i;if(!Jm(r,i)){if(dd(r))throw Error(n(418));i=vr(c.nextSibling);var h=Kn;i&&Jm(r,i)?Km(h,c):(r.flags=r.flags&-4097|2,Et=!1,Kn=r)}}else{if(dd(r))throw Error(n(418));r.flags=r.flags&-4097|2,Et=!1,Kn=r}}}function qm(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;Kn=r}function Ql(r){if(r!==Kn)return!1;if(!Et)return qm(r),Et=!0,!1;var i;if((i=r.tag!==3)&&!(i=r.tag!==5)&&(i=r.type,i=i!=="head"&&i!=="body"&&!sd(r.type,r.memoizedProps)),i&&(i=Jn)){if(dd(r))throw Ym(),Error(n(418));for(;i;)Km(r,i),i=vr(i.nextSibling)}if(qm(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(n(317));e:{for(r=r.nextSibling,i=0;r;){if(r.nodeType===8){var c=r.data;if(c==="/$"){if(i===0){Jn=vr(r.nextSibling);break e}i--}else c!=="$"&&c!=="$!"&&c!=="$?"||i++}r=r.nextSibling}Jn=null}}else Jn=Kn?vr(r.stateNode.nextSibling):null;return!0}function Ym(){for(var r=Jn;r;)r=vr(r.nextSibling)}function eo(){Jn=Kn=null,Et=!1}function hd(r){ws===null?ws=[r]:ws.push(r)}var Jb=N.ReactCurrentBatchConfig;function pi(r,i,c){if(r=c.ref,r!==null&&typeof r!="function"&&typeof r!="object"){if(c._owner){if(c=c._owner,c){if(c.tag!==1)throw Error(n(309));var h=c.stateNode}if(!h)throw Error(n(147,r));var w=h,b=""+r;return i!==null&&i.ref!==null&&typeof i.ref=="function"&&i.ref._stringRef===b?i.ref:(i=function(A){var P=w.refs;A===null?delete P[b]:P[b]=A},i._stringRef=b,i)}if(typeof r!="string")throw Error(n(284));if(!c._owner)throw Error(n(290,r))}return r}function Xl(r,i){throw r=Object.prototype.toString.call(i),Error(n(31,r==="[object Object]"?"object with keys {"+Object.keys(i).join(", ")+"}":r))}function Qm(r){var i=r._init;return i(r._payload)}function Xm(r){function i(X,G){if(r){var ee=X.deletions;ee===null?(X.deletions=[G],X.flags|=16):ee.push(G)}}function c(X,G){if(!r)return null;for(;G!==null;)i(X,G),G=G.sibling;return null}function h(X,G){for(X=new Map;G!==null;)G.key!==null?X.set(G.key,G):X.set(G.index,G),G=G.sibling;return X}function w(X,G){return X=$r(X,G),X.index=0,X.sibling=null,X}function b(X,G,ee){return X.index=ee,r?(ee=X.alternate,ee!==null?(ee=ee.index,ee<G?(X.flags|=2,G):ee):(X.flags|=2,G)):(X.flags|=1048576,G)}function A(X){return r&&X.alternate===null&&(X.flags|=2),X}function P(X,G,ee,ke){return G===null||G.tag!==6?(G=rf(ee,X.mode,ke),G.return=X,G):(G=w(G,ee),G.return=X,G)}function U(X,G,ee,ke){var Me=ee.type;return Me===I?pe(X,G,ee.props.children,ke,ee.key):G!==null&&(G.elementType===Me||typeof Me=="object"&&Me!==null&&Me.$$typeof===J&&Qm(Me)===G.type)?(ke=w(G,ee.props),ke.ref=pi(X,G,ee),ke.return=X,ke):(ke=xc(ee.type,ee.key,ee.props,null,X.mode,ke),ke.ref=pi(X,G,ee),ke.return=X,ke)}function re(X,G,ee,ke){return G===null||G.tag!==4||G.stateNode.containerInfo!==ee.containerInfo||G.stateNode.implementation!==ee.implementation?(G=af(ee,X.mode,ke),G.return=X,G):(G=w(G,ee.children||[]),G.return=X,G)}function pe(X,G,ee,ke,Me){return G===null||G.tag!==7?(G=fa(ee,X.mode,ke,Me),G.return=X,G):(G=w(G,ee),G.return=X,G)}function ye(X,G,ee){if(typeof G=="string"&&G!==""||typeof G=="number")return G=rf(""+G,X.mode,ee),G.return=X,G;if(typeof G=="object"&&G!==null){switch(G.$$typeof){case E:return ee=xc(G.type,G.key,G.props,null,X.mode,ee),ee.ref=pi(X,null,G),ee.return=X,ee;case j:return G=af(G,X.mode,ee),G.return=X,G;case J:var ke=G._init;return ye(X,ke(G._payload),ee)}if(ce(G)||te(G))return G=fa(G,X.mode,ee,null),G.return=X,G;Xl(X,G)}return null}function me(X,G,ee,ke){var Me=G!==null?G.key:null;if(typeof ee=="string"&&ee!==""||typeof ee=="number")return Me!==null?null:P(X,G,""+ee,ke);if(typeof ee=="object"&&ee!==null){switch(ee.$$typeof){case E:return ee.key===Me?U(X,G,ee,ke):null;case j:return ee.key===Me?re(X,G,ee,ke):null;case J:return Me=ee._init,me(X,G,Me(ee._payload),ke)}if(ce(ee)||te(ee))return Me!==null?null:pe(X,G,ee,ke,null);Xl(X,ee)}return null}function Ce(X,G,ee,ke,Me){if(typeof ke=="string"&&ke!==""||typeof ke=="number")return X=X.get(ee)||null,P(G,X,""+ke,Me);if(typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case E:return X=X.get(ke.key===null?ee:ke.key)||null,U(G,X,ke,Me);case j:return X=X.get(ke.key===null?ee:ke.key)||null,re(G,X,ke,Me);case J:var Be=ke._init;return Ce(X,G,ee,Be(ke._payload),Me)}if(ce(ke)||te(ke))return X=X.get(ee)||null,pe(G,X,ke,Me,null);Xl(G,ke)}return null}function Ae(X,G,ee,ke){for(var Me=null,Be=null,We=G,Je=G=0,sn=null;We!==null&&Je<ee.length;Je++){We.index>Je?(sn=We,We=null):sn=We.sibling;var lt=me(X,We,ee[Je],ke);if(lt===null){We===null&&(We=sn);break}r&&We&&lt.alternate===null&&i(X,We),G=b(lt,G,Je),Be===null?Me=lt:Be.sibling=lt,Be=lt,We=sn}if(Je===ee.length)return c(X,We),Et&&ra(X,Je),Me;if(We===null){for(;Je<ee.length;Je++)We=ye(X,ee[Je],ke),We!==null&&(G=b(We,G,Je),Be===null?Me=We:Be.sibling=We,Be=We);return Et&&ra(X,Je),Me}for(We=h(X,We);Je<ee.length;Je++)sn=Ce(We,X,Je,ee[Je],ke),sn!==null&&(r&&sn.alternate!==null&&We.delete(sn.key===null?Je:sn.key),G=b(sn,G,Je),Be===null?Me=sn:Be.sibling=sn,Be=sn);return r&&We.forEach(function(Tr){return i(X,Tr)}),Et&&ra(X,Je),Me}function Re(X,G,ee,ke){var Me=te(ee);if(typeof Me!="function")throw Error(n(150));if(ee=Me.call(ee),ee==null)throw Error(n(151));for(var Be=Me=null,We=G,Je=G=0,sn=null,lt=ee.next();We!==null&&!lt.done;Je++,lt=ee.next()){We.index>Je?(sn=We,We=null):sn=We.sibling;var Tr=me(X,We,lt.value,ke);if(Tr===null){We===null&&(We=sn);break}r&&We&&Tr.alternate===null&&i(X,We),G=b(Tr,G,Je),Be===null?Me=Tr:Be.sibling=Tr,Be=Tr,We=sn}if(lt.done)return c(X,We),Et&&ra(X,Je),Me;if(We===null){for(;!lt.done;Je++,lt=ee.next())lt=ye(X,lt.value,ke),lt!==null&&(G=b(lt,G,Je),Be===null?Me=lt:Be.sibling=lt,Be=lt);return Et&&ra(X,Je),Me}for(We=h(X,We);!lt.done;Je++,lt=ee.next())lt=Ce(We,X,Je,lt.value,ke),lt!==null&&(r&&lt.alternate!==null&&We.delete(lt.key===null?Je:lt.key),G=b(lt,G,Je),Be===null?Me=lt:Be.sibling=lt,Be=lt);return r&&We.forEach(function(Cx){return i(X,Cx)}),Et&&ra(X,Je),Me}function Ft(X,G,ee,ke){if(typeof ee=="object"&&ee!==null&&ee.type===I&&ee.key===null&&(ee=ee.props.children),typeof ee=="object"&&ee!==null){switch(ee.$$typeof){case E:e:{for(var Me=ee.key,Be=G;Be!==null;){if(Be.key===Me){if(Me=ee.type,Me===I){if(Be.tag===7){c(X,Be.sibling),G=w(Be,ee.props.children),G.return=X,X=G;break e}}else if(Be.elementType===Me||typeof Me=="object"&&Me!==null&&Me.$$typeof===J&&Qm(Me)===Be.type){c(X,Be.sibling),G=w(Be,ee.props),G.ref=pi(X,Be,ee),G.return=X,X=G;break e}c(X,Be);break}else i(X,Be);Be=Be.sibling}ee.type===I?(G=fa(ee.props.children,X.mode,ke,ee.key),G.return=X,X=G):(ke=xc(ee.type,ee.key,ee.props,null,X.mode,ke),ke.ref=pi(X,G,ee),ke.return=X,X=ke)}return A(X);case j:e:{for(Be=ee.key;G!==null;){if(G.key===Be)if(G.tag===4&&G.stateNode.containerInfo===ee.containerInfo&&G.stateNode.implementation===ee.implementation){c(X,G.sibling),G=w(G,ee.children||[]),G.return=X,X=G;break e}else{c(X,G);break}else i(X,G);G=G.sibling}G=af(ee,X.mode,ke),G.return=X,X=G}return A(X);case J:return Be=ee._init,Ft(X,G,Be(ee._payload),ke)}if(ce(ee))return Ae(X,G,ee,ke);if(te(ee))return Re(X,G,ee,ke);Xl(X,ee)}return typeof ee=="string"&&ee!==""||typeof ee=="number"?(ee=""+ee,G!==null&&G.tag===6?(c(X,G.sibling),G=w(G,ee),G.return=X,X=G):(c(X,G),G=rf(ee,X.mode,ke),G.return=X,X=G),A(X)):c(X,G)}return Ft}var to=Xm(!0),Zm=Xm(!1),Zl=_r(null),ec=null,no=null,md=null;function pd(){md=no=ec=null}function gd(r){var i=Zl.current;kt(Zl),r._currentValue=i}function yd(r,i,c){for(;r!==null;){var h=r.alternate;if((r.childLanes&i)!==i?(r.childLanes|=i,h!==null&&(h.childLanes|=i)):h!==null&&(h.childLanes&i)!==i&&(h.childLanes|=i),r===c)break;r=r.return}}function so(r,i){ec=r,md=no=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&i)!==0&&(Ln=!0),r.firstContext=null)}function os(r){var i=r._currentValue;if(md!==r)if(r={context:r,memoizedValue:i,next:null},no===null){if(ec===null)throw Error(n(308));no=r,ec.dependencies={lanes:0,firstContext:r}}else no=no.next=r;return i}var aa=null;function wd(r){aa===null?aa=[r]:aa.push(r)}function ep(r,i,c,h){var w=i.interleaved;return w===null?(c.next=c,wd(i)):(c.next=w.next,w.next=c),i.interleaved=c,Ys(r,h)}function Ys(r,i){r.lanes|=i;var c=r.alternate;for(c!==null&&(c.lanes|=i),c=r,r=r.return;r!==null;)r.childLanes|=i,c=r.alternate,c!==null&&(c.childLanes|=i),c=r,r=r.return;return c.tag===3?c.stateNode:null}var kr=!1;function vd(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function tp(r,i){r=r.updateQueue,i.updateQueue===r&&(i.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function Qs(r,i){return{eventTime:r,lane:i,tag:0,payload:null,callback:null,next:null}}function Sr(r,i,c){var h=r.updateQueue;if(h===null)return null;if(h=h.shared,(it&2)!==0){var w=h.pending;return w===null?i.next=i:(i.next=w.next,w.next=i),h.pending=i,Ys(r,c)}return w=h.interleaved,w===null?(i.next=i,wd(h)):(i.next=w.next,w.next=i),h.interleaved=i,Ys(r,c)}function tc(r,i,c){if(i=i.updateQueue,i!==null&&(i=i.shared,(c&4194240)!==0)){var h=i.lanes;h&=r.pendingLanes,c|=h,i.lanes=c,Ws(r,c)}}function np(r,i){var c=r.updateQueue,h=r.alternate;if(h!==null&&(h=h.updateQueue,c===h)){var w=null,b=null;if(c=c.firstBaseUpdate,c!==null){do{var A={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};b===null?w=b=A:b=b.next=A,c=c.next}while(c!==null);b===null?w=b=i:b=b.next=i}else w=b=i;c={baseState:h.baseState,firstBaseUpdate:w,lastBaseUpdate:b,shared:h.shared,effects:h.effects},r.updateQueue=c;return}r=c.lastBaseUpdate,r===null?c.firstBaseUpdate=i:r.next=i,c.lastBaseUpdate=i}function nc(r,i,c,h){var w=r.updateQueue;kr=!1;var b=w.firstBaseUpdate,A=w.lastBaseUpdate,P=w.shared.pending;if(P!==null){w.shared.pending=null;var U=P,re=U.next;U.next=null,A===null?b=re:A.next=re,A=U;var pe=r.alternate;pe!==null&&(pe=pe.updateQueue,P=pe.lastBaseUpdate,P!==A&&(P===null?pe.firstBaseUpdate=re:P.next=re,pe.lastBaseUpdate=U))}if(b!==null){var ye=w.baseState;A=0,pe=re=U=null,P=b;do{var me=P.lane,Ce=P.eventTime;if((h&me)===me){pe!==null&&(pe=pe.next={eventTime:Ce,lane:0,tag:P.tag,payload:P.payload,callback:P.callback,next:null});e:{var Ae=r,Re=P;switch(me=i,Ce=c,Re.tag){case 1:if(Ae=Re.payload,typeof Ae=="function"){ye=Ae.call(Ce,ye,me);break e}ye=Ae;break e;case 3:Ae.flags=Ae.flags&-65537|128;case 0:if(Ae=Re.payload,me=typeof Ae=="function"?Ae.call(Ce,ye,me):Ae,me==null)break e;ye=W({},ye,me);break e;case 2:kr=!0}}P.callback!==null&&P.lane!==0&&(r.flags|=64,me=w.effects,me===null?w.effects=[P]:me.push(P))}else Ce={eventTime:Ce,lane:me,tag:P.tag,payload:P.payload,callback:P.callback,next:null},pe===null?(re=pe=Ce,U=ye):pe=pe.next=Ce,A|=me;if(P=P.next,P===null){if(P=w.shared.pending,P===null)break;me=P,P=me.next,me.next=null,w.lastBaseUpdate=me,w.shared.pending=null}}while(!0);if(pe===null&&(U=ye),w.baseState=U,w.firstBaseUpdate=re,w.lastBaseUpdate=pe,i=w.shared.interleaved,i!==null){w=i;do A|=w.lane,w=w.next;while(w!==i)}else b===null&&(w.shared.lanes=0);la|=A,r.lanes=A,r.memoizedState=ye}}function sp(r,i,c){if(r=i.effects,i.effects=null,r!==null)for(i=0;i<r.length;i++){var h=r[i],w=h.callback;if(w!==null){if(h.callback=null,h=c,typeof w!="function")throw Error(n(191,w));w.call(h)}}}var gi={},Ts=_r(gi),yi=_r(gi),wi=_r(gi);function oa(r){if(r===gi)throw Error(n(174));return r}function _d(r,i){switch(vt(wi,i),vt(yi,r),vt(Ts,gi),r=i.nodeType,r){case 9:case 11:i=(i=i.documentElement)?i.namespaceURI:ae(null,"");break;default:r=r===8?i.parentNode:i,i=r.namespaceURI||null,r=r.tagName,i=ae(i,r)}kt(Ts),vt(Ts,i)}function ro(){kt(Ts),kt(yi),kt(wi)}function rp(r){oa(wi.current);var i=oa(Ts.current),c=ae(i,r.type);i!==c&&(vt(yi,r),vt(Ts,c))}function bd(r){yi.current===r&&(kt(Ts),kt(yi))}var $t=_r(0);function sc(r){for(var i=r;i!==null;){if(i.tag===13){var c=i.memoizedState;if(c!==null&&(c=c.dehydrated,c===null||c.data==="$?"||c.data==="$!"))return i}else if(i.tag===19&&i.memoizedProps.revealOrder!==void 0){if((i.flags&128)!==0)return i}else if(i.child!==null){i.child.return=i,i=i.child;continue}if(i===r)break;for(;i.sibling===null;){if(i.return===null||i.return===r)return null;i=i.return}i.sibling.return=i.return,i=i.sibling}return null}var xd=[];function kd(){for(var r=0;r<xd.length;r++)xd[r]._workInProgressVersionPrimary=null;xd.length=0}var rc=N.ReactCurrentDispatcher,Sd=N.ReactCurrentBatchConfig,ia=0,Tt=null,qt=null,tn=null,ac=!1,vi=!1,_i=0,qb=0;function mn(){throw Error(n(321))}function jd(r,i){if(i===null)return!1;for(var c=0;c<i.length&&c<r.length;c++)if(!ys(r[c],i[c]))return!1;return!0}function Nd(r,i,c,h,w,b){if(ia=b,Tt=i,i.memoizedState=null,i.updateQueue=null,i.lanes=0,rc.current=r===null||r.memoizedState===null?Zb:ex,r=c(h,w),vi){b=0;do{if(vi=!1,_i=0,25<=b)throw Error(n(301));b+=1,tn=qt=null,i.updateQueue=null,rc.current=tx,r=c(h,w)}while(vi)}if(rc.current=lc,i=qt!==null&&qt.next!==null,ia=0,tn=qt=Tt=null,ac=!1,i)throw Error(n(300));return r}function Cd(){var r=_i!==0;return _i=0,r}function Rs(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return tn===null?Tt.memoizedState=tn=r:tn=tn.next=r,tn}function is(){if(qt===null){var r=Tt.alternate;r=r!==null?r.memoizedState:null}else r=qt.next;var i=tn===null?Tt.memoizedState:tn.next;if(i!==null)tn=i,qt=r;else{if(r===null)throw Error(n(310));qt=r,r={memoizedState:qt.memoizedState,baseState:qt.baseState,baseQueue:qt.baseQueue,queue:qt.queue,next:null},tn===null?Tt.memoizedState=tn=r:tn=tn.next=r}return tn}function bi(r,i){return typeof i=="function"?i(r):i}function Ed(r){var i=is(),c=i.queue;if(c===null)throw Error(n(311));c.lastRenderedReducer=r;var h=qt,w=h.baseQueue,b=c.pending;if(b!==null){if(w!==null){var A=w.next;w.next=b.next,b.next=A}h.baseQueue=w=b,c.pending=null}if(w!==null){b=w.next,h=h.baseState;var P=A=null,U=null,re=b;do{var pe=re.lane;if((ia&pe)===pe)U!==null&&(U=U.next={lane:0,action:re.action,hasEagerState:re.hasEagerState,eagerState:re.eagerState,next:null}),h=re.hasEagerState?re.eagerState:r(h,re.action);else{var ye={lane:pe,action:re.action,hasEagerState:re.hasEagerState,eagerState:re.eagerState,next:null};U===null?(P=U=ye,A=h):U=U.next=ye,Tt.lanes|=pe,la|=pe}re=re.next}while(re!==null&&re!==b);U===null?A=h:U.next=P,ys(h,i.memoizedState)||(Ln=!0),i.memoizedState=h,i.baseState=A,i.baseQueue=U,c.lastRenderedState=h}if(r=c.interleaved,r!==null){w=r;do b=w.lane,Tt.lanes|=b,la|=b,w=w.next;while(w!==r)}else w===null&&(c.lanes=0);return[i.memoizedState,c.dispatch]}function Ad(r){var i=is(),c=i.queue;if(c===null)throw Error(n(311));c.lastRenderedReducer=r;var h=c.dispatch,w=c.pending,b=i.memoizedState;if(w!==null){c.pending=null;var A=w=w.next;do b=r(b,A.action),A=A.next;while(A!==w);ys(b,i.memoizedState)||(Ln=!0),i.memoizedState=b,i.baseQueue===null&&(i.baseState=b),c.lastRenderedState=b}return[b,h]}function ap(){}function op(r,i){var c=Tt,h=is(),w=i(),b=!ys(h.memoizedState,w);if(b&&(h.memoizedState=w,Ln=!0),h=h.queue,$d(cp.bind(null,c,h,r),[r]),h.getSnapshot!==i||b||tn!==null&&tn.memoizedState.tag&1){if(c.flags|=2048,xi(9,lp.bind(null,c,h,w,i),void 0,null),nn===null)throw Error(n(349));(ia&30)!==0||ip(c,i,w)}return w}function ip(r,i,c){r.flags|=16384,r={getSnapshot:i,value:c},i=Tt.updateQueue,i===null?(i={lastEffect:null,stores:null},Tt.updateQueue=i,i.stores=[r]):(c=i.stores,c===null?i.stores=[r]:c.push(r))}function lp(r,i,c,h){i.value=c,i.getSnapshot=h,up(i)&&dp(r)}function cp(r,i,c){return c(function(){up(i)&&dp(r)})}function up(r){var i=r.getSnapshot;r=r.value;try{var c=i();return!ys(r,c)}catch{return!0}}function dp(r){var i=Ys(r,1);i!==null&&xs(i,r,1,-1)}function fp(r){var i=Rs();return typeof r=="function"&&(r=r()),i.memoizedState=i.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:bi,lastRenderedState:r},i.queue=r,r=r.dispatch=Xb.bind(null,Tt,r),[i.memoizedState,r]}function xi(r,i,c,h){return r={tag:r,create:i,destroy:c,deps:h,next:null},i=Tt.updateQueue,i===null?(i={lastEffect:null,stores:null},Tt.updateQueue=i,i.lastEffect=r.next=r):(c=i.lastEffect,c===null?i.lastEffect=r.next=r:(h=c.next,c.next=r,r.next=h,i.lastEffect=r)),r}function hp(){return is().memoizedState}function oc(r,i,c,h){var w=Rs();Tt.flags|=r,w.memoizedState=xi(1|i,c,void 0,h===void 0?null:h)}function ic(r,i,c,h){var w=is();h=h===void 0?null:h;var b=void 0;if(qt!==null){var A=qt.memoizedState;if(b=A.destroy,h!==null&&jd(h,A.deps)){w.memoizedState=xi(i,c,b,h);return}}Tt.flags|=r,w.memoizedState=xi(1|i,c,b,h)}function mp(r,i){return oc(8390656,8,r,i)}function $d(r,i){return ic(2048,8,r,i)}function pp(r,i){return ic(4,2,r,i)}function gp(r,i){return ic(4,4,r,i)}function yp(r,i){if(typeof i=="function")return r=r(),i(r),function(){i(null)};if(i!=null)return r=r(),i.current=r,function(){i.current=null}}function wp(r,i,c){return c=c!=null?c.concat([r]):null,ic(4,4,yp.bind(null,i,r),c)}function Td(){}function vp(r,i){var c=is();i=i===void 0?null:i;var h=c.memoizedState;return h!==null&&i!==null&&jd(i,h[1])?h[0]:(c.memoizedState=[r,i],r)}function _p(r,i){var c=is();i=i===void 0?null:i;var h=c.memoizedState;return h!==null&&i!==null&&jd(i,h[1])?h[0]:(r=r(),c.memoizedState=[r,i],r)}function bp(r,i,c){return(ia&21)===0?(r.baseState&&(r.baseState=!1,Ln=!0),r.memoizedState=c):(ys(c,i)||(c=$n(),Tt.lanes|=c,la|=c,r.baseState=!0),i)}function Yb(r,i){var c=at;at=c!==0&&4>c?c:4,r(!0);var h=Sd.transition;Sd.transition={};try{r(!1),i()}finally{at=c,Sd.transition=h}}function xp(){return is().memoizedState}function Qb(r,i,c){var h=Er(r);if(c={lane:h,action:c,hasEagerState:!1,eagerState:null,next:null},kp(r))Sp(i,c);else if(c=ep(r,i,c,h),c!==null){var w=jn();xs(c,r,h,w),jp(c,i,h)}}function Xb(r,i,c){var h=Er(r),w={lane:h,action:c,hasEagerState:!1,eagerState:null,next:null};if(kp(r))Sp(i,w);else{var b=r.alternate;if(r.lanes===0&&(b===null||b.lanes===0)&&(b=i.lastRenderedReducer,b!==null))try{var A=i.lastRenderedState,P=b(A,c);if(w.hasEagerState=!0,w.eagerState=P,ys(P,A)){var U=i.interleaved;U===null?(w.next=w,wd(i)):(w.next=U.next,U.next=w),i.interleaved=w;return}}catch{}finally{}c=ep(r,i,w,h),c!==null&&(w=jn(),xs(c,r,h,w),jp(c,i,h))}}function kp(r){var i=r.alternate;return r===Tt||i!==null&&i===Tt}function Sp(r,i){vi=ac=!0;var c=r.pending;c===null?i.next=i:(i.next=c.next,c.next=i),r.pending=i}function jp(r,i,c){if((c&4194240)!==0){var h=i.lanes;h&=r.pendingLanes,c|=h,i.lanes=c,Ws(r,c)}}var lc={readContext:os,useCallback:mn,useContext:mn,useEffect:mn,useImperativeHandle:mn,useInsertionEffect:mn,useLayoutEffect:mn,useMemo:mn,useReducer:mn,useRef:mn,useState:mn,useDebugValue:mn,useDeferredValue:mn,useTransition:mn,useMutableSource:mn,useSyncExternalStore:mn,useId:mn,unstable_isNewReconciler:!1},Zb={readContext:os,useCallback:function(r,i){return Rs().memoizedState=[r,i===void 0?null:i],r},useContext:os,useEffect:mp,useImperativeHandle:function(r,i,c){return c=c!=null?c.concat([r]):null,oc(4194308,4,yp.bind(null,i,r),c)},useLayoutEffect:function(r,i){return oc(4194308,4,r,i)},useInsertionEffect:function(r,i){return oc(4,2,r,i)},useMemo:function(r,i){var c=Rs();return i=i===void 0?null:i,r=r(),c.memoizedState=[r,i],r},useReducer:function(r,i,c){var h=Rs();return i=c!==void 0?c(i):i,h.memoizedState=h.baseState=i,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:i},h.queue=r,r=r.dispatch=Qb.bind(null,Tt,r),[h.memoizedState,r]},useRef:function(r){var i=Rs();return r={current:r},i.memoizedState=r},useState:fp,useDebugValue:Td,useDeferredValue:function(r){return Rs().memoizedState=r},useTransition:function(){var r=fp(!1),i=r[0];return r=Yb.bind(null,r[1]),Rs().memoizedState=r,[i,r]},useMutableSource:function(){},useSyncExternalStore:function(r,i,c){var h=Tt,w=Rs();if(Et){if(c===void 0)throw Error(n(407));c=c()}else{if(c=i(),nn===null)throw Error(n(349));(ia&30)!==0||ip(h,i,c)}w.memoizedState=c;var b={value:c,getSnapshot:i};return w.queue=b,mp(cp.bind(null,h,b,r),[r]),h.flags|=2048,xi(9,lp.bind(null,h,b,c,i),void 0,null),c},useId:function(){var r=Rs(),i=nn.identifierPrefix;if(Et){var c=qs,h=Js;c=(h&~(1<<32-Vt(h)-1)).toString(32)+c,i=":"+i+"R"+c,c=_i++,0<c&&(i+="H"+c.toString(32)),i+=":"}else c=qb++,i=":"+i+"r"+c.toString(32)+":";return r.memoizedState=i},unstable_isNewReconciler:!1},ex={readContext:os,useCallback:vp,useContext:os,useEffect:$d,useImperativeHandle:wp,useInsertionEffect:pp,useLayoutEffect:gp,useMemo:_p,useReducer:Ed,useRef:hp,useState:function(){return Ed(bi)},useDebugValue:Td,useDeferredValue:function(r){var i=is();return bp(i,qt.memoizedState,r)},useTransition:function(){var r=Ed(bi)[0],i=is().memoizedState;return[r,i]},useMutableSource:ap,useSyncExternalStore:op,useId:xp,unstable_isNewReconciler:!1},tx={readContext:os,useCallback:vp,useContext:os,useEffect:$d,useImperativeHandle:wp,useInsertionEffect:pp,useLayoutEffect:gp,useMemo:_p,useReducer:Ad,useRef:hp,useState:function(){return Ad(bi)},useDebugValue:Td,useDeferredValue:function(r){var i=is();return qt===null?i.memoizedState=r:bp(i,qt.memoizedState,r)},useTransition:function(){var r=Ad(bi)[0],i=is().memoizedState;return[r,i]},useMutableSource:ap,useSyncExternalStore:op,useId:xp,unstable_isNewReconciler:!1};function vs(r,i){if(r&&r.defaultProps){i=W({},i),r=r.defaultProps;for(var c in r)i[c]===void 0&&(i[c]=r[c]);return i}return i}function Rd(r,i,c,h){i=r.memoizedState,c=c(h,i),c=c==null?i:W({},i,c),r.memoizedState=c,r.lanes===0&&(r.updateQueue.baseState=c)}var cc={isMounted:function(r){return(r=r._reactInternals)?Ns(r)===r:!1},enqueueSetState:function(r,i,c){r=r._reactInternals;var h=jn(),w=Er(r),b=Qs(h,w);b.payload=i,c!=null&&(b.callback=c),i=Sr(r,b,w),i!==null&&(xs(i,r,w,h),tc(i,r,w))},enqueueReplaceState:function(r,i,c){r=r._reactInternals;var h=jn(),w=Er(r),b=Qs(h,w);b.tag=1,b.payload=i,c!=null&&(b.callback=c),i=Sr(r,b,w),i!==null&&(xs(i,r,w,h),tc(i,r,w))},enqueueForceUpdate:function(r,i){r=r._reactInternals;var c=jn(),h=Er(r),w=Qs(c,h);w.tag=2,i!=null&&(w.callback=i),i=Sr(r,w,h),i!==null&&(xs(i,r,h,c),tc(i,r,h))}};function Np(r,i,c,h,w,b,A){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(h,b,A):i.prototype&&i.prototype.isPureReactComponent?!li(c,h)||!li(w,b):!0}function Cp(r,i,c){var h=!1,w=br,b=i.contextType;return typeof b=="object"&&b!==null?b=os(b):(w=In(i)?na:hn.current,h=i.contextTypes,b=(h=h!=null)?Qa(r,w):br),i=new i(c,b),r.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,i.updater=cc,r.stateNode=i,i._reactInternals=r,h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=w,r.__reactInternalMemoizedMaskedChildContext=b),i}function Ep(r,i,c,h){r=i.state,typeof i.componentWillReceiveProps=="function"&&i.componentWillReceiveProps(c,h),typeof i.UNSAFE_componentWillReceiveProps=="function"&&i.UNSAFE_componentWillReceiveProps(c,h),i.state!==r&&cc.enqueueReplaceState(i,i.state,null)}function Id(r,i,c,h){var w=r.stateNode;w.props=c,w.state=r.memoizedState,w.refs={},vd(r);var b=i.contextType;typeof b=="object"&&b!==null?w.context=os(b):(b=In(i)?na:hn.current,w.context=Qa(r,b)),w.state=r.memoizedState,b=i.getDerivedStateFromProps,typeof b=="function"&&(Rd(r,i,b,c),w.state=r.memoizedState),typeof i.getDerivedStateFromProps=="function"||typeof w.getSnapshotBeforeUpdate=="function"||typeof w.UNSAFE_componentWillMount!="function"&&typeof w.componentWillMount!="function"||(i=w.state,typeof w.componentWillMount=="function"&&w.componentWillMount(),typeof w.UNSAFE_componentWillMount=="function"&&w.UNSAFE_componentWillMount(),i!==w.state&&cc.enqueueReplaceState(w,w.state,null),nc(r,c,w,h),w.state=r.memoizedState),typeof w.componentDidMount=="function"&&(r.flags|=4194308)}function ao(r,i){try{var c="",h=i;do c+=oe(h),h=h.return;while(h);var w=c}catch(b){w=`
39
- Error generating stack: `+b.message+`
40
- `+b.stack}return{value:r,source:i,stack:w,digest:null}}function Ld(r,i,c){return{value:r,source:null,stack:c??null,digest:i??null}}function Md(r,i){try{console.error(i.value)}catch(c){setTimeout(function(){throw c})}}var nx=typeof WeakMap=="function"?WeakMap:Map;function Ap(r,i,c){c=Qs(-1,c),c.tag=3,c.payload={element:null};var h=i.value;return c.callback=function(){gc||(gc=!0,Yd=h),Md(r,i)},c}function $p(r,i,c){c=Qs(-1,c),c.tag=3;var h=r.type.getDerivedStateFromError;if(typeof h=="function"){var w=i.value;c.payload=function(){return h(w)},c.callback=function(){Md(r,i)}}var b=r.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(c.callback=function(){Md(r,i),typeof h!="function"&&(Nr===null?Nr=new Set([this]):Nr.add(this));var A=i.stack;this.componentDidCatch(i.value,{componentStack:A!==null?A:""})}),c}function Tp(r,i,c){var h=r.pingCache;if(h===null){h=r.pingCache=new nx;var w=new Set;h.set(i,w)}else w=h.get(i),w===void 0&&(w=new Set,h.set(i,w));w.has(c)||(w.add(c),r=gx.bind(null,r,i,c),i.then(r,r))}function Rp(r){do{var i;if((i=r.tag===13)&&(i=r.memoizedState,i=i!==null?i.dehydrated!==null:!0),i)return r;r=r.return}while(r!==null);return null}function Ip(r,i,c,h,w){return(r.mode&1)===0?(r===i?r.flags|=65536:(r.flags|=128,c.flags|=131072,c.flags&=-52805,c.tag===1&&(c.alternate===null?c.tag=17:(i=Qs(-1,1),i.tag=2,Sr(c,i,1))),c.lanes|=1),r):(r.flags|=65536,r.lanes=w,r)}var sx=N.ReactCurrentOwner,Ln=!1;function Sn(r,i,c,h){i.child=r===null?Zm(i,null,c,h):to(i,r.child,c,h)}function Lp(r,i,c,h,w){c=c.render;var b=i.ref;return so(i,w),h=Nd(r,i,c,h,b,w),c=Cd(),r!==null&&!Ln?(i.updateQueue=r.updateQueue,i.flags&=-2053,r.lanes&=~w,Xs(r,i,w)):(Et&&c&&cd(i),i.flags|=1,Sn(r,i,h,w),i.child)}function Mp(r,i,c,h,w){if(r===null){var b=c.type;return typeof b=="function"&&!sf(b)&&b.defaultProps===void 0&&c.compare===null&&c.defaultProps===void 0?(i.tag=15,i.type=b,Op(r,i,b,h,w)):(r=xc(c.type,null,h,i,i.mode,w),r.ref=i.ref,r.return=i,i.child=r)}if(b=r.child,(r.lanes&w)===0){var A=b.memoizedProps;if(c=c.compare,c=c!==null?c:li,c(A,h)&&r.ref===i.ref)return Xs(r,i,w)}return i.flags|=1,r=$r(b,h),r.ref=i.ref,r.return=i,i.child=r}function Op(r,i,c,h,w){if(r!==null){var b=r.memoizedProps;if(li(b,h)&&r.ref===i.ref)if(Ln=!1,i.pendingProps=h=b,(r.lanes&w)!==0)(r.flags&131072)!==0&&(Ln=!0);else return i.lanes=r.lanes,Xs(r,i,w)}return Od(r,i,c,h,w)}function Pp(r,i,c){var h=i.pendingProps,w=h.children,b=r!==null?r.memoizedState:null;if(h.mode==="hidden")if((i.mode&1)===0)i.memoizedState={baseLanes:0,cachePool:null,transitions:null},vt(io,qn),qn|=c;else{if((c&1073741824)===0)return r=b!==null?b.baseLanes|c:c,i.lanes=i.childLanes=1073741824,i.memoizedState={baseLanes:r,cachePool:null,transitions:null},i.updateQueue=null,vt(io,qn),qn|=r,null;i.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:c,vt(io,qn),qn|=h}else b!==null?(h=b.baseLanes|c,i.memoizedState=null):h=c,vt(io,qn),qn|=h;return Sn(r,i,w,c),i.child}function Dp(r,i){var c=i.ref;(r===null&&c!==null||r!==null&&r.ref!==c)&&(i.flags|=512,i.flags|=2097152)}function Od(r,i,c,h,w){var b=In(c)?na:hn.current;return b=Qa(i,b),so(i,w),c=Nd(r,i,c,h,b,w),h=Cd(),r!==null&&!Ln?(i.updateQueue=r.updateQueue,i.flags&=-2053,r.lanes&=~w,Xs(r,i,w)):(Et&&h&&cd(i),i.flags|=1,Sn(r,i,c,w),i.child)}function Fp(r,i,c,h,w){if(In(c)){var b=!0;Kl(i)}else b=!1;if(so(i,w),i.stateNode===null)dc(r,i),Cp(i,c,h),Id(i,c,h,w),h=!0;else if(r===null){var A=i.stateNode,P=i.memoizedProps;A.props=P;var U=A.context,re=c.contextType;typeof re=="object"&&re!==null?re=os(re):(re=In(c)?na:hn.current,re=Qa(i,re));var pe=c.getDerivedStateFromProps,ye=typeof pe=="function"||typeof A.getSnapshotBeforeUpdate=="function";ye||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(P!==h||U!==re)&&Ep(i,A,h,re),kr=!1;var me=i.memoizedState;A.state=me,nc(i,h,A,w),U=i.memoizedState,P!==h||me!==U||Rn.current||kr?(typeof pe=="function"&&(Rd(i,c,pe,h),U=i.memoizedState),(P=kr||Np(i,c,P,h,me,U,re))?(ye||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(i.flags|=4194308)):(typeof A.componentDidMount=="function"&&(i.flags|=4194308),i.memoizedProps=h,i.memoizedState=U),A.props=h,A.state=U,A.context=re,h=P):(typeof A.componentDidMount=="function"&&(i.flags|=4194308),h=!1)}else{A=i.stateNode,tp(r,i),P=i.memoizedProps,re=i.type===i.elementType?P:vs(i.type,P),A.props=re,ye=i.pendingProps,me=A.context,U=c.contextType,typeof U=="object"&&U!==null?U=os(U):(U=In(c)?na:hn.current,U=Qa(i,U));var Ce=c.getDerivedStateFromProps;(pe=typeof Ce=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(P!==ye||me!==U)&&Ep(i,A,h,U),kr=!1,me=i.memoizedState,A.state=me,nc(i,h,A,w);var Ae=i.memoizedState;P!==ye||me!==Ae||Rn.current||kr?(typeof Ce=="function"&&(Rd(i,c,Ce,h),Ae=i.memoizedState),(re=kr||Np(i,c,re,h,me,Ae,U)||!1)?(pe||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(h,Ae,U),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(h,Ae,U)),typeof A.componentDidUpdate=="function"&&(i.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(i.flags|=1024)):(typeof A.componentDidUpdate!="function"||P===r.memoizedProps&&me===r.memoizedState||(i.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||P===r.memoizedProps&&me===r.memoizedState||(i.flags|=1024),i.memoizedProps=h,i.memoizedState=Ae),A.props=h,A.state=Ae,A.context=U,h=re):(typeof A.componentDidUpdate!="function"||P===r.memoizedProps&&me===r.memoizedState||(i.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||P===r.memoizedProps&&me===r.memoizedState||(i.flags|=1024),h=!1)}return Pd(r,i,c,h,b,w)}function Pd(r,i,c,h,w,b){Dp(r,i);var A=(i.flags&128)!==0;if(!h&&!A)return w&&Vm(i,c,!1),Xs(r,i,b);h=i.stateNode,sx.current=i;var P=A&&typeof c.getDerivedStateFromError!="function"?null:h.render();return i.flags|=1,r!==null&&A?(i.child=to(i,r.child,null,b),i.child=to(i,null,P,b)):Sn(r,i,P,b),i.memoizedState=h.state,w&&Vm(i,c,!0),i.child}function zp(r){var i=r.stateNode;i.pendingContext?Wm(r,i.pendingContext,i.pendingContext!==i.context):i.context&&Wm(r,i.context,!1),_d(r,i.containerInfo)}function Bp(r,i,c,h,w){return eo(),hd(w),i.flags|=256,Sn(r,i,c,h),i.child}var Dd={dehydrated:null,treeContext:null,retryLane:0};function Fd(r){return{baseLanes:r,cachePool:null,transitions:null}}function Wp(r,i,c){var h=i.pendingProps,w=$t.current,b=!1,A=(i.flags&128)!==0,P;if((P=A)||(P=r!==null&&r.memoizedState===null?!1:(w&2)!==0),P?(b=!0,i.flags&=-129):(r===null||r.memoizedState!==null)&&(w|=1),vt($t,w&1),r===null)return fd(i),r=i.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?((i.mode&1)===0?i.lanes=1:r.data==="$!"?i.lanes=8:i.lanes=1073741824,null):(A=h.children,r=h.fallback,b?(h=i.mode,b=i.child,A={mode:"hidden",children:A},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=A):b=kc(A,h,0,null),r=fa(r,h,c,null),b.return=i,r.return=i,b.sibling=r,i.child=b,i.child.memoizedState=Fd(c),i.memoizedState=Dd,r):zd(i,A));if(w=r.memoizedState,w!==null&&(P=w.dehydrated,P!==null))return rx(r,i,A,h,P,w,c);if(b){b=h.fallback,A=i.mode,w=r.child,P=w.sibling;var U={mode:"hidden",children:h.children};return(A&1)===0&&i.child!==w?(h=i.child,h.childLanes=0,h.pendingProps=U,i.deletions=null):(h=$r(w,U),h.subtreeFlags=w.subtreeFlags&14680064),P!==null?b=$r(P,b):(b=fa(b,A,c,null),b.flags|=2),b.return=i,h.return=i,h.sibling=b,i.child=h,h=b,b=i.child,A=r.child.memoizedState,A=A===null?Fd(c):{baseLanes:A.baseLanes|c,cachePool:null,transitions:A.transitions},b.memoizedState=A,b.childLanes=r.childLanes&~c,i.memoizedState=Dd,h}return b=r.child,r=b.sibling,h=$r(b,{mode:"visible",children:h.children}),(i.mode&1)===0&&(h.lanes=c),h.return=i,h.sibling=null,r!==null&&(c=i.deletions,c===null?(i.deletions=[r],i.flags|=16):c.push(r)),i.child=h,i.memoizedState=null,h}function zd(r,i){return i=kc({mode:"visible",children:i},r.mode,0,null),i.return=r,r.child=i}function uc(r,i,c,h){return h!==null&&hd(h),to(i,r.child,null,c),r=zd(i,i.pendingProps.children),r.flags|=2,i.memoizedState=null,r}function rx(r,i,c,h,w,b,A){if(c)return i.flags&256?(i.flags&=-257,h=Ld(Error(n(422))),uc(r,i,A,h)):i.memoizedState!==null?(i.child=r.child,i.flags|=128,null):(b=h.fallback,w=i.mode,h=kc({mode:"visible",children:h.children},w,0,null),b=fa(b,w,A,null),b.flags|=2,h.return=i,b.return=i,h.sibling=b,i.child=h,(i.mode&1)!==0&&to(i,r.child,null,A),i.child.memoizedState=Fd(A),i.memoizedState=Dd,b);if((i.mode&1)===0)return uc(r,i,A,null);if(w.data==="$!"){if(h=w.nextSibling&&w.nextSibling.dataset,h)var P=h.dgst;return h=P,b=Error(n(419)),h=Ld(b,h,void 0),uc(r,i,A,h)}if(P=(A&r.childLanes)!==0,Ln||P){if(h=nn,h!==null){switch(A&-A){case 4:w=2;break;case 16:w=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:w=32;break;case 536870912:w=268435456;break;default:w=0}w=(w&(h.suspendedLanes|A))!==0?0:w,w!==0&&w!==b.retryLane&&(b.retryLane=w,Ys(r,w),xs(h,r,w,-1))}return nf(),h=Ld(Error(n(421))),uc(r,i,A,h)}return w.data==="$?"?(i.flags|=128,i.child=r.child,i=yx.bind(null,r),w._reactRetry=i,null):(r=b.treeContext,Jn=vr(w.nextSibling),Kn=i,Et=!0,ws=null,r!==null&&(rs[as++]=Js,rs[as++]=qs,rs[as++]=sa,Js=r.id,qs=r.overflow,sa=i),i=zd(i,h.children),i.flags|=4096,i)}function Up(r,i,c){r.lanes|=i;var h=r.alternate;h!==null&&(h.lanes|=i),yd(r.return,i,c)}function Bd(r,i,c,h,w){var b=r.memoizedState;b===null?r.memoizedState={isBackwards:i,rendering:null,renderingStartTime:0,last:h,tail:c,tailMode:w}:(b.isBackwards=i,b.rendering=null,b.renderingStartTime=0,b.last=h,b.tail=c,b.tailMode=w)}function Vp(r,i,c){var h=i.pendingProps,w=h.revealOrder,b=h.tail;if(Sn(r,i,h.children,c),h=$t.current,(h&2)!==0)h=h&1|2,i.flags|=128;else{if(r!==null&&(r.flags&128)!==0)e:for(r=i.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Up(r,c,i);else if(r.tag===19)Up(r,c,i);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===i)break e;for(;r.sibling===null;){if(r.return===null||r.return===i)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}h&=1}if(vt($t,h),(i.mode&1)===0)i.memoizedState=null;else switch(w){case"forwards":for(c=i.child,w=null;c!==null;)r=c.alternate,r!==null&&sc(r)===null&&(w=c),c=c.sibling;c=w,c===null?(w=i.child,i.child=null):(w=c.sibling,c.sibling=null),Bd(i,!1,w,c,b);break;case"backwards":for(c=null,w=i.child,i.child=null;w!==null;){if(r=w.alternate,r!==null&&sc(r)===null){i.child=w;break}r=w.sibling,w.sibling=c,c=w,w=r}Bd(i,!0,c,null,b);break;case"together":Bd(i,!1,null,null,void 0);break;default:i.memoizedState=null}return i.child}function dc(r,i){(i.mode&1)===0&&r!==null&&(r.alternate=null,i.alternate=null,i.flags|=2)}function Xs(r,i,c){if(r!==null&&(i.dependencies=r.dependencies),la|=i.lanes,(c&i.childLanes)===0)return null;if(r!==null&&i.child!==r.child)throw Error(n(153));if(i.child!==null){for(r=i.child,c=$r(r,r.pendingProps),i.child=c,c.return=i;r.sibling!==null;)r=r.sibling,c=c.sibling=$r(r,r.pendingProps),c.return=i;c.sibling=null}return i.child}function ax(r,i,c){switch(i.tag){case 3:zp(i),eo();break;case 5:rp(i);break;case 1:In(i.type)&&Kl(i);break;case 4:_d(i,i.stateNode.containerInfo);break;case 10:var h=i.type._context,w=i.memoizedProps.value;vt(Zl,h._currentValue),h._currentValue=w;break;case 13:if(h=i.memoizedState,h!==null)return h.dehydrated!==null?(vt($t,$t.current&1),i.flags|=128,null):(c&i.child.childLanes)!==0?Wp(r,i,c):(vt($t,$t.current&1),r=Xs(r,i,c),r!==null?r.sibling:null);vt($t,$t.current&1);break;case 19:if(h=(c&i.childLanes)!==0,(r.flags&128)!==0){if(h)return Vp(r,i,c);i.flags|=128}if(w=i.memoizedState,w!==null&&(w.rendering=null,w.tail=null,w.lastEffect=null),vt($t,$t.current),h)break;return null;case 22:case 23:return i.lanes=0,Pp(r,i,c)}return Xs(r,i,c)}var Gp,Wd,Hp,Kp;Gp=function(r,i){for(var c=i.child;c!==null;){if(c.tag===5||c.tag===6)r.appendChild(c.stateNode);else if(c.tag!==4&&c.child!==null){c.child.return=c,c=c.child;continue}if(c===i)break;for(;c.sibling===null;){if(c.return===null||c.return===i)return;c=c.return}c.sibling.return=c.return,c=c.sibling}},Wd=function(){},Hp=function(r,i,c,h){var w=r.memoizedProps;if(w!==h){r=i.stateNode,oa(Ts.current);var b=null;switch(c){case"input":w=qe(r,w),h=qe(r,h),b=[];break;case"select":w=W({},w,{value:void 0}),h=W({},h,{value:void 0}),b=[];break;case"textarea":w=H(r,w),h=H(r,h),b=[];break;default:typeof w.onClick!="function"&&typeof h.onClick=="function"&&(r.onclick=Vl)}St(c,h);var A;c=null;for(re in w)if(!h.hasOwnProperty(re)&&w.hasOwnProperty(re)&&w[re]!=null)if(re==="style"){var P=w[re];for(A in P)P.hasOwnProperty(A)&&(c||(c={}),c[A]="")}else re!=="dangerouslySetInnerHTML"&&re!=="children"&&re!=="suppressContentEditableWarning"&&re!=="suppressHydrationWarning"&&re!=="autoFocus"&&(o.hasOwnProperty(re)?b||(b=[]):(b=b||[]).push(re,null));for(re in h){var U=h[re];if(P=w!=null?w[re]:void 0,h.hasOwnProperty(re)&&U!==P&&(U!=null||P!=null))if(re==="style")if(P){for(A in P)!P.hasOwnProperty(A)||U&&U.hasOwnProperty(A)||(c||(c={}),c[A]="");for(A in U)U.hasOwnProperty(A)&&P[A]!==U[A]&&(c||(c={}),c[A]=U[A])}else c||(b||(b=[]),b.push(re,c)),c=U;else re==="dangerouslySetInnerHTML"?(U=U?U.__html:void 0,P=P?P.__html:void 0,U!=null&&P!==U&&(b=b||[]).push(re,U)):re==="children"?typeof U!="string"&&typeof U!="number"||(b=b||[]).push(re,""+U):re!=="suppressContentEditableWarning"&&re!=="suppressHydrationWarning"&&(o.hasOwnProperty(re)?(U!=null&&re==="onScroll"&&xt("scroll",r),b||P===U||(b=[])):(b=b||[]).push(re,U))}c&&(b=b||[]).push("style",c);var re=b;(i.updateQueue=re)&&(i.flags|=4)}},Kp=function(r,i,c,h){c!==h&&(i.flags|=4)};function ki(r,i){if(!Et)switch(r.tailMode){case"hidden":i=r.tail;for(var c=null;i!==null;)i.alternate!==null&&(c=i),i=i.sibling;c===null?r.tail=null:c.sibling=null;break;case"collapsed":c=r.tail;for(var h=null;c!==null;)c.alternate!==null&&(h=c),c=c.sibling;h===null?i||r.tail===null?r.tail=null:r.tail.sibling=null:h.sibling=null}}function pn(r){var i=r.alternate!==null&&r.alternate.child===r.child,c=0,h=0;if(i)for(var w=r.child;w!==null;)c|=w.lanes|w.childLanes,h|=w.subtreeFlags&14680064,h|=w.flags&14680064,w.return=r,w=w.sibling;else for(w=r.child;w!==null;)c|=w.lanes|w.childLanes,h|=w.subtreeFlags,h|=w.flags,w.return=r,w=w.sibling;return r.subtreeFlags|=h,r.childLanes=c,i}function ox(r,i,c){var h=i.pendingProps;switch(ud(i),i.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return pn(i),null;case 1:return In(i.type)&&Hl(),pn(i),null;case 3:return h=i.stateNode,ro(),kt(Rn),kt(hn),kd(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(r===null||r.child===null)&&(Ql(i)?i.flags|=4:r===null||r.memoizedState.isDehydrated&&(i.flags&256)===0||(i.flags|=1024,ws!==null&&(Zd(ws),ws=null))),Wd(r,i),pn(i),null;case 5:bd(i);var w=oa(wi.current);if(c=i.type,r!==null&&i.stateNode!=null)Hp(r,i,c,h,w),r.ref!==i.ref&&(i.flags|=512,i.flags|=2097152);else{if(!h){if(i.stateNode===null)throw Error(n(166));return pn(i),null}if(r=oa(Ts.current),Ql(i)){h=i.stateNode,c=i.type;var b=i.memoizedProps;switch(h[$s]=i,h[hi]=b,r=(i.mode&1)!==0,c){case"dialog":xt("cancel",h),xt("close",h);break;case"iframe":case"object":case"embed":xt("load",h);break;case"video":case"audio":for(w=0;w<ui.length;w++)xt(ui[w],h);break;case"source":xt("error",h);break;case"img":case"image":case"link":xt("error",h),xt("load",h);break;case"details":xt("toggle",h);break;case"input":ge(h,b),xt("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},xt("invalid",h);break;case"textarea":le(h,b),xt("invalid",h)}St(c,b),w=null;for(var A in b)if(b.hasOwnProperty(A)){var P=b[A];A==="children"?typeof P=="string"?h.textContent!==P&&(b.suppressHydrationWarning!==!0&&Ul(h.textContent,P,r),w=["children",P]):typeof P=="number"&&h.textContent!==""+P&&(b.suppressHydrationWarning!==!0&&Ul(h.textContent,P,r),w=["children",""+P]):o.hasOwnProperty(A)&&P!=null&&A==="onScroll"&&xt("scroll",h)}switch(c){case"input":Pe(h),tt(h,b,!0);break;case"textarea":Pe(h),Q(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=Vl)}h=w,i.updateQueue=h,h!==null&&(i.flags|=4)}else{A=w.nodeType===9?w:w.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=_e(c)),r==="http://www.w3.org/1999/xhtml"?c==="script"?(r=A.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof h.is=="string"?r=A.createElement(c,{is:h.is}):(r=A.createElement(c),c==="select"&&(A=r,h.multiple?A.multiple=!0:h.size&&(A.size=h.size))):r=A.createElementNS(r,c),r[$s]=i,r[hi]=h,Gp(r,i,!1,!1),i.stateNode=r;e:{switch(A=jt(c,h),c){case"dialog":xt("cancel",r),xt("close",r),w=h;break;case"iframe":case"object":case"embed":xt("load",r),w=h;break;case"video":case"audio":for(w=0;w<ui.length;w++)xt(ui[w],r);w=h;break;case"source":xt("error",r),w=h;break;case"img":case"image":case"link":xt("error",r),xt("load",r),w=h;break;case"details":xt("toggle",r),w=h;break;case"input":ge(r,h),w=qe(r,h),xt("invalid",r);break;case"option":w=h;break;case"select":r._wrapperState={wasMultiple:!!h.multiple},w=W({},h,{value:void 0}),xt("invalid",r);break;case"textarea":le(r,h),w=H(r,h),xt("invalid",r);break;default:w=h}St(c,w),P=w;for(b in P)if(P.hasOwnProperty(b)){var U=P[b];b==="style"?De(r,U):b==="dangerouslySetInnerHTML"?(U=U?U.__html:void 0,U!=null&&Oe(r,U)):b==="children"?typeof U=="string"?(c!=="textarea"||U!=="")&&Fe(r,U):typeof U=="number"&&Fe(r,""+U):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?U!=null&&b==="onScroll"&&xt("scroll",r):U!=null&&R(r,b,U,A))}switch(c){case"input":Pe(r),tt(r,h,!1);break;case"textarea":Pe(r),Q(r);break;case"option":h.value!=null&&r.setAttribute("value",""+q(h.value));break;case"select":r.multiple=!!h.multiple,b=h.value,b!=null?fe(r,!!h.multiple,b,!1):h.defaultValue!=null&&fe(r,!!h.multiple,h.defaultValue,!0);break;default:typeof w.onClick=="function"&&(r.onclick=Vl)}switch(c){case"button":case"input":case"select":case"textarea":h=!!h.autoFocus;break e;case"img":h=!0;break e;default:h=!1}}h&&(i.flags|=4)}i.ref!==null&&(i.flags|=512,i.flags|=2097152)}return pn(i),null;case 6:if(r&&i.stateNode!=null)Kp(r,i,r.memoizedProps,h);else{if(typeof h!="string"&&i.stateNode===null)throw Error(n(166));if(c=oa(wi.current),oa(Ts.current),Ql(i)){if(h=i.stateNode,c=i.memoizedProps,h[$s]=i,(b=h.nodeValue!==c)&&(r=Kn,r!==null))switch(r.tag){case 3:Ul(h.nodeValue,c,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&Ul(h.nodeValue,c,(r.mode&1)!==0)}b&&(i.flags|=4)}else h=(c.nodeType===9?c:c.ownerDocument).createTextNode(h),h[$s]=i,i.stateNode=h}return pn(i),null;case 13:if(kt($t),h=i.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(Et&&Jn!==null&&(i.mode&1)!==0&&(i.flags&128)===0)Ym(),eo(),i.flags|=98560,b=!1;else if(b=Ql(i),h!==null&&h.dehydrated!==null){if(r===null){if(!b)throw Error(n(318));if(b=i.memoizedState,b=b!==null?b.dehydrated:null,!b)throw Error(n(317));b[$s]=i}else eo(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;pn(i),b=!1}else ws!==null&&(Zd(ws),ws=null),b=!0;if(!b)return i.flags&65536?i:null}return(i.flags&128)!==0?(i.lanes=c,i):(h=h!==null,h!==(r!==null&&r.memoizedState!==null)&&h&&(i.child.flags|=8192,(i.mode&1)!==0&&(r===null||($t.current&1)!==0?Yt===0&&(Yt=3):nf())),i.updateQueue!==null&&(i.flags|=4),pn(i),null);case 4:return ro(),Wd(r,i),r===null&&di(i.stateNode.containerInfo),pn(i),null;case 10:return gd(i.type._context),pn(i),null;case 17:return In(i.type)&&Hl(),pn(i),null;case 19:if(kt($t),b=i.memoizedState,b===null)return pn(i),null;if(h=(i.flags&128)!==0,A=b.rendering,A===null)if(h)ki(b,!1);else{if(Yt!==0||r!==null&&(r.flags&128)!==0)for(r=i.child;r!==null;){if(A=sc(r),A!==null){for(i.flags|=128,ki(b,!1),h=A.updateQueue,h!==null&&(i.updateQueue=h,i.flags|=4),i.subtreeFlags=0,h=c,c=i.child;c!==null;)b=c,r=h,b.flags&=14680066,A=b.alternate,A===null?(b.childLanes=0,b.lanes=r,b.child=null,b.subtreeFlags=0,b.memoizedProps=null,b.memoizedState=null,b.updateQueue=null,b.dependencies=null,b.stateNode=null):(b.childLanes=A.childLanes,b.lanes=A.lanes,b.child=A.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=A.memoizedProps,b.memoizedState=A.memoizedState,b.updateQueue=A.updateQueue,b.type=A.type,r=A.dependencies,b.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),c=c.sibling;return vt($t,$t.current&1|2),i.child}r=r.sibling}b.tail!==null&&Nt()>lo&&(i.flags|=128,h=!0,ki(b,!1),i.lanes=4194304)}else{if(!h)if(r=sc(A),r!==null){if(i.flags|=128,h=!0,c=r.updateQueue,c!==null&&(i.updateQueue=c,i.flags|=4),ki(b,!0),b.tail===null&&b.tailMode==="hidden"&&!A.alternate&&!Et)return pn(i),null}else 2*Nt()-b.renderingStartTime>lo&&c!==1073741824&&(i.flags|=128,h=!0,ki(b,!1),i.lanes=4194304);b.isBackwards?(A.sibling=i.child,i.child=A):(c=b.last,c!==null?c.sibling=A:i.child=A,b.last=A)}return b.tail!==null?(i=b.tail,b.rendering=i,b.tail=i.sibling,b.renderingStartTime=Nt(),i.sibling=null,c=$t.current,vt($t,h?c&1|2:c&1),i):(pn(i),null);case 22:case 23:return tf(),h=i.memoizedState!==null,r!==null&&r.memoizedState!==null!==h&&(i.flags|=8192),h&&(i.mode&1)!==0?(qn&1073741824)!==0&&(pn(i),i.subtreeFlags&6&&(i.flags|=8192)):pn(i),null;case 24:return null;case 25:return null}throw Error(n(156,i.tag))}function ix(r,i){switch(ud(i),i.tag){case 1:return In(i.type)&&Hl(),r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 3:return ro(),kt(Rn),kt(hn),kd(),r=i.flags,(r&65536)!==0&&(r&128)===0?(i.flags=r&-65537|128,i):null;case 5:return bd(i),null;case 13:if(kt($t),r=i.memoizedState,r!==null&&r.dehydrated!==null){if(i.alternate===null)throw Error(n(340));eo()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 19:return kt($t),null;case 4:return ro(),null;case 10:return gd(i.type._context),null;case 22:case 23:return tf(),null;case 24:return null;default:return null}}var fc=!1,gn=!1,lx=typeof WeakSet=="function"?WeakSet:Set,Ee=null;function oo(r,i){var c=r.ref;if(c!==null)if(typeof c=="function")try{c(null)}catch(h){Mt(r,i,h)}else c.current=null}function Ud(r,i,c){try{c()}catch(h){Mt(r,i,h)}}var Jp=!1;function cx(r,i){if(td=za,r=Nm(),Ku(r)){if("selectionStart"in r)var c={start:r.selectionStart,end:r.selectionEnd};else e:{c=(c=r.ownerDocument)&&c.defaultView||window;var h=c.getSelection&&c.getSelection();if(h&&h.rangeCount!==0){c=h.anchorNode;var w=h.anchorOffset,b=h.focusNode;h=h.focusOffset;try{c.nodeType,b.nodeType}catch{c=null;break e}var A=0,P=-1,U=-1,re=0,pe=0,ye=r,me=null;t:for(;;){for(var Ce;ye!==c||w!==0&&ye.nodeType!==3||(P=A+w),ye!==b||h!==0&&ye.nodeType!==3||(U=A+h),ye.nodeType===3&&(A+=ye.nodeValue.length),(Ce=ye.firstChild)!==null;)me=ye,ye=Ce;for(;;){if(ye===r)break t;if(me===c&&++re===w&&(P=A),me===b&&++pe===h&&(U=A),(Ce=ye.nextSibling)!==null)break;ye=me,me=ye.parentNode}ye=Ce}c=P===-1||U===-1?null:{start:P,end:U}}else c=null}c=c||{start:0,end:0}}else c=null;for(nd={focusedElem:r,selectionRange:c},za=!1,Ee=i;Ee!==null;)if(i=Ee,r=i.child,(i.subtreeFlags&1028)!==0&&r!==null)r.return=i,Ee=r;else for(;Ee!==null;){i=Ee;try{var Ae=i.alternate;if((i.flags&1024)!==0)switch(i.tag){case 0:case 11:case 15:break;case 1:if(Ae!==null){var Re=Ae.memoizedProps,Ft=Ae.memoizedState,X=i.stateNode,G=X.getSnapshotBeforeUpdate(i.elementType===i.type?Re:vs(i.type,Re),Ft);X.__reactInternalSnapshotBeforeUpdate=G}break;case 3:var ee=i.stateNode.containerInfo;ee.nodeType===1?ee.textContent="":ee.nodeType===9&&ee.documentElement&&ee.removeChild(ee.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(ke){Mt(i,i.return,ke)}if(r=i.sibling,r!==null){r.return=i.return,Ee=r;break}Ee=i.return}return Ae=Jp,Jp=!1,Ae}function Si(r,i,c){var h=i.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var w=h=h.next;do{if((w.tag&r)===r){var b=w.destroy;w.destroy=void 0,b!==void 0&&Ud(i,c,b)}w=w.next}while(w!==h)}}function hc(r,i){if(i=i.updateQueue,i=i!==null?i.lastEffect:null,i!==null){var c=i=i.next;do{if((c.tag&r)===r){var h=c.create;c.destroy=h()}c=c.next}while(c!==i)}}function Vd(r){var i=r.ref;if(i!==null){var c=r.stateNode;switch(r.tag){case 5:r=c;break;default:r=c}typeof i=="function"?i(r):i.current=r}}function qp(r){var i=r.alternate;i!==null&&(r.alternate=null,qp(i)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(i=r.stateNode,i!==null&&(delete i[$s],delete i[hi],delete i[od],delete i[Gb],delete i[Hb])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Yp(r){return r.tag===5||r.tag===3||r.tag===4}function Qp(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Yp(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Gd(r,i,c){var h=r.tag;if(h===5||h===6)r=r.stateNode,i?c.nodeType===8?c.parentNode.insertBefore(r,i):c.insertBefore(r,i):(c.nodeType===8?(i=c.parentNode,i.insertBefore(r,c)):(i=c,i.appendChild(r)),c=c._reactRootContainer,c!=null||i.onclick!==null||(i.onclick=Vl));else if(h!==4&&(r=r.child,r!==null))for(Gd(r,i,c),r=r.sibling;r!==null;)Gd(r,i,c),r=r.sibling}function Hd(r,i,c){var h=r.tag;if(h===5||h===6)r=r.stateNode,i?c.insertBefore(r,i):c.appendChild(r);else if(h!==4&&(r=r.child,r!==null))for(Hd(r,i,c),r=r.sibling;r!==null;)Hd(r,i,c),r=r.sibling}var an=null,_s=!1;function jr(r,i,c){for(c=c.child;c!==null;)Xp(r,i,c),c=c.sibling}function Xp(r,i,c){if(Ut&&typeof Ut.onCommitFiberUnmount=="function")try{Ut.onCommitFiberUnmount(Es,c)}catch{}switch(c.tag){case 5:gn||oo(c,i);case 6:var h=an,w=_s;an=null,jr(r,i,c),an=h,_s=w,an!==null&&(_s?(r=an,c=c.stateNode,r.nodeType===8?r.parentNode.removeChild(c):r.removeChild(c)):an.removeChild(c.stateNode));break;case 18:an!==null&&(_s?(r=an,c=c.stateNode,r.nodeType===8?ad(r.parentNode,c):r.nodeType===1&&ad(r,c),Vs(r)):ad(an,c.stateNode));break;case 4:h=an,w=_s,an=c.stateNode.containerInfo,_s=!0,jr(r,i,c),an=h,_s=w;break;case 0:case 11:case 14:case 15:if(!gn&&(h=c.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){w=h=h.next;do{var b=w,A=b.destroy;b=b.tag,A!==void 0&&((b&2)!==0||(b&4)!==0)&&Ud(c,i,A),w=w.next}while(w!==h)}jr(r,i,c);break;case 1:if(!gn&&(oo(c,i),h=c.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=c.memoizedProps,h.state=c.memoizedState,h.componentWillUnmount()}catch(P){Mt(c,i,P)}jr(r,i,c);break;case 21:jr(r,i,c);break;case 22:c.mode&1?(gn=(h=gn)||c.memoizedState!==null,jr(r,i,c),gn=h):jr(r,i,c);break;default:jr(r,i,c)}}function Zp(r){var i=r.updateQueue;if(i!==null){r.updateQueue=null;var c=r.stateNode;c===null&&(c=r.stateNode=new lx),i.forEach(function(h){var w=wx.bind(null,r,h);c.has(h)||(c.add(h),h.then(w,w))})}}function bs(r,i){var c=i.deletions;if(c!==null)for(var h=0;h<c.length;h++){var w=c[h];try{var b=r,A=i,P=A;e:for(;P!==null;){switch(P.tag){case 5:an=P.stateNode,_s=!1;break e;case 3:an=P.stateNode.containerInfo,_s=!0;break e;case 4:an=P.stateNode.containerInfo,_s=!0;break e}P=P.return}if(an===null)throw Error(n(160));Xp(b,A,w),an=null,_s=!1;var U=w.alternate;U!==null&&(U.return=null),w.return=null}catch(re){Mt(w,i,re)}}if(i.subtreeFlags&12854)for(i=i.child;i!==null;)eg(i,r),i=i.sibling}function eg(r,i){var c=r.alternate,h=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(bs(i,r),Is(r),h&4){try{Si(3,r,r.return),hc(3,r)}catch(Re){Mt(r,r.return,Re)}try{Si(5,r,r.return)}catch(Re){Mt(r,r.return,Re)}}break;case 1:bs(i,r),Is(r),h&512&&c!==null&&oo(c,c.return);break;case 5:if(bs(i,r),Is(r),h&512&&c!==null&&oo(c,c.return),r.flags&32){var w=r.stateNode;try{Fe(w,"")}catch(Re){Mt(r,r.return,Re)}}if(h&4&&(w=r.stateNode,w!=null)){var b=r.memoizedProps,A=c!==null?c.memoizedProps:b,P=r.type,U=r.updateQueue;if(r.updateQueue=null,U!==null)try{P==="input"&&b.type==="radio"&&b.name!=null&&$e(w,b),jt(P,A);var re=jt(P,b);for(A=0;A<U.length;A+=2){var pe=U[A],ye=U[A+1];pe==="style"?De(w,ye):pe==="dangerouslySetInnerHTML"?Oe(w,ye):pe==="children"?Fe(w,ye):R(w,pe,ye,re)}switch(P){case"input":st(w,b);break;case"textarea":he(w,b);break;case"select":var me=w._wrapperState.wasMultiple;w._wrapperState.wasMultiple=!!b.multiple;var Ce=b.value;Ce!=null?fe(w,!!b.multiple,Ce,!1):me!==!!b.multiple&&(b.defaultValue!=null?fe(w,!!b.multiple,b.defaultValue,!0):fe(w,!!b.multiple,b.multiple?[]:"",!1))}w[hi]=b}catch(Re){Mt(r,r.return,Re)}}break;case 6:if(bs(i,r),Is(r),h&4){if(r.stateNode===null)throw Error(n(162));w=r.stateNode,b=r.memoizedProps;try{w.nodeValue=b}catch(Re){Mt(r,r.return,Re)}}break;case 3:if(bs(i,r),Is(r),h&4&&c!==null&&c.memoizedState.isDehydrated)try{Vs(i.containerInfo)}catch(Re){Mt(r,r.return,Re)}break;case 4:bs(i,r),Is(r);break;case 13:bs(i,r),Is(r),w=r.child,w.flags&8192&&(b=w.memoizedState!==null,w.stateNode.isHidden=b,!b||w.alternate!==null&&w.alternate.memoizedState!==null||(qd=Nt())),h&4&&Zp(r);break;case 22:if(pe=c!==null&&c.memoizedState!==null,r.mode&1?(gn=(re=gn)||pe,bs(i,r),gn=re):bs(i,r),Is(r),h&8192){if(re=r.memoizedState!==null,(r.stateNode.isHidden=re)&&!pe&&(r.mode&1)!==0)for(Ee=r,pe=r.child;pe!==null;){for(ye=Ee=pe;Ee!==null;){switch(me=Ee,Ce=me.child,me.tag){case 0:case 11:case 14:case 15:Si(4,me,me.return);break;case 1:oo(me,me.return);var Ae=me.stateNode;if(typeof Ae.componentWillUnmount=="function"){h=me,c=me.return;try{i=h,Ae.props=i.memoizedProps,Ae.state=i.memoizedState,Ae.componentWillUnmount()}catch(Re){Mt(h,c,Re)}}break;case 5:oo(me,me.return);break;case 22:if(me.memoizedState!==null){sg(ye);continue}}Ce!==null?(Ce.return=me,Ee=Ce):sg(ye)}pe=pe.sibling}e:for(pe=null,ye=r;;){if(ye.tag===5){if(pe===null){pe=ye;try{w=ye.stateNode,re?(b=w.style,typeof b.setProperty=="function"?b.setProperty("display","none","important"):b.display="none"):(P=ye.stateNode,U=ye.memoizedProps.style,A=U!=null&&U.hasOwnProperty("display")?U.display:null,P.style.display=Ke("display",A))}catch(Re){Mt(r,r.return,Re)}}}else if(ye.tag===6){if(pe===null)try{ye.stateNode.nodeValue=re?"":ye.memoizedProps}catch(Re){Mt(r,r.return,Re)}}else if((ye.tag!==22&&ye.tag!==23||ye.memoizedState===null||ye===r)&&ye.child!==null){ye.child.return=ye,ye=ye.child;continue}if(ye===r)break e;for(;ye.sibling===null;){if(ye.return===null||ye.return===r)break e;pe===ye&&(pe=null),ye=ye.return}pe===ye&&(pe=null),ye.sibling.return=ye.return,ye=ye.sibling}}break;case 19:bs(i,r),Is(r),h&4&&Zp(r);break;case 21:break;default:bs(i,r),Is(r)}}function Is(r){var i=r.flags;if(i&2){try{e:{for(var c=r.return;c!==null;){if(Yp(c)){var h=c;break e}c=c.return}throw Error(n(160))}switch(h.tag){case 5:var w=h.stateNode;h.flags&32&&(Fe(w,""),h.flags&=-33);var b=Qp(r);Hd(r,b,w);break;case 3:case 4:var A=h.stateNode.containerInfo,P=Qp(r);Gd(r,P,A);break;default:throw Error(n(161))}}catch(U){Mt(r,r.return,U)}r.flags&=-3}i&4096&&(r.flags&=-4097)}function ux(r,i,c){Ee=r,tg(r)}function tg(r,i,c){for(var h=(r.mode&1)!==0;Ee!==null;){var w=Ee,b=w.child;if(w.tag===22&&h){var A=w.memoizedState!==null||fc;if(!A){var P=w.alternate,U=P!==null&&P.memoizedState!==null||gn;P=fc;var re=gn;if(fc=A,(gn=U)&&!re)for(Ee=w;Ee!==null;)A=Ee,U=A.child,A.tag===22&&A.memoizedState!==null?rg(w):U!==null?(U.return=A,Ee=U):rg(w);for(;b!==null;)Ee=b,tg(b),b=b.sibling;Ee=w,fc=P,gn=re}ng(r)}else(w.subtreeFlags&8772)!==0&&b!==null?(b.return=w,Ee=b):ng(r)}}function ng(r){for(;Ee!==null;){var i=Ee;if((i.flags&8772)!==0){var c=i.alternate;try{if((i.flags&8772)!==0)switch(i.tag){case 0:case 11:case 15:gn||hc(5,i);break;case 1:var h=i.stateNode;if(i.flags&4&&!gn)if(c===null)h.componentDidMount();else{var w=i.elementType===i.type?c.memoizedProps:vs(i.type,c.memoizedProps);h.componentDidUpdate(w,c.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=i.updateQueue;b!==null&&sp(i,b,h);break;case 3:var A=i.updateQueue;if(A!==null){if(c=null,i.child!==null)switch(i.child.tag){case 5:c=i.child.stateNode;break;case 1:c=i.child.stateNode}sp(i,A,c)}break;case 5:var P=i.stateNode;if(c===null&&i.flags&4){c=P;var U=i.memoizedProps;switch(i.type){case"button":case"input":case"select":case"textarea":U.autoFocus&&c.focus();break;case"img":U.src&&(c.src=U.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(i.memoizedState===null){var re=i.alternate;if(re!==null){var pe=re.memoizedState;if(pe!==null){var ye=pe.dehydrated;ye!==null&&Vs(ye)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}gn||i.flags&512&&Vd(i)}catch(me){Mt(i,i.return,me)}}if(i===r){Ee=null;break}if(c=i.sibling,c!==null){c.return=i.return,Ee=c;break}Ee=i.return}}function sg(r){for(;Ee!==null;){var i=Ee;if(i===r){Ee=null;break}var c=i.sibling;if(c!==null){c.return=i.return,Ee=c;break}Ee=i.return}}function rg(r){for(;Ee!==null;){var i=Ee;try{switch(i.tag){case 0:case 11:case 15:var c=i.return;try{hc(4,i)}catch(U){Mt(i,c,U)}break;case 1:var h=i.stateNode;if(typeof h.componentDidMount=="function"){var w=i.return;try{h.componentDidMount()}catch(U){Mt(i,w,U)}}var b=i.return;try{Vd(i)}catch(U){Mt(i,b,U)}break;case 5:var A=i.return;try{Vd(i)}catch(U){Mt(i,A,U)}}}catch(U){Mt(i,i.return,U)}if(i===r){Ee=null;break}var P=i.sibling;if(P!==null){P.return=i.return,Ee=P;break}Ee=i.return}}var dx=Math.ceil,mc=N.ReactCurrentDispatcher,Kd=N.ReactCurrentOwner,ls=N.ReactCurrentBatchConfig,it=0,nn=null,Ht=null,on=0,qn=0,io=_r(0),Yt=0,ji=null,la=0,pc=0,Jd=0,Ni=null,Mn=null,qd=0,lo=1/0,Zs=null,gc=!1,Yd=null,Nr=null,yc=!1,Cr=null,wc=0,Ci=0,Qd=null,vc=-1,_c=0;function jn(){return(it&6)!==0?Nt():vc!==-1?vc:vc=Nt()}function Er(r){return(r.mode&1)===0?1:(it&2)!==0&&on!==0?on&-on:Jb.transition!==null?(_c===0&&(_c=$n()),_c):(r=at,r!==0||(r=window.event,r=r===void 0?16:bl(r.type)),r)}function xs(r,i,c,h){if(50<Ci)throw Ci=0,Qd=null,Error(n(185));dr(r,c,h),((it&2)===0||r!==nn)&&(r===nn&&((it&2)===0&&(pc|=c),Yt===4&&Ar(r,on)),On(r,h),c===1&&it===0&&(i.mode&1)===0&&(lo=Nt()+500,Jl&&xr()))}function On(r,i){var c=r.callbackNode;Jo(r,i);var h=es(r,r===nn?on:0);if(h===0)c!==null&&Aa(c),r.callbackNode=null,r.callbackPriority=0;else if(i=h&-h,r.callbackPriority!==i){if(c!=null&&Aa(c),i===1)r.tag===0?Kb(og.bind(null,r)):Gm(og.bind(null,r)),Ub(function(){(it&6)===0&&xr()}),c=null;else{switch(fn(h)){case 1:c=$a;break;case 4:c=wl;break;case 16:c=Ta;break;case 536870912:c=Ye;break;default:c=Ta}c=mg(c,ag.bind(null,r))}r.callbackPriority=i,r.callbackNode=c}}function ag(r,i){if(vc=-1,_c=0,(it&6)!==0)throw Error(n(327));var c=r.callbackNode;if(co()&&r.callbackNode!==c)return null;var h=es(r,r===nn?on:0);if(h===0)return null;if((h&30)!==0||(h&r.expiredLanes)!==0||i)i=bc(r,h);else{i=h;var w=it;it|=2;var b=lg();(nn!==r||on!==i)&&(Zs=null,lo=Nt()+500,ua(r,i));do try{mx();break}catch(P){ig(r,P)}while(!0);pd(),mc.current=b,it=w,Ht!==null?i=0:(nn=null,on=0,i=Yt)}if(i!==0){if(i===2&&(w=La(r),w!==0&&(h=w,i=Xd(r,w))),i===1)throw c=ji,ua(r,0),Ar(r,h),On(r,Nt()),c;if(i===6)Ar(r,h);else{if(w=r.current.alternate,(h&30)===0&&!fx(w)&&(i=bc(r,h),i===2&&(b=La(r),b!==0&&(h=b,i=Xd(r,b))),i===1))throw c=ji,ua(r,0),Ar(r,h),On(r,Nt()),c;switch(r.finishedWork=w,r.finishedLanes=h,i){case 0:case 1:throw Error(n(345));case 2:da(r,Mn,Zs);break;case 3:if(Ar(r,h),(h&130023424)===h&&(i=qd+500-Nt(),10<i)){if(es(r,0)!==0)break;if(w=r.suspendedLanes,(w&h)!==h){jn(),r.pingedLanes|=r.suspendedLanes&w;break}r.timeoutHandle=rd(da.bind(null,r,Mn,Zs),i);break}da(r,Mn,Zs);break;case 4:if(Ar(r,h),(h&4194240)===h)break;for(i=r.eventTimes,w=-1;0<h;){var A=31-Vt(h);b=1<<A,A=i[A],A>w&&(w=A),h&=~b}if(h=w,h=Nt()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*dx(h/1960))-h,10<h){r.timeoutHandle=rd(da.bind(null,r,Mn,Zs),h);break}da(r,Mn,Zs);break;case 5:da(r,Mn,Zs);break;default:throw Error(n(329))}}}return On(r,Nt()),r.callbackNode===c?ag.bind(null,r):null}function Xd(r,i){var c=Ni;return r.current.memoizedState.isDehydrated&&(ua(r,i).flags|=256),r=bc(r,i),r!==2&&(i=Mn,Mn=c,i!==null&&Zd(i)),r}function Zd(r){Mn===null?Mn=r:Mn.push.apply(Mn,r)}function fx(r){for(var i=r;;){if(i.flags&16384){var c=i.updateQueue;if(c!==null&&(c=c.stores,c!==null))for(var h=0;h<c.length;h++){var w=c[h],b=w.getSnapshot;w=w.value;try{if(!ys(b(),w))return!1}catch{return!1}}}if(c=i.child,i.subtreeFlags&16384&&c!==null)c.return=i,i=c;else{if(i===r)break;for(;i.sibling===null;){if(i.return===null||i.return===r)return!0;i=i.return}i.sibling.return=i.return,i=i.sibling}}return!0}function Ar(r,i){for(i&=~Jd,i&=~pc,r.suspendedLanes|=i,r.pingedLanes&=~i,r=r.expirationTimes;0<i;){var c=31-Vt(i),h=1<<c;r[c]=-1,i&=~h}}function og(r){if((it&6)!==0)throw Error(n(327));co();var i=es(r,0);if((i&1)===0)return On(r,Nt()),null;var c=bc(r,i);if(r.tag!==0&&c===2){var h=La(r);h!==0&&(i=h,c=Xd(r,h))}if(c===1)throw c=ji,ua(r,0),Ar(r,i),On(r,Nt()),c;if(c===6)throw Error(n(345));return r.finishedWork=r.current.alternate,r.finishedLanes=i,da(r,Mn,Zs),On(r,Nt()),null}function ef(r,i){var c=it;it|=1;try{return r(i)}finally{it=c,it===0&&(lo=Nt()+500,Jl&&xr())}}function ca(r){Cr!==null&&Cr.tag===0&&(it&6)===0&&co();var i=it;it|=1;var c=ls.transition,h=at;try{if(ls.transition=null,at=1,r)return r()}finally{at=h,ls.transition=c,it=i,(it&6)===0&&xr()}}function tf(){qn=io.current,kt(io)}function ua(r,i){r.finishedWork=null,r.finishedLanes=0;var c=r.timeoutHandle;if(c!==-1&&(r.timeoutHandle=-1,Wb(c)),Ht!==null)for(c=Ht.return;c!==null;){var h=c;switch(ud(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&Hl();break;case 3:ro(),kt(Rn),kt(hn),kd();break;case 5:bd(h);break;case 4:ro();break;case 13:kt($t);break;case 19:kt($t);break;case 10:gd(h.type._context);break;case 22:case 23:tf()}c=c.return}if(nn=r,Ht=r=$r(r.current,null),on=qn=i,Yt=0,ji=null,Jd=pc=la=0,Mn=Ni=null,aa!==null){for(i=0;i<aa.length;i++)if(c=aa[i],h=c.interleaved,h!==null){c.interleaved=null;var w=h.next,b=c.pending;if(b!==null){var A=b.next;b.next=w,h.next=A}c.pending=h}aa=null}return r}function ig(r,i){do{var c=Ht;try{if(pd(),rc.current=lc,ac){for(var h=Tt.memoizedState;h!==null;){var w=h.queue;w!==null&&(w.pending=null),h=h.next}ac=!1}if(ia=0,tn=qt=Tt=null,vi=!1,_i=0,Kd.current=null,c===null||c.return===null){Yt=1,ji=i,Ht=null;break}e:{var b=r,A=c.return,P=c,U=i;if(i=on,P.flags|=32768,U!==null&&typeof U=="object"&&typeof U.then=="function"){var re=U,pe=P,ye=pe.tag;if((pe.mode&1)===0&&(ye===0||ye===11||ye===15)){var me=pe.alternate;me?(pe.updateQueue=me.updateQueue,pe.memoizedState=me.memoizedState,pe.lanes=me.lanes):(pe.updateQueue=null,pe.memoizedState=null)}var Ce=Rp(A);if(Ce!==null){Ce.flags&=-257,Ip(Ce,A,P,b,i),Ce.mode&1&&Tp(b,re,i),i=Ce,U=re;var Ae=i.updateQueue;if(Ae===null){var Re=new Set;Re.add(U),i.updateQueue=Re}else Ae.add(U);break e}else{if((i&1)===0){Tp(b,re,i),nf();break e}U=Error(n(426))}}else if(Et&&P.mode&1){var Ft=Rp(A);if(Ft!==null){(Ft.flags&65536)===0&&(Ft.flags|=256),Ip(Ft,A,P,b,i),hd(ao(U,P));break e}}b=U=ao(U,P),Yt!==4&&(Yt=2),Ni===null?Ni=[b]:Ni.push(b),b=A;do{switch(b.tag){case 3:b.flags|=65536,i&=-i,b.lanes|=i;var X=Ap(b,U,i);np(b,X);break e;case 1:P=U;var G=b.type,ee=b.stateNode;if((b.flags&128)===0&&(typeof G.getDerivedStateFromError=="function"||ee!==null&&typeof ee.componentDidCatch=="function"&&(Nr===null||!Nr.has(ee)))){b.flags|=65536,i&=-i,b.lanes|=i;var ke=$p(b,P,i);np(b,ke);break e}}b=b.return}while(b!==null)}ug(c)}catch(Me){i=Me,Ht===c&&c!==null&&(Ht=c=c.return);continue}break}while(!0)}function lg(){var r=mc.current;return mc.current=lc,r===null?lc:r}function nf(){(Yt===0||Yt===3||Yt===2)&&(Yt=4),nn===null||(la&268435455)===0&&(pc&268435455)===0||Ar(nn,on)}function bc(r,i){var c=it;it|=2;var h=lg();(nn!==r||on!==i)&&(Zs=null,ua(r,i));do try{hx();break}catch(w){ig(r,w)}while(!0);if(pd(),it=c,mc.current=h,Ht!==null)throw Error(n(261));return nn=null,on=0,Yt}function hx(){for(;Ht!==null;)cg(Ht)}function mx(){for(;Ht!==null&&!Ou();)cg(Ht)}function cg(r){var i=hg(r.alternate,r,qn);r.memoizedProps=r.pendingProps,i===null?ug(r):Ht=i,Kd.current=null}function ug(r){var i=r;do{var c=i.alternate;if(r=i.return,(i.flags&32768)===0){if(c=ox(c,i,qn),c!==null){Ht=c;return}}else{if(c=ix(c,i),c!==null){c.flags&=32767,Ht=c;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Yt=6,Ht=null;return}}if(i=i.sibling,i!==null){Ht=i;return}Ht=i=r}while(i!==null);Yt===0&&(Yt=5)}function da(r,i,c){var h=at,w=ls.transition;try{ls.transition=null,at=1,px(r,i,c,h)}finally{ls.transition=w,at=h}return null}function px(r,i,c,h){do co();while(Cr!==null);if((it&6)!==0)throw Error(n(327));c=r.finishedWork;var w=r.finishedLanes;if(c===null)return null;if(r.finishedWork=null,r.finishedLanes=0,c===r.current)throw Error(n(177));r.callbackNode=null,r.callbackPriority=0;var b=c.lanes|c.childLanes;if(fr(r,b),r===nn&&(Ht=nn=null,on=0),(c.subtreeFlags&2064)===0&&(c.flags&2064)===0||yc||(yc=!0,mg(Ta,function(){return co(),null})),b=(c.flags&15990)!==0,(c.subtreeFlags&15990)!==0||b){b=ls.transition,ls.transition=null;var A=at;at=1;var P=it;it|=4,Kd.current=null,cx(r,c),eg(c,r),Mb(nd),za=!!td,nd=td=null,r.current=c,ux(c),Ho(),it=P,at=A,ls.transition=b}else r.current=c;if(yc&&(yc=!1,Cr=r,wc=w),b=r.pendingLanes,b===0&&(Nr=null),Ko(c.stateNode),On(r,Nt()),i!==null)for(h=r.onRecoverableError,c=0;c<i.length;c++)w=i[c],h(w.value,{componentStack:w.stack,digest:w.digest});if(gc)throw gc=!1,r=Yd,Yd=null,r;return(wc&1)!==0&&r.tag!==0&&co(),b=r.pendingLanes,(b&1)!==0?r===Qd?Ci++:(Ci=0,Qd=r):Ci=0,xr(),null}function co(){if(Cr!==null){var r=fn(wc),i=ls.transition,c=at;try{if(ls.transition=null,at=16>r?16:r,Cr===null)var h=!1;else{if(r=Cr,Cr=null,wc=0,(it&6)!==0)throw Error(n(331));var w=it;for(it|=4,Ee=r.current;Ee!==null;){var b=Ee,A=b.child;if((Ee.flags&16)!==0){var P=b.deletions;if(P!==null){for(var U=0;U<P.length;U++){var re=P[U];for(Ee=re;Ee!==null;){var pe=Ee;switch(pe.tag){case 0:case 11:case 15:Si(8,pe,b)}var ye=pe.child;if(ye!==null)ye.return=pe,Ee=ye;else for(;Ee!==null;){pe=Ee;var me=pe.sibling,Ce=pe.return;if(qp(pe),pe===re){Ee=null;break}if(me!==null){me.return=Ce,Ee=me;break}Ee=Ce}}}var Ae=b.alternate;if(Ae!==null){var Re=Ae.child;if(Re!==null){Ae.child=null;do{var Ft=Re.sibling;Re.sibling=null,Re=Ft}while(Re!==null)}}Ee=b}}if((b.subtreeFlags&2064)!==0&&A!==null)A.return=b,Ee=A;else e:for(;Ee!==null;){if(b=Ee,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:Si(9,b,b.return)}var X=b.sibling;if(X!==null){X.return=b.return,Ee=X;break e}Ee=b.return}}var G=r.current;for(Ee=G;Ee!==null;){A=Ee;var ee=A.child;if((A.subtreeFlags&2064)!==0&&ee!==null)ee.return=A,Ee=ee;else e:for(A=G;Ee!==null;){if(P=Ee,(P.flags&2048)!==0)try{switch(P.tag){case 0:case 11:case 15:hc(9,P)}}catch(Me){Mt(P,P.return,Me)}if(P===A){Ee=null;break e}var ke=P.sibling;if(ke!==null){ke.return=P.return,Ee=ke;break e}Ee=P.return}}if(it=w,xr(),Ut&&typeof Ut.onPostCommitFiberRoot=="function")try{Ut.onPostCommitFiberRoot(Es,r)}catch{}h=!0}return h}finally{at=c,ls.transition=i}}return!1}function dg(r,i,c){i=ao(c,i),i=Ap(r,i,1),r=Sr(r,i,1),i=jn(),r!==null&&(dr(r,1,i),On(r,i))}function Mt(r,i,c){if(r.tag===3)dg(r,r,c);else for(;i!==null;){if(i.tag===3){dg(i,r,c);break}else if(i.tag===1){var h=i.stateNode;if(typeof i.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(Nr===null||!Nr.has(h))){r=ao(c,r),r=$p(i,r,1),i=Sr(i,r,1),r=jn(),i!==null&&(dr(i,1,r),On(i,r));break}}i=i.return}}function gx(r,i,c){var h=r.pingCache;h!==null&&h.delete(i),i=jn(),r.pingedLanes|=r.suspendedLanes&c,nn===r&&(on&c)===c&&(Yt===4||Yt===3&&(on&130023424)===on&&500>Nt()-qd?ua(r,0):Jd|=c),On(r,i)}function fg(r,i){i===0&&((r.mode&1)===0?i=1:(i=Gr,Gr<<=1,(Gr&130023424)===0&&(Gr=4194304)));var c=jn();r=Ys(r,i),r!==null&&(dr(r,i,c),On(r,c))}function yx(r){var i=r.memoizedState,c=0;i!==null&&(c=i.retryLane),fg(r,c)}function wx(r,i){var c=0;switch(r.tag){case 13:var h=r.stateNode,w=r.memoizedState;w!==null&&(c=w.retryLane);break;case 19:h=r.stateNode;break;default:throw Error(n(314))}h!==null&&h.delete(i),fg(r,c)}var hg;hg=function(r,i,c){if(r!==null)if(r.memoizedProps!==i.pendingProps||Rn.current)Ln=!0;else{if((r.lanes&c)===0&&(i.flags&128)===0)return Ln=!1,ax(r,i,c);Ln=(r.flags&131072)!==0}else Ln=!1,Et&&(i.flags&1048576)!==0&&Hm(i,Yl,i.index);switch(i.lanes=0,i.tag){case 2:var h=i.type;dc(r,i),r=i.pendingProps;var w=Qa(i,hn.current);so(i,c),w=Nd(null,i,h,r,w,c);var b=Cd();return i.flags|=1,typeof w=="object"&&w!==null&&typeof w.render=="function"&&w.$$typeof===void 0?(i.tag=1,i.memoizedState=null,i.updateQueue=null,In(h)?(b=!0,Kl(i)):b=!1,i.memoizedState=w.state!==null&&w.state!==void 0?w.state:null,vd(i),w.updater=cc,i.stateNode=w,w._reactInternals=i,Id(i,h,r,c),i=Pd(null,i,h,!0,b,c)):(i.tag=0,Et&&b&&cd(i),Sn(null,i,w,c),i=i.child),i;case 16:h=i.elementType;e:{switch(dc(r,i),r=i.pendingProps,w=h._init,h=w(h._payload),i.type=h,w=i.tag=_x(h),r=vs(h,r),w){case 0:i=Od(null,i,h,r,c);break e;case 1:i=Fp(null,i,h,r,c);break e;case 11:i=Lp(null,i,h,r,c);break e;case 14:i=Mp(null,i,h,vs(h.type,r),c);break e}throw Error(n(306,h,""))}return i;case 0:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:vs(h,w),Od(r,i,h,w,c);case 1:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:vs(h,w),Fp(r,i,h,w,c);case 3:e:{if(zp(i),r===null)throw Error(n(387));h=i.pendingProps,b=i.memoizedState,w=b.element,tp(r,i),nc(i,h,null,c);var A=i.memoizedState;if(h=A.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:A.cache,pendingSuspenseBoundaries:A.pendingSuspenseBoundaries,transitions:A.transitions},i.updateQueue.baseState=b,i.memoizedState=b,i.flags&256){w=ao(Error(n(423)),i),i=Bp(r,i,h,c,w);break e}else if(h!==w){w=ao(Error(n(424)),i),i=Bp(r,i,h,c,w);break e}else for(Jn=vr(i.stateNode.containerInfo.firstChild),Kn=i,Et=!0,ws=null,c=Zm(i,null,h,c),i.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{if(eo(),h===w){i=Xs(r,i,c);break e}Sn(r,i,h,c)}i=i.child}return i;case 5:return rp(i),r===null&&fd(i),h=i.type,w=i.pendingProps,b=r!==null?r.memoizedProps:null,A=w.children,sd(h,w)?A=null:b!==null&&sd(h,b)&&(i.flags|=32),Dp(r,i),Sn(r,i,A,c),i.child;case 6:return r===null&&fd(i),null;case 13:return Wp(r,i,c);case 4:return _d(i,i.stateNode.containerInfo),h=i.pendingProps,r===null?i.child=to(i,null,h,c):Sn(r,i,h,c),i.child;case 11:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:vs(h,w),Lp(r,i,h,w,c);case 7:return Sn(r,i,i.pendingProps,c),i.child;case 8:return Sn(r,i,i.pendingProps.children,c),i.child;case 12:return Sn(r,i,i.pendingProps.children,c),i.child;case 10:e:{if(h=i.type._context,w=i.pendingProps,b=i.memoizedProps,A=w.value,vt(Zl,h._currentValue),h._currentValue=A,b!==null)if(ys(b.value,A)){if(b.children===w.children&&!Rn.current){i=Xs(r,i,c);break e}}else for(b=i.child,b!==null&&(b.return=i);b!==null;){var P=b.dependencies;if(P!==null){A=b.child;for(var U=P.firstContext;U!==null;){if(U.context===h){if(b.tag===1){U=Qs(-1,c&-c),U.tag=2;var re=b.updateQueue;if(re!==null){re=re.shared;var pe=re.pending;pe===null?U.next=U:(U.next=pe.next,pe.next=U),re.pending=U}}b.lanes|=c,U=b.alternate,U!==null&&(U.lanes|=c),yd(b.return,c,i),P.lanes|=c;break}U=U.next}}else if(b.tag===10)A=b.type===i.type?null:b.child;else if(b.tag===18){if(A=b.return,A===null)throw Error(n(341));A.lanes|=c,P=A.alternate,P!==null&&(P.lanes|=c),yd(A,c,i),A=b.sibling}else A=b.child;if(A!==null)A.return=b;else for(A=b;A!==null;){if(A===i){A=null;break}if(b=A.sibling,b!==null){b.return=A.return,A=b;break}A=A.return}b=A}Sn(r,i,w.children,c),i=i.child}return i;case 9:return w=i.type,h=i.pendingProps.children,so(i,c),w=os(w),h=h(w),i.flags|=1,Sn(r,i,h,c),i.child;case 14:return h=i.type,w=vs(h,i.pendingProps),w=vs(h.type,w),Mp(r,i,h,w,c);case 15:return Op(r,i,i.type,i.pendingProps,c);case 17:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:vs(h,w),dc(r,i),i.tag=1,In(h)?(r=!0,Kl(i)):r=!1,so(i,c),Cp(i,h,w),Id(i,h,w,c),Pd(null,i,h,!0,r,c);case 19:return Vp(r,i,c);case 22:return Pp(r,i,c)}throw Error(n(156,i.tag))};function mg(r,i){return Ea(r,i)}function vx(r,i,c,h){this.tag=r,this.key=c,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=i,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=h,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function cs(r,i,c,h){return new vx(r,i,c,h)}function sf(r){return r=r.prototype,!(!r||!r.isReactComponent)}function _x(r){if(typeof r=="function")return sf(r)?1:0;if(r!=null){if(r=r.$$typeof,r===ie)return 11;if(r===M)return 14}return 2}function $r(r,i){var c=r.alternate;return c===null?(c=cs(r.tag,i,r.key,r.mode),c.elementType=r.elementType,c.type=r.type,c.stateNode=r.stateNode,c.alternate=r,r.alternate=c):(c.pendingProps=i,c.type=r.type,c.flags=0,c.subtreeFlags=0,c.deletions=null),c.flags=r.flags&14680064,c.childLanes=r.childLanes,c.lanes=r.lanes,c.child=r.child,c.memoizedProps=r.memoizedProps,c.memoizedState=r.memoizedState,c.updateQueue=r.updateQueue,i=r.dependencies,c.dependencies=i===null?null:{lanes:i.lanes,firstContext:i.firstContext},c.sibling=r.sibling,c.index=r.index,c.ref=r.ref,c}function xc(r,i,c,h,w,b){var A=2;if(h=r,typeof r=="function")sf(r)&&(A=1);else if(typeof r=="string")A=5;else e:switch(r){case I:return fa(c.children,w,b,i);case L:A=8,w|=8;break;case z:return r=cs(12,c,i,w|2),r.elementType=z,r.lanes=b,r;case F:return r=cs(13,c,i,w),r.elementType=F,r.lanes=b,r;case D:return r=cs(19,c,i,w),r.elementType=D,r.lanes=b,r;case B:return kc(c,w,b,i);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case V:A=10;break e;case Z:A=9;break e;case ie:A=11;break e;case M:A=14;break e;case J:A=16,h=null;break e}throw Error(n(130,r==null?r:typeof r,""))}return i=cs(A,c,i,w),i.elementType=r,i.type=h,i.lanes=b,i}function fa(r,i,c,h){return r=cs(7,r,h,i),r.lanes=c,r}function kc(r,i,c,h){return r=cs(22,r,h,i),r.elementType=B,r.lanes=c,r.stateNode={isHidden:!1},r}function rf(r,i,c){return r=cs(6,r,null,i),r.lanes=c,r}function af(r,i,c){return i=cs(4,r.children!==null?r.children:[],r.key,i),i.lanes=c,i.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},i}function bx(r,i,c,h,w){this.tag=i,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vn(0),this.expirationTimes=Vn(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vn(0),this.identifierPrefix=h,this.onRecoverableError=w,this.mutableSourceEagerHydrationData=null}function of(r,i,c,h,w,b,A,P,U){return r=new bx(r,i,c,P,U),i===1?(i=1,b===!0&&(i|=8)):i=0,b=cs(3,null,null,i),r.current=b,b.stateNode=r,b.memoizedState={element:h,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null},vd(b),r}function xx(r,i,c){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:j,key:h==null?null:""+h,children:r,containerInfo:i,implementation:c}}function pg(r){if(!r)return br;r=r._reactInternals;e:{if(Ns(r)!==r||r.tag!==1)throw Error(n(170));var i=r;do{switch(i.tag){case 3:i=i.stateNode.context;break e;case 1:if(In(i.type)){i=i.stateNode.__reactInternalMemoizedMergedChildContext;break e}}i=i.return}while(i!==null);throw Error(n(171))}if(r.tag===1){var c=r.type;if(In(c))return Um(r,c,i)}return i}function gg(r,i,c,h,w,b,A,P,U){return r=of(c,h,!0,r,w,b,A,P,U),r.context=pg(null),c=r.current,h=jn(),w=Er(c),b=Qs(h,w),b.callback=i??null,Sr(c,b,w),r.current.lanes=w,dr(r,w,h),On(r,h),r}function Sc(r,i,c,h){var w=i.current,b=jn(),A=Er(w);return c=pg(c),i.context===null?i.context=c:i.pendingContext=c,i=Qs(b,A),i.payload={element:r},h=h===void 0?null:h,h!==null&&(i.callback=h),r=Sr(w,i,A),r!==null&&(xs(r,w,A,b),tc(r,w,A)),A}function jc(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function yg(r,i){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var c=r.retryLane;r.retryLane=c!==0&&c<i?c:i}}function lf(r,i){yg(r,i),(r=r.alternate)&&yg(r,i)}function kx(){return null}var wg=typeof reportError=="function"?reportError:function(r){console.error(r)};function cf(r){this._internalRoot=r}Nc.prototype.render=cf.prototype.render=function(r){var i=this._internalRoot;if(i===null)throw Error(n(409));Sc(r,i,null,null)},Nc.prototype.unmount=cf.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var i=r.containerInfo;ca(function(){Sc(null,r,null,null)}),i[Hs]=null}};function Nc(r){this._internalRoot=r}Nc.prototype.unstable_scheduleHydration=function(r){if(r){var i=Pa();r={blockedOn:null,target:r,priority:i};for(var c=0;c<Ct.length&&i!==0&&i<Ct[c].priority;c++);Ct.splice(c,0,r),c===0&&Da(r)}};function uf(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Cc(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function vg(){}function Sx(r,i,c,h,w){if(w){if(typeof h=="function"){var b=h;h=function(){var re=jc(A);b.call(re)}}var A=gg(i,h,r,0,null,!1,!1,"",vg);return r._reactRootContainer=A,r[Hs]=A.current,di(r.nodeType===8?r.parentNode:r),ca(),A}for(;w=r.lastChild;)r.removeChild(w);if(typeof h=="function"){var P=h;h=function(){var re=jc(U);P.call(re)}}var U=of(r,0,!1,null,null,!1,!1,"",vg);return r._reactRootContainer=U,r[Hs]=U.current,di(r.nodeType===8?r.parentNode:r),ca(function(){Sc(i,U,c,h)}),U}function Ec(r,i,c,h,w){var b=c._reactRootContainer;if(b){var A=b;if(typeof w=="function"){var P=w;w=function(){var U=jc(A);P.call(U)}}Sc(i,A,r,w)}else A=Sx(c,i,r,w,h);return jc(A)}Hr=function(r){switch(r.tag){case 3:var i=r.stateNode;if(i.current.memoizedState.isDehydrated){var c=dn(i.pendingLanes);c!==0&&(Ws(i,c|1),On(i,Nt()),(it&6)===0&&(lo=Nt()+500,xr()))}break;case 13:ca(function(){var h=Ys(r,1);if(h!==null){var w=jn();xs(h,r,1,w)}}),lf(r,1)}},Ma=function(r){if(r.tag===13){var i=Ys(r,134217728);if(i!==null){var c=jn();xs(i,r,134217728,c)}lf(r,134217728)}},Oa=function(r){if(r.tag===13){var i=Er(r),c=Ys(r,i);if(c!==null){var h=jn();xs(c,r,i,h)}lf(r,i)}},Pa=function(){return at},qo=function(r,i){var c=at;try{return at=r,i()}finally{at=c}},Fo=function(r,i,c){switch(i){case"input":if(st(r,c),i=c.name,c.type==="radio"&&i!=null){for(c=r;c.parentNode;)c=c.parentNode;for(c=c.querySelectorAll("input[name="+JSON.stringify(""+i)+'][type="radio"]'),i=0;i<c.length;i++){var h=c[i];if(h!==r&&h.form===r.form){var w=Gl(h);if(!w)throw Error(n(90));Qe(h),st(h,w)}}}break;case"textarea":he(r,c);break;case"select":i=c.value,i!=null&&fe(r,!!c.multiple,i,!1)}},zo=ef,ir=ca;var jx={usingClientEntryPoint:!1,Events:[mi,qa,Gl,Zt,ja,ef]},Ei={findFiberByHostInstance:ta,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Nx={bundleType:Ei.bundleType,version:Ei.version,rendererPackageName:Ei.rendererPackageName,rendererConfig:Ei.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:N.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=Xn(r),r===null?null:r.stateNode},findFiberByHostInstance:Ei.findFiberByHostInstance||kx,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 Ac=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ac.isDisabled&&Ac.supportsFiber)try{Es=Ac.inject(Nx),Ut=Ac}catch{}}return Pn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=jx,Pn.createPortal=function(r,i){var c=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!uf(i))throw Error(n(200));return xx(r,i,null,c)},Pn.createRoot=function(r,i){if(!uf(r))throw Error(n(299));var c=!1,h="",w=wg;return i!=null&&(i.unstable_strictMode===!0&&(c=!0),i.identifierPrefix!==void 0&&(h=i.identifierPrefix),i.onRecoverableError!==void 0&&(w=i.onRecoverableError)),i=of(r,1,!1,null,null,c,!1,h,w),r[Hs]=i.current,di(r.nodeType===8?r.parentNode:r),new cf(i)},Pn.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var i=r._reactInternals;if(i===void 0)throw typeof r.render=="function"?Error(n(188)):(r=Object.keys(r).join(","),Error(n(268,r)));return r=Xn(i),r=r===null?null:r.stateNode,r},Pn.flushSync=function(r){return ca(r)},Pn.hydrate=function(r,i,c){if(!Cc(i))throw Error(n(200));return Ec(null,r,i,!0,c)},Pn.hydrateRoot=function(r,i,c){if(!uf(r))throw Error(n(405));var h=c!=null&&c.hydratedSources||null,w=!1,b="",A=wg;if(c!=null&&(c.unstable_strictMode===!0&&(w=!0),c.identifierPrefix!==void 0&&(b=c.identifierPrefix),c.onRecoverableError!==void 0&&(A=c.onRecoverableError)),i=gg(i,null,r,1,c??null,w,!1,b,A),r[Hs]=i.current,di(r),h)for(r=0;r<h.length;r++)c=h[r],w=c._getVersion,w=w(c._source),i.mutableSourceEagerHydrationData==null?i.mutableSourceEagerHydrationData=[c,w]:i.mutableSourceEagerHydrationData.push(c,w);return new Nc(i)},Pn.render=function(r,i,c){if(!Cc(i))throw Error(n(200));return Ec(null,r,i,!1,c)},Pn.unmountComponentAtNode=function(r){if(!Cc(r))throw Error(n(40));return r._reactRootContainer?(ca(function(){Ec(null,null,r,!1,function(){r._reactRootContainer=null,r[Hs]=null})}),!0):!1},Pn.unstable_batchedUpdates=ef,Pn.unstable_renderSubtreeIntoContainer=function(r,i,c,h){if(!Cc(c))throw Error(n(200));if(r==null||r._reactInternals===void 0)throw Error(n(38));return Ec(r,i,c,!1,h)},Pn.version="18.3.1-next-f1338f8080-20240426",Pn}var Cg;function bw(){if(Cg)return hf.exports;Cg=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(),hf.exports=Mx(),hf.exports}var Eg;function Ox(){if(Eg)return $c;Eg=1;var e=bw();return $c.createRoot=e.createRoot,$c.hydrateRoot=e.hydrateRoot,$c}var Px=Ox();const Dx=_w(Px),xw=[{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"]}];xw.map(e=>({id:e.id,label:e.label}));function Fx(e){return`theme-${String(e||"").trim()||"dark"}`}function Ag(e){try{const t=document.documentElement,n=Array.from(t.classList).filter(s=>s.startsWith("theme-"));for(const s of n)t.classList.remove(s);t.classList.add(Fx(e))}catch{}}const sh=[{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}],rh=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function zx(e){const t=String(e).trim();return sh.find(n=>n.id===t)||sh[1]}function Bx(e){const t=String(e).trim();return rh.find(n=>n.id===t)||rh[1]}function $g(e){try{const t=document.documentElement,n=zx(e.font_scale||"md"),s=Bx(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(s.density))}catch{}}const Gc={md:"(max-width: 1023.98px)",lg:"(max-width: 1439.98px)"};function Wx(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function Hc(e){const[t,n]=y.useState(()=>Wx(e));return y.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const s=window.matchMedia(e),o=()=>n(s.matches);return o(),typeof s.addEventListener=="function"?s.addEventListener("change",o):s.addListener(o),()=>{typeof s.removeEventListener=="function"?s.removeEventListener("change",o):s.removeListener(o)}},[e]),t}let $i=null;function Ux(e,t){const n=Math.max(0,Math.round(e));if(!(t.scale<=1.01))return{vvHeight:n,keyboardInset:0};const s=Math.max(0,Math.min(n,Math.round(t.height))),o=Math.max(0,Math.round(e-t.height-Math.max(0,t.offsetTop)));return{vvHeight:s,keyboardInset:o}}function Vx(){if($i)return $i;if(typeof window>"u"||typeof document>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};const t=document.documentElement;let n=0;const s=()=>{n=0;const{vvHeight:l,keyboardInset:u}=Ux(window.innerHeight,{height:e.height,offsetTop:e.offsetTop,scale:e.scale||1});t.style.setProperty("--vv-height",`${l}px`),t.style.setProperty("--keyboard-inset",`${u}px`)},o=()=>{n||(n=window.requestAnimationFrame(s))};return s(),e.addEventListener("resize",o),e.addEventListener("scroll",o),window.addEventListener("orientationchange",o),$i=()=>{e.removeEventListener("resize",o),e.removeEventListener("scroll",o),window.removeEventListener("orientationchange",o),n&&window.cancelAnimationFrame(n),t.style.removeProperty("--vv-height"),t.style.removeProperty("--keyboard-inset"),$i=null},$i}var il=bw();function uo(...e){return e.filter(Boolean).join(" ")}function bn({value:e,options:t,placeholder:n="Select…",disabled:s=!1,loading:o=!1,searchable:l=!0,searchPlaceholder:u="Search…",allowCustom:d=!1,clearable:f=!1,minPopoverWidth:m=240,variant:p="panel",className:g,triggerClassName:_,ariaLabel:v,id:C,includeValueOption:x=!1,onOpen:k,customOptionLabel:S,validateCustomValue:$,onChange:R,renderOption:N,renderValue:E}){const j=y.useRef(null),I=y.useRef(null),L=y.useRef(null),z=y.useRef(k),V=y.useId(),Z=C||`af-select-${V.replace(/[^a-zA-Z0-9_-]/g,"")}`,ie=`${Z}-listbox`,[F,D]=y.useState(!1),[M,J]=y.useState(""),[B,Y]=y.useState(0),[te,W]=y.useState("bottom"),[T,K]=y.useState({left:0,top:0,width:0});y.useEffect(()=>{z.current=k},[k]);const ne=y.useMemo(()=>{if(!x)return t;const ce=String(e??"").trim();return!ce||t.some(fe=>fe.value===ce)?t:[...t,{value:ce,label:ce}]},[x,t,e]),ue=y.useMemo(()=>{const ce=String(e??"");return ne.find(fe=>fe.value===ce)||null},[ne,e]),oe=y.useMemo(()=>(ue==null?void 0:ue.label)||String(e||"").trim()||"",[ue,e]),ve=y.useMemo(()=>{const ce=M.trim().toLowerCase();return ce?ne.filter(fe=>fe.label.toLowerCase().includes(ce)||fe.value.toLowerCase().includes(ce)):ne},[ne,M]),Ne=y.useMemo(()=>{if(!d)return null;const ce=M.trim();if(!ce||ne.some(le=>le.value===ce))return null;const H=($==null?void 0:$(ce,{options:ne}))||"";return{value:ce,label:S?S(ce):`Use "${ce}"`,disabled:!!H,reason:H}},[d,S,ne,M,$]),q=y.useMemo(()=>{const ce=Ne?[Ne,...ve]:ve;if(ce.length>0)return ce;const fe=String(e??"").trim();return o&&fe?[{value:fe,label:oe||fe}]:ce},[Ne,ve,o,oe,e]),be=y.useCallback(()=>{const ce=j.current;if(!ce)return;const fe=ce.getBoundingClientRect(),H=Math.max(fe.width,m),le=Math.max(8,Math.min(fe.left,window.innerWidth-H-8)),he=window.innerHeight-fe.bottom,Q=fe.top,_e=he>=220||he>=Q?"bottom":"top";W(_e);const ae=_e==="bottom"?fe.bottom+6:fe.top-6;K({left:le,top:ae,width:H})},[m]),xe=y.useCallback(()=>{D(!1),J("")},[]);y.useEffect(()=>{var ce;F&&((ce=z.current)==null||ce.call(z))},[F]),y.useEffect(()=>{if(!F)return;be();const ce=()=>be();return window.addEventListener("resize",ce),window.addEventListener("scroll",ce,!0),()=>{window.removeEventListener("resize",ce),window.removeEventListener("scroll",ce,!0)}},[F,be]),y.useEffect(()=>{if(!F)return;const ce=fe=>{var le,he;const H=fe.target;H&&((le=j.current)!=null&&le.contains(H)||(he=I.current)!=null&&he.contains(H)||xe())};return document.addEventListener("mousedown",ce,!0),()=>document.removeEventListener("mousedown",ce,!0)},[F,xe]),y.useEffect(()=>{if(!F)return;const ce=Math.max(0,q.findIndex(fe=>fe.value===e));Y(ce===-1?0:ce),l&&setTimeout(()=>{var fe;return(fe=L.current)==null?void 0:fe.focus()},0)},[F,l,e,q]);const Pe=ce=>{var H;const fe=q.find(le=>le.value===ce);fe!=null&&fe.disabled||(R(ce),xe(),(H=j.current)==null||H.focus())},Qe=ce=>{var fe,H;if(ce.key==="Escape")return ce.preventDefault(),xe(),(fe=j.current)==null||fe.focus(),!0;if(ce.key==="Tab")return xe(),(H=j.current)==null||H.focus(),!1;if(ce.key==="ArrowDown")return ce.preventDefault(),Y(le=>Math.min(le+1,Math.max(0,q.length-1))),!0;if(ce.key==="ArrowUp")return ce.preventDefault(),Y(le=>Math.max(le-1,0)),!0;if(ce.key==="Home")return ce.preventDefault(),Y(0),!0;if(ce.key==="End")return ce.preventDefault(),Y(Math.max(0,q.length-1)),!0;if(ce.key==="Enter"){ce.preventDefault();const le=q[B];return le&&Pe(le.value),!0}return!1},He=ce=>{if(!s){if(F){if(Qe(ce))return;if(ce.key===" "&&!l){ce.preventDefault();const fe=q[B];fe&&Pe(fe.value)}return}(ce.key==="Enter"||ce.key===" "||ce.key==="ArrowDown"||ce.key==="ArrowUp")&&(ce.preventDefault(),D(!0))}},qe=!!String(e||"").trim(),ge=qe?oe:n,$e=Ne!=null&&Ne.disabled?Ne.reason||"Unavailable":"",st=F&&q.length>0?`${Z}-opt-${B}`:void 0,tt=a.jsx("span",{className:uo("af-select-value",!qe&&"af-select-value--placeholder"),children:o&&!qe?"Loading…":ge}),Lt=E?E(ue,String(e||"")):tt;return a.jsxs("span",{className:uo("af-select",p==="pin"?"af-select--pin":"af-select--panel",g),children:[a.jsxs("button",{ref:j,id:Z,type:"button",className:uo("af-select-trigger",f&&qe&&"af-select-trigger--clearable",_),disabled:s,onMouseDown:ce=>ce.stopPropagation(),onClick:ce=>{ce.stopPropagation(),!s&&D(fe=>!fe)},onKeyDown:He,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":F,"aria-controls":F?ie:void 0,"aria-activedescendant":l?void 0:st,"aria-label":v,children:[Lt,a.jsx("span",{className:uo("af-select-caret",F&&"af-select-caret--open"),children:"▾"})]}),f&&qe?a.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:s,onMouseDown:ce=>{ce.preventDefault(),ce.stopPropagation()},onClick:ce=>{var fe;ce.preventDefault(),ce.stopPropagation(),R(""),xe(),(fe=j.current)==null||fe.focus()},title:"Clear",children:"×"}):null,F?il.createPortal(a.jsxs("div",{ref:I,className:uo("af-select-popover",te==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${T.left}px`,top:`${T.top}px`,width:`${T.width}px`},onMouseDown:ce=>ce.stopPropagation(),onClick:ce=>ce.stopPropagation(),onWheel:ce=>ce.stopPropagation(),onKeyDown:Qe,tabIndex:-1,children:[l?a.jsxs("div",{className:"af-select-search",children:[a.jsx("input",{ref:L,className:"af-select-search-input",value:M,onChange:ce=>J(ce.target.value),placeholder:u,onKeyDown:Qe,role:"combobox","aria-expanded":!0,"aria-controls":ie,"aria-activedescendant":st,"aria-invalid":!!$e,"aria-describedby":$e?`${Z}-custom-error`:void 0}),$e?a.jsx("div",{id:`${Z}-custom-error`,className:"af-select-custom-error",role:"alert",children:$e}):null]}):null,a.jsx("div",{className:"af-select-options",role:"listbox",id:ie,"aria-label":v,children:o&&q.length===0?a.jsx("div",{className:"af-select-empty",children:"Loading…"}):q.length===0?a.jsx("div",{className:"af-select-empty",children:"No results"}):q.map((ce,fe)=>{var ae;const H=ce.value===e,le=fe===B,he=String(ce.group||"").trim(),Q=fe>0?String(((ae=q[fe-1])==null?void 0:ae.group)||"").trim():"",_e=!!he&&he!==Q;return a.jsxs(yt.Fragment,{children:[_e?a.jsx("div",{className:"af-select-group",role:"presentation",children:he}):null,a.jsx("div",{id:`${Z}-opt-${fe}`,role:"option","aria-selected":H,className:uo("af-select-option",H&&"af-select-option--selected",le&&"af-select-option--highlighted",ce.disabled&&"af-select-option--disabled"),title:ce.disabled?ce.reason||"Unavailable":void 0,onMouseEnter:()=>Y(fe),onMouseDown:Se=>{Se.preventDefault(),Se.stopPropagation()},onClick:()=>Pe(ce.value),"aria-disabled":ce.disabled?!0:void 0,children:N?N(ce,{selected:H,highlighted:le}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"af-select-option-label",children:[a.jsx("span",{children:ce.label}),ce.reason?a.jsx("small",{className:"af-select-option-reason",children:ce.reason}):null]}),H?a.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},ce.value)})})]}),document.body):null]})}function Gx(e){const t=new Set,n=[];for(const s of e||[]){if(!s||typeof s!="object")continue;const o=String(s.name||"").trim();!o||t.has(o)||(t.add(o),n.push({name:o,display_name:typeof s.display_name=="string"?s.display_name:void 0}))}return n.sort((s,o)=>s.name.localeCompare(o.name)),n}function Hx(e){const t=new Set,n=[];for(const s of e||[]){const o=String(s||"").trim();!o||t.has(o)||(t.add(o),n.push(o))}return n.sort(),n}const ah="Provided by connected pin";function Kx(e){const t=e.disabled===!0,n=e.layout||"stack",s=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=String(e.providerLabel||"Provider"),u=String(e.modelLabel||"Model"),d=String(e.providerPlaceholder||"(select)"),f=String(e.modelPlaceholder||"(select)"),m=String(e.provider||"").trim(),p=String(e.model||"").trim(),g=Gx(e.providers),_=Hx(e.models),v=typeof e.markSaved=="object"?e.markSaved:null,C=(N,E,j,I)=>e.markSaved&&!j&&!I&&(!v||v[E]===N)?`${N} (saved)`:N,x=t||!!e.loadingProviders,k=t||!!e.loadingModels,S=[...s?[{value:"",label:o}]:[],...g.map(N=>({value:N.name,label:N.display_name?`${N.display_name} (${N.name})`:N.name})),...e.markSaved&&m&&!g.some(N=>N.name===m)?[{value:m,label:C(m,"provider",e.loadingProviders,e.providerError)}]:[]],$=[...s?[{value:"",label:o}]:[],..._.map(N=>{var E;return{value:N,label:((E=e.modelDisplayNames)==null?void 0:E[N])||N}}),...e.markSaved&&p&&!_.includes(p)?[{value:p,label:C(p,"model",e.loadingModels,e.modelError)}]:[]],R=(N,E)=>a.jsxs("div",{className:"af-pmp__pinned","data-pinned":N,children:[a.jsx("span",{className:"af-pmp__pinned-text",children:ah}),E?a.jsxs("span",{className:"mono muted",children:[" · ",E]}):null]});return a.jsxs("div",{className:e.className,style:n==="row"?{display:"flex",gap:"10px",flexWrap:"wrap",alignItems:"flex-start"}:{display:"flex",flexDirection:"column",gap:"10px"},children:[a.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[a.jsx("label",{children:l}),e.providerPinned?R("provider",m):a.jsx(bn,{value:m,options:S,placeholder:s?o:d,disabled:x,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:s,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:l,onChange:N=>e.onChange({provider:String(N||"").trim(),model:""})}),e.loadingProviders?a.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading providers…"}):null,e.providerError?a.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.providerError}):null]}),a.jsxs("div",{style:n==="row"?{flex:"1 1 260px",minWidth:240}:void 0,children:[a.jsx("label",{children:u}),e.modelPinned?R("model",p):a.jsx(bn,{value:p,options:$,placeholder:s?o:f,disabled:k,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:s,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:u,onChange:N=>e.onChange({provider:m,model:String(N||"").trim()})}),e.loadingModels?a.jsx("div",{className:"mono muted",style:{fontSize:"12px",marginTop:"6px"},children:"Loading models…"}):null,e.modelError?a.jsx("div",{className:"mono",style:{color:"var(--error)",fontSize:"12px",marginTop:"6px"},children:e.modelError}):null]})]})}function Fh(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 Jx(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(s=>typeof s=="number"&&Number.isInteger(s)&&s>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 Tg(e){const t=Fh(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function qx(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 Yx(e){const t=Jx(e.capabilities),n=Tg(e.value),s=(t==null?void 0:t.supported_depths.map(String))||[],o=Tg(t==null?void 0:t.default),l=e.inheritLabel||"Workflow / Gateway default",u=o?`${l} (${o==="off"?"Off":`depth ${o}`})`:l,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 a.jsxs("div",{className:"af-pmp__speculation",children:[a.jsx("label",{children:"MTP depth"}),a.jsx(bn,{ariaLabel:"MTP depth",value:n,placeholder:u,disabled:e.disabled||e.loading,options:[{value:"",label:u},{value:"off",label:"Off"},...s.map(f=>({value:f,label:`Depth ${f}`})),...n&&n!=="off"&&!s.includes(n)?[{value:n,label:`Depth ${n} (saved)`}]:[]],onChange:f=>e.onChange(qx(f))}),d&&!e.hideNote?a.jsx("div",{role:"status",className:"af-pmp__hint",children:d}):null]})}const Br="api/gateway",ll="api/connection/gateway";function we(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?`${Br}/${t}`:Br}function ut(e,t){const n=String(t||"");if(n.startsWith("/"))throw new Error(`joinBaseUrl takes a relative path, got ${JSON.stringify(n)}.`);let s=String(e??"");for(;s.endsWith("/");)s=s.slice(0,-1);return s?`${s}/${n}`:n}function Qx(e){const t=String(e||""),n=`/${Br}/`;if(!t.startsWith(n)||t.length===n.length)throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (expected ${JSON.stringify(n)}…).`);const s=t.slice(n.length).split(/[?#]/,1)[0];if(/\\|%2f|%5c/i.test(s))throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (encoded slash or backslash).`);for(const o of s.split("/")){const l=o.replace(/%2e/gi,".");if(l==="."||l==="..")throw new Error(`Not a gateway API path: ${JSON.stringify(t)} (a "." or ".." segment).`)}return t.slice(1)}const Xx=(e,t)=>{const n=String(e||"");if(!n)throw new Error(`A voice route needs a ${t}.`);return encodeURIComponent(n)},Zx={clones:"voice/clones"};function oh(e){return`voice/clones/${Xx(e,"voice id")}`}function ek(e){return`${oh(e)}/deploy`}const kw="discovery/providers",tk="discovery/models/capabilities",nk="config/capability-defaults",sk="discovery/capabilities";function rk(e){const t=String(e||"").trim();if(!t)throw new Error("gatewayProviderModelsRoute needs a provider.");return`${kw}/${encodeURIComponent(t)}/models`}const Sw=/^(?!\.+$)[A-Za-z0-9_.:-]{1,256}$/;function ak(e){const t=String(e??"");if(!Sw.test(t))throw new Error(`A session id is 1-256 characters [A-Za-z0-9_.:-], not only dots, got ${JSON.stringify(t)}.`);return`sessions/${t}/tool-policy`}const wn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,Rt=e=>typeof e=="string"?e.trim():"";function jw(e){var p,g;const t=wn(e);if((t==null?void 0:t.ok)===!1){const _=Array.isArray(t.errors)?t.errors.map(Rt).filter(Boolean):[];throw new Error(_.length?_.join("; "):"The gateway could not read its capability defaults.")}const n=t==null?void 0:t.routes;if(!Array.isArray(n))throw new Error("The gateway's capability defaults have no routes.");const s=_=>n.map(wn).find(v=>v&&Rt(v.key)===_&&Rt(v.source)!=="not_configured"),o=s("output.text"),l=s("input.text"),u=[o,l].find(_=>_&&Rt(_.provider)&&Rt(_.model));if(!u)return null;const d=Rt(o==null?void 0:o.reasoning)||Rt(l==null?void 0:l.reasoning),f=Fh(((p=wn(l==null?void 0:l.options))==null?void 0:p.speculation)??((g=wn(o==null?void 0:o.options))==null?void 0:g.speculation)),m=Array.isArray(t==null?void 0:t.warnings)?t.warnings.map(Rt).filter(Boolean):[];return{provider:Rt(u.provider),model:Rt(u.model),...d?{reasoning:d}:{},...f!==void 0?{speculation:f}:{},...Rt(u.source)?{source:Rt(u.source)}:{},...m.length?{warnings:m}:{}}}function ok(e){if(!e)return"";const t=[`${e.provider} / ${e.model}`];return e.reasoning&&t.push(`reasoning ${e.reasoning}`),e.speculation===!1?t.push("MTP off"):e.speculation&&t.push(`MTP depth ${e.speculation.num_draft_tokens}`),t.join(" · ")}function ik(e,t="Gateway default"){const n=ok(e);return n?`${t} · ${n}`:t}function lk(e){var s,o,l,u,d,f;const t=wn((s=wn(e))==null?void 0:s.capabilities)??wn(e),n=(f=wn((d=wn((u=wn((l=wn((o=wn(t==null?void 0:t.contracts))==null?void 0:o.common))==null?void 0:l.runs))==null?void 0:u.start))==null?void 0:d.thinking_control))==null?void 0:f.values;return Array.isArray(n)?[...new Set(n.map(Rt).filter(Boolean))]:[]}function ck(e){if(typeof e=="string")return e.trim()?{name:e.trim()}:null;const t=wn(e),n=Rt(t==null?void 0:t.id)||Rt(t==null?void 0:t.provider)||Rt(t==null?void 0:t.name);if(!n)return null;const s=Rt(t==null?void 0:t.label)||Rt(t==null?void 0:t.display_name);return s&&s!==n?{name:n,display_name:s}:{name:n}}function uk(e){return{async fetchProviders(){const t=wn(await e(we(`${kw}?include_models=false`))),n=Array.isArray(t==null?void 0:t.items)?t.items.map(ck).filter(s=>!!s):[];if(!n.length&&Rt(t==null?void 0:t.error))throw new Error(Rt(t==null?void 0:t.error));return n},async fetchModels(t){const n=wn(await e(we(`${rk(t)}?capability_route=output.text`))),s=Array.isArray(n==null?void 0:n.models)?n.models:Array.isArray(n==null?void 0:n.items)?n.items:[],o=[...new Set(s.map(l=>{var u;return typeof l=="string"?l.trim():Rt((u=wn(l))==null?void 0:u.id)}).filter(Boolean))];if(!o.length&&Rt(n==null?void 0:n.error))throw new Error(Rt(n==null?void 0:n.error));return o},async fetchModelCapabilities(t,n){const s=new URLSearchParams({model_name:t});return n&&s.set("provider",n),e(we(`${tk}?${s.toString()}`))},async fetchGatewayDefault(){return jw(await e(we(nk)))},async fetchReasoningLadder(){return lk(await e(we(sk)))}}}const dk="The gateway does not say which reasoning levels this model supports.",fk="Set anyway",hk="Reasoning and MTP choices appear when the gateway can describe the selected model.",mk="Reasoning choices appear when the gateway can describe the selected model.";function _u(e){const t=e.disabled===!0,n=e.value||{provider:"",model:""},s=!String(n.provider||"").trim()&&!String(n.model||"").trim(),o=e.layout==="compact",l=e.pinned||{},u=!!(l.provider||l.model),[d,f]=y.useState(!s),m=o||u||!(s&&!d),p=s&&(o||u||!d),g=y.useRef(s);y.useEffect(()=>{s&&!g.current&&f(!1),g.current=s},[s]);const[_,v]=y.useState([]),[C,x]=y.useState(!1),[k,S]=y.useState(""),[$,R]=y.useState([]),[N,E]=y.useState({}),[j,I]=y.useState(!1),[L,z]=y.useState(""),V=y.useRef(e);V.current=e;const[Z,ie]=y.useState({status:"idle",value:null,message:""}),F=e.fetchGatewayDefault;y.useEffect(()=>{if(!F||t)return;let fe=!0;const H=le=>ie(he=>JSON.stringify(he)===JSON.stringify(le)?he:le);return ie(le=>le.status==="idle"?{...le,status:"loading"}:le),F().then(le=>{var he;fe&&(le?(he=le.warnings)!=null&&he.length?H({status:"unusable",value:le,message:le.warnings.join(" ")}):H({status:"resolved",value:le,message:""}):H({status:"none",value:null,message:""}))}).catch(le=>{fe&&H({status:"error",value:null,message:String((le==null?void 0:le.message)||le)})}),()=>{fe=!1}},[F,t]);const D=Z.status==="resolved"?Z.value:null,M=y.useRef({provider:String(n.provider||"").trim(),model:String(n.model||"").trim()});y.useEffect(()=>{if(!m||l.provider||t)return;let fe=!0;return x(!0),(async()=>{try{const H=await V.current.fetchProviders();if(!fe)return;v(Array.isArray(H)?H:[]),S("")}catch(H){if(!fe)return;v([]),S(`#FALLBACK provider discovery failed: ${String((H==null?void 0:H.message)||H)}`)}finally{fe&&x(!1)}})(),()=>{fe=!1}},[m,l.provider,t]);const J=String(n.provider||"").trim();y.useEffect(()=>{if(!J||t||l.model){R([]),z(""),I(!1);return}let fe=!0;return R([]),I(!0),z(""),(async()=>{try{const H=await V.current.fetchModels(J);if(!fe)return;const le=[],he={};for(const Q of Array.isArray(H)?H:[]){const _e=typeof Q=="string"?Q:String((Q==null?void 0:Q.id)||"");_e&&(le.push(_e),typeof Q!="string"&&(Q!=null&&Q.label)&&Q.label!==_e&&(he[_e]=String(Q.label)))}R(le),E(he)}catch(H){if(!fe)return;R([]),z(`#FALLBACK model discovery failed: ${String((H==null?void 0:H.message)||H)}`)}finally{fe&&I(!1)}})(),()=>{fe=!1}},[J,t,l.model]);const B=String(n.model||"").trim(),Y=e.defaultModeLabel||"Gateway default",te=Z.status==="none"?`${Y} · none configured`:ik(D,Y),W=e.customModeLabel||"Custom",T=e.effectiveDefault||(Z.value?{provider:Z.value.provider,model:Z.value.model}:void 0),K=J||(T==null?void 0:T.provider)||"",ne=B||(J?"":T==null?void 0:T.model)||"",[ue,oe]=y.useState({levels:[],error:"",loading:!1}),[ve,Ne]=y.useState(!1),q=!!e.fetchModelCapabilities,[be,xe]=y.useState();y.useEffect(()=>{let fe=!0;if(xe(void 0),oe({levels:[],error:"",loading:q&&!!ne}),!(!q||!ne||t))return V.current.fetchModelCapabilities(ne,K).then(H=>{var ae;if(!fe)return;if(H!=null&&H.error)throw new Error(String(H.error));xe(H);const le=(H==null?void 0:H.capabilities)||H||{},he=le.reasoning_levels||le.thinking_levels,Q=Array.isArray(he)?[...new Set(he.filter(Se=>typeof Se=="string"&&!!Se.trim()))]:[];!Q.length&&le.thinking_support===!0&&((ae=le.thinking_control)!=null&&ae.prompt_disable_token)&&Q.push("off","auto");const _e=typeof le.thinking_support=="boolean"?le.thinking_support:void 0;oe({levels:Q,support:_e,error:"",loading:!1})}).catch(H=>{fe&&oe({levels:[],error:String((H==null?void 0:H.message)||H),loading:!1})}),()=>{fe=!1}},[K,ne,q,t]),y.useEffect(()=>Ne(!1),[K,ne]);const Pe=e.inheritLabel||"Workflow / Gateway default",Qe=p&&(D!=null&&D.reasoning)?`${Pe} (${D.reasoning})`:Pe,He=!p||e.optionsInDefaultMode!==!1,qe=e.reasoningLadder?[...new Set(e.reasoningLadder.filter(fe=>typeof fe=="string"&&fe.trim()))]:null,ge=ue.loading?"loading":ue.levels.length||ue.support===!0?"supported":ue.support===!1?"unsupported":"unknown",$e=e.unknownReasoning==="allow-override"&&!!(qe!=null&&qe.length),st=String(n.reasoning||"").trim();let tt=[],Lt=!1;if(!qe)tt=ue.levels.map(fe=>({value:fe,label:fe}));else if(ge==="supported"||ge==="loading"){const fe=ue.levels;tt=[...qe,...fe.filter(le=>!qe.includes(le))].map(le=>!fe.length||fe.includes(le)?{value:le,label:le}:{value:le,label:le,disabled:!0,reason:"This model does not advertise it"})}else ge==="unknown"&&$e&&(Lt=!ve,tt=qe.map(fe=>({value:fe,label:fe})));st&&!tt.some(fe=>fe.value===st)&&tt.push({value:st,label:`${st} (saved)`});const ce=(q||$e)&&(tt.length>0||ge==="unknown"&&$e);return a.jsxs("div",{className:`af-pmp${o?" af-pmp--compact":""}${e.className?` ${e.className}`:""}`,"data-gateway-default":F?Z.status:void 0,children:[o||u?null:a.jsxs("div",{className:"af-pmp__seg",role:"tablist","aria-label":"Provider mode",children:[a.jsx("button",{type:"button",role:"tab","aria-selected":p,className:`af-pmp__seg-btn${p?" is-active":""}`,onClick:()=>{f(!1),e.onChange({...n,provider:"",model:"",...q?{reasoning:""}:{}})},disabled:t,title:te,"data-default-choice":"",children:te}),a.jsx("button",{type:"button",role:"tab","aria-selected":!p,className:`af-pmp__seg-btn${p?"":" is-active"}`,onClick:()=>{f(!0)},disabled:t,children:W})]}),Z.status==="error"||Z.status==="unusable"?a.jsx("div",{role:"status",className:"af-pmp__hint","data-gateway-default-problem":Z.status,children:Z.status==="error"?`The gateway's default could not be read: ${Z.message}`:`Gateway warning: ${Z.message}`}):null,m?a.jsx(Kx,{provider:J,model:B,providers:_,models:$,modelDisplayNames:N,markSaved:M.current,providerPinned:l.provider,modelPinned:l.model,disabled:t,loadingProviders:C,loadingModels:j,providerError:k||void 0,modelError:L||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:o,gatewayDefaultLabel:o?te:void 0,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:fe=>e.onChange({...n,provider:fe.provider,model:fe.model,...q?{reasoning:""}:{}})}):a.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}),He&&l.reasoning?a.jsxs("div",{className:"af-pmp__reasoning",children:[a.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),a.jsx("div",{className:"af-pmp__pinned","data-pinned":"reasoning",children:ah})]}):He&&ce?a.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":ge,children:[a.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),a.jsx(bn,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:Qe,value:n.reasoning||"",options:[{value:"",label:Qe},...tt],disabled:t||ue.loading||Lt,onChange:fe=>e.onChange({...n,reasoning:fe})}),ge==="unknown"&&$e?a.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[dk," ",a.jsxs("label",{className:"af-pmp__override",children:[a.jsx("input",{type:"checkbox",checked:ve,disabled:t,onChange:fe=>{Ne(fe.target.checked),!fe.target.checked&&n.reasoning&&e.onChange({...n,reasoning:""})}})," ",fk]})]}):null]}):null,He&&e.enableSpeculation&&l.speculation?a.jsxs("div",{className:"af-pmp__speculation",children:[a.jsx("label",{children:"MTP depth"}),a.jsx("div",{className:"af-pmp__pinned","data-pinned":"speculation",children:ah})]}):He&&e.enableSpeculation?a.jsx(Yx,{value:n.speculation,inheritLabel:Pe,onChange:fe=>e.onChange({...n,speculation:fe}),capabilities:be,disabled:t,loading:ue.loading,hideNote:!!ue.error}):null,He&&ue.error?a.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?hk:mk,a.jsxs("details",{className:"af-pmp__details",children:[a.jsx("summary",{children:"Technical details"}),a.jsx("span",{children:ue.error})]})]}):null]})}function Rg(...e){return e.filter(Boolean).join(" ")}function pk({kicker:e="AbstractGateway connection",title:t="Connect to AbstractGateway",description:n="Sign in with the Gateway user token assigned by the Gateway admin.",statusLabel:s="Not signed in",statusTone:o="neutral",showGatewayUrl:l=!1,gatewayUrl:u="",gatewayUrlPlaceholder:d="http://127.0.0.1:8080",onGatewayUrlChange:f,userId:m,userPlaceholder:p="admin",onUserIdChange:g,token:_,tokenPlaceholder:v="Paste Gateway user token",showToken:C=!1,onTokenChange:x,onShowTokenChange:k,remember:S=!1,rememberLabel:$="Remember this browser",onRememberChange:R,loading:N=!1,submitting:E=!1,submitDisabled:j=!1,submitLabel:I="Sign in",submittingLabel:L="Signing in...",closeLabel:z="Close",signOutLabel:V="Sign out",showClose:Z=!1,showSignOut:ie=!1,error:F,message:D,className:M,onSubmit:J,onClose:B,onSignOut:Y}){const te=N||E,W=te||j||!String(m||"").trim()||!String(_||"").trim(),T=K=>{K.preventDefault(),!W&&J()};return a.jsxs("form",{className:Rg("af-gateway-signin",M),onSubmit:T,children:[a.jsxs("div",{className:"af-gateway-signin__hero",children:[a.jsxs("div",{children:[a.jsx("div",{className:"af-gateway-signin__kicker",children:e}),a.jsx("h2",{children:t}),n?a.jsx("p",{children:n}):null]}),a.jsx("div",{className:"af-gateway-signin__mark","aria-hidden":"true",children:"↔"})]}),a.jsx("div",{className:"af-gateway-signin__status-row",children:a.jsx("span",{className:Rg("af-gateway-signin__status",`af-gateway-signin__status--${o}`),children:s})}),a.jsxs("div",{className:"af-gateway-signin__form",children:[l?a.jsxs(a.Fragment,{children:[a.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-url",children:"Gateway URL"}),a.jsx("input",{id:"gateway-session-url",value:u,onChange:K=>f==null?void 0:f(K.target.value),placeholder:d,autoComplete:"url",disabled:te})]}):null,a.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-user",children:"Gateway user"}),a.jsx("input",{id:"gateway-session-user",value:m,onChange:K=>g(K.target.value),placeholder:p,autoComplete:"username",disabled:te}),a.jsx("label",{className:"af-gateway-signin__label",htmlFor:"gateway-session-token",children:"Gateway token"}),a.jsxs("div",{className:"af-gateway-signin__token-input",children:[a.jsx("input",{id:"gateway-session-token",type:C?"text":"password",value:_,onChange:K=>x(K.target.value),placeholder:v,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:te}),a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>k==null?void 0:k(!C),disabled:te,children:C?"Hide":"Show"})]}),a.jsxs("label",{className:"af-gateway-signin__checkbox",children:[a.jsx("input",{type:"checkbox",checked:!!S,onChange:K=>R==null?void 0:R(K.target.checked),disabled:te}),$]})]}),F?a.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:F}):null,!F&&D?a.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:D}):null,a.jsxs("div",{className:"af-gateway-signin__actions",children:[Z?a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:B,disabled:te,children:z}):null,ie?a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(Y==null?void 0:Y()),disabled:te,children:V}):null,a.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:W,children:E?L:I})]})]})}function gk(e){return e==="light"?"Light":"Dark"}function yk(e){const t=e.themes&&e.themes.length?e.themes:xw,n=e.showSwatches!==!1,s=e.variant||"panel",o=y.useMemo(()=>{const u={};for(const d of t)u[d.id]=d;return u},[t]),l=y.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:gk(u.group)})),[t]);return a.jsx(bn,{value:e.value,options:l,placeholder:e.placeholder||"Select theme…",disabled:e.disabled===!0,searchable:!0,allowCustom:!1,clearable:!1,variant:s,className:e.className,triggerClassName:e.triggerClassName,onChange:u=>e.onChange(String(u||"").trim()),renderValue:(u,d)=>{const f=String(d||"").trim(),m=o[f],p=(m==null?void 0:m.label)||f||e.placeholder||"Select theme…",g=(m==null?void 0:m.swatches)||null,_=!f;return a.jsxs("span",{className:"af-theme-value",children:[a.jsx("span",{className:`af-theme-label ${_?"af-theme-label--placeholder":""}`.trim(),children:p}),n&&g?a.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((v,C)=>a.jsx("span",{className:"af-theme-swatch",style:{background:v}},`${f}:${C}`))}):null]})},renderOption:(u,d)=>{const f=String(u.value||"").trim(),m=o[f],p=(m==null?void 0:m.swatches)||null;return a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"af-theme-option-label",children:u.label}),a.jsxs("span",{className:"af-theme-option-right",children:[n&&p?a.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:p.map((g,_)=>a.jsx("span",{className:"af-theme-swatch",style:{background:g}},`${f}:${_}`))}):null,d.selected?a.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function wk(e){const t=e.scales&&e.scales.length?e.scales:sh,n=e.variant||"panel",s=y.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return a.jsx(bn,{value:e.value,options:s,placeholder:e.placeholder||"Font size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:o=>e.onChange(String(o||"").trim())})}function vk(e){const t=e.densities&&e.densities.length?e.densities:rh,n=e.variant||"panel",s=y.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return a.jsx(bn,{value:e.value,options:s,placeholder:e.placeholder||"Header size…",disabled:e.disabled===!0,searchable:!1,allowCustom:!1,clearable:!1,variant:n,className:e.className,triggerClassName:e.triggerClassName,onChange:o=>e.onChange(String(o||"").trim())})}const _k=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function bk(e){switch(e){case"chat":return a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"M5 12h14"})]});case"history":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"9"}),a.jsx("path",{d:"M12 7v5l3 3"})]});case"refresh":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M21 12a9 9 0 0 0-15.5-6.4L3 8"}),a.jsx("path",{d:"M3 3v5h5"}),a.jsx("path",{d:"M3 12a9 9 0 0 0 15.5 6.4L21 16"}),a.jsx("path",{d:"M21 21v-5h-5"})]});case"cog":return a.jsxs(a.Fragment,{children:[a.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"}),a.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"activity":return a.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2"});case"settings":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M4 6h16"}),a.jsx("circle",{cx:"8",cy:"6",r:"2"}),a.jsx("path",{d:"M4 12h16"}),a.jsx("circle",{cx:"16",cy:"12",r:"2"}),a.jsx("path",{d:"M4 18h16"}),a.jsx("circle",{cx:"10",cy:"18",r:"2"})]});case"user":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"8",r:"4"}),a.jsx("path",{d:"M4 21a8 8 0 0 1 16 0"})]});case"bot":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 2v3"}),a.jsx("rect",{x:"5",y:"6",width:"14",height:"14",rx:"3"}),a.jsx("circle",{cx:"9",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"15",cy:"13",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("path",{d:"M9 17h6"})]});case"paperclip":return a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3z"}),a.jsx("path",{d:"M19 11a7 7 0 0 1-14 0"}),a.jsx("path",{d:"M12 18v4"}),a.jsx("path",{d:"M8 22h8"})]});case"speaker":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M11 5L6 9H2v6h4l5 4V5z"}),a.jsx("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),a.jsx("path",{d:"M18 6a9 9 0 0 1 0 12"})]});case"pause":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"}),a.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",fill:"currentColor",stroke:"none"})]});case"terminal":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2",ry:"2"}),a.jsx("path",{d:"M7 9l3 3-3 3"}),a.jsx("path",{d:"M12 15h5"})]});case"edit":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 20h9"}),a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),a.jsx("path",{d:"M7 10l5 5 5-5"}),a.jsx("path",{d:"M12 15V3"})]});case"loader":return a.jsx("path",{d:"M21 12a9 9 0 1 1-3.3-6.9"});case"info":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("path",{d:"M12 16v-4"}),a.jsx("circle",{cx:"12",cy:"8",r:"0.75",fill:"currentColor",stroke:"none"})]});case"warning":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 3l10 18H2L12 3z"}),a.jsx("path",{d:"M12 9v4"}),a.jsx("circle",{cx:"12",cy:"17",r:"0.75",fill:"currentColor",stroke:"none"})]});case"error":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("path",{d:"M15 9l-6 6"}),a.jsx("path",{d:"M9 9l6 6"})]});case"copy":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),a.jsx("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]});case"check":return a.jsx("path",{d:"M20 6L9 17l-5-5"});case"x":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M18 6L6 18"}),a.jsx("path",{d:"M6 6l12 12"})]});case"chevronDown":return a.jsx("path",{d:"M6 9l6 6 6-6"});case"chevronRight":return a.jsx("path",{d:"M9 18l6-6-6-6"});case"trash":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M3 6h18"}),a.jsx("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),a.jsx("path",{d:"M6 6l1 16h10l1-16"}),a.jsx("path",{d:"M10 11v6"}),a.jsx("path",{d:"M14 11v6"})]});case"send":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M22 2L11 13"}),a.jsx("path",{d:"M22 2L15 22l-4-9-9-4 20-7z"})]});case"thumbsUp":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M7 10v11"}),a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M17 14V3"}),a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M7 10v11"}),a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M17 14V3"}),a.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 a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"1.5",y:"2",width:"3.6",height:"12",rx:"1"}),a.jsx("rect",{x:"6.2",y:"2",width:"3.6",height:"8.5",rx:"1"}),a.jsx("rect",{x:"10.9",y:"2",width:"3.6",height:"5.5",rx:"1"})]});case"inbox":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M2 9.5 L4 3.5 h8 l2 6"}),a.jsx("path",{d:"M2 9.5 v3 h12 v-3"}),a.jsx("path",{d:"M2 9.5 h3.4 l1 1.6 h3.2 l1-1.6 H14"})]});case"server":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"2",y:"2.5",width:"12",height:"4.6",rx:"1.2"}),a.jsx("rect",{x:"2",y:"8.9",width:"12",height:"4.6",rx:"1.2"}),a.jsx("circle",{cx:"4.6",cy:"4.8",r:"0.8",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"4.6",cy:"11.2",r:"0.8",fill:"currentColor",stroke:"none"})]});case"agent":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"3",y:"4.5",width:"10",height:"8",rx:"2"}),a.jsx("path",{d:"M8 4.5V2.2"}),a.jsx("circle",{cx:"8",cy:"1.8",r:"0.9",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"5.8",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"10.2",cy:"8.4",r:"0.9",fill:"currentColor",stroke:"none"})]});case"playCircle":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),a.jsx("path",{d:"M6.5 5.6 L11 8 L6.5 10.4 Z",fill:"currentColor",stroke:"none"})]});case"list":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M2.5 4h11"}),a.jsx("path",{d:"M2.5 8h11"}),a.jsx("path",{d:"M2.5 12h7"})]});case"gear":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"8",cy:"8",r:"2.2"}),a.jsx("path",{d:"M8 1.6v2"}),a.jsx("path",{d:"M8 12.4v2"}),a.jsx("path",{d:"M1.6 8h2"}),a.jsx("path",{d:"M12.4 8h2"}),a.jsx("path",{d:"M3.5 3.5l1.4 1.4"}),a.jsx("path",{d:"M11.1 11.1l1.4 1.4"}),a.jsx("path",{d:"M12.5 3.5l-1.4 1.4"}),a.jsx("path",{d:"M4.9 11.1l-1.4 1.4"})]});case"sparkle":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"}),a.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 a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"9"}),a.jsx("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor",stroke:"none"})]});case"logout":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),a.jsx("path",{d:"M16 17l5-5-5-5"}),a.jsx("path",{d:"M21 12H9"})]});case"play":return a.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 a.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2",fill:"currentColor",stroke:"none"});case"folder":return a.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 a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("path",{d:"M14 2v6h6"})]});case"archive":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),a.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),a.jsx("path",{d:"M10 12h4"})]});case"unarchive":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),a.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),a.jsx("path",{d:"M12 18v-6"}),a.jsx("path",{d:"m9 14 3-3 3 3"})]});case"clock":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"10"}),a.jsx("path",{d:"M12 6v6h4"})]});case"book":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M2 4h6a4 4 0 0 1 4 4v13a3 3 0 0 0-3-3H2z"}),a.jsx("path",{d:"M22 4h-6a4 4 0 0 0-4 4v13a3 3 0 0 1 3-3h7z"})]});case"compose":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),a.jsx("path",{d:"M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"})]});case"image":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),a.jsx("circle",{cx:"9",cy:"9",r:"2"}),a.jsx("path",{d:"M21 15l-3.1-3.1a2 2 0 0 0-2.8 0L6 21"})]});case"video":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"2",y:"6",width:"14",height:"12",rx:"2"}),a.jsx("path",{d:"M16 10.5l5.2-3.1a.5.5 0 0 1 .8.4v8.4a.5.5 0 0 1-.8.4L16 13.5"})]});case"camera":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3z"}),a.jsx("circle",{cx:"12",cy:"13",r:"3"})]});case"music":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M9 18V5l12-2v13"}),a.jsx("circle",{cx:"6",cy:"18",r:"3"}),a.jsx("circle",{cx:"18",cy:"16",r:"3"})]});case"database":return a.jsxs(a.Fragment,{children:[a.jsx("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),a.jsx("path",{d:"M3 5v14a9 3 0 0 0 18 0V5"}),a.jsx("path",{d:"M3 12a9 3 0 0 0 18 0"})]});case"branch":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M6 3v12"}),a.jsx("circle",{cx:"18",cy:"6",r:"3"}),a.jsx("circle",{cx:"6",cy:"18",r:"3"}),a.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]});case"loop":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M17 2l4 4-4 4"}),a.jsx("path",{d:"M3 11v-1a4 4 0 0 1 4-4h14"}),a.jsx("path",{d:"M7 22l-4-4 4-4"}),a.jsx("path",{d:"M21 13v1a4 4 0 0 1-4 4H3"})]});case"variable":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M8 21s-4-3-4-9 4-9 4-9"}),a.jsx("path",{d:"M16 3s4 3 4 9-4 9-4 9"}),a.jsx("path",{d:"M15 9l-6 6"}),a.jsx("path",{d:"M9 9l6 6"})]});case"minus":return a.jsx("path",{d:"M5 12h14"});case"divide":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"6",r:"1.25",fill:"currentColor",stroke:"none"}),a.jsx("path",{d:"M5 12h14"}),a.jsx("circle",{cx:"12",cy:"18",r:"1.25",fill:"currentColor",stroke:"none"})]});case"function":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),a.jsx("path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3"}),a.jsx("path",{d:"M9 11.2h5.7"})]});case"zoomIn":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"11",cy:"11",r:"8"}),a.jsx("path",{d:"M21 21l-4.35-4.35"}),a.jsx("path",{d:"M11 8v6"}),a.jsx("path",{d:"M8 11h6"})]});case"zoomOut":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"11",cy:"11",r:"8"}),a.jsx("path",{d:"M21 21l-4.35-4.35"}),a.jsx("path",{d:"M8 11h6"})]});case"fitView":return a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),a.jsx("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),a.jsx("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),a.jsx("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]});case"lock":return a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"4",y:"11",width:"16",height:"10",rx:"2"}),a.jsx("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"})]});default:return null}}function de({name:e,size:t=16,className:n,title:s,...o}){const l=s?void 0:!0,u=_k.has(e);return a.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":l,role:s?"img":"presentation",...o,children:[s?a.jsx("title",{children:s}):null,bk(e)]})}function xk(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function kk(e){return xk(e)?!e.checked:null}let Sk=0;function Wr(e){const{label:t,checked:n,onChange:s,description:o,reasonVisible:l=!0,describedBy:u,hint:d,busy:f=!1,variant:m="inline",ariaLabel:p,className:g,id:_,action:v}=e,C=String(e.unavailableReason||"").trim(),x=!!C,k=u||(_?`${_}-reason`:x?`af-switch-reason-${++Sk}`:void 0),S=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",x?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),$=N=>{const E=kk({checked:n,unavailableReason:C,busy:f});if(E===null){N.preventDefault();return}s==null||s(E)},R=a.jsxs("button",{type:"button",role:"switch",id:_,className:S,"data-action":v,"aria-checked":n?"true":"false","aria-disabled":x?"true":void 0,"aria-describedby":x?k:void 0,"aria-busy":f?"true":void 0,"aria-label":p,"aria-description":o?void 0:d,title:x?d?`${C}
41
- ${d}`:C:d,onClick:$,children:[a.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:a.jsx("span",{className:"af-switch__thumb"})}),a.jsxs("span",{className:"af-switch__text",children:[a.jsx("span",{className:"af-switch__label",children:t}),o?a.jsx("span",{className:"af-switch__desc",children:o}):null]})]});return!x||u?R:a.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[R,a.jsx("span",{id:k,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:C})]})}function jk(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(" "),s=t?`${e.id||e.name}-reason`:void 0,o=a.jsxs("label",{className:n,title:t||void 0,"data-action":e.action,children:[a.jsx("input",{type:"checkbox",role:"switch",className:"af-switch__input",id:e.id,name:e.name,defaultChecked:e.defaultChecked,onChange:l=>{var u;return(u=e.onChange)==null?void 0:u.call(e,l.target.checked)},disabled:!!t,"aria-describedby":s}),a.jsx("span",{className:"af-switch__track","aria-hidden":"true",children:a.jsx("span",{className:"af-switch__thumb"})}),a.jsx("span",{className:"af-switch__text",children:a.jsx("span",{className:"af-switch__label",children:e.label})})]});return t?a.jsxs("span",{className:e.variant==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[o,a.jsx("span",{id:s,className:"af-switch__reason",children:t})]}):o}const Nk=150,zh="data-af-tip";function Ck(e,t,n,s=6,o=8){let l="top",u=e.top-s-t.height;if(u<o){const m=e.bottom+s;(m+t.height<=n.height-o||n.height-e.bottom>e.top)&&(u=m,l="bottom")}let f=(e.left+e.right)/2-t.width/2;return f=Math.max(o,Math.min(f,n.width-o-t.width)),u=Math.max(o,Math.min(u,n.height-o-t.height)),{top:Math.round(u),left:Math.round(f),side:l}}let Ig=0;function Nw(e){return e?String(e.getAttribute(zh)||"").trim():""}function gf(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const s=n.closest(`[${zh}]`);return!s||!t.contains(s)||!Nw(s)?null:s}function Ek(e,t={}){if(!e)throw new Error("bindAfTooltips: a root (document or element) is required");const n=e.nodeType===9?e:e.ownerDocument,s=n.defaultView||globalThis,o=typeof t.delayMs=="number"&&t.delayMs>=0?t.delayMs:Nk;Ig+=1;const l=n.createElement("div");l.className="af-tooltip",l.setAttribute("role","tooltip");const u=`af-tooltip-${Ig}`;l.setAttribute("id",u),l.hidden=!0,(n.body||n.documentElement).appendChild(l);let d=null,f=null,m=null,p=null,g=!1,_=null;const v=()=>{m&&clearTimeout(m),m=null,f=null},C=()=>{p&&clearTimeout(p),p=null},x=()=>{if(!d)return;const M=d.getBoundingClientRect(),J=l.getBoundingClientRect(),B=Ck(M,{width:J.width,height:J.height},{width:s.innerWidth,height:s.innerHeight});l.style.top=`${B.top}px`,l.style.left=`${B.left}px`,l.setAttribute("data-side",B.side)},k=()=>{if(v(),C(),!d)return;String(d.getAttribute("aria-describedby")||"").split(/\s+/).includes(u)&&(_?d.setAttribute("aria-describedby",_):d.removeAttribute("aria-describedby")),_=null,d=null,l.hidden=!0,l.textContent=""},S=M=>{v(),C(),d&&d!==M&&k();const J=Nw(M);if(!J||M.isConnected===!1)return;if(d=M,l.textContent=J,l.hidden=!1,String(M.getAttribute("aria-label")||"").trim()!==J){const Y=M.getAttribute("aria-describedby");_=Y&&Y!==u?Y:null,M.setAttribute("aria-describedby",_?`${_} ${u}`:u)}x()},$=M=>{C(),d!==M&&f!==M&&(v(),f=M,m=setTimeout(()=>{const J=f;m=null,f=null,J&&S(J)},o))},R=()=>{v(),d&&(C(),p=setTimeout(k,100))},N=M=>{try{if(typeof M.matches=="function")return M.matches(":focus-visible")}catch{}return g},E=M=>{if(M.pointerType==="touch")return;if(l.contains(M.target)){C();return}const B=gf(M.target,e);B&&$(B)},j=M=>{const B=M.relatedTarget||null;if(!(B&&(l.contains(B)||d&&d.contains(B)||f&&f.contains(B)))){if(f&&!d){v();return}d&&R()}},I=M=>{const J=M.relatedTarget||null;J&&(l.contains(J)||d&&d.contains(J))||R()},L=M=>{const J=gf(M.target,e);J&&N(J)&&$(J)},z=M=>{const J=gf(M.target,e);J&&(J===d||J===f)&&k()},V=()=>{g=!1,k()},Z=M=>{if(M.key==="Escape"||M.key==="Esc"){d?(M.preventDefault(),k()):v();return}!M.metaKey&&!M.ctrlKey&&!M.altKey&&(g=!0)},ie=()=>k(),F=e;F.addEventListener("pointerover",E),F.addEventListener("pointerout",j),F.addEventListener("focusin",L),F.addEventListener("focusout",z),l.addEventListener("pointerover",E),l.addEventListener("pointerout",I),n.addEventListener("pointerdown",V,!0),s.addEventListener("keydown",Z,!0),s.addEventListener("scroll",ie,!0),s.addEventListener("resize",ie);let D=!1;return()=>{D||(D=!0,k(),F.removeEventListener("pointerover",E),F.removeEventListener("pointerout",j),F.removeEventListener("focusin",L),F.removeEventListener("focusout",z),l.removeEventListener("pointerover",E),l.removeEventListener("pointerout",I),n.removeEventListener("pointerdown",V,!0),s.removeEventListener("keydown",Z,!0),s.removeEventListener("scroll",ie,!0),s.removeEventListener("resize",ie),l.parentNode&&l.parentNode.removeChild(l))}}const Tc=new WeakMap;function Ak(e){let t=Tc.get(e);t||(t={count:0,release:Ek(e)},Tc.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const s=Tc.get(e);s&&(s.count-=1,s.count<=0&&(s.release(),Tc.delete(e)))}}function Io(){y.useEffect(()=>{if(!(typeof document>"u"))return Ak(document)},[])}function Zc(e){Io();const t=yt.Children.only(e.children),n=String(e.content||"").trim();return n?yt.cloneElement(t,{[zh]:n}):t}function $k(e,t,n){const s=String(e||"").trim().toLowerCase();if(!s&&!t&&!n)return null;let o;return s==="approval"||s==="local_approval"||s==="local-approval"?o={label:"APPROVAL",detail:"Safe tools auto-run; mutating tools ask for approval.",tone:"safe"}:s==="passthrough"?o={label:"PASSTHROUGH",detail:"All tools require approval before execution.",tone:"warn"}:s==="delegated"||s==="delegate"||s==="job"?o={label:"DELEGATED",detail:"Tool calls wait for external executors.",tone:"info"}:s==="local"||s==="local_all"||s==="local-all"?o={label:"LOCAL",detail:"All tools run locally; client policy may still require approval.",tone:"danger"}:o={label:"UNKNOWN",detail:"#FALLBACK: gateway tool mode not reported.",tone:"warn"},t&&(o={...o,label:t}),n&&(o={...o,detail:n}),o}async function ih(e=ll){const t=await fetch(e),n=await t.json().catch(()=>null);if(!t.ok){const s=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(s)}return n}async function Tk(e,t=ll){const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await n.json().catch(()=>null);if(!n.ok){const o=s&&typeof s=="object"&&s.detail?String(s.detail):`HTTP ${n.status}`;throw new Error(o)}return s}async function Cw(e=ll){const t=await fetch(e,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({})),s=n&&typeof n=="object"&&n.detail?String(n.detail):`HTTP ${t.status}`;throw new Error(s)}}function yf(e){let t=String(e||"").trim();for(let n=0;n<2&&t;n+=1){try{const l=JSON.parse(t);if(typeof l=="string"&&l!==t){t=l.trim();continue}}catch{}const s=t[0],o=t[t.length-1];if(s==='"'&&o==='"'||s==="'"&&o==="'"){t=t.slice(1,-1).trim();continue}break}return t.replace(/\/+$/,"")}function Rk(e){var l,u;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(l=t.principal)==null?void 0:l.user_id,s=(u=t.principal)==null?void 0:u.runtime_id;if(t.ok&&n)return{label:`Signed in as ${n}${s?` · runtime ${s}`:""}`,tone:"ok"};if(t.ok)return{label:"Signed in",tone:"ok"};const o=t.error||t.detail;return typeof o=="string"&&o.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function Ik(e){const t=e.connectionPath||ll,[n,s]=y.useState(!1),[o,l]=y.useState(!1),[u,d]=y.useState(null),[f,m]=y.useState(!1);y.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[p,g]=y.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[_,v]=y.useState("admin"),[C,x]=y.useState(""),[k,S]=y.useState(!1),[$,R]=y.useState(!0),[N,E]=y.useState(""),[j,I]=y.useState(""),L=y.useMemo(()=>Rk(u),[u]),z=F=>{var D;d(F),(D=e.onStatusChange)==null||D.call(e,F)},V=y.useRef(!1);if(y.useEffect(()=>{var D;if(!e.isOpen)return;const F=!V.current;if(V.current=!0,F&&e.initialStatus!==void 0&&e.initialStatus!==null){const M=e.initialStatus;z(M),typeof M.gateway_url=="string"&&M.gateway_url.trim()&&g(yf(M.gateway_url));const J=(D=M.gateway)==null?void 0:D.principal;J!=null&&J.user_id&&v(J.user_id);return}s(!0),E(""),ih(t).then(M=>{var B;z(M),typeof M.gateway_url=="string"&&M.gateway_url.trim()&&g(yf(M.gateway_url));const J=(B=M.gateway)==null?void 0:B.principal;J!=null&&J.user_id&&v(J.user_id)}).catch(M=>E(`Failed to load connection status: ${String((M==null?void 0:M.message)||M)}`)).finally(()=>s(!1))},[e.isOpen]),y.useEffect(()=>{if(!e.isOpen)return;const F=D=>{D.key==="Escape"&&!D.defaultPrevented&&!e.blocking&&(D.preventDefault(),e.onClose())};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const Z=async()=>{l(!0),E(""),I("");try{const F=yf(p);g(F);const D=await Tk({gateway_url:F,gateway_user_id:_,gateway_token:C,persist:$},t);z(D),x(""),m(!0),e.onClose()}catch(F){E(String((F==null?void 0:F.message)||F))}finally{l(!1)}},ie=async()=>{l(!0),E(""),I("");try{await Cw(t),x("");const F=await ih(t).catch(()=>null);z(F),I("Signed out. This browser no longer holds a gateway session.")}catch(F){E(String((F==null?void 0:F.message)||F))}finally{l(!1)}};return a.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:F=>{!e.blocking&&F.target===F.currentTarget&&e.onClose()},children:a.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:a.jsx(pk,{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:F=>g(F),userId:_,onUserIdChange:v,token:C,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:k,onTokenChange:x,onShowTokenChange:S,remember:$,rememberLabel:"Keep this browser signed in",onRememberChange:R,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:ie,error:N,message:j,onSubmit:Z})})})}function Ew(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function Lk(e){const t=e||{},n=t.connectionPath||ll,s=t.variant||"dismissable",o=y.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=y.useRef(s);l.current=s;const u=y.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[d,f]=y.useState(null),[m,p]=y.useState("loading"),[g,_]=y.useState(!1),v=y.useRef(!1),C=y.useRef(!1),x=y.useRef("loading"),k=y.useRef("none"),S=y.useRef(!1),$=y.useRef(0),R=y.useCallback(D=>{var J;$.current+=1,f(D),(J=o.current)==null||J.call(o,D);const M=Ew(D);if(M)p("connected"),x.current="connected",v.current=!1,k.current="none",C.current||_(!1);else if(D!==null){const B=x.current;p("disconnected"),x.current="disconnected",B!=="disconnected"&&(k.current=S.current?"signout":B==="connected"?"mid":"boot");const Y=l.current==="blocking"||k.current!=="mid"||u.current;!v.current&&Y&&_(!0)}D!==null&&(C.current=M)},[]),N=y.useCallback(async()=>{const D=$.current;try{const M=await ih(n);if($.current!==D)return;R(M)}catch{if($.current!==D)return;R(null)}},[n,R]),[E,j]=y.useState(!1),[I,L]=y.useState(null),z=y.useCallback(async()=>{j(!0),L(null),$.current+=1;let D=null;try{await Cw(n)}catch(M){D=String((M==null?void 0:M.message)||M||"Sign-out request failed")}S.current=!0;try{await N()}finally{S.current=!1}return L(D),j(!1),D===null&&x.current!=="connected"},[n,N]),V=y.useRef(!1);y.useEffect(()=>{V.current||(V.current=!0,N())},[N]);const Z=y.useCallback(()=>{_(!0)},[]),ie=y.useCallback(()=>{const D=x.current;s==="blocking"&&D==="disconnected"||(D==="disconnected"&&(v.current=!0),_(!1))},[s]),F=y.useMemo(()=>({isOpen:g,onClose:ie,blocking:s==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:d,onStatusChange:R}),[g,ie,s,m,t.appName,n,t.defaultGatewayUrl,d,R]);return{status:d,phase:m,connected:m==="connected",modalOpen:g,signingOut:E,signOutError:I,openModal:Z,refresh:N,signOut:z,modalProps:F}}function Mk(){return globalThis.crypto}function Ok(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(s=>s.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 Fr(){const e=Mk();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return Ok(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function bu(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.`}const wf={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},Pk=/^var\(--[a-z0-9-]+\)$/i;function Dk(e,t){const n=e||"neutral";if(n==="custom"){const s=String(t||"").trim();return Pk.test(s)?s:wf.neutral}return wf[n]||wf.neutral}function Aw(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n||"",t.className||""].filter(Boolean).join(" ")}function $w(e){return{"--af-chip-hue":Dk(e.tone,e.hue)}}function Fk(e){return a.jsxs("span",{className:Aw("af-chip",e,e.onRemove?"af-chip--removable":""),style:$w(e),title:e.title,children:[a.jsx("span",{className:"af-chip__label",children:e.children}),e.onRemove?a.jsx("button",{type:"button",className:"af-chip__remove","aria-label":e.removeLabel||"Remove",onClick:t=>{var n;t.stopPropagation(),(n=e.onRemove)==null||n.call(e)},children:a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",children:[a.jsx("path",{d:"M18 6L6 18"}),a.jsx("path",{d:"M6 6l12 12"})]})}):null]})}function zk(e){return a.jsx("button",{type:"button",className:Aw("af-chip",e,"af-chip--button"),style:$w(e),title:e.title,onClick:e.onClick,"aria-pressed":typeof e.pressed=="boolean"?e.pressed:void 0,"aria-expanded":typeof e.expanded=="boolean"?e.expanded:void 0,"aria-label":e.ariaLabel,disabled:e.disabled,tabIndex:e.tabIndex,children:a.jsx("span",{className:"af-chip__label",children:e.children})})}const Bk=["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 Wk(e,t,n,s){if(e.length===0)return null;const o=e[0],l=e[e.length-1];return s?n&&t===o?l:!n&&t===l?o:null:n?l:o}function Uk(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 vf(e){return Array.from(e.querySelectorAll(Bk)).filter(n=>!(typeof n.closest=="function"&&n.closest("[hidden], [inert], [aria-hidden='true']")||Uk(n)||typeof n.getClientRects=="function"&&n.getClientRects().length===0))}const Lg=new WeakMap;function Vk(e,t){const n=t.document||e.ownerDocument,s=e.querySelector(".af-modal")||e,o=n.activeElement,l=Lg.get(n)||[];Lg.set(n,l),l.push(e);const u=t.lockScroll!==!1;u&&n.documentElement.classList.add("af-modal-open");const d=()=>{const x=s.querySelector(".af-modal__body"),k=t.initialFocus||s.querySelector("[data-af-autofocus], [autofocus]")||(x?vf(x)[0]:void 0)||vf(s)[0]||s;k===s&&!s.hasAttribute("tabindex")&&s.setAttribute("tabindex","-1"),k.focus({preventScroll:!0})};d();const f=()=>l[l.length-1]===e,m=x=>{if(!f())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 k=vf(s),S=n.activeElement,$=!!S&&s.contains(S);if(k.length===0){x.preventDefault(),s.focus({preventScroll:!0});return}const R=Wk(k,S,x.shiftKey,$&&S!==s);R&&(x.preventDefault(),R.focus({preventScroll:!0}))},p=x=>{if(!f())return;const k=x.target;k&&!s.contains(k)&&d()};let g=!1;const _=x=>{g=x.target===e},v=x=>{const k=x.target===e&&g;g=!1,!(!k||!f()||t.closeOnBackdrop===!1)&&t.onClose()};n.addEventListener("keydown",m,!0),n.addEventListener("focusin",p,!0),e.addEventListener("mousedown",_),e.addEventListener("click",v);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",v);const x=l.lastIndexOf(e);x>=0&&l.splice(x,1),u&&l.length===0&&n.documentElement.classList.remove("af-modal-open"),o&&typeof o.focus=="function"&&o.isConnected!==!1&&o.focus({preventScroll:!0})}}function Gk(e){const t=y.useId().replace(/:/g,""),n=e.id||`af-modal-${t}`,s=y.useRef(null),o=y.useRef(e.onClose);if(o.current=e.onClose,y.useEffect(()=>{if(!(!e.open||!s.current))return Vk(s.current,{onClose:()=>o.current(),closeOnEscape:e.closeOnEscape!==!1,closeOnBackdrop:e.closeOnBackdrop!==!1,initialFocus:e.initialFocusRef?e.initialFocusRef.current:null})},[e.open]),!e.open)return null;const l=a.jsx("div",{className:"af-modal-backdrop",ref:s,children:a.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:[a.jsxs("div",{className:"af-modal__header",children:[a.jsx("h2",{className:"af-modal__title",id:`${n}-title`,children:e.title}),a.jsx("button",{type:"button",className:"af-modal__close","aria-label":e.closeLabel||"Close",onClick:()=>o.current(),children:a.jsx("span",{"aria-hidden":"true",children:"×"})})]}),a.jsx("div",{className:"af-modal__body",children:e.children}),e.footer!==void 0||e.footerNote!==void 0?a.jsxs("div",{className:"af-modal__footer",children:[e.footerNote!==void 0?a.jsx("p",{className:"af-modal__footer-note",children:e.footerNote}):null,e.footer]}):null]})});return e.portal!==!1&&typeof document<"u"&&!!document.body?il.createPortal(l,document.body):l}function Hk(e,t,n,s=4,o=8){let l=e.bottom+s,u=!1;if(l+t.height>n.height-o){const m=e.top-s-t.height;(m>=o||e.top>n.height-e.bottom)&&(l=m,u=!0)}let d=e.left,f=!1;return d+t.width>n.width-o&&(d=e.right-t.width,f=!0),d=Math.max(o,Math.min(d,n.width-o-t.width)),l=Math.max(o,l),{top:Math.round(l),left:Math.round(d),up:u,leftward:f}}let Mg=0;function Kk(e,t,n={}){if(!e||!t)throw new Error("bindAfMenu: button and menu are required");const s=n.document||e.ownerDocument,o=s.defaultView||globalThis;t.getAttribute("id")||(Mg+=1,t.setAttribute("id",`af-menu-${Mg}`)),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 l=()=>{const R=Array.from(t.querySelectorAll(".af-menu__item")),N=R.filter(E=>!E.hidden&&!E.hasAttribute("disabled"));for(const E of R)E.setAttribute("role","menuitem"),E.setAttribute("tabindex","-1");return N};l();let u=!1;const d=()=>{if(!u)return;const R=e.getBoundingClientRect(),N=t.getBoundingClientRect(),E=Hk(R,{width:N.width,height:N.height},{width:o.innerWidth,height:o.innerHeight});t.style.top=`${E.top}px`,t.style.left=`${E.left}px`,t.setAttribute("data-placement",`${E.up?"top":"bottom"}-${E.leftward?"end":"start"}`)},f=R=>{const N=l();if(!N.length)return;const E=(R%N.length+N.length)%N.length;N[E].focus({preventScroll:!0})},m=R=>{u||(u=!0,t.hidden=!1,e.setAttribute("aria-expanded","true"),d(),f(R),s.addEventListener("pointerdown",g,!0),s.addEventListener("mousedown",g,!0),o.addEventListener("scroll",d,!0),o.addEventListener("resize",_),o.addEventListener("keydown",x,!0),n.onOpen&&n.onOpen())},p=R=>{u&&(u=!1,t.hidden=!0,e.setAttribute("aria-expanded","false"),s.removeEventListener("pointerdown",g,!0),s.removeEventListener("mousedown",g,!0),o.removeEventListener("scroll",d,!0),o.removeEventListener("resize",_),o.removeEventListener("keydown",x,!0),R&&e.focus({preventScroll:!0}),n.onClose&&n.onClose())};function g(R){const N=R.target;N&&(t.contains(N)||e.contains(N))||p(!1)}function _(){p(!1)}const v=R=>{R.preventDefault(),u?p(!0):m(0)},C=R=>{R.key==="ArrowDown"||(R.key==="Enter"||R.key===" ")&&!u?(R.preventDefault(),m(0)):R.key==="ArrowUp"&&(R.preventDefault(),m(-1))},x=R=>{if(!u||R.key!=="Escape"&&R.key!=="Esc")return;const N=R.target;N&&N!==e&&!t.contains(N)&&N!==s.body||(R.preventDefault(),p(!0))},k=R=>{if(!u)return;const E=l().indexOf(s.activeElement);R.key==="ArrowDown"?(R.preventDefault(),f(E+1)):R.key==="ArrowUp"?(R.preventDefault(),f(E<0?-1:E-1)):R.key==="Home"?(R.preventDefault(),f(0)):R.key==="End"?(R.preventDefault(),f(-1)):R.key==="Tab"&&p(!1)},S=R=>{const N=R.target,E=N&&typeof N.closest=="function"?N.closest(".af-menu__item"):null;if(!E||!t.contains(E))return;const j=s.activeElement,I=!j||j===s.body||t.contains(j);p(I)};e.addEventListener("click",v),e.addEventListener("keydown",C),t.addEventListener("keydown",k),t.addEventListener("click",S);let $=!1;return()=>{$||($=!0,p(!1),e.removeEventListener("click",v),e.removeEventListener("keydown",C),t.removeEventListener("keydown",k),t.removeEventListener("click",S))}}function Bh(e){const t=y.useRef(null),n=y.useRef(null),s=e.items.filter(l=>l&&!l.hidden),o=s.length>0;return y.useEffect(()=>{if(!(!o||!t.current||!n.current))return Kk(t.current,n.current)},[o]),o?a.jsxs("div",{className:`af-menu${e.className?` ${e.className}`:""}`,children:[a.jsx("button",{type:"button",ref:t,className:`af-menu__button${e.buttonClassName?` ${e.buttonClassName}`:""}`,"aria-label":e.label,title:e.title,"data-af-tip":e.tip,"aria-haspopup":"menu","aria-expanded":"false",children:e.buttonContent!==void 0?e.buttonContent:a.jsx("span",{"aria-hidden":"true",children:"⋯"})}),a.jsxs("div",{className:"af-menu__list",role:"menu",ref:n,hidden:!0,children:[e.header!==void 0&&e.header!==null?a.jsx("div",{className:"af-menu__header",role:"presentation",children:e.header}):null,s.map(l=>a.jsx("button",{type:"button",role:"menuitem",tabIndex:-1,"data-menu-id":l.id,className:`af-menu__item${l.danger?" af-menu__item--danger":""}`,onClick:()=>l.onSelect(),children:l.label},l.id))]})]}):null}const Jk={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"},qk={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"}},Yk={framework:Jk,apps:qk},eu=Yk;function Tw(){return{...eu.framework}}function Qk(){return Object.keys(eu.apps).sort()}function Xk(e,t){const n=Object.prototype.hasOwnProperty.call(eu.apps,e)?eu.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Qk().join(", ")})`);return{id:e,name:n.name,version:t,website:n.website,repo:n.repo,docs:n.docs,issues:n.issues,feedback:n.feedback}}async function Zk(e,t){try{const n=await e(we("about"),{method:"GET",headers:{Accept:"application/json"},signal:t});if(!n.ok)return _f(null,`HTTP ${n.status}`);const s=await n.json().catch(()=>null);return _f(s)}catch(n){return _f(null,String((n==null?void 0:n.message)||n||"request failed"))}}const eS={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function bo(e){return typeof e=="string"?e.trim():""}function _f(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:{},s=bo(n.abstractgateway),o=bo(n.abstractframework);return{framework:o||null,gateway:s||null,...s&&!o?{frameworkNote:"not installed on the gateway host"}:{},...s?{}:{gatewayNote:"unavailable (the gateway did not report its version)"}}}function tS(e){const t=Tw();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 nS(e){const t=e||{},n=bo(t.framework),s=bo(t.gateway);return[["AbstractFramework",n||bo(t.frameworkNote)||"not reported"],["AbstractGateway",s||bo(t.gatewayNote)||"not connected"]]}const sS='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Rw(e,t,n){if(e.key!=="Tab"||!t)return;const s=Array.from(t.querySelectorAll(sS));if(s.length===0){e.preventDefault();return}const o=s[0],l=s[s.length-1],u=!!n&&t.contains(n);e.shiftKey?(n===o||!u)&&(e.preventDefault(),l.focus()):(n===l||!u)&&(e.preventDefault(),o.focus())}function rS(e){const t=Tw();return a.jsxs("div",{className:`af-about-card${e.className?` ${e.className}`:""}`,"data-app":e.identity.id,children:[a.jsxs("div",{className:"af-about-card__head",children:[a.jsxs("h2",{className:"af-about-card__name",id:e.titleId,children:[e.identity.name," ",a.jsx("span",{className:"af-about-card__version",children:e.identity.version})]}),e.action]}),a.jsx("dl",{className:"af-about-card__versions",children:nS(e.versions).map(([n,s])=>a.jsxs("div",{className:"af-about-card__fact",children:[a.jsx("dt",{children:n}),a.jsx("dd",{children:s})]},n))}),a.jsx("nav",{className:"af-about-card__links","aria-label":`${e.identity.name} links`,children:tS(e.identity).map(n=>n.href.startsWith("mailto:")?a.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,children:n.label},n.id):a.jsx("a",{className:"af-about-card__link","data-link":n.id,href:n.href,title:n.title,target:"_blank",rel:"noopener noreferrer",children:n.label},n.id))}),e.extra!==void 0&&e.extra!==null?a.jsx("div",{className:"af-about-card__extra",children:e.extra}):null,a.jsx("p",{className:"af-about-card__legal",children:t.copyright})]})}function aS(e){Io();const t=y.useRef(null),n=y.useRef(null),s=y.useId(),o=y.useRef(e.onClose);return o.current=e.onClose,y.useEffect(()=>{var d;if(!e.open)return;const l=document.activeElement;(d=t.current)==null||d.focus();const u=f=>{if(!f.defaultPrevented){if(f.key==="Escape"){f.preventDefault(),o.current();return}Rw(f,n.current,document.activeElement)}};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u),l&&typeof l.focus=="function"&&l.focus()}},[e.open]),e.open?a.jsx("div",{className:"af-appearance-overlay af-about-overlay",onClick:e.onClose,role:"presentation",children:a.jsx("div",{ref:n,className:"af-appearance af-about",role:"dialog","aria-modal":"true","aria-labelledby":s,onClick:l=>l.stopPropagation(),children:a.jsx(rS,{identity:e.identity,versions:e.versions,extra:e.extra,titleId:s,action:a.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:a.jsx(de,{name:"x",size:16})})})})}):null}const Kc={theme:"dark",font_scale:"md",header_density:"standard"};function oS(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Kc.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Kc.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Kc.header_density}}function iS(e){return`af_appearance_${e}_v1`}function lS(e,t){const n=iS(e),s=y.useMemo(()=>({...Kc,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=y.useState(()=>{let u=s;try{const d=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);d&&(u=oS({...s,...JSON.parse(d)}))}catch{}try{Ag(u.theme),$g({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return y.useEffect(()=>{Ag(o.theme),$g({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function cS(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?a.jsx("div",{className:"af-appearance-overlay",onClick:e.onClose,role:"presentation",children:a.jsxs("div",{className:"af-appearance",role:"dialog","aria-modal":"true","aria-label":e.title||"Appearance",onClick:t=>t.stopPropagation(),children:[a.jsx("div",{className:"af-appearance__title",children:e.title||"Appearance"}),a.jsx("div",{className:"af-appearance__note",children:e.note||"Stored locally in this browser, per app."}),a.jsxs("div",{className:"af-appearance__grid",children:[a.jsx("label",{className:"af-appearance__label",children:"Theme"}),a.jsx(yk,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),a.jsx("label",{className:"af-appearance__label",children:"Font size"}),a.jsx(wk,{value:e.value.font_scale,onChange:t=>e.onChange({...e.value,font_scale:t})}),a.jsx("label",{className:"af-appearance__label",children:"Header size"}),a.jsx(vk,{value:e.value.header_density,onChange:t=>e.onChange({...e.value,header_density:t})})]}),a.jsx("div",{className:"af-appearance__actions",children:a.jsx("button",{type:"button",className:"af-appearance__close",onClick:e.onClose,children:"Close"})})]})}):null}const uS="default";function Pr(e){return typeof e=="string"?e.trim():""}function Og(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0}function dS(e){var m;if(!e||!Ew(e))return null;const t=(m=e.gateway)==null?void 0:m.principal;if(!t||typeof t!="object")return null;const n=Pr(t.user_id);if(!n)return null;const s={userId:n},o=Pr(t.tenant_id);o&&(s.tenantId=o);const l=Pr(t.runtime_id);l&&(s.runtimeId=l);const u=Og(t.roles);u&&(s.roles=u);const d=Og(t.scopes);d&&(s.scopes=d);const f=Pr(t.source);return f&&(s.source=f),typeof t.admin=="boolean"&&(s.admin=t.admin),s}function Iw(e){const t=Pr(e.displayName)||Pr(e.userId),n=Pr(e.tenantId);return n&&n!==uS?`${n}/${t}`:t}function Lw(e){const t=Pr(e);if(!t)return"";try{return new URL(t).host||t}catch{return t}}function fS(e,t){return{label:t?"Disconnecting…":e==="connected"?"Disconnect":e==="loading"?"Connecting…":"Connect",title:e==="connected"?"Disconnect from gateway":e==="loading"?"Checking gateway session…":"Connect to gateway"}}function hS(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function mS(e,t){return hS(e)?{phase:e.phase,signingOut:e.signingOut===!0,connect:e.openModal,disconnect:async()=>{await e.signOut()===!0&&(t==null||t())},status:e.status,signOutError:e.signOutError||null}:{phase:e.phase,signingOut:e.signingOut===!0,connect:e.onConnect,disconnect:async()=>{e.onDisconnect()},status:e.status??null,signOutError:e.signOutError||null}}function pS(e,t){const n=Lw(t);return`Signed in as ${Iw(e)}${n?` · gateway ${n}`:""}`}const bf="--af-topbar-h";function gS(e,t=!0){y.useEffect(()=>{if(!t||typeof window>"u"||typeof document>"u")return;const n=e.current;if(!n)return;const s=n.closest("[data-af-topbar], header")||n.parentElement||n,o=document.documentElement;let l="";const u=()=>{l=`${Math.max(0,Math.round(s.getBoundingClientRect().bottom))}px`,o.style.setProperty(bf,l)};u();const d=typeof ResizeObserver<"u"?new ResizeObserver(u):null;d==null||d.observe(s);const f={passive:!0,capture:!0};return window.addEventListener("resize",u),window.addEventListener("scroll",u,f),()=>{d==null||d.disconnect(),window.removeEventListener("resize",u),window.removeEventListener("scroll",u,f),l&&o.style.getPropertyValue(bf)===l&&o.style.removeProperty(bf)}},[e,t])}function yS(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function wS(e){var N,E;const t=mS(e.connection,e.onSignOut),{phase:n,signingOut:s}=t,[o,l]=y.useState(!1),[u,d]=y.useState(!1),[f,m]=y.useState(void 0),p=y.useRef(null);Io(),gS(p,e.publishHeight!==!1);const g=e.about,_=e.appearance,v=!!(_&&"value"in _),C=g&&!g.versions?g.fetch:void 0,x=y.useRef(C);x.current=C,y.useEffect(()=>{const j=x.current;if(!o||!j)return;const I=typeof AbortController<"u"?new AbortController:null;let L=!0;return m(eS),Zk(j,I==null?void 0:I.signal).then(z=>{L&&m(z)}),()=>{L=!1,I==null||I.abort()}},[o]);const k=fS(n,s),S=e.identity&&n==="connected"?dS(t.status):null,$=()=>void t.disconnect();let R=null;if(S&&e.identity){const j=Iw(S),I=pS(S,(N=t.status)==null?void 0:N.gateway_url),L=a.jsxs(a.Fragment,{children:[a.jsx(de,{name:"user",size:14}),a.jsx("span",{className:"af-topbar__identity-label",children:j})]});if(e.identity==="badge")R=a.jsx("span",{className:"af-topbar__identity af-topbar__identity--badge","data-af-identity":"badge","data-af-tip":I,"aria-label":I,children:L});else{const z=yS(S.userId),V=Lw((E=t.status)==null?void 0:E.gateway_url);R=a.jsx(Bh,{label:`Account: ${I}`,tip:I,className:"af-topbar__account",buttonClassName:"af-topbar__identity af-topbar__identity--menu",buttonContent:L,header:a.jsxs("span",{className:"af-topbar__account-head","data-af-identity":"menu",children:[a.jsxs("span",{className:"af-topbar__account-who",children:["Signed in as ",j]}),V?a.jsxs("span",{className:"af-topbar__account-host",children:["Gateway ",V]}):null]}),items:[{id:"copy-user-id",label:"Copy user id",onSelect:z||(()=>{}),hidden:!z},{id:"disconnect",label:"Disconnect",onSelect:$,danger:!0,hidden:s}]})}}return a.jsxs("div",{ref:p,className:`af-topbar${e.className?` ${e.className}`:""}`,role:"group","aria-label":"App actions",children:[e.extraActions,e.docs?a.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:a.jsx(de,{name:"book",size:16})}):null,e.assistant?a.jsx("button",{type:"button",className:`af-topbar__btn af-topbar__btn--assistant${e.assistant.open?" is-active":""}`,"aria-pressed":e.assistant.open,"aria-label":e.assistant.label||"Open assistant","data-af-tip":e.assistant.label||"Assistant",onClick:e.assistant.onToggle,children:a.jsx(de,{name:"sparkle",size:16})}):null,_?a.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--appearance","aria-label":_.label||"Appearance (theme and typography)","data-af-tip":_.label||"Appearance (theme and text size)","aria-haspopup":v?"dialog":void 0,onClick:()=>{"value"in _?d(!0):_.onOpen()},children:a.jsx(de,{name:"contrast",size:16})}):null,g?a.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":g.label||`About ${g.identity.name}`,"data-af-tip":g.label||`About ${g.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var j;l(!0),(j=g.onOpen)==null||j.call(g)},children:a.jsx(de,{name:"info",size:16})}):null,R,t.signOutError?a.jsxs("span",{className:"af-topbar__signout-error",role:"alert","data-af-tip":`Disconnect failed: ${t.signOutError}`,"aria-label":`Disconnect failed: ${t.signOutError}`,children:[a.jsx(de,{name:"warning",size:14}),a.jsx("span",{className:"af-topbar__signout-error-label",children:"Disconnect failed"})]}):null,a.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?$:t.connect,disabled:s,title:k.title,"aria-label":k.title,children:[a.jsx("span",{className:`af-topbar__dot af-topbar__dot--${n}`,"aria-hidden":"true"}),a.jsx("span",{className:"af-topbar__pill-label",children:k.label})]}),g?a.jsx(aS,{open:o,onClose:()=>l(!1),identity:g.identity,versions:g.versions||(g.fetch?f:void 0),extra:g.extra}):null,_&&"value"in _?a.jsx(cS,{open:u,onClose:()=>d(!1),value:_.value,onChange:_.onChange,title:_.title,note:_.note}):null]})}function lh(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function Pg(e,t,n=!1){if(n)return"unknown";if(!e)return"";const s=e[t];return!s||!s.configured?"not set":lh(s)||"not set"}function vS(e,t){var n;return e.stt_provider?lh({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?lh(t.stt):""}function Mw(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function _S(e,t,n){return`Transcribing… ${Mw(e,t)}${n?` · ${n}`:""}`}const xu=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function tu(e){var o;const t=bu("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(!((o=xu())!=null&&o.getUserMedia))return"This browser cannot record audio.";const s=String((e==null?void 0:e.message)||e||"").trim();return s?`The microphone did not start: ${s.replace(/\.$/,"")}.`:"The microphone did not start."}async function Ow(e){const t=xu();if(!t||typeof t.enumerateDevices!="function")return{devices:[],labelled:!1};const s=(await t.enumerateDevices()).filter(u=>u.kind===e),o=s.some(u=>!!u.label);return{devices:s.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:o}}async function bS(){const e=xu();if(!(e!=null&&e.getUserMedia))throw new Error(bu("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Pw(e){const t=xu();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 ku(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Dw(){const e=ku();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function Fw(e,t,n=1){const s=ku();if(!s)return()=>{};const o=new s,l=o.createMediaStreamSource(e),u=o.createAnalyser();u.fftSize=1024,l.connect(u);const d=new Float32Array(u.fftSize);let f=!0;const p=setInterval(()=>{if(!f)return;u.getFloatTimeDomainData(d);let g=0;for(let _=0;_<d.length;_+=1)g+=d[_]*d[_];t(Math.min(1,Math.sqrt(g/d.length)*4*n))},50);return()=>{var g;f=!1,clearInterval(p);try{l.disconnect()}catch{}(g=o.close)==null||g.call(o)}}const zw=.02;function Dg(){return Object.assign(new Error("The recording was stopped before it began."),{name:"AbortError"})}async function Bw(e){var l,u,d;const t=globalThis.MediaRecorder;if(typeof t!="function")throw Object.assign(new Error("This browser cannot record audio."),{name:"NotSupportedError"});if((l=e.signal)!=null&&l.aborted)throw Dg();const n=await Pw(e.deviceId);if((u=e.signal)!=null&&u.aborted)throw n.getTracks().forEach(f=>f.stop()),Dg();let s=0;const o=Fw(n,f=>{var m;s=Math.max(s,f),(m=e.onLevel)==null||m.call(e,f)},e.gain??1);try{const f=new t(n),m=[],p=new Promise((_,v)=>{f.ondataavailable=C=>(C==null?void 0:C.data)&&m.push(C.data),f.onstop=()=>_(),f.onerror=C=>v((C==null?void 0:C.error)||new Error("Recording failed."))});f.start(),await new Promise(_=>{var C,x;if((C=e.signal)!=null&&C.aborted)return _();const v=setTimeout(_,e.ms??3e3);(x=e.signal)==null||x.addEventListener("abort",()=>{clearTimeout(v),_()},{once:!0})}),f.stop(),await p;const g=String(f.mimeType||"audio/webm");return{blob:new Blob(m,{type:g}),peak:s,mime:g}}finally{o(),n.getTracks().forEach(f=>f.stop()),(d=e.onLevel)==null||d.call(e,0)}}async function Ww(e,t={}){var o,l,u,d;if((o=t.signal)!=null&&o.aborted)return;const n=ku();if(!n)throw new Error("This browser cannot play audio.");const s=new n;try{t.deviceId&&typeof s.setSinkId=="function"&&await s.setSinkId(t.deviceId);const f=e instanceof Blob?await e.arrayBuffer():e,m=await s.decodeAudioData(f.slice(0));if((l=t.signal)!=null&&l.aborted)return;if(s.state==="suspended"&&await((u=s.resume)==null?void 0:u.call(s)),s.state==="suspended")throw new Error("The browser held the sound back: press play to hear it");const p=s.createGain();p.gain.value=ba(t.volume),p.connect(s.destination);const g=s.createBufferSource();g.buffer=m,g.connect(p),await new Promise(_=>{var C,x;const v=()=>{try{g.stop()}catch{}_()};g.onended=()=>{var k,S;(S=(k=t.signal)==null?void 0:k.removeEventListener)==null||S.call(k,"abort",v),_()},(x=(C=t.signal)==null?void 0:C.addEventListener)==null||x.call(C,"abort",v,{once:!0}),g.start()})}finally{(d=s.close)==null||d.call(s)}}async function xS(e={}){var s,o;const t=ku();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((s=n.resume)==null?void 0:s.call(n));const l=n.createGain();l.connect(n.destination);const u=.3*ba(e.volume),d=n.currentTime+.02;[660,880].forEach((f,m)=>{const p=n.createOscillator(),g=n.createGain();p.frequency.value=f,p.connect(g),g.connect(l);const _=d+m*.22;g.gain.setValueAtTime(0,_),g.gain.linearRampToValueAtTime(u,_+.02),g.gain.exponentialRampToValueAtTime(1e-4,_+.2),p.start(_),p.stop(_+.21)}),await new Promise(f=>setTimeout(f,520))}finally{(o=n.close)==null||o.call(n)}}function ba(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}function Eo(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}async function*kS(e){var s,o,l;const t=new AbortController,n=()=>t.abort();(s=e.signal)!=null&&s.aborted?n():(o=e.signal)==null||o.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),g=p&&typeof p=="object"&&p.detail?String(p.detail):`HTTP ${u.status}`;throw new Error(g)}if(!u.body)throw new Error("TTS stream has no body");const d=u.body.getReader(),f=new TextDecoder;let m="";for(;;){const{done:p,value:g}=await d.read();m+=p?f.decode():f.decode(g,{stream:!0}),p&&m.trim()&&(m+=`
42
- `);let _;for(;(_=m.indexOf(`
43
- `))>=0;){const v=m.slice(0,_).trim();if(m=m.slice(_+1),!v)continue;let C=null;try{C=JSON.parse(v)}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 k=atob(x),S=new Uint8Array(k.length);for(let $=0;$<k.length;$+=1)S[$]=k.charCodeAt($);yield S.buffer}if(C&&(C.type==="done"||C.type==="cancelled"))return}if(p)throw new Error("TTS stream ended before synthesis completed.")}}finally{(l=e.signal)==null||l.removeEventListener("abort",n),t.abort()}}function Ti(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const Uw=350;function SS(){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 jS(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function NS(){const e=window.MediaRecorder,t=s=>{var o;try{return!!((o=e==null?void 0:e.isTypeSupported)!=null&&o.call(e,s))}catch{return!1}},n=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"];for(const s of n)if(t(s))return s;return""}async function xf(e,t){var o;const n=t.slice(0),s=(o=e.decodeAudioData)==null?void 0:o.bind(e);if(typeof s!="function")throw new Error("decodeAudioData not available");try{const l=s(n);if(l&&typeof l.then=="function")return await l}catch{}return await new Promise((l,u)=>{try{s(n,l,u)}catch(d){u(d)}})}function CS(e){const t=new Uint8Array(e);if(t.length<44)return null;const n=l=>String.fromCharCode(t[l],t[l+1],t[l+2],t[l+3]);if(n(0)!=="RIFF"||n(8)!=="WAVE")return null;const s=new DataView(e);let o=12;for(;o+8<=t.length;){const l=n(o),u=s.getUint32(o+4,!0);if(l==="data")return t.slice(0,o+8);o+=8+u+u%2}return null}function ES(e,t){const n=new Uint8Array(t),s=new Uint8Array(e.length+n.length);s.set(e,0),s.set(n,e.length);const o=new DataView(s.buffer);return o.setUint32(4,s.length-8,!0),o.setUint32(e.length-4,n.length,!0),s.buffer}function Vw(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const Rc=new WeakMap;function AS(e,t){const n=e;if(!(typeof n.setSinkId!="function"||Rc.get(e)===t)){Rc.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>Rc.delete(e))}catch{Rc.delete(e)}}}function $S(e){const t=y.useRef(e);t.current=e;const n=Q=>{var _e,ae;return(ae=(_e=t.current).on_error)==null?void 0:ae.call(_e,Q)},s=y.useMemo(()=>jS()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),o=y.useMemo(()=>SS()&&typeof e.transcribe=="function",[e.transcribe]),[l,u]=y.useState({key:"",status:"idle"}),d=y.useRef(l),f=y.useCallback(Q=>{d.current=Q,u(_e=>_e.key===Q.key&&_e.status===Q.status?_e:Q)},[]),m=y.useRef(""),p=y.useRef(""),g=y.useRef(null),_=y.useRef(null),v=y.useRef(null),C=y.useRef(null),x=y.useRef(0),k=y.useRef(0),S=y.useRef(0),$=y.useRef(null),R=y.useRef([]),N=y.useRef(0),E=y.useRef(!0),j=y.useRef(!1),I=()=>{try{const Q=globalThis,_e=(Q==null?void 0:Q.AudioContext)||(Q==null?void 0:Q.webkitAudioContext);if(!_e)return null;if(!g.current){const Oe=new _e,Fe=Oe.createGain();Fe.gain.value=1,Fe.connect(Oe.destination),g.current=Oe,_.current=Fe}const ae=g.current,Se=_.current;if(!ae||!Se)return null;AS(ae,t.current.output_device_id||""),Se.gain.value=ba(t.current.volume)*(t.current.muted?0:1);try{ae.state==="suspended"&&ae.resume()}catch{}return{ctx:ae,gain:Se}}catch{return null}};y.useEffect(()=>{const Q=_.current;Q&&(Q.gain.value=ba(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const L=y.useCallback(()=>{const Q=v.current;if(v.current=null,!!Q){try{Q.onended=null}catch{}try{Q.stop()}catch{}try{Q.disconnect()}catch{}}},[]),z=y.useCallback(()=>{var Q;L(),S.current+=1,(Q=$.current)==null||Q.abort(),$.current=null,R.current=[],N.current=0,E.current=!0,j.current=!1,p.current="",m.current="",C.current=null,x.current=0,k.current=0,f({key:"",status:"idle"})},[L,f]);y.useEffect(()=>()=>{var Q,_e;z();try{(Q=_.current)==null||Q.disconnect()}catch{}try{(_e=g.current)==null||_e.close()}catch{}g.current=null,_.current=null,C.current=null},[]);const V=async(Q,_e,ae)=>{const Se=S.current,Oe=I();if(!Oe)throw new Error("TTS playback is not supported in this browser");const{ctx:Fe,gain:Ze}=Oe;try{Fe.state==="suspended"&&await Fe.resume()}catch{}if(Se!==S.current)return;L();const Le=Fe.createBufferSource();Le.buffer=_e,Le.connect(Ze);const Ke=Number.isFinite(Number(_e.duration))?Number(_e.duration):0,De=Math.max(0,Math.min(Number(ae||0),Ke>0?Math.max(0,Ke-.01):0));k.current=Fe.currentTime-De,x.current=De,v.current=Le,m.current=Q,Le.onended=()=>{v.current===Le&&(v.current=null,x.current=0,k.current=0,m.current="",f({key:"",status:"idle"}))},Le.start(0,De),f({key:Q,status:"playing"})},Z=(Q,_e)=>{if(_e!==S.current)return;const ae=I();if(!ae)return;const Se=R.current,Oe=N.current;if(Oe>=Se.length){E.current&&(m.current="",x.current=0,k.current=0,f({key:"",status:"idle"}));return}const Fe=Se[Oe],{ctx:Ze,gain:Le}=ae;L();const Ke=Ze.createBufferSource();Ke.buffer=Fe,Ke.connect(Le);const De=Number.isFinite(Number(Fe.duration))?Number(Fe.duration):0,pt=Math.max(0,Math.min(Number(x.current||0),De>0?Math.max(0,De-.01):0));k.current=Ze.currentTime-pt,v.current=Ke,m.current=Q,Ke.onended=()=>{_e===S.current&&v.current===Ke&&(v.current=null,N.current=Oe+1,x.current=0,Z(Q,_e))};try{Ze.state==="suspended"&&Ze.resume()}catch{}Ke.start(0,pt),f({key:Q,status:"playing"})},ie=async(Q,_e,ae)=>{var Le;const Se=I();if(!Se){n==null||n("This browser cannot play spoken replies.");return}L();const Oe=++S.current;(Le=$.current)==null||Le.abort();const Fe=new AbortController;$.current=Fe,R.current=[],N.current=0,E.current=!1,j.current=!1,C.current=null,x.current=0,k.current=0,m.current=Q,p.current=Q,f({key:Q,status:"loading"}),n==null||n("");let Ze=null;try{for await(const Ke of ae(_e,Fe.signal)){if(Oe!==S.current)return;let De;try{De=await xf(Se.ctx,Ke),Ze||(Ze=CS(Ke))}catch{if(!Ze)continue;try{De=await xf(Se.ctx,ES(Ze,Ke))}catch{continue}}if(Oe!==S.current)return;R.current.push(De),!v.current&&!j.current&&(p.current="",Z(Q,Oe))}if(Oe!==S.current)return;if(E.current=!0,R.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),z();return}!v.current&&!j.current&&Z(Q,Oe)}catch(Ke){if(Oe!==S.current)return;n==null||n(Ti("Reading aloud failed",Ke)),z()}finally{$.current===Fe&&($.current=null)}},F=y.useCallback(async(Q,_e)=>{var pt;const ae=String(Q||"").trim(),Se=String(_e||"").trim();if(!ae||!Se)return;const Oe=t.current.tts,Fe=t.current.tts_stream;if(typeof Oe!="function"&&typeof Fe!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Ze=I();if(!Ze){n==null||n("This browser cannot play spoken replies.");return}const Le=d.current,Ke=Le.key===ae;if(Ke&&Le.status==="playing"){if(v.current){const St=Math.max(0,Ze.ctx.currentTime-Number(k.current||0));x.current=St}else x.current=0;j.current=!0,L(),f({key:ae,status:"paused"});return}if(Ke&&Le.status==="paused"){if(R.current.length>0){n==null||n(""),j.current=!1,f({key:ae,status:"playing"}),Z(ae,S.current);return}const St=C.current;if(St){n==null||n(""),j.current=!1;try{await V(ae,St,x.current)}catch(jt){n==null||n(Ti("Reading aloud failed",jt)),f({key:"",status:"idle"})}return}}if(Ke&&Le.status==="loading")return;if(typeof Fe=="function"){await ie(ae,Se,Fe);return}L(),S.current+=1,(pt=$.current)==null||pt.abort(),$.current=null;const De=S.current;R.current=[],N.current=0,E.current=!0,j.current=!1,C.current=null,x.current=0,k.current=0,m.current=ae,p.current=ae,f({key:ae,status:"loading"}),n==null||n("");try{const St=await Oe(Se);if(p.current!==ae||S.current!==De)return;const jt=await xf(Ze.ctx,St);if(p.current!==ae||S.current!==De)return;C.current=jt,x.current=0,await V(ae,jt,0)}catch(St){if(S.current!==De)return;p.current===ae&&(p.current="",m.current="",f({key:"",status:"idle"})),n==null||n(Ti("Reading aloud failed",St))}},[]),[D,M]=y.useState(!1),[J,B]=y.useState(!1),Y=y.useRef(!1),te=y.useRef(o);te.current=o;const W=y.useCallback(Q=>{Y.current=Q,M(_e=>_e===Q?_e:Q)},[]),T=y.useRef(!1),K=y.useRef(null),ne=y.useRef(null),ue=y.useRef([]),oe=y.useRef(""),ve=y.useRef(0),Ne=y.useRef(!1),q=y.useRef(!1),[be,xe]=y.useState(0),Pe=y.useRef(0),Qe=y.useRef(null),He=y.useRef(0),qe=y.useRef(new Set),ge=y.useRef(null),$e=y.useCallback(Q=>{const _e=Math.round(Math.min(1,Math.max(0,Number(Q)||0))*20)/20;if(_e!==He.current){He.current=_e;for(const ae of Array.from(qe.current))ae(_e)}},[]),st=y.useCallback(Q=>(qe.current.add(Q),Q(He.current),()=>{qe.current.delete(Q)}),[]),tt=y.useRef(new Set),Lt=y.useCallback(Q=>(tt.current.add(Q),()=>{tt.current.delete(Q)}),[]);function ce(){var ae,Se;const Q=ge.current;ge.current=null;try{Q==null||Q()}catch{}$e(0);try{(Se=(ae=K.current)==null?void 0:ae.getTracks)==null||Se.call(ae).forEach(Oe=>{try{Oe.stop()}catch{}})}catch{}K.current=null;const _e=Qe.current;Qe.current=null;try{_e==null||_e.close()}catch{}}const fe=y.useCallback(()=>{ve.current+=1,Ne.current=!1;const Q=ne.current;if(Q){Q.onstop=null,Q.ondataavailable=null,Q.onerror=null;try{Q.stop()}catch{}}ne.current=null,ce(),W(!1),T.current=!1,B(!1),xe(0),ue.current=[]},[W]);y.useEffect(()=>()=>fe(),[fe]);async function H(Q,_e){var Fe,Ze;if(n==null||n(""),T.current)return;const ae=Pe.current?Date.now()-Pe.current:1/0;if(!Q||!Q.size||ae<Uw){xe(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 Se=t.current.transcribe;if(typeof Se!="function"){n==null||n("Speech to text is not available on this gateway.");return}T.current=!0;const Oe=ve.current;B(!0),xe(Date.now());try{const Le=await Se(Q,_e),Ke=typeof Le=="string"||!Le?{text:String(Le||"")}:Le,De=String(Ke.text||"").trim();if(Oe!==ve.current)return;if(De){(Ze=(Fe=t.current).on_transcript)==null||Ze.call(Fe,De,{...Ke,text:De});for(const pt of Array.from(tt.current))pt(De,{...Ke,text:De})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(Le){if(Oe===ve.current){const Ke=String((Le==null?void 0:Le.message)||Le||"").trim().replace(/\.$/,"");n==null||n(Ke?`Transcription failed: ${Ke}.`:"Transcription failed.")}}finally{Oe===ve.current&&(T.current=!1,B(!1),xe(0))}}const le=y.useCallback(async()=>{if(n==null||n(""),!te.current){n==null||n(bu("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(T.current||Ne.current||Y.current||ne.current)return;ue.current=[];const Q=ve.current;Ne.current=!0,q.current=!1;try{const _e=await Pw(t.current.input_device_id||"");if(Q!==ve.current){_e.getTracks().forEach(Le=>Le.stop());return}if(q.current){q.current=!1,_e.getTracks().forEach(Le=>Le.stop()),xe(0);return}K.current=_e;const ae=Number(t.current.input_gain??1);try{ge.current=Fw(_e,$e,Number.isFinite(ae)&&ae>0?ae:1)}catch{}const Se=NS();oe.current=Se;let Oe=_e;const Fe=Number(t.current.input_gain??1);if(Number.isFinite(Fe)&&Fe>0&&Fe!==1&&Dw()){const Le=globalThis.AudioContext||globalThis.webkitAudioContext,Ke=new Le,De=Ke.createGain();De.gain.value=Fe;const pt=Ke.createMediaStreamDestination();Ke.createMediaStreamSource(_e).connect(De),De.connect(pt),Qe.current=Ke,Oe=pt.stream}const Ze=Se?new MediaRecorder(Oe,{mimeType:Se}):new MediaRecorder(Oe);ne.current=Ze,Ze.ondataavailable=Le=>{if(Q===ve.current)try{Le!=null&&Le.data&&ue.current.push(Le.data)}catch{}},Ze.onerror=()=>{Q===ve.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Ze.onstop=()=>{if(Q===ve.current){W(!1),ce(),ne.current=null;try{const Le=new Blob(ue.current,{type:oe.current||""});H(Le,oe.current)}catch(Le){n==null||n(Ti("The recording could not be prepared",Le))}}},Ze.start(),Pe.current=Date.now(),xe(Pe.current),W(!0)}catch(_e){if(Q!==ve.current)return;ce(),ne.current=null,W(!1),xe(0),n==null||n(tu(_e))}finally{Q===ve.current&&(Ne.current=!1)}},[]),he=y.useCallback(()=>{const Q=ne.current;if(Ne.current&&!Q){q.current=!0;return}if(!(!Y.current||!Q)){W(!1);try{Q.stop()}catch(_e){n==null||n(Ti("The recording could not stop",_e))}}},[]);return y.useEffect(()=>{if(!D||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&Eo(t.current.capture_mode)==="toggle")return;const Q=()=>he();return window.addEventListener("pointerup",Q),window.addEventListener("pointercancel",Q),()=>{window.removeEventListener("pointerup",Q),window.removeEventListener("pointercancel",Q)}},[D]),{tts_supported:s,tts_playback:l,toggle_tts:F,stop_tts:z,voice_ptt_supported:o,voice_ptt_recording:D,voice_ptt_busy:J,start_voice_ptt_recording:le,stop_voice_ptt_recording:he,cancel_voice_ptt_recording:fe,voice_ptt_since:be,subscribe_level:st,voice_capture_mode:Eo(e.capture_mode),add_transcript_listener:Lt}}const Fg=["Your voices","Engine voices","Shared voices"];function Gw(e){var s,o;const t=e&&e.tags||{},n=(o=(s=e==null?void 0:e.params)==null?void 0:s.meta)==null?void 0:o.scope;return t.builtin?"Shared voices":(e==null?void 0:e.kind)==="clone"||(e==null?void 0:e.voice_kind)==="clone"?n==="library"?"Shared voices":"Your voices":"Engine voices"}function Su(e){var t;return String((e==null?void 0:e.language)||((t=e==null?void 0:e.tags)==null?void 0:t.language_code)||"").trim().toLowerCase()}function TS(e){return Array.from(new Set(e.map(Su).filter(Boolean))).sort()}function RS(e,t){if(!t)return!0;const n=Su(e);if(n===t)return!0;const s=Array.isArray(e==null?void 0:e.languages)?e.languages.map(o=>String(o).toLowerCase()):[];return!n&&s.length===0?!0:s.includes(t)}const Hw={en:"English",fr:"French",de:"German",es:"Spanish",it:"Italian",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ko:"Korean",nl:"Dutch",pl:"Polish",tr:"Turkish",ar:"Arabic",hi:"Hindi"},Kw=Hw,xa=e=>Kw[e]||e,kf=e=>String((e==null?void 0:e.voice_id)||(e==null?void 0:e.id)||""),Ic=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):[],IS=200;function LS({value:e,onChange:t,fetchCatalog:n,intro:s,delivery:o=!0,quality:l=!0,showReset:u=!0,defaultHint:d,voiceDefaultLabel:f,createVoice:m,voiceLibrary:p,previewVoice:g,previewOn:_,recordFrom:v}){var st,tt,Lt,ce,fe;const C=p||m,[x,k]=y.useState({state:"idle",error:""}),S=y.useRef(0),$=y.useRef(null),R=y.useRef(null),N=y.useRef(null),E=y.useRef(null),j=y.useRef(n);j.current=n;const[I,L]=y.useState({}),[z,V]=y.useState(""),[Z,ie]=y.useState(!1),[F,D]=y.useState(""),[M,J]=y.useState(0),B=y.useRef(e);B.current=e;const Y=y.useRef(!0),te=()=>{var H,le;S.current+=1,E.current!==null&&clearTimeout(E.current),E.current=null,(H=$.current)==null||H.abort(),$.current=null,(le=R.current)==null||le.abort(),R.current=null};y.useEffect(()=>(Y.current=!0,()=>{Y.current=!1,te()}),[]);const W=H=>JSON.stringify([H.provider||"",H.model||"",H.voice||"",H.profile||""]),T=H=>`The sample did not play: ${String((H==null?void 0:H.message)||H).replace(/\.$/,"")}.`,K=(H,le)=>{const he=new AbortController;R.current=he,k({state:"playing",error:""}),Ww(H,{deviceId:(_==null?void 0:_.deviceId)||"",volume:_==null?void 0:_.volume,signal:he.signal}).then(()=>Y.current&&S.current===le&&k({state:"idle",error:""})).catch(Q=>Y.current&&S.current===le&&k({state:"idle",error:T(Q)}))},ne=H=>{if(!g)return;te();const le=S.current,he=new AbortController;$.current=he,k({state:"loading",error:""}),g(H,void 0,{signal:he.signal}).then(Q=>{!Y.current||S.current!==le||($.current=null,N.current={key:W(H),bytes:Q},K(Q,le))}).catch(Q=>{!Y.current||S.current!==le||($.current=null,k({state:"idle",error:T(Q)}))})},ue=H=>{if(!g)return;te();const le=S.current;if(N.current&&N.current.key===W(H)){K(N.current.bytes,le);return}k({state:"loading",error:""}),E.current=setTimeout(()=>{E.current=null,Y.current&&S.current===le&&ne(H)},IS)},oe=()=>{if(x.state!=="idle"){te(),k({state:"idle",error:""});return}const H=B.current;if(N.current&&N.current.key===W(H)){te(),K(N.current.bytes,S.current);return}ne(H)};y.useEffect(()=>{D("")},[e.provider]),y.useEffect(()=>{let H=!0;return ie(!0),L({}),V(""),j.current(e.provider,e.model).then(le=>{H&&(L(le),V(le.error?String(le.error):""))}).catch(le=>{H&&V(String((le==null?void 0:le.message)||le))}).finally(()=>{H&&ie(!1)}),()=>{H=!1}},[e.provider,e.model,M]);const ve=Array.isArray(I.items)?I.items:[...Array.isArray(I.profiles)?I.profiles.map(H=>({...H,voice_kind:"profile"})):[],...Array.isArray(I.voices)?I.voices.map(H=>({...H,voice_kind:"voice"})):[]],Ne=H=>JSON.stringify([H.provider||"",H.model||"",H.voice_kind==="profile"?"profile":"voice",H.id]),q=H=>(!e.provider||!H.provider||H.provider===e.provider)&&(!e.model||!H.model||H.model===e.model),be=ve.find(H=>H.id===(e.profile||e.voice)&&H.voice_kind==="profile"==!!e.profile&&q(H))||(!e.profile&&e.voice?ve.find(H=>H.id===e.voice&&H.voice_kind==="profile"&&q(H)):void 0),xe=be?Ne(be):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",Pe=TS(ve),Qe=Pe.length>1;y.useEffect(()=>{!Qe&&!Z&&D("")},[Qe,Z]);const He=Qe?F:"",qe=ve.filter(H=>(H==null?void 0:H.id)&&(!e.provider||!H.provider||H.provider===e.provider)&&(RS(H,He)||Ne(H)===xe)).map(H=>{const le=Su(H);return{value:Ne(H),group:Gw(H),label:`${H.label||H.name||H.id}${le?` · ${xa(le)}`:""}${!e.provider&&H.provider?` · ${H.provider}`:""}`}}).sort((H,le)=>Fg.indexOf(H.group)-Fg.indexOf(le.group)),ge=String(((st=be==null?void 0:be.tags)==null?void 0:st.description)||"").trim();xe&&!qe.some(H=>H.value===xe)&&qe.unshift({value:xe,group:"",label:`${e.profile||e.voice} (saved)`});const $e=H=>t({...e,...H});return a.jsxs("div",{className:"af-voice-settings",children:[s===void 0?a.jsx("p",{children:"Speech is generated by your authenticated Gateway. Leave routing and voice unset to use its defaults."}):s,a.jsx(_u,{defaultHint:d,value:{provider:e.provider||"",model:e.model||""},onChange:H=>{te(),k({state:"idle",error:""}),t({...e,...H,voice:"",profile:""})},fetchProviders:async()=>{const H=await j.current();if(H.error&&!Ic(H.tts_providers||H.providers).length)throw new Error(H.error);return Ic(H.tts_providers||H.providers).map(le=>({name:le}))},fetchModels:async H=>{var ae,Se;const le=await j.current(H),he=Ic(((ae=le.tts_models_by_provider)==null?void 0:ae[H])||le.tts_models||le.models),Q=Array.isArray((Se=le.tts_model_details_by_provider)==null?void 0:Se[H])?le.tts_model_details_by_provider[H]:[],_e=new Map(Q.filter(Oe=>Oe&&Oe.id).map(Oe=>[String(Oe.id),String(Oe.label||(Oe.role==="cloning"?`${Oe.id} (clones)`:Oe.id))]));return he.map(Oe=>({id:Oe,label:_e.get(Oe)||Oe}))},providerLabel:"Speech provider",modelLabel:"Speech model"}),Qe?a.jsxs("label",{children:["Voices that speak",a.jsx(bn,{ariaLabel:"Voice language",placeholder:"Any language",value:F,searchable:!1,options:[{value:"",label:"Any language"},...Pe.map(H=>({value:H,label:xa(H)}))],onChange:D})]}):null,a.jsxs("label",{children:["Voice / profile",a.jsxs("span",{className:"af-voice-settings__voice-row",children:[a.jsx(bn,{ariaLabel:"AI voice",placeholder:f||"Gateway / provider default",value:xe,disabled:Z,options:[{value:"",label:f||"Gateway / provider default"},...qe],onChange:H=>{let le;if(!H)le={voice:"",profile:""};else{const[he,Q,_e,ae]=JSON.parse(H);le={provider:he||e.provider||"",model:Q||(he&&he!==e.provider?"":e.model)||"",voice:_e==="voice"?ae:"",profile:_e==="profile"?ae:""}}$e(le),ue({...e,...le})}}),g?a.jsx("button",{type:"button",className:"af-voice-settings__sample","data-action":"play-sample","data-state":x.state,"aria-busy":x.state==="loading","aria-label":x.state==="playing"?"Stop the sample":x.state==="loading"?"Cancel the sample":"Play a sample of this voice",title:x.state==="playing"?"Stop":x.state==="loading"?"Synthesizing… (click to cancel)":"Play a sample",disabled:Z&&x.state==="idle",onClick:oe,children:a.jsx("span",{"aria-hidden":"true",children:x.state==="playing"?"■":"▶"})}):null]})]}),x.error?a.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"sample",children:x.error}):null,ge?a.jsx("p",{className:"af-voice-settings__description",children:ge}):null,Z?a.jsx("p",{role:"status",children:"Loading available voices…"}):null,z?a.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",z,". Your saved choice is preserved."]}):null,!Z&&!z&&e.provider&&ve.length===0&&String(I.unavailable_reason||"").trim()?a.jsx("p",{className:"af-voice-note",role:"status","data-voice-note":"unavailable",children:String(I.unavailable_reason).trim()}):null,o?a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Speaking speed",a.jsxs("select",{"aria-label":"Speech speed",value:e.speed??"",onChange:H=>$e({speed:H.target.value?Number(H.target.value):void 0}),children:[a.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(H=>a.jsxs("option",{value:H,children:[H,"×"]},H))]})]}),l&&((Lt=(tt=I.controls)==null?void 0:tt.quality_preset)!=null&&Lt.supported)?a.jsxs("label",{children:["Quality",a.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:H=>$e({quality_preset:H.target.value}),children:[a.jsx("option",{value:"",children:"Gateway default"}),Ic(I.controls.quality_preset.values).map(H=>a.jsx("option",{value:H,children:H},H))]})]}):null,(fe=(ce=I.controls)==null?void 0:ce.instructions)!=null&&fe.supported?a.jsxs("label",{children:["Delivery instructions",a.jsx("textarea",{"aria-label":"Voice delivery instructions",rows:3,placeholder:"For example: calm, clear, and conversational",value:e.instructions||"",onChange:H=>$e({instructions:H.target.value})})]}):null]}):null,C&&(C.design||C.clone)?a.jsx(PS,{creation:C,defaultLanguage:He,recordFrom:v,onCreated:(H,le)=>{const he=B.current;t({...he,provider:le||he.provider||"",model:"",voice:H,profile:""}),J(Q=>Q+1)}}):null,p!=null&&p.list?a.jsx(FS,{library:p,refreshKey:M,onChanged:()=>J(H=>H+1),onRemoved:H=>{const le=B.current;le.voice===H&&t({...le,voice:""})}}):null,u?a.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const MS={value:"",label:"Detect from the recording"},OS=3e4;function PS({creation:e,defaultLanguage:t,onCreated:n,recordFrom:s,cloneRoute:o}){const[l,u]=y.useState(e.design?"design":"clone"),[d,f]=y.useState(""),[m,p]=y.useState(""),[g,_]=y.useState(t||"en"),[v,C]=y.useState(""),[x,k]=y.useState(null),[S,$]=y.useState(""),[R,N]=y.useState(!1),[E,j]=y.useState(!1),[I,L]=y.useState(0),[z,V]=y.useState({text:"",tone:"info"}),Z=y.useRef(!1),ie=y.useRef(!0),F=y.useRef(null);y.useEffect(()=>(ie.current=!0,()=>{var te;ie.current=!1,(te=F.current)==null||te.abort()}),[]);const D=Object.keys(Kw).map(te=>({value:te,label:xa(te)})),M=l==="design"?g:v,J=()=>{if(F.current){F.current.abort();return}const te=new AbortController;F.current=te;const W=Date.now();j(!0),V({text:"Recording — read a few sentences, then press Stop.",tone:"info"}),Bw({deviceId:(s==null?void 0:s.deviceId)||"",gain:s==null?void 0:s.gain,ms:OS,signal:te.signal,onLevel:T=>ie.current&&L(T)}).then(({blob:T,peak:K})=>{if(ie.current){if(K<zw){V({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}k(T),V({text:`Recording ready (${Math.max(1,Math.round((Date.now()-W)/1e3))} s).`,tone:"ok"})}}).catch(T=>{ie.current&&((T==null?void 0:T.name)==="AbortError"?V({text:"Recording cancelled.",tone:"info"}):V({text:tu(T),tone:"error"}))}).finally(()=>{F.current===te&&(F.current=null),ie.current&&(j(!1),L(0))})},B=async()=>{if(!(Z.current||F.current)){Z.current=!0,N(!0),V({text:l==="design"?"Creating the voice from your description…":"Cloning the voice from your recording…",tone:"info"});try{const te=l==="design"?await e.design({description:d.trim(),name:m.trim()||void 0,language:g}):await e.clone(x,{name:m.trim()||void 0,reference_text:S.trim()||void 0,...v?{language:v}:{},...o!=null&&o.provider?{provider:o.provider}:{},...o!=null&&o.provider&&o.model?{model:o.model}:{}});if(!ie.current)return;V({text:`Voice ready: ${te.name||te.voice_id}. It is selected above.`,tone:"ok"}),n(te.voice_id,te.engine||(l==="design"?"qwen3-tts":void 0))}catch(te){if(!ie.current)return;V({text:`The voice was not created: ${String((te==null?void 0:te.message)||te).replace(/\.$/,"")}.`,tone:"error"})}finally{Z.current=!1,ie.current&&N(!1)}}},Y=l==="design"?!!d.trim():!!x&&!E;return a.jsxs("fieldset",{className:"af-voice-create","data-voice-create":!0,children:[a.jsx("legend",{children:"Create a voice"}),a.jsxs("div",{className:"af-voice-create__modes",role:"tablist",children:[e.design?a.jsx("button",{type:"button",role:"tab","aria-selected":l==="design","data-create-mode":"design",disabled:R||E,onClick:()=>u("design"),children:"From a description"}):null,e.clone?a.jsx("button",{type:"button",role:"tab","aria-selected":l==="clone","data-create-mode":"clone",disabled:R||E,onClick:()=>u("clone"),children:"From a recording"}):null]}),l==="design"?a.jsxs("label",{children:["Describe the voice",a.jsx("textarea",{"aria-label":"Voice description",rows:3,placeholder:"A calm, warm adult female voice with a slight British accent, speaking slowly.",value:d,onChange:te=>f(te.target.value)})]}):a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Recording",a.jsx("input",{"aria-label":"Voice recording",type:"file",accept:"audio/*",disabled:E,onChange:te=>{const W=te.target.files&&te.target.files[0]||null;k(W),W&&V({text:"",tone:"info"})}})]}),a.jsxs("div",{className:"af-voice-create__record",children:[a.jsx("button",{type:"button","data-action":"record-sample",disabled:R,onClick:J,children:E?"Stop":"Record"}),E?a.jsx("div",{className:"af-voice-meter","data-voice-meter":!0,role:"meter","aria-label":"Recording level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(I*100),children:a.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(I*100)}%`}})}):null]}),a.jsxs("label",{children:["What the recording says (optional)",a.jsx("input",{"aria-label":"Recording transcript",value:S,onChange:te=>$(te.target.value)})]})]}),a.jsxs("label",{children:["Name",a.jsx("input",{"aria-label":"Voice name",value:m,placeholder:"My voice",onChange:te=>p(te.target.value)})]}),a.jsxs("label",{children:["Language",a.jsx(bn,{ariaLabel:"Voice language for creation",value:M,searchable:!1,options:l==="design"?D:[MS,...D],onChange:l==="design"?_:C})]}),a.jsx("button",{type:"button","data-action":"create-voice",disabled:R||!Y,onClick:B,children:R?"Creating…":"Create voice"}),z.text?a.jsx("p",{className:`af-voice-note af-voice-note--${z.tone}`,role:"status","data-voice-note":"create",children:z.text}):null]})}const DS=e=>Array.isArray(e)?e:Array.isArray(e==null?void 0:e.voices)?e.voices:[],zg=e=>String((e==null?void 0:e.message)||e||"").trim().replace(/\.$/,"");function FS({library:e,refreshKey:t,onChanged:n,onRemoved:s}){const[o,l]=y.useState([]),[u,d]=y.useState({loading:!0,error:""}),[f,m]=y.useState(null),[p,g]=y.useState(""),[_,v]=y.useState(""),[C,x]=y.useState({text:"",tone:"info"}),[k,S]=y.useState(0),$=y.useRef(e);$.current=e;const R=y.useRef(!1),N=y.useRef(!0);y.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]),y.useEffect(()=>{const I=$.current.list;if(!I)return;let L=!0;return d(z=>({loading:!0,error:z.error})),I().then(z=>{L&&(l(DS(z).filter(V=>{var Z;return kf(V)&&!((Z=V==null?void 0:V.tags)!=null&&Z.builtin)})),d({loading:!1,error:""}))}).catch(z=>L&&d({loading:!1,error:`The voices could not be listed: ${zg(z)}.`})),()=>{L=!1}},[t,k]);const E=(I,L,z,V)=>{R.current||(R.current=!0,v(I),x({text:"",tone:"info"}),L().then(()=>{N.current&&(x({text:z,tone:"ok"}),m(null),g(""),V==null||V(),S(Z=>Z+1),n==null||n())}).catch(Z=>N.current&&x({text:`${zg(Z)||"The gateway refused"}.`,tone:"error"})).finally(()=>{R.current=!1,N.current&&v("")}))},j=I=>String(I.name||I.label||kf(I));return a.jsxs("fieldset",{className:"af-voice-library","data-voice-library":!0,children:[a.jsx("legend",{children:"Manage voices"}),u.loading&&!o.length?a.jsx("p",{role:"status",children:"Loading your voices…"}):null,u.error?a.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"library",children:u.error}):null,!u.loading&&!u.error&&!o.length?a.jsx("p",{className:"af-voice-library__empty",children:"No voices of your own yet."}):null,o.length?a.jsx("ul",{className:"af-voice-library__list",children:o.map(I=>{const L=kf(I),z=Gw(I)==="Shared voices",V=Su(I),Z=String(I.engine||I.provider||""),ie=_===L;return a.jsxs("li",{className:"af-voice-library__item","data-voice-id":L,children:[(f==null?void 0:f.id)===L?a.jsxs("span",{className:"af-voice-library__edit",children:[a.jsx("input",{"aria-label":`New name for ${j(I)}`,value:f.name,onChange:F=>m({id:L,name:F.target.value})}),a.jsx("button",{type:"button","data-action":"save-voice-name",disabled:ie||!f.name.trim(),onClick:()=>E(L,()=>$.current.rename(L,{name:f.name.trim()}),`Renamed to ${f.name.trim()}.`),children:"Save"}),a.jsx("button",{type:"button","data-action":"cancel-voice-name",disabled:ie,onClick:()=>m(null),children:"Cancel"})]}):a.jsxs("span",{className:"af-voice-library__name",children:[j(I),a.jsx("span",{className:"af-voice-library__meta",children:[z?"Shared":"Yours",V?xa(V):"",Z].filter(Boolean).join(" · ")})]}),p===L?a.jsxs("span",{className:"af-voice-library__confirm",role:"group","aria-label":`Delete ${j(I)}?`,children:["Delete ",j(I),"?",a.jsx("button",{type:"button","data-action":"confirm-delete-voice",disabled:ie,onClick:()=>E(L,()=>$.current.remove(L),`${j(I)} was deleted.`,()=>s==null?void 0:s(L)),children:"Delete"}),a.jsx("button",{type:"button","data-action":"keep-voice",disabled:ie,onClick:()=>g(""),children:"Keep"})]}):(f==null?void 0:f.id)!==L?a.jsxs("span",{className:"af-voice-library__actions",children:[e.rename?a.jsx("button",{type:"button","data-action":"rename-voice",disabled:!!_,onClick:()=>m({id:L,name:j(I)}),children:"Rename"}):null,e.remove?a.jsx("button",{type:"button","data-action":"delete-voice",disabled:!!_,onClick:()=>g(L),children:"Delete"}):null,e.share&&!z?a.jsx("button",{type:"button","data-action":"share-voice",disabled:!!_,onClick:()=>E(L,()=>$.current.share(L),`${j(I)} is shared with everyone.`),children:"Share"}):null]}):null]},L)})}):null,C.text?a.jsx("p",{className:`af-voice-note af-voice-note--${C.tone}`,role:"status","data-voice-note":"library-action",children:C.text}):null]})}const Sf=we("automations"),zS=we("trigger-sources"),BS=we("me/email"),WS=we("me/email/accounts"),US=we("triggers/connections"),VS=we("automations/schedule-preview");class Bg 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 GS(e,t){const n=t&&typeof t=="object"?t.detail:void 0;if(n&&typeof n=="object"&&!Array.isArray(n)){const s=n;if(typeof s.reason_code=="string"&&s.reason_code&&typeof s.message=="string"){const o={status:e,code:s.reason_code,message:s.message};return typeof s.field=="string"&&(o.field=s.field),typeof s.command_id=="string"&&(o.command_id=s.command_id),o}}return{status:e,code:"invalid_response",message:`The gateway answered HTTP ${e} without an automation error envelope.`}}function jf(e){const t=new URLSearchParams;for(const[s,o]of Object.entries(e))o!==void 0&&t.set(s,String(o));const n=t.toString();return n?`?${n}`:""}function HS(){return Fr()}function KS(e){const t=e.newId??HS,n=o=>`${Sf}/${encodeURIComponent(o)}`;async function s(o,l,u){const d={accept:"application/json",...e.headers?e.headers():{}},f={method:o,headers:d};u!==void 0&&(d["content-type"]="application/json",f.body=JSON.stringify(u));const m=await e.fetch(ut(e.baseUrl,l),f),p=await m.text();let g,_=!1;if(p)try{g=JSON.parse(p),_=!0}catch{_=!1}if(!m.ok)throw new Bg(GS(m.status,g));if(!_||g===null||typeof g!="object")throw new Bg({status:m.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return g}return{listAutomations:(o={})=>s("GET",`${Sf}${jf({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>s("GET",n(o)),createAutomation:o=>s("POST",Sf,o),reviseAutomation:(o,l)=>s("PATCH",n(o),{command_id:l.command_id??t(),...l.expected_revision!==void 0?{expected_revision:l.expected_revision}:{},changes:l.changes}),sendAutomationCommand:(o,l)=>s("POST",`${n(o)}/commands`,{command_id:l.command_id??t(),type:l.type,...l.payload!==void 0?{payload:l.payload}:{}}),listOccurrences:(o,l={})=>s("GET",`${n(o)}/occurrences${jf({cursor:l.cursor,limit:l.limit})}`),discuss:(o,l)=>s("POST",`${n(o)}/discuss`,{request_id:l.request_id??t(),occurrence_index:l.occurrence_index,prompt:l.prompt}),markSeen:(o,l)=>s("POST",`${n(o)}/seen`,{attention_cursor:l}),listAttention:(o,l={})=>s("GET",`${n(o)}/attention${jf({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>s("GET",zS),getMyEmail:()=>s("GET",BS),listTriggerConnections:()=>s("GET",US),listMailboxes:()=>s("GET",WS),previewSchedule:o=>s("POST",VS,{trigger:o})}}function ju(e){const t=e==null?void 0:e._runtime,n=Array.isArray(t==null?void 0:t.allowed_tools)?t.allowed_tools:null,s=Array.isArray(e==null?void 0:e.tools)?e.tools:n;return Array.isArray(s)?s.filter(o=>typeof o=="string"&&(!n||n.includes(o))):null}function Wh(e,t){const n={...e},s=e._runtime&&typeof e._runtime=="object"?{...e._runtime}:{};return t===null?(delete n.tools,delete s.allowed_tools):(n.tools=[...t],s.allowed_tools=[...t]),Object.keys(s).length?n._runtime=s:delete n._runtime,n}function JS(e){const t=["prompt","tools","provider","model","temperature","seed","max_iterations","max_in_tokens","system","_limits"],n={};for(const o of t)o in e&&(n[o]=e[o]);const s=e._runtime;if(s&&typeof s=="object"){const o={};for(const l of["allowed_tools","provider","model","thinking","speculation","stream"])l in s&&(o[l]=s[l]);Object.keys(o).length&&(n._runtime=o)}return n}function ch(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const qS={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},YS={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.`},QS="Next scheduled run: {time}.",XS="Growing context: later runs see this run in their history.",ZS={run_now:{name:"playCircle"}},ej={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."},tj={legend:"When",kind_every:"Repeat",kind_daily:"Daily",kind_weekly:"Weekly",kind_monthly:"Monthly",kind_once:"Once at…",every_label:"Every",at_label:"at",time_label:"Time of day",days_legend:"On",days:{mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"},day_label:"on day",last_day:"last",once_label:"Run once at",time_zone_line:"in {time_zone} (your account's time zone)",time_zone_line_automation:"in {time_zone} (this automation's time zone)",time_zone_hint:"Daily, weekly, monthly and one-time runs keep this wall-clock time when daylight saving time changes. A day the month does not have (31 in April) runs on its last day. Repeat runs at a fixed interval in UTC.",time_zone_change:"Change in preferences",time_zone_change_hint:"Your account's time zone is set in your preferences; new automations use it.",time_zone_default:"Gateway default ({time_zone})",time_zone_search:"Search time zones",describing:"Checking the schedule…",incomplete:"Incomplete schedule.",error_at:"Pick the time of day (HH:MM).",error_days:"Pick at least one day.",error_day:"Pick a day of the month: 1 to 31, or last.",error_once:"Pick the date and time to run once."},Uh={labels:qS,hints:YS,run_now_next_run_line:QS,run_now_growing_line:XS,icons:ZS,email:ej,schedule:tj},Qi={manual:"By hand",schedule:"On a schedule",something:"When something arrives",main_mailbox:"your main mailbox"};function Nu(e){const t=String(e||"");return t.startsWith("feed")?"feed":t.startsWith("webhook")?"webhook":"other"}function nj(e,t){const n=Nu(t);return n==="feed"?`When ${e} has a new item`:n==="webhook"?`When ${e} is called`:`When ${e} sends something`}function Jw(e){if(!e)return"";const t=e.config??{};return(typeof t.connection_id=="string"?t.connection_id:typeof e.connection_id=="string"?e.connection_id:"").trim()}function qw(e){if(!e)return!1;const t=String(e.source_id||"");return!(t==="schedule"||t==="manual"||!t)}function Vh(e,t){const n=typeof e=="string"?e.trim():"",s=!n||n==="self"?"default":n,o=(t??[]).find(l=>l.account_id===s)??(s==="default"?(t??[]).find(l=>l.primary):void 0);return o!=null&&o.address?o.address:s==="default"?Qi.main_mailbox:s}function Gh(e,t){const n=Jw(e);return n?(t??[]).find(s=>s.connection_id===n)??null:null}function sj(e,t,n){var u;if(!e||!qw(e))return"";const s=String(e.source_id||"");if(s.startsWith("email"))return Vh((u=e.config)==null?void 0:u.account,n);const o=Gh(e,t);if(o!=null&&o.label)return o.label;const l=Nu(s);return l==="feed"?"A feed":l==="webhook"?"A webhook":"A connection"}function Hh(e,t,n,s){var d;const o=typeof(s==null?void 0:s.trigger_text)=="string"?s.trigger_text.trim():"";if(o)return o;if(!e)return"";const l=String(e.source_id||"");if(l==="schedule"){const f=s==null?void 0:s.schedule_rule_text;return typeof f=="string"&&f.trim()?f.trim():Qi.schedule}if(l==="manual")return Qi.manual;if(l.startsWith("email"))return`When mail arrives in ${Vh((d=e.config)==null?void 0:d.account,n)}`;if(Jw(e)){const f=Gh(e,t),m=Nu(l),p=(f==null?void 0:f.label)||(m==="feed"?"a feed":m==="webhook"?"a webhook":"a connection");return nj(p,l)}return Qi.something}const rj=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Nf(e,t){const n=new Date(e),s=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(n),o=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(n),[,l,u]=s.split("-"),d=`${Number(u)} ${rj[Number(l)-1]??l}`;return{day:s,clock:o,label:d}}function aj(e){const t=typeof e=="string"?e.trim():"";if(!t)return null;try{return new Intl.DateTimeFormat("en-GB",{timeZone:t}),t}catch{return null}}function uh(e,t={}){if(!e)return"";const n=Date.parse(e);if(Number.isNaN(n))return"";const s=aj(t.timeZone),o=s??"UTC",l=s?"":" UTC",u=t.nowMs??Date.now(),d=Nf(n,o),f=Nf(u,o).day,m=Nf(u-864e5,o).day;return d.day===f?`${t.style==="day"?"today ":""}${d.clock}${l}`:d.day===m?`yesterday ${d.clock}${l}`:`${d.label} ${d.clock}${l}`}function er(e){return typeof e=="string"?e.trim():""}function Lc(e){return e?`: “${e}”`:""}function Mc(e,t,n){return`${e} ${e===1?t:n}`}function oj(e,t={}){var p,g,_;if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,s=er(n.type),o=/^abstract\.(.+)\.v(\d+)$/.exec(s),l=o?o[1]:"";if(!l||l==="schedule"||l==="manual")return null;const u=n.data&&typeof n.data=="object"&&!Array.isArray(n.data)?n.data:{},d=uh(er(n.time),{timeZone:t.timeZone,nowMs:t.nowMs});let f="",m="";if(l.startsWith("email")){const v=Array.isArray(u.messages)?u.messages:[],C=typeof u.count=="number"?u.count:v.length;if(!C)return null;f=Vh((g=(p=t.trigger)==null?void 0:p.config)==null?void 0:g.account,t.mailboxes),m=`${Mc(C,"new message","new messages")}${Lc(er((_=v[0])==null?void 0:_.subject))}`}else{const v=Array.isArray(u.events)?u.events:[],C=typeof u.count=="number"?u.count:v.length;if(!C)return null;const x=v[0]&&typeof v[0]=="object"?v[0]:{},k=x.data&&typeof x.data=="object"&&!Array.isArray(x.data)?x.data:{},S=er(u.connection_id)||er(n.connectionid),$={source_id:l,config:{connection_id:S}},R=Gh(S?$:t.trigger,t.connections),N=Nu(l);f=(R==null?void 0:R.label)||sj(S?$:t.trigger??$,t.connections,t.mailboxes);const E=j=>{var I;return!!j&&typeof j=="object"&&((I=j.data)==null?void 0:I.test)===!0};v.length&&v.every(E)?m=C===1?"Test event":`${C} test events`:N==="webhook"?m=`${Mc(C,"call","calls")}${Lc(er(x.subject))}`:N==="feed"?m=`${Mc(C,"new item","new items")}${Lc(er(k.title)||er(x.subject))}`:m=`${Mc(C,"new event","new events")}${Lc(er(x.subject))}`}return{source:f,what:m,at:d,text:[f,m,d].filter(Boolean).join(" · ")}}const ij=/^([1-9][0-9]*)([smhd])$/,lj={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function cl(e){if(typeof e!="string")return null;const t=ij.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function cj(e){const t=cl(e);if(!t)return`every ${e}`;const[n,s]=lj[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${s}`}function nu(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;const n=new Date(t).toISOString(),s=n.slice(17,19);return`${n.slice(0,10)} ${n.slice(11,16)}${s==="00"?"":`:${s}`} UTC`}function Yw(e,t,n){return Hh(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function Qw(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const uj={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},et=Uh.email,Xw="email.received",Zw=1,dj="1h",fj="60s",ev=60,Kh=100,dh=1e3,Wg=200,Ug=200,Vg=50;function ul(e){return!!e&&e.source_id===Xw&&e.source_version===Zw}function Jh(e){return!!e&&e.effective_enabled===!0}function tv(e){const t=[];for(const n of String(e??"").split(/[\s,;]+/)){const s=n.trim().toLowerCase();s&&!t.includes(s)&&t.push(s)}return t}const hj=/[\s<>,;:"()[\]]/;function fh(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!hj.test(t)}function mj(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const qh={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function Yh(e){return e?dj:fj}function nv(e){const t=cl(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function Cf(e,t,n,s,o){const l=tv(e);if(!l.length)return null;const u=l.filter(d=>!n(d));return u.length&&o.push(`${t}: ${u.join(", ")} ${u.length===1?"is not":"are not"} ${s}.`),l.length>Wg&&o.push(`${t}: at most ${Wg} entries.`),l}function sv(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=Yh(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&&(nv(n.every)??0)<ev&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=Kh:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>dh?t.push(`At most this many emails per run: a whole number from 1 to ${dh}.`):n.max_batch=e.maxBatch;const s={},o=Cf(e.fromIn,et.from_in,fh,"an email address",t);o&&(s.from_in=o);const l=Cf(e.fromDomainIn,et.from_domain_in,mj,"a domain like example.com",t);l&&(s.from_domain_in=l);const u=Cf(e.toIn,et.to_in,fh,"an email address",t);u&&(s.to_in=u);const d=e.subjectContains.trim();return d&&(d.length>Ug||/[\r\n]/.test(d)?t.push(`${et.subject_contains}: one line of at most ${Ug} characters.`):s.subject_contains=d),e.hasAttachment==="yes"?s.has_attachment=!0:e.hasAttachment==="no"&&(s.has_attachment=!1),Object.keys(s).length&&(n.filter=s),{config:n,errors:t}}function rv(e){const t=e,n=t.filter??{},s=["when an email arrives"],o=[...n.from_in??[],...n.from_domain_in??[]];o.length&&s.push(`from ${o.join(", ")}`),n.to_in&&n.to_in.length&&s.push(`to ${n.to_in.join(", ")}`),typeof n.subject_contains=="string"&&n.subject_contains&&s.push(`subject contains “${n.subject_contains}”`),n.has_attachment===!0&&s.push("with attachments"),n.has_attachment===!1&&s.push("without attachments");const l=typeof t.every=="string"?t.every:Yh(t.uses_model!==!1);s.push(`checked ${cj(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:Kh;return s.push(`up to ${u} per run`),s.join(" · ")}const Xi={mode:"self",addresses:""};function hh(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=tv(e.addresses).filter(o=>o!=="self");n.length||t.push("Name at least one address the automation may email, or choose Only me.");const s=n.filter(o=>!fh(o));return s.length&&t.push(`${et.recipients_list}: ${s.join(", ")} ${s.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>Vg&&t.push(`At most ${Vg-1} addresses.`),{recipients:["self",...n],errors:t}}function pj(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function gj(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function av(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function ov(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function yj(e){return ov(e)?"In the console and by email":"In the console"}const It={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},wj=new Set(["running","waiting","backoff"]);function vj(e,t=[]){return e.current_occurrence!=null}function _j(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 bj(e,t){var n;return e.next_run_at&&e.next_run_local?`${pv(e.next_run_local,e.time_zone)} (${xj(e.next_run_at,t)})`:e.status==="paused"?"none while paused":e.status==="active"&&e.trigger&&qw(e.trigger)?Gg.event:e.status==="active"&&((n=e.trigger)==null?void 0:n.source_id)==="manual"?Gg.manual:"none scheduled"}const Gg={event:"when something new arrives",manual:"when someone presses Run now"};function xj(e,t){const n=Date.parse(e);if(Number.isNaN(n))return"";const s=Math.round((n-t)/6e4);if(s<=0)return"due now";if(s<60)return`in ${s} min`;const o=Math.floor(s/60);return o<24?`in ${o} h${s%60?` ${s%60} min`:""}`:`in ${Math.floor(o/24)} d${o%24?` ${o%24} h`:""}`}function Ao(e,t=[],n=!1){const s=new Set(e.capabilities),o=e.status,l=vj(e,t),u=(p,g,_)=>n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:s.has(p)?o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:g?{enabled:!0}:{enabled:!1,reason:_}:{enabled:!1,reason:"Not permitted for this automation."},d=o==="active"||o==="paused",f=o==="active"?"pause":"resume";return{active:n?{enabled:!1,reason:"Working…"}:e.legacy?{enabled:!1,reason:"Legacy schedule: managed with its existing controls."}:o==="archived"?{enabled:!1,reason:"Archived: history is kept, nothing runs."}:d?s.has(f)?{enabled:!0}:{enabled:!1,reason:"Not permitted for this automation."}:{enabled:!1,reason:"The automation has ended."},pause:u("pause",o==="active",o==="paused"?"Already paused.":"The automation has ended."),resume:u("resume",o==="paused",o==="active"?"Already running on schedule.":"The automation has ended."),run_now:u("run_now",d&&!l,l?"An occurrence is in progress.":"The automation has ended."),stop_current:u("stop_current",l,"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."}:o!=="archived"?{enabled:!1,reason:"Not archived."}:s.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."}:s.has("discuss")?{enabled:!0}:{enabled:!1,reason:"Discussion is not permitted for this automation."}}}function iv(e){return e.status==="active"?It.pause:It.resume}function kj(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 Sj(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=kj(t),s=`${t.attempts} ${t.attempts===1?"attempt":"attempts"}`,o=n==="failed"?`Failed after ${s}`:n==="waiting"?"Waiting for you":n==="notified"?"Notified":n==="running"?"Running":null,l=t.status==="completed"&&t.attempts>1?`completed after ${s}`:t.status;return{row:t,tone:n,notable:n==="failed"||n==="waiting"||n==="notified",badge:o,statusText:l,canDiscuss:!wj.has(t.status)}})}function jj(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function Nj(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 Cj={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 Lo(e){return{title:Cj[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function dl(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 lv(e,t){var l,u,d;const n=e.trigger,s=n.source_id==="schedule"||ul(n)?n.config.every:void 0,o=t?t.target.input_data.prompt:void 0;return{title:e.title,every:typeof s=="string"?s:null,calendar:Ej(n)?Ij(n.config):null,context:e.context_mode,growingMaxTokens:Number(((u=(l=t==null?void 0:t.context)==null?void 0:l.growing)==null?void 0:u.max_tokens)??e.growing_max_tokens??sl),prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,tools:ju(t==null?void 0:t.target.input_data),notifyEmail:t?ov(t.notify):null,emailRecipients:t?pj((d=t.notify)==null?void 0:d.recipients):null}}function cv(e,t,n){var f;const s=[],o={},l=t.title.trim();l?l.length>120?s.push("Title is at most 120 characters."):l!==e.title&&(o.title=l):s.push("Title is required.");const u=lv(e,n);if(t.every!==u.every&&t.every!==null){const m=ul(e.trigger);if(!cl(t.every))s.push("Interval must be a whole number of minutes, hours or days.");else if(m&&(nv(t.every)??0)<ev)s.push("The check interval is at least 60 seconds.");else{const p={...e.trigger.config,every:t.every};m&&delete p.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:p}}}if(t.calendar&&u.calendar&&JSON.stringify(t.calendar)!==JSON.stringify(u.calendar)){const m=Xh(t.calendar);if(!m.config)s.push(...m.errors);else{const p=e.trigger.config,g={...m.config,...typeof p.time_zone=="string"?{time_zone:p.time_zone}:{},...typeof p.count=="number"?{count:p.count}:{},...typeof p.until=="string"?{until:p.until}:{}};o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:g}}}const d=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(fv(d)||s.push(dv),(t.context!==e.context_mode||d!==u.growingMaxTokens)&&(o.context=hv(t.context,d)),n&&typeof u.prompt=="string"&&typeof t.prompt=="string"&&t.prompt.trim()!==u.prompt.trim()){const m=t.prompt.trim();m?o.target={bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:{...n.target.input_data,prompt:m}}:s.push("Task is required.")}if(n&&t.tools!==void 0&&JSON.stringify(t.tools)!==JSON.stringify(u.tools)){const m=o.target||{bundle_ref:n.target.bundle_ref,flow_id:n.target.flow_id,input_data:n.target.input_data};o.target={...m,input_data:Wh(m.input_data||{},t.tools)}}if(n&&t.toolApproval&&t.toolApproval!==u.toolApproval&&(o.policy={tool_approval:t.toolApproval}),n&&typeof t.notifyEmail=="boolean"){const m=hh(t.notifyEmail?t.emailRecipients??Xi:u.emailRecipients??Xi),p=hh(u.emailRecipients??Xi).recipients;m.errors.length?s.push(...m.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(m.recipients)!==JSON.stringify(p))&&(o.notify=av(t.notifyEmail,m.recipients))}if(s.length)return{errors:s};if(n&&t.target&&ch(t.target)!==ch(n.target)){const m=((f=o.target)==null?void 0:f.input_data)||n.target.input_data;o.target={...t.target,input_data:JS(m)}}return Object.keys(o).length?o:null}const sl=5e4,uv="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.",dv="Max growing context must be a positive whole number of tokens.";function fv(e){return Number.isSafeInteger(e)&&e>0}function hv(e,t){return{mode:e,...t!==sl?{growing:{max_tokens:t}}:{}}}const dt=Uh.schedule,su=["mon","tue","wed","thu","fri","sat","sun"],mv=["daily","weekly","monthly"],Qh=2;function Ej(e){return e.source_id==="schedule"&&e.source_version===Qh}function Aj(e,t=Qh){const n=e==null?void 0:e.schedule_rule_text;return typeof n=="string"&&n?n:Qi.schedule}const $j=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function pv(e,t){if(!e)return"";const n=$j.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function Tj(e,t="account"){return(t==="account"?dt.time_zone_line:dt.time_zone_line_automation).replace("{time_zone}",e)}const Rj=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function gv(e){return mv.includes(e.kind)}function Xh(e){const t=[];if(Rj.test(e.at)||t.push(dt.error_at),e.kind==="weekly"){const n=su.filter(s=>e.days.includes(s));return n.length||t.push(dt.error_days),t.length?{config:null,errors:t}:{config:{kind:"weekly",days:n,at:e.at},errors:t}}return e.kind==="monthly"?(e.day==="last"||Number.isInteger(e.day)&&e.day>=1&&e.day<=31||t.push(dt.error_day),t.length?{config:null,errors:t}:{config:{kind:"monthly",day:e.day,at:e.at},errors:t}):t.length?{config:null,errors:t}:{config:{kind:"daily",at:e.at},errors:t}}function Ij(e){const t=e,n=typeof t.at=="string"?t.at:"";return t.kind==="daily"?{kind:"daily",at:n}:t.kind==="weekly"?{kind:"weekly",at:n,days:Array.isArray(t.days)?su.filter(s=>t.days.includes(s)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const Lj=[{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 yv(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 Mj(e){const t=e.trim().split(`
56
- `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const Oj=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function Hg(e,t){const n={};if(e.count!==void 0&&(!Number.isInteger(e.count)||e.count<1?t.push("Maximum runs must be a whole number of at least 1."):n.count=e.count),e.until){const s=yv(e.until);s?n.until=s:t.push("Stop at must be a date and time (UTC).")}return n}function Pj(e){const t=[],n=e.when;if(n.kind==="once"){const d=(n.at||"").trim().slice(0,16);return Oj.test(d)?{config:{kind:"once",at:d},errors:t}:{config:null,errors:[dt.error_once]}}if(gv(n)){const d=Xh(n),f=Hg(e,d.errors);return d.config&&!d.errors.length?{config:{...d.config,...f},errors:[]}:{config:null,errors:d.errors}}const s=n.amount;let o=null;!Number.isInteger(s)||s<1?t.push("The interval must be a whole number of at least 1."):o=`${s}${n.unit}`;let l=null;e.startAt&&(l=yv(e.startAt),l||t.push("First run must be a date and time (UTC)."));const u=Hg(e,t);return t.length||!o?{config:null,errors:t}:{config:{kind:"every",every:o,...l?{start_at:l}:{},...u},errors:t}}function wv(e){const t=Pj(e);return t.config?{trigger:{source_id:"schedule",source_version:Qh,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function Dj(e){return e.kind==="every"||e.kind==="once"||gv(e)}function Fj(e){if(e.trigger==="email"){const t=sv(e.email??qh);return t.errors.length?"":rv(t.config)}return""}function zj(e,t){const n=[];t.target||n.push("Choose what to run.");const s=e.prompt.trim();s||n.push("Write the task to run.");const o=(e.title??"").trim()||Mj(s);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?sv(e.email??qh):null,d=l?null:wv(e);n.push(...u?u.errors:d.errors);const f=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?hh(e.emailRecipients):null;f&&n.push(...f.errors);const m=e.growingMaxTokens??sl;if(e.context==="growing"&&!fv(m)&&n.push(dv),n.length||!t.target)return{ok:!1,errors:n};const p={...t.target,input_data:{...t.target.input_data??{},prompt:s}},g={request_id:t.requestId,title:o,target:p,trigger:u?{source_id:Xw,source_version:Zw,config:u.config}:d.trigger,context:hv(e.context,e.context==="growing"?m:sl),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(g.notify=av(!0,f==null?void 0:f.recipients)),{ok:!0,body:g}}const Bj="Tools run without asking (you approve them now by creating this automation)";function Wj(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 s=n;if(typeof s.name!="string"||!s.arguments||typeof s.arguments!="object"||Array.isArray(s.arguments)||s.call_id!==void 0&&typeof s.call_id!="string")return null;t.push({name:s.name,arguments:s.arguments,...typeof s.call_id=="string"?{call_id:s.call_id}:{}})}return t}function Uj(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 vv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class _v{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||Vj(n.error))&&this.open.delete(t)}}function Vj(e){return dl(e)&&e.status>0&&e.code!=="invalid_response"}function bv(){return Fr()}class Gj{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 Kg(e,t){if(!e)return null;for(const n of t){const s=e.querySelector(n);if(s&&s.disabled!==!0&&typeof s.focus=="function")return s}return null}const Hj="08:00",Kj=["mon"],xv={at:Hj,days:[...Kj],day:1};function kv(e,t){return e==="weekly"?{kind:e,at:t.at,days:[...t.days]}:e==="monthly"?{kind:e,at:t.at,day:t.day}:{kind:e,at:t.at}}function Zh(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function Jg(e){return Zh(xv,e)}const Jj=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function Sv(e){const t=e.value,n=s=>{if(t.kind!=="weekly")return;const o=t.days.includes(s);e.onChange({...t,days:su.filter(l=>l===s?!o:t.days.includes(l))})};return a.jsxs("div",{className:"af-schedule__calendar","data-calendar-kind":t.kind,children:[t.kind==="weekly"?a.jsxs("div",{className:"af-auto__row af-schedule__days",role:"group","aria-label":dt.days_legend,children:[a.jsx("span",{children:dt.days_legend}),su.map(s=>a.jsx(zk,{className:"af-schedule__day",pressed:t.days.includes(s),disabled:e.disabled,onClick:()=>n(s),tone:"accent",children:a.jsx("span",{"data-day":s,children:dt.days[s]})},s))]}):null,a.jsxs("div",{className:"af-auto__row",children:[t.kind==="monthly"?a.jsxs(a.Fragment,{children:[a.jsx("label",{htmlFor:`${e.idBase}-month-day`,children:dt.day_label}),a.jsx("select",{id:`${e.idBase}-month-day`,name:"calendar_day",value:String(t.day),disabled:e.disabled,onChange:s=>e.onChange({...t,day:s.target.value==="last"?"last":Number(s.target.value)}),children:Jj.map(s=>a.jsx("option",{value:s,children:s==="last"?dt.last_day:s},s))})]}):null,a.jsx("label",{htmlFor:`${e.idBase}-at`,children:dt.at_label}),a.jsx("input",{id:`${e.idBase}-at`,name:"calendar_at",type:"time",step:60,required:!0,value:t.at,disabled:e.disabled,"aria-label":dt.time_label,onChange:s=>e.onChange({...t,at:s.target.value.slice(0,5)})})]})]})}function qj(e){return a.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[a.jsx(Zc,{content:dt.time_zone_hint,children:a.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:Tj(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?a.jsxs(a.Fragment,{children:[" · ",a.jsx(Zc,{content:dt.time_zone_change_hint,children:a.jsx("button",{type:"button",className:"af-auto__link af-schedule__tz-change",onClick:e.onOpenPreferences,children:dt.time_zone_change})})]}):null]})}function Yj(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function jv(e,t,n=250){const s=e?JSON.stringify(e):"",[o,l]=y.useState({phase:"idle"}),u=y.useRef(0),d=y.useRef(t);return d.current=t,y.useEffect(()=>{const f=++u.current;if(!s){l({phase:"idle"});return}l({phase:"loading"});const m=setTimeout(()=>{d.current(JSON.parse(s)).then(p=>{u.current===f&&l({phase:"ok",description:p})},p=>{u.current===f&&l({phase:"error",message:Yj(p)})})},n);return()=>clearTimeout(m)},[s,n]),o}function Nv(e){const t=e.state;return t.phase==="ok"?a.jsxs(a.Fragment,{children:[e.showZone===!1?null:a.jsx(qj,{timeZone:t.description.time_zone,whose:e.whose,onOpenPreferences:e.onOpenPreferences}),a.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":"served",children:t.description.first_run_sentence})]}):t.phase==="error"?a.jsx("p",{className:"af-schedule__preview af-auto__warn",role:"alert","data-preview":"error",children:t.message}):a.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":t.phase,children:t.phase==="loading"?dt.describing:e.incompleteText??dt.incomplete})}function qg(e){const t=Array.from(new Set(e.map(n=>String(n||"").trim()).filter(Boolean)));return t.sort((n,s)=>n.localeCompare(s)),t}function Qj(e){const t=e.disabled===!0,n=y.useMemo(()=>qg([...e.options||[],...e.value||[]]),[e.options,e.value]),s=y.useMemo(()=>qg(e.value||[]),[e.value]),[o,l]=y.useState(!1),[u,d]=y.useState(""),f=y.useMemo(()=>{const g=u.trim().toLowerCase();return g?n.filter(_=>_.toLowerCase().includes(g)):n},[n,u]),m=y.useMemo(()=>new Set(s),[s]),p=typeof e.max_list_height_px=="number"?e.max_list_height_px:220;return a.jsxs("div",{className:"af_multi_select",children:[a.jsxs("div",{className:"af_multi_select_row",children:[a.jsxs("button",{className:"btn",type:"button",onClick:()=>l(g=>!g),disabled:t||!n.length,"aria-expanded":o,children:[o?"Hide":"Select"," • ",s.length>0?`${s.length} of ${n.length}`:e.placeholder||"(none)"]}),a.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange(n.slice()),disabled:t||!n.length||s.length===n.length,title:"Select all",children:"All"}),a.jsx("button",{className:"btn",type:"button",onClick:()=>e.onChange([]),disabled:t||s.length===0,title:"Clear selection",children:"Clear"})]}),s.length>0?a.jsx("div",{className:"af_multi_select_chips",children:s.map(g=>a.jsxs("button",{type:"button",disabled:t,"aria-label":`Remove ${g}`,className:"af_multi_select_chip",title:g,onClick:()=>{if(t)return;const _=new Set(m);_.delete(g),e.onChange(Array.from(_.values()))},children:[g,t?null:a.jsx("span",{className:"af_multi_select_chip_x",children:"×"})]},g))}):null,o?a.jsxs("div",{className:"af_multi_select_panel",children:[a.jsx("input",{className:"mono",value:u,onChange:g=>d(String(g.target.value||"")),placeholder:"filter…","aria-label":"Filter options",disabled:t}),a.jsxs("div",{className:"af_multi_select_list",style:{maxHeight:`${p}px`},children:[f.map(g=>{const _=m.has(g);return a.jsxs("label",{className:`af_multi_select_item mono ${_?"checked":""}`,children:[a.jsx("input",{type:"checkbox",checked:_,disabled:t,onChange:v=>{const C=new Set(m);v.target.checked?C.add(g):C.delete(g),e.onChange(Array.from(C.values()))}}),a.jsx("span",{children:g})]},g)}),f.length?null:a.jsx("div",{className:"mono muted",children:"(no matches)"})]})]}):null]})}function Cv(e){return a.jsxs("div",{className:"af-auto__field","data-field":"tool-selection",children:[a.jsxs("label",{children:[a.jsx("input",{type:"checkbox",checked:e.value===null,disabled:e.disabled,onChange:t=>e.onChange(t.target.checked?null:[])})," Use the flow's default tools"]}),e.value!==null?a.jsx(Qj,{options:e.availableTools,value:e.value,disabled:e.disabled,placeholder:"No tools enabled",onChange:e.onChange}):null,a.jsx("p",{className:"af-auto__hint",children:"Choose which tools this automation can use. An empty selection disables tools. Gateway restrictions always apply."})]})}const Cu="@default",Ev="No workflows available for this app — ask your admin.",Av={shared:"Shared",mine:"Mine"};class Rr extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function $v(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 Xj(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function Zj(e,t={}){return e===null?Xj(t):$v(e,t)}function Yn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Kt(e){return typeof e=="string"?e.trim():""}const Oc="update the gateway";function e0(e,t){var d,f;const n=Yn(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const s=Yn(n[t]);if(!s)return{status:"unavailable",reason:Kt((f=Yn((d=Yn(e.default_agent_workflows_unavailable))==null?void 0:d[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const o=Kt(s.bundle_id),l=Kt(s.flow_id);if(!o||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=Kt(s.bundle_version);return{status:"ok",name:Kt(s.name)||l,bundleId:o,bundleVersion:u,flowId:l,workflowId:Kt(s.workflow_id)||`${o}${u?`@${u}`:""}:${l}`}}function t0(e,t){return Tv(e,t)}function Tv(e,t,n={}){var d,f;const s=Yn(e);if(!s)throw new Rr("The gateway's workflow list is not a JSON object.");const o=Kt(s.executable_for);if(t===null){if(o)throw new Rr(`Asked for every workflow, the gateway listed only ${o}.`)}else if(o!==t)throw new Rr(o?`The gateway listed workflows for ${o}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${Oc}.`);if(!Array.isArray(s.items))throw new Rr("The gateway's workflow list has no items.");const l=[];for(const m of s.items){const p=Yn(m),g=Kt(p==null?void 0:p.bundle_id);if(!p||!g)throw new Rr("The gateway listed a workflow without a bundle id.");const _=Yn(p.owner),v=Kt(_==null?void 0:_.kind);if(v!=="gateway"&&v!=="user")throw new Rr(`The gateway did not say who owns ${g} (owner missing): ${Oc}.`);if(typeof p.shipped!="boolean")throw new Rr(`The gateway did not say whether ${g} ships with it (shipped missing): ${Oc}.`);const C=Kt(p.bundle_version),x=Array.isArray(p.entrypoints)?p.entrypoints:[];for(const k of x){const S=Yn(k),$=Kt(S==null?void 0:S.flow_id);if(!S||!$)continue;const R=Array.isArray(S.interfaces)?S.interfaces.map(Kt).filter(Boolean):[],N=o0((d=Yn(p.automation_defaults))==null?void 0:d[$]),E=S.triggerable===!0||!!N;if(t===null){if(!R.length&&!E)continue}else if(!R.includes(t))throw new Rr(`The gateway offered ${g}:${$}, which does not declare ${t}: ${Oc}.`);l.push({value:Kt(S.workflow_id)||`${g}${C?`@${C}`:""}:${$}`,bundleId:g,bundleVersion:C,flowId:$,name:Kt(S.name)||Kt((f=Yn(p.metadata))==null?void 0:f.name)||g,description:Kt(S.description)||Kt(p.description),registryScope:Kt(p.registry_scope)||"private",group:v==="user"?"mine":"shared",shipped:p.shipped,interfaces:R,...t===null?{showInterfaces:!0}:{},...N?{automationTrigger:N}:{},...E?{triggerable:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:u?e0(s,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function n0(e){const t=(n,s)=>n.name.localeCompare(s.name)||s.bundleVersion.localeCompare(n.bundleVersion,void 0,{numeric:!0})||n.value.localeCompare(s.value);return["shared","mine"].map(n=>({id:n,label:Av[n],entries:e.filter(s=>s.group===n).sort(t)})).filter(n=>n.entries.length>0)}const s0={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function r0(e){return s0[e]??e}function a0(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?!e.interfaces.length&&e.automationTrigger?[Hh(e.automationTrigger),n].filter(Boolean).join(" · "):[[...new Set(e.interfaces.map(r0))].join(", "),n].filter(Boolean).join(" · "):n}function o0(e){var l;const t=Yn((l=Yn(e))==null?void 0:l.trigger),n=Kt(t==null?void 0:t.source_id);if(!t||!n||typeof t.source_version!="number")return;const s=Yn(t.config)??{},o=Kt(t.connection_id);return{source_id:n,source_version:t.source_version,config:s,...o?{connection_id:o}:{}}}function i0(e){return e.value}function l0(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function c0(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 u0(e,t=!0){const n=(e==null?void 0:e.entries)??[],s=[];t&&s.push({key:"default",value:Cu,name:"Gateway default",detail:l0((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of n0(n))for(const l of o.entries)s.push({key:l.value,value:l.value,name:l.name,detail:a0(l,n),title:i0(l),group:o.id,entry:l});return s}async function d0(e,t,n){var l;const s=await fetch(ut(e,we(t)),{credentials:"include",headers:{Accept:"application/json"},signal:n}),o=await s.json().catch(()=>null);if(!s.ok){const u=((l=o==null?void 0:o.detail)==null?void 0:l.message)||(o==null?void 0:o.message)||(typeof(o==null?void 0:o.detail)=="string"?o.detail:"");throw new Error(u||`The gateway answered ${s.status}.`)}return o}function f0(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 h0(e){const{interfaceId:t,defaultInterface:n,allVersions:s=!1,enabled:o=!0,gatewayBaseUrl:l,reloadKey:u}=e,d=y.useRef(e.request);d.current=e.request;const[f,m]=y.useState(0),[p,g]=y.useState({status:"idle",data:null,error:""});y.useEffect(()=>{if(!o){g({status:"idle",data:null,error:""});return}const v=new AbortController;g(k=>({...k,status:"loading",error:""}));const C=Zj(t,{allVersions:s});return(d.current?d.current(C,{signal:v.signal}):d0(l,C,v.signal)).then(k=>{v.signal.aborted||g({status:"ready",data:Tv(k,t,{defaultInterface:n}),error:""})}).catch(k=>{v.signal.aborted||g({status:"error",data:null,error:f0(k)})}),()=>v.abort()},[t,n,s,o,l,u,f]);const _=y.useCallback(()=>m(v=>v+1),[]);return{...p,reload:_}}function m0(e){if(!e||typeof window>"u")return{};const t=e.getBoundingClientRect(),n=window.innerWidth,s=window.innerHeight,o=Math.min(Math.max(t.width,300),440,n-32),l=Math.max(16,Math.min(t.left,n-16-o)),u=s-t.bottom-16;return u>=220||u>=t.top?{position:"fixed",left:l,width:o,top:t.bottom+4,maxHeight:Math.max(160,u)}:{position:"fixed",left:l,width:o,bottom:s-t.top+4,maxHeight:Math.max(160,t.top-16)}}function Rv(...e){return e.filter(Boolean).join(" ")}function Iv(e){const t=h0({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,s=e.showDefault!==!1&&(e.interfaceId!==null||!!e.defaultInterface),o=y.useId().replace(/:/g,""),l=`${o}-list`,[u,d]=y.useState(!1),[f,m]=y.useState(-1),p=y.useRef(null),g=y.useRef(null),[_,v]=y.useState({}),C=e.entryDetail,x=y.useMemo(()=>u0(n.data,s).map(L=>{const z=L.entry&&C?C(L.entry):null;return z?{...L,detail:z}:L}),[n.data,s,C]),k=x.find(L=>L.value===e.value),S=k?{name:k.name,detail:k.detail}:e.currentLabel?{name:e.currentLabel.name,detail:e.currentLabel.detail||""}:n.status==="loading"?{name:"Loading flows…",detail:""}:{name:e.value===Cu?"Gateway default":"Choose a flow",detail:""},$=String(e.unavailableReason||"").trim(),R=!$&&n.status==="ready",N=y.useCallback(()=>{d(!1),m(-1)},[]),E=y.useCallback(()=>{if(!R)return;v(m0(g.current)),d(!0);const L=x.findIndex(z=>z.value===e.value);m(L>=0?L:0)},[R,x,e.value]),j=y.useCallback(L=>{var z;N(),L.value!==e.value&&e.onChange(L.value,L.entry),(z=g.current)==null||z.focus()},[N,e]);y.useEffect(()=>{if(!u)return;const L=V=>{p.current&&!p.current.contains(V.target)&&N()},z=()=>N();return document.addEventListener("mousedown",L),document.addEventListener("touchstart",L),window.addEventListener("resize",z),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("touchstart",L),window.removeEventListener("resize",z)}},[u,N]),y.useEffect(()=>{var z;if(!u||f<0)return;const L=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(z=L==null?void 0:L.scrollIntoView)==null||z.call(L,{block:"nearest"})},[u,f,o]);const I=L=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(L.key)&&(L.preventDefault(),E());return}if(L.key==="Escape"){L.preventDefault(),N();return}if(L.key==="Tab"){N();return}if(L.key==="Enter"||L.key===" "){L.preventDefault(),f>=0&&x[f]&&j(x[f]);return}const z=c0(L.key,f,x.length);z!==null&&(L.preventDefault(),m(z))};return a.jsxs("div",{ref:p,className:Rv("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[a.jsxs("button",{ref:g,id:e.id,type:"button",role:"combobox",className:"af-workflow-picker__trigger","aria-label":e.ariaLabel||"Workflow","aria-describedby":`${o}-value`,"aria-haspopup":"listbox","aria-expanded":u,"aria-controls":l,"aria-activedescendant":u&&f>=0?`${o}-opt-${f}`:void 0,"aria-disabled":R?void 0:!0,title:$||void 0,onClick:()=>u?N():E(),onKeyDown:I,children:[a.jsxs("span",{className:"af-workflow-picker__value",id:`${o}-value`,children:[a.jsx("span",{className:"af-workflow-picker__name",children:S.name}),S.detail?a.jsx("span",{className:"af-workflow-picker__detail",children:S.detail}):null]}),a.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?a.jsx(p0,{id:l,idBase:o,rows:x,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:_,onHighlight:m,onChoose:j}):null,n.status==="error"?a.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&x.every(L=>!L.entry)&&!s?a.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:Ev}):null]})}function p0(e){const t=(l,u)=>a.jsxs("div",{id:`${e.idBase}-opt-${u}`,role:"option","aria-selected":l.value===e.value,"data-value":l.value,title:l.title,className:Rv("af-workflow-picker__option",u===e.highlight&&"af-workflow-picker__option--highlighted",l.value===e.value&&"af-workflow-picker__option--selected"),onMouseEnter:()=>e.onHighlight(u),onMouseDown:d=>d.preventDefault(),onClick:()=>e.onChoose(l),children:[a.jsx("span",{className:"af-workflow-picker__name",children:l.name}),l.detail?a.jsx("span",{className:"af-workflow-picker__detail",children:l.detail}):null]},l.key),n=e.rows.map((l,u)=>({row:l,index:u})),s=n.filter(l=>l.row.group===null),o=["shared","mine"].map(l=>({g:l,items:n.filter(u=>u.row.group===l)})).filter(l=>l.items.length>0);return a.jsxs("div",{id:e.id,role:"listbox","aria-label":e.ariaLabel,className:"af-workflow-picker__list",style:e.style,children:[s.map(l=>t(l.row,l.index)),o.map(({g:l,items:u})=>a.jsxs("div",{role:"group","aria-labelledby":`${e.idBase}-g-${l}`,"data-group":l,children:[a.jsx("div",{id:`${e.idBase}-g-${l}`,className:"af-workflow-picker__group",role:"presentation",children:Av[l]}),u.map(d=>t(d.row,d.index))]},l)),o.length===0?a.jsx("p",{className:"af-workflow-picker__empty",children:Ev}):null]})}function Lv(e){const t=ch(e.target);return a.jsxs("div",{className:"af-auto__field",children:[a.jsx("span",{children:"Flow"}),a.jsx(Iv,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:g0(t,e.options)},onChange:(n,s)=>e.onChange(n==="@default"?{flow_id:"@default",interface:e.options.interfaceId||e.options.defaultInterface||"abstractcode.agent.v1"}:{bundle_ref:`${s.bundleId}@${s.bundleVersion}`,flow_id:s.flowId})})]})}function g0(e,t){var f,m,p;const n=((m=(f=t.workflows)==null?void 0:f.data)==null?void 0:m.entries)??[],s=n.find(g=>g.value===e);if(s)return s.name;const o=e.indexOf("@"),l=e.lastIndexOf(":"),u=o>0?e.slice(0,o):l>0?e.slice(0,l):e,d=l>0?e.slice(l+1):"";return((p=n.find(g=>g.bundleId===u&&(!d||g.flowId===d)))==null?void 0:p.name)||u||e}async function y0(e,t){var _,v;const n=e.flow_id==="@default"?(v=(_=t.workflows)==null?void 0:_.data)==null?void 0:v.gatewayDefault:null,s="bundle_ref"in e?e.bundle_ref:(n==null?void 0:n.status)==="ok"?`${n.bundleId}@${n.bundleVersion}`:"",o=e.flow_id!=="@default"?e.flow_id:(n==null?void 0:n.status)==="ok"?n.flowId:"";if(!s||!o||!t.request)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const l=s.lastIndexOf("@"),u=l<0?s:s.slice(0,l),d=l<0?"":s.slice(l+1),f=await t.request(`bundles/${encodeURIComponent(u)}/flows/${encodeURIComponent(o)}/input_schema${d?`?bundle_version=${encodeURIComponent(d)}`:""}`,{signal:new AbortController().signal}),m=(f==null?void 0:f.input_data_schema)||f;if(!m||typeof m!="object"||!m.properties)throw new Error("This workflow does not report its input requirements. Choose another workflow.");const p={...f.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 g=(Array.isArray(m.required)?m.required:[]).filter(C=>p[C]===void 0);if(g.length)throw new Error(`This workflow needs additional inputs: ${g.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:p}}function mh(e){if(Jh(e.status))return null;const t=et.not_set_up,n=et.open_my_email,s=t.endsWith(n)?t.slice(0,t.length-n.length):`${t} `,o=e.status&&e.status.admin_disabled&&typeof e.status.admin_disabled.cause=="string"?e.status.admin_disabled.cause:"";return a.jsxs("p",{className:"af-auto__hint af-email__notice",role:"note","data-email-setup":"missing",children:[s,e.onOpenMyEmail?a.jsx("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-my-email",onClick:e.onOpenMyEmail,children:n}):n,o?a.jsxs("span",{className:"af-email__cause",children:[" (",o,")"]}):null]})}function w0(e){const t=e.value,n=d=>e.onChange({...t,...d}),s=d=>`${e.idBase}-email-${d}`,o=cl(Yh(t.usesModel)),l=t.every??(o&&o.unit==="s"?{amount:Math.max(1,Math.round(o.amount/60)),unit:"m"}:{amount:o?o.amount:1,unit:o?o.unit:"h"}),u=e.disabled===!0;return a.jsxs("div",{className:"af-email__trigger","data-field":"email-trigger",children:[a.jsxs("div",{className:"af-auto__row",children:[a.jsx("span",{children:et.every_label}),a.jsx("input",{type:"number",min:1,step:1,value:String(l.amount),disabled:u,"aria-label":"Check interval amount",name:"email_every_amount",onChange:d=>n({every:{amount:Number(d.target.value),unit:l.unit}})}),a.jsxs("select",{value:l.unit,disabled:u,"aria-label":"Check interval unit",name:"email_every_unit",onChange:d=>n({every:{amount:l.amount,unit:d.target.value}}),children:[a.jsx("option",{value:"m",children:"minutes"}),a.jsx("option",{value:"h",children:"hours"}),a.jsx("option",{value:"d",children:"days"})]})]}),a.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:et.interval_rule}),a.jsxs("label",{className:"af-auto__field",htmlFor:s("batch"),children:[a.jsx("span",{children:et.max_batch_label}),a.jsx("input",{id:s("batch"),name:"email_max_batch",type:"number",min:1,max:dh,step:1,disabled:u,value:String(t.maxBatch??Kh),onChange:d=>n({maxBatch:d.target.value.trim()===""?null:Number(d.target.value)})})]}),a.jsx("p",{className:"af-auto__hint",children:et.max_batch_hint}),a.jsxs("fieldset",{className:"af-auto__field af-email__filters",disabled:u,children:[a.jsx("legend",{children:et.filters_legend}),a.jsxs("label",{className:"af-auto__field",htmlFor:s("from"),children:[a.jsx("span",{children:et.from_in}),a.jsx("input",{id:s("from"),name:"email_from_in",value:t.fromIn,spellCheck:!1,placeholder:"alice@example.com, billing@example.org",onChange:d=>n({fromIn:d.target.value})})]}),a.jsxs("label",{className:"af-auto__field",htmlFor:s("domain"),children:[a.jsx("span",{children:et.from_domain_in}),a.jsx("input",{id:s("domain"),name:"email_from_domain_in",value:t.fromDomainIn,spellCheck:!1,placeholder:"example.com",onChange:d=>n({fromDomainIn:d.target.value})})]}),a.jsxs("label",{className:"af-auto__field",htmlFor:s("to"),children:[a.jsx("span",{children:et.to_in}),a.jsx("input",{id:s("to"),name:"email_to_in",value:t.toIn,spellCheck:!1,onChange:d=>n({toIn:d.target.value})})]}),a.jsxs("label",{className:"af-auto__field",htmlFor:s("subject"),children:[a.jsx("span",{children:et.subject_contains}),a.jsx("input",{id:s("subject"),name:"email_subject_contains",value:t.subjectContains,maxLength:200,onChange:d=>n({subjectContains:d.target.value})})]}),a.jsxs("label",{className:"af-auto__field",htmlFor:s("attach"),children:[a.jsx("span",{children:et.has_attachment}),a.jsxs("select",{id:s("attach"),name:"email_has_attachment",value:t.hasAttachment,onChange:d=>n({hasAttachment:d.target.value}),children:[a.jsx("option",{value:"any",children:et.has_attachment_any}),a.jsx("option",{value:"yes",children:et.has_attachment_yes}),a.jsx("option",{value:"no",children:et.has_attachment_no})]})]}),a.jsx("p",{className:"af-auto__hint",children:et.list_hint})]})]})}function v0(e){const t=s=>`${e.idBase}-email-${s}`,n=e.disabled===!0;return a.jsxs("div",{className:"af-email__options","data-field":"email-options",children:[a.jsx(Wr,{variant:"row",action:"notify-email",label:et.notify_label,checked:e.notifyEmail,unavailableReason:n?"Connect a mailbox first.":null,onChange:s=>e.onNotifyEmailChange(s)}),a.jsxs("p",{className:"af-auto__hint",children:[et.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),e.notifyEmail?a.jsxs("fieldset",{className:"af-auto__field",disabled:n,"data-field":"email-recipients",children:[a.jsx("legend",{children:et.recipients_legend}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:t("rcpt"),value:"self",checked:e.recipients.mode==="self",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"self"})})," ",et.recipients_self]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:t("rcpt"),value:"list",checked:e.recipients.mode==="list",onChange:()=>e.onRecipientsChange({...e.recipients,mode:"list"})})," ",et.recipients_list]}),e.recipients.mode==="list"?a.jsx("textarea",{name:"email_recipient_list","aria-label":et.recipients_list,rows:2,spellCheck:!1,value:e.recipients.addresses,placeholder:"colleague@example.com",onChange:s=>e.onRecipientsChange({mode:"list",addresses:s.target.value})}):null,a.jsx("p",{className:"af-auto__hint",children:et.recipients_hint})]}):null]})}const _0={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function b0(e){const t=String(e.status),n=_0[t];return a.jsxs("span",{className:`af-auto__status af-auto__status--${t}${e.className?` ${e.className}`:""}`,"data-state":t,children:[a.jsx("span",{className:"af-auto__status-word",children:uj[t]??t}),n?a.jsx(de,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const Yg="Discuss this run",Eu=e=>a.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function x0(e){return dl(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function k0(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return a.jsx("code",{className:"af-auto__path-text",children:t.map((n,s)=>a.jsxs(yt.Fragment,{children:[n,s<t.length-1?a.jsx("wbr",{}):null]},s))})}function Mv(e,t){const n=e.trigger,s=t.find(o=>o.id===n.source_id&&o.version===n.source_version);return s?"available"in s&&s.available===!1?`Trigger source ${n.source_id}@${n.source_version} is unavailable${s.unavailable_reason?`: ${s.unavailable_reason}`:"."}`:null:`This gateway does not list the trigger source ${n.source_id}@${n.source_version}.`}function S0(e){const t=e.summary,n=_j(t),s=Mv(t,e.triggerSources),o=bj(t,e.nowMs??Date.now());return a.jsxs("header",{className:"af-auto__head",children:[a.jsxs("div",{className:"af-auto__titlebar",children:[a.jsx("h2",{className:"af-auto__title",id:e.titleId,tabIndex:-1,children:t.title}),a.jsx(b0,{status:t.status}),t.legacy?a.jsx("span",{className:"af-auto__legacy",children:"Legacy schedule"}):null]}),a.jsxs("dl",{className:"af-auto__facts",children:[e.workflowLabel?a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:"Flow"}),a.jsx("dd",{"data-fact":"workflow",children:e.workflowLabel})]}):null,a.jsx("dt",{children:"When"}),a.jsxs("dd",{"data-fact":"trigger",children:[Yw(t.trigger,t,{connections:e.triggerConnections,mailboxes:e.mailboxes}),s?a.jsxs("span",{className:"af-auto__warn",role:"note",children:[" ",s]}):null]}),a.jsx("dt",{children:"Context"}),a.jsx("dd",{"data-fact":"context",children:Qw(t.context_mode)}),n?a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:"Now"}),a.jsx("dd",{"data-fact":"current",className:"is-notable",children:n})]}):null,a.jsx("dt",{children:"Next run"}),a.jsx("dd",{"data-fact":"next",children:o}),a.jsx("dt",{children:"Runs"}),a.jsx("dd",{"data-fact":"count",children:t.occurrence_count}),t.workspace_root&&e.onOpenWorkspace?a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:"Files"}),a.jsx("dd",{"data-fact":"workspace",className:"af-auto__workspace",children:a.jsxs("button",{type:"button",className:"af-auto__path","data-action":"open-workspace",title:`Browse the automation's folder
57
- ${t.workspace_root}`,"aria-label":"Browse the automation's files",onClick:()=>{var l;return(l=e.onOpenWorkspace)==null?void 0:l.call(e,t.automation_id)},children:[a.jsx(de,{name:"folder",size:14,className:"af-auto__path-icon"}),a.jsx("span",{children:"Browse its files"})]})})]}):null,a.jsx("dt",{children:"Attention"}),a.jsx("dd",{"data-fact":"attention",className:t.attention.unread||t.attention.pending_waits?"is-notable":void 0,children:Nj(t)})]})]})}function j0(e){var u,d;const t=e.definition,n=e.renderText??Eu,s=t.target.input_data.prompt,o=t.policy.retry,l=t.policy.tool_approval;return a.jsxs("details",{className:"af-auto__definition","data-definition-revision":t.revision,open:e.open,children:[a.jsxs("summary",{children:[a.jsx(de,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),a.jsx(de,{name:"file",size:14}),a.jsx("span",{className:"af-auto__definition-title",children:"Details"})]}),a.jsxs("dl",{className:"af-auto__facts",children:[a.jsx("dt",{children:"Target"}),a.jsx("dd",{"data-def":"target",children:a.jsx("code",{children:t.target.workflow_id})}),typeof s=="string"&&s?a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:"Task"}),a.jsx("dd",{"data-def":"prompt",children:n(s)})]}):null,a.jsx("dt",{children:"Trigger"}),a.jsxs("dd",{"data-def":"trigger",children:[t.trigger.source_id,"@",t.trigger.source_version," · ",Yw(t.trigger,e.served,{connections:e.triggerConnections,mailboxes:e.mailboxes}),ul(t.trigger)?a.jsx("div",{className:"af-auto__hint","data-def":"email_rule",children:rv(t.trigger.config)}):null,a.jsx("pre",{className:"af-auto__json",children:JSON.stringify(t.trigger.config,null,2)})]}),a.jsx("dt",{children:"Context"}),a.jsxs("dd",{"data-def":"context",children:[Qw(t.context.mode),t.context.mode==="growing"?` · ${Number(((u=t.context.growing)==null?void 0:u.max_tokens)??5e4).toLocaleString()} tokens`:""]}),a.jsx("dt",{children:"Tools"}),a.jsx("dd",{"data-def":"tool_approval",children:l==="ask"?"Ask before each tool call (ask)":l==="auto"?"Run without asking (auto)":String(l)}),a.jsx("dt",{children:"Notify"}),a.jsx("dd",{"data-def":"notify",children:yj(t.notify)}),(d=t.notify)!=null&&d.channels.includes("email")?a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:"Recipients"}),a.jsx("dd",{"data-def":"email_recipients",children:gj(t.notify.recipients)})]}):null,a.jsx("dt",{children:"Retries"}),a.jsxs("dd",{"data-def":"retry",children:[o.max_attempts," ",o.max_attempts===1?"attempt":"attempts",", backoff ",o.backoff.initial," ×",o.backoff.factor," up to ",o.backoff.max]}),t.workspace_root?a.jsxs(a.Fragment,{children:[a.jsx("dt",{children:"Folder"}),a.jsx("dd",{"data-def":"workspace",children:a.jsx(k0,{path:t.workspace_root})})]}):null,a.jsx("dt",{children:"Revision"}),a.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const fl=Uh,ph=fl.labels,Ov={active:"play",pause:"pause",resume:"play",run_now:fl.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},gh=fl.hints,N0=fl.run_now_next_run_line,C0=fl.run_now_growing_line;function rl(e,t){const n=[gh[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push(N0.replace("{time}",pv(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(C0)),n.join(`
58
- `)}function E0(e,t,n){const s=new Map;for(const u of t){const d=e[u];if(d.enabled)continue;const f=d.reason??"Not available now.";s.set(f,[...s.get(f)??[],u])}const o=[],l={};return[...s.entries()].forEach(([u,d],f)=>{const m=`${n}-why-${f}`;o.push({id:m,text:`${d.map(p=>ph[p]).join(", ")}: ${u}`});for(const p of d)l[p]=m}),{lines:o,describedBy:l}}function vn(e){return a.jsxs(a.Fragment,{children:[a.jsx(de,{name:e.icon,size:14,className:"af-auto__btn-icon"}),a.jsx("span",{children:e.label})]})}function A0(e){const t=Ao(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",o=E0(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),l=(u,d,f)=>{const m=rl(u,e.summary);return a.jsx("button",{type:"button",className:`af-auto__btn${f!=null&&f.danger?" af-auto__btn--danger":""}`,"data-action":(f==null?void 0:f.action)??u,disabled:!t[u].enabled,title:t[u].enabled?m:`${t[u].reason}
59
- ${m}`,"aria-description":m,"aria-describedby":o.describedBy[u],"aria-pressed":f==null?void 0:f.pressed,onClick:d,children:a.jsx(vn,{icon:Ov[u],label:(f==null?void 0:f.label)??ph[u]})},u)};return a.jsxs("div",{className:"af-auto__controls-wrap",children:[a.jsxs("div",{className:"af-auto__actionbar",children:[a.jsxs("div",{className:"af-auto__controls",role:"toolbar","aria-label":"Automation controls",children:[a.jsx(Wr,{className:"af-auto__switch",action:"active",label:ph.active,checked:e.summary.status==="active",unavailableReason:t.active.enabled?null:t.active.reason??"Not available now.",describedBy:o.describedBy.active,busy:e.busy,hint:rl("active",e.summary),onChange:()=>e.onCommand(iv(e.summary))},"active"),l("run_now",()=>e.onCommand(It.run_now)),l("stop_current",()=>e.onCommand(It.stop_current)),l("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?l("unarchive",()=>e.onCommand(It.unarchive)):l("archive",e.onAskArchive,{danger:!0,label:"Archive…"})]}),a.jsx("span",{className:`af-auto__notice${e.notice?" af-auto__notice--on":""}`,role:"status",tabIndex:-1,children:e.notice?a.jsxs(a.Fragment,{children:[a.jsx(de,{name:"check",size:13}),a.jsx("span",{className:"af-auto__notice-text",children:e.notice}),e.onDismissNotice?a.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:a.jsx(de,{name:"x",size:12})}):null]}):null})]}),o.lines.length?a.jsxs("p",{className:"af-auto__reasons",children:[a.jsx(de,{name:"info",size:12,className:"af-auto__reasons-icon"}),o.lines.map(u=>a.jsx("span",{id:u.id,children:u.text},u.id))]}):null,e.summary.status==="paused"&&t.run_now.enabled?a.jsx("p",{className:"af-auto__hint",children:"Paused: scheduled runs are skipped. Run now works and keeps it paused."}):null,e.confirmingArchive&&!n?a.jsxs("div",{className:"af-auto__confirm",role:"group","aria-label":"Confirm archive",children:[a.jsxs("p",{children:["Archive “",e.summary.title,"”? Its history stays readable; it will not run again. The current run, if any, finishes."]}),a.jsxs("div",{className:"af-auto__row",children:[a.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"archive-confirm",disabled:!t.archive.enabled,onClick:()=>e.onCommand(It.archive),children:a.jsx(vn,{icon:"archive",label:"Archive"})}),a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:a.jsx(vn,{icon:"x",label:"Keep it"})})]})]}):null]})}const Qg=[["m","minutes"],["h","hours"],["d","days"]];function $0(e,t){const n=k=>{const S=e.elements.namedItem(k);return S&&typeof S.value=="string"?S.value:null},s=n("every_amount"),o=n("every_unit"),l=s!==null&&o!==null?`${s.trim()}${o}`:t.every,u=e.elements.namedItem("context"),d=u&&(u.value==="growing"||u.value==="independent")?u.value:t.context,f=n("prompt"),m=e.elements.namedItem("tool_approval"),p=m&&(m.value==="auto"||m.value==="ask")?m.value:t.toolApproval??null,g=e.elements.namedItem("notify_email"),_=g&&typeof g.checked=="boolean"?g.checked:t.notifyEmail??null,v=e.elements.namedItem("email_recipients"),C=n("email_recipient_list"),x=v&&(v.value==="self"||v.value==="list")?{mode:v.value,addresses:C??""}:t.emailRecipients??null;return{title:n("title")??t.title,every:l,context:d,growingMaxTokens:n("growing_max_tokens")===null?t.growingMaxTokens:Number(n("growing_max_tokens")),prompt:f??t.prompt??null,toolApproval:p,notifyEmail:_,emailRecipients:x}}function Pv(e){var j;const t=lv(e.summary,e.definition),[n,s]=y.useState(),[o,l]=y.useState(t.tools??null),[u,d]=y.useState(t.context),[f,m]=y.useState(!!t.notifyEmail),[p,g]=y.useState(((j=t.calendar)==null?void 0:j.kind)??null),[_,v]=y.useState(t.calendar?Jg(t.calendar):null),C=p&&_?kv(p,_):null,x=(()=>{if(!C)return null;const I=Xh(C);if(!I.config)return null;const L=e.summary.trigger.config.time_zone;return{source_id:e.summary.trigger.source_id,source_version:e.summary.trigger.source_version,config:{...I.config,...typeof L=="string"?{time_zone:L}:{}}}})(),k=jv(x,e.previewSchedule),S=t.every?cl(t.every):null,$=S&&S.unit==="s"?[["s","seconds"],...Qg]:Qg,R=`af-auto-revise-${e.summary.automation_id}`,N=Jh(e.emailStatus),E=ul(e.summary.trigger);return a.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${R}-heading`,onSubmit:I=>{I.preventDefault(),e.onSubmit({...$0(I.currentTarget,t),...C?{calendar:C}:{},...n?{target:n}:{},...e.availableTools!==void 0?{tools:o}:{}})},onKeyDown:I=>{I.key==="Escape"&&e.onCancel&&(I.preventDefault(),e.onCancel())},children:[e.heading===null?a.jsx("span",{id:`${R}-heading`,hidden:!0,children:"Edit automation"}):a.jsxs("h3",{className:"af-auto__form-title",id:`${R}-heading`,children:[a.jsx(de,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?a.jsx(Lv,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:s}):null,a.jsxs("label",{className:"af-auto__field",htmlFor:`${R}-title`,children:[a.jsx("span",{children:"Title"}),a.jsx("input",{id:`${R}-title`,name:"title",defaultValue:t.title,maxLength:120,required:!0})]}),t.prompt!==null&&t.prompt!==void 0?a.jsxs("label",{className:"af-auto__field",htmlFor:`${R}-prompt`,children:[a.jsx("span",{children:"Task"}),a.jsx("textarea",{id:`${R}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
60
- `).length+1)),required:!0})]}):null,S?a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:E?et.every_label:"Repeat every (UTC)"}),a.jsxs("div",{className:"af-auto__row",children:[a.jsx("input",{name:"every_amount",type:"number",min:1,step:1,defaultValue:S.amount,"aria-label":"Interval amount"}),a.jsx("select",{name:"every_unit",defaultValue:S.unit,"aria-label":"Interval unit",children:$.map(([I,L])=>a.jsx("option",{value:I,children:L},I))})]}),E?a.jsx("p",{className:"af-auto__hint","data-email-rule":"interval",children:et.interval_rule}):null]}):C?a.jsxs("fieldset",{className:"af-auto__field","data-field":"calendar",children:[a.jsx("legend",{children:dt.legend}),a.jsx("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:mv.map(I=>a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:`${R}-calendar-kind`,value:I,checked:C.kind===I,disabled:e.busy,onChange:()=>g(I)})," ",dt[`kind_${I}`]]},I))}),a.jsx(Sv,{value:C,onChange:I=>v(L=>Zh(L??Jg(I),I)),idBase:R,disabled:e.busy}),a.jsx(Nv,{state:k,whose:"automation"})]}):a.jsx("p",{className:"af-auto__hint",children:"This trigger has no interval to change."}),a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:"Context"}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"context",value:"independent",defaultChecked:t.context==="independent",onChange:()=>d("independent")})," Independent — each run starts fresh"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"context",value:"growing",defaultChecked:t.context==="growing",onChange:()=>d("growing")})," Growing — each run sees the previous runs"]}),a.jsx("div",{hidden:u!=="growing",children:a.jsxs("label",{className:"af-auto__field",children:[a.jsx("span",{children:"Max growing context (tokens)"}),a.jsx("input",{name:"growing_max_tokens",type:"number",min:1,step:1,disabled:e.busy||u!=="growing",defaultValue:t.growingMaxTokens}),a.jsx("span",{className:"af-auto__hint",children:uv})]})})]}),t.toolApproval?a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?a.jsx(Cv,{availableTools:e.availableTools,value:o,onChange:l,disabled:e.busy}):null,a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"tool_approval",value:"auto",defaultChecked:t.toolApproval==="auto"})," Run without asking"]}),a.jsxs("label",{children:[a.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?a.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[a.jsx("legend",{children:"Mailbox"}),N?null:a.jsx(mh,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),a.jsx(jk,{variant:"row",action:"notify-email",name:"notify_email",label:et.notify_label,defaultChecked:!!t.notifyEmail,onChange:m,unavailableReason:!N&&!t.notifyEmail?"Connect a mailbox first.":null}),a.jsxs("p",{className:"af-auto__hint",children:[et.notify_hint," Turn on Email result to choose yourself or other email addresses."]}),a.jsx("div",{hidden:!f,children:a.jsxs("fieldset",{className:"af-auto__field",disabled:!f,"data-field":"email-recipients",children:[a.jsx("legend",{children:et.recipients_legend}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"email_recipients",value:"self",defaultChecked:t.emailRecipients.mode==="self"})," ",et.recipients_self]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"email_recipients",value:"list",defaultChecked:t.emailRecipients.mode==="list",disabled:!N&&t.emailRecipients.mode!=="list"})," ",et.recipients_list]}),a.jsx("textarea",{name:"email_recipient_list","aria-label":et.recipients_list,rows:2,spellCheck:!1,defaultValue:t.emailRecipients.addresses,disabled:!N&&t.emailRecipients.mode!=="list"}),a.jsx("p",{className:"af-auto__hint",children:et.recipients_hint})]})})]}):null,a.jsx("p",{className:"af-auto__hint",children:"Changes apply from the next run; runs that a new schedule would have had in the past are not made up."}),e.errors.length?a.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:e.errors.map(I=>a.jsx("li",{children:I},I))}):null,a.jsxs("div",{className:"af-auto__row",children:[a.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"edit-save",disabled:e.busy,children:a.jsx(vn,{icon:"check",label:e.submitLabel??"Save changes"})}),e.onCancel?a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"edit-cancel",onClick:e.onCancel,children:a.jsx(vn,{icon:"x",label:"Cancel"})}):null]})]})}function T0(e,t){const n=typeof t=="string"?t.trim():"",s=typeof e=="string"?e:"",o=s.indexOf(`
61
- `);if(!n||o<0||!s.startsWith("["))return null;const l=s.slice(o+1);return l===n||l.startsWith(`${n}
62
- `)?n:null}function R0(e){var n;const t=String(((n=e.trigger)==null?void 0:n.source_id)||"");return t==="schedule"?"on schedule":t==="manual"?"run by hand":t.startsWith("email")?"new mail":t?"something arrived":""}const I0="What the agent received";function yh(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function L0(e){const t=e.wait,n=`${e.idBase}-${t.run_id}-${t.wait_key}-prompt`,s=u=>e.onAnswerWait(t.run_id,t.wait_key,u),o=e.renderText??Eu,l=u=>a.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[a.jsx("span",{className:"af-auto-wait__kind",children:vv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):a.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=Wj(t);return a.jsxs("div",{className:"af-auto-wait af-auto-wait--tool_approval",role:"group","data-wait-key":t.wait_key,"data-wait-kind":t.kind,"aria-labelledby":n,children:[l("A tool call needs your approval."),u&&u.length?a.jsx("ul",{className:"af-auto-wait__calls","aria-label":"Tool calls to approve",children:u.map((d,f)=>a.jsxs("li",{"data-tool":d.name,children:[a.jsx("code",{className:"af-auto-wait__tool",children:d.name}),a.jsx("pre",{className:"af-auto-wait__args",children:JSON.stringify(d.arguments,null,2)})]},d.call_id??`${d.name}:${f}`))}):a.jsx("p",{className:"af-auto__hint",children:"The gateway did not list the tool calls; open the run to see them before approving."}),a.jsxs("div",{className:"af-auto__row",children:[a.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-approve",disabled:e.busy,onClick:()=>s({approved:!0}),children:a.jsx(vn,{icon:"check",label:"Approve"})}),a.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--danger","data-action":"wait-deny",disabled:e.busy,onClick:()=>s({approved:!1}),children:a.jsx(vn,{icon:"x",label:"Deny"})})]})]})}return t.kind==="event"?a.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 f;u.preventDefault();const d=Uj(yh(u.currentTarget,"payload"));d.ok?s({payload:d.payload}):(f=e.onWaitError)==null||f.call(e,d.error)},children:[l("The run waits for an event."),a.jsx("textarea",{name:"payload",rows:3,"aria-label":"Event payload (JSON)",placeholder:'{"key": "value"}',disabled:e.busy}),a.jsx("div",{className:"af-auto__row",children:a.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-send-event",disabled:e.busy,children:a.jsx(vn,{icon:"send",label:"Send event"})})})]}):t.kind==="ask_user"?a.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=yh(u.currentTarget,"response");d&&s({response:d})},children:[l("The run is waiting for your input."),t.choices&&t.choices.length?a.jsx("div",{className:"af-auto__row",role:"group","aria-label":"Choices",children:t.choices.map(u=>a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"wait-choice",disabled:e.busy,onClick:()=>s({response:u}),children:u},u))}):null,a.jsxs("div",{className:"af-auto__row",children:[a.jsx("input",{name:"response","aria-label":"Your answer",placeholder:"Your answer",disabled:e.busy}),a.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"wait-answer",disabled:e.busy,children:a.jsx(vn,{icon:"send",label:"Answer"})})]})]}):a.jsxs("div",{className:"af-auto-wait",role:"group","data-wait-key":t.wait_key,"data-wait-kind":String(t.kind),"aria-labelledby":n,children:[l("The run is waiting."),a.jsxs("p",{className:"af-auto__hint",children:["This kind of wait (",String(t.kind),") cannot be answered here; open the run."]})]})}function M0(e){const{row:t,tone:n,badge:s,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Eu,d=e.discuss.enabled&&e.view.canDiscuss&&!e.busy,f=e.discuss.enabled?e.view.canDiscuss?null:"Available once this run finishes.":e.discuss.reason??"Not available.",m=(k,S)=>e.renderTurn?e.renderTurn({kind:k,role:k==="trigger"?"user":"assistant",text:S,index:t.index,runId:t.run_id}):u(S),p=e.renderTurn?" af-auto-turn--card":"",g=typeof e.task=="string"?e.task.trim():"",_=T0(t.user_turn,g)!==null,v=R0(t),C=uh(t.fired_at,{timeZone:e.timeZone,nowMs:e.nowMs,style:"day"}),x=n==="failed"?t.failure?"No answer.":"No answer: the run failed.":n==="waiting"?"Waiting for your answer.":n==="running"?"Running…":"No answer.";return a.jsxs("li",{className:`af-auto-occ af-auto-occ--${n}`,"data-index":t.index,"data-tone":n,"aria-labelledby":`${l}-h`,children:[a.jsxs("div",{className:`af-auto-turn af-auto-turn--trigger${p}`,"data-turn":"trigger",children:[a.jsxs("div",{className:"af-auto-turn__meta",id:`${l}-h`,title:`${t.trigger.summary} · fired ${nu(t.fired_at)}`,children:[a.jsxs("span",{className:"af-auto-turn__index",children:["Run #",t.index]}),v?` · ${v}`:"",C?` · ${C}`:""]}),e.eventCard?a.jsxs("div",{className:"af-auto-event","data-event-card":"true",children:[a.jsx(de,{name:"inbox",size:14,className:"af-auto__btn-icon"}),a.jsxs("span",{className:"af-auto-event__text",children:[a.jsx("strong",{className:"af-auto-event__source",children:e.eventCard.source}),e.eventCard.what?a.jsxs("span",{children:[" · ",e.eventCard.what]}):null,e.eventCard.at?a.jsxs("span",{className:"af-auto-turn__muted",children:[" · ",e.eventCard.at]}):null]})]}):null,(_?g:t.user_turn).trim()?a.jsx("div",{className:"af-auto-turn__text",children:m("trigger",_?g:t.user_turn)}):null,_?a.jsxs("details",{className:"af-auto-received","data-received":"true",children:[a.jsx("summary",{children:I0}),a.jsx("div",{className:"af-auto-received__body",children:u(t.user_turn)})]}):null]}),a.jsxs("div",{className:`af-auto-turn af-auto-turn--answer${p}`,"data-turn":"answer",children:[a.jsxs("div",{className:"af-auto-turn__meta",children:[s?a.jsx("span",{className:`af-auto-badge af-auto-badge--${n}`,children:s}):null,a.jsx("span",{className:"af-auto-turn__status",children:o}),t.finished_at?a.jsxs("span",{title:nu(t.finished_at),children:[" · ",uh(t.finished_at,{timeZone:e.timeZone,nowMs:e.nowMs,style:"day"})]}):null]}),t.notify?a.jsxs("div",{className:"af-auto-notify","data-notify":"true",children:[a.jsx("strong",{children:t.notify.title}),t.notify.body?a.jsx("div",{className:"af-auto-notify__body",children:u(t.notify.body)}):null]}):null,t.failure?a.jsxs("div",{className:"af-auto-failure","data-failure":t.failure.reason_code,children:[a.jsx("strong",{children:t.failure.reason_code}),": ",t.failure.message," ",a.jsxs("span",{className:"af-auto-turn__muted",children:["(after ",t.failure.attempts," ",t.failure.attempts===1?"attempt":"attempts",")"]})]}):null,t.answer?a.jsx("div",{className:"af-auto-turn__text",children:m("answer",t.answer)}):a.jsx("div",{className:"af-auto-turn__empty",children:x}),t.artifacts.length?a.jsx("ul",{className:"af-auto-artifacts","aria-label":"Artifacts",children:t.artifacts.map(k=>a.jsxs("li",{children:[e.onOpenResource?a.jsxs("button",{type:"button",className:"af-auto__linkbtn","data-action":"open-artifact",onClick:()=>{var S;return(S=e.onOpenResource)==null?void 0:S.call(e,{kind:"artifact",url:k.url,name:k.name,mimeType:k.mime_type,runId:t.run_id})},children:[a.jsx(de,{name:"file",size:13,className:"af-auto__btn-icon"})," ",k.name]}):a.jsx("span",{className:"af-auto-artifact__name",children:k.name})," ",a.jsx("span",{className:"af-auto-turn__muted",children:k.mime_type})]},k.artifact_id))}):null,t.waits.map(k=>a.jsx(L0,{wait:k,busy:e.busy,idBase:l,onAnswerWait:e.onAnswerWait,onWaitError:e.onWaitError,renderText:e.renderText},`${k.run_id}:${k.wait_key}`))]}),a.jsxs("div",{className:"af-auto-occ__foot",children:[a.jsxs("details",{className:"af-auto-occ__details",children:[a.jsx("summary",{children:"Run details"}),a.jsxs("dl",{className:"af-auto__facts",children:[a.jsx("dt",{children:"Run"}),a.jsx("dd",{children:a.jsx("code",{children:t.run_id})}),a.jsx("dt",{children:"Attempts"}),a.jsx("dd",{children:t.attempts})]}),a.jsxs("div",{className:"af-auto__row",children:[a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-run",onClick:()=>e.onOpenRun(t.run_id),children:a.jsx(vn,{icon:"list",label:"Open run ledger"})}),e.onOpenResource?a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-ledger-json",onClick:()=>{var k;return(k=e.onOpenResource)==null?void 0:k.call(e,{kind:"ledger",url:t.ledger_url,name:`run-${t.run_id}-ledger.json`,runId:t.run_id})},children:a.jsx(vn,{icon:"file",label:"Ledger (JSON)"})}):null,t.workspace_url&&e.onOpenWorkspace?a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"open-workspace",title:"Browse this run's folder",onClick:()=>{var k;return(k=e.onOpenWorkspace)==null?void 0:k.call(e,t.run_id)},children:a.jsx(vn,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?a.jsxs("form",{className:"af-auto-discuss","aria-label":`${Yg}, from run ${t.index}`,onSubmit:k=>{k.preventDefault();const S=yh(k.currentTarget,"prompt");S&&e.onDiscussSubmit(t.index,S)},children:[a.jsxs("p",{className:"af-auto__hint",children:["Starts a new conversation from run #",t.index," with the automation's whole history (runs 1–",t.index,"). It works in its own folder; the automation's files can be read but not changed (by the file tools; shell commands are not sandboxed), and nothing is written back into the automation."]}),a.jsx("textarea",{name:"prompt",rows:3,"aria-label":"Your message",placeholder:"Ask about this result…",required:!0}),a.jsxs("div",{className:"af-auto__row",children:[a.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary","data-action":"discuss-submit",disabled:e.busy,children:a.jsx(vn,{icon:"send",label:"Start discussion"})}),a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:a.jsx(vn,{icon:"x",label:"Cancel"})})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","data-action":"discuss",disabled:!d,title:gh.discuss,"aria-description":gh.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:a.jsx(vn,{icon:Ov.discuss,label:Yg})}),f?a.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const O0=5e3,P0={[It.pause]:"Automation paused.",[It.resume]:"Automation active.",[It.run_now]:"Run requested.",[It.stop_current]:"Stop requested.",[It.unarchive]:"Unarchived: it is paused until you make it active."};function D0(e){var ve,Ne;const{summary:t,busy:n}=e,s=e.renderText??Eu,o=y.useId(),l=y.useRef(null),[u,d]=y.useState(!1),f=e.editOpen!==void 0,p=Ao(t,e.occurrences,!1).revise.enabled&&(f?e.editOpen===!0:u),g=y.useRef(null);p?(!g.current||g.current.summary.automation_id!==t.automation_id)&&(g.current={summary:t,definition:e.definition}):g.current=null;const _=g.current,v=y.useRef(e.onEditOpenChange);v.current=e.onEditOpenChange;const C=q=>{var be;f||d(q),(be=v.current)==null||be.call(v,q)},[x,k]=y.useState([]),[S,$]=y.useState(!1),[R,N]=y.useState(null),[E,j]=y.useState(null),[I,L]=y.useState(null);y.useEffect(()=>{if(!I)return;const q=setTimeout(()=>L(null),O0);return()=>clearTimeout(q)},[I]),y.useEffect(()=>{var be;if(!p)return;k([]);const q=Kg(l.current,['.af-auto__revise [name="title"]']);q==null||q.focus(),(be=q==null?void 0:q.scrollIntoView)==null||be.call(q,{block:"nearest"})},[p,t.automation_id]);const[z,V]=y.useState(null);y.useEffect(()=>{var q;z&&((q=Kg(l.current,[...z,".af-auto__notice",".af-auto__title"]))==null||q.focus(),V(null))},[z]);const Z=y.useRef(null);Z.current||(Z.current=new _v(e.newId??bv));const ie=Z.current,F=q=>j(x0(q)),D=(q,be,xe)=>{j(null),L(null),be(ie.idFor(q)).then(Pe=>{ie.settle(q,{ok:!0}),xe(Pe)},Pe=>{ie.settle(q,{ok:!1,error:Pe}),F(Pe)})},M=jj(t),J=y.useRef(e.onSeen);J.current=e.onSeen;const B=y.useRef(null);B.current||(B.current=new Gj),y.useEffect(()=>{const q=B.current,be=M?`${t.automation_id}|${M}`:null;if(!M||!q.next(be,t))return;const xe=t;J.current(M).then(()=>q.succeeded(be),Pe=>{q.failed(be,xe),F(Pe)})});const Y=Ao(t,e.occurrences,n),te=Sj(e.occurrences),W=(Ne=(ve=e.definition)==null?void 0:ve.target.input_data)==null?void 0:Ne.prompt,T=q=>e.occurrenceEvents&&q in e.occurrenceEvents?oj(e.occurrenceEvents[q],{trigger:t.trigger,connections:e.triggerConnections,mailboxes:e.mailboxes,timeZone:t.time_zone,nowMs:e.nowMs}):null,K=t.occurrence_count-e.occurrences.length,ne=E??e.error??null,ue=ne?Lo(ne):null,oe=t.attention;return a.jsxs("section",{ref:l,className:`af-auto${e.className?` ${e.className}`:""}`,...e.hideHeader?{"aria-label":t.title}:{"aria-labelledby":o},"aria-busy":n,"data-text-rendering":e.renderText?"rich":"unformatted",children:[e.hideHeader?null:a.jsxs(a.Fragment,{children:[a.jsx(S0,{summary:t,workflowLabel:e.workflowName,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}),a.jsx(A0,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:S,reviseOpen:p,notice:I,onDismissNotice:()=>L(null),idBase:`${o}-ctl`,onCommand:q=>D(`command:${q}`,be=>e.onCommand(q,void 0,{command_id:be}),()=>{q===It.archive?($(!1),L("Archive requested."),V(['[data-action="archive"]'])):L(P0[q]??"Command sent.")}),onToggleRevise:()=>{k([]),C(!p)},onAskArchive:()=>$(!0),onCancelArchive:()=>{$(!1),V(['[data-action="archive"]'])}})]}),p&&_?a.jsx(Pv,{summary:_.summary,definition:_.definition,busy:n,errors:x,availableTools:e.availableTools,workflowPickerOptions:e.workflowPickerOptions,emailStatus:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail,previewSchedule:e.previewSchedule,onCancel:()=>{C(!1),V(['[data-action="edit"]'])},onSubmit:q=>{const be=_.summary,xe=cv(be,q,_.definition);if(xe===null){k(["Nothing changed."]);return}if("errors"in xe){k(xe.errors);return}k([]),D(`revise:${be.revision}:${JSON.stringify(xe)}`,async Pe=>{const Qe=q.target&&xe.target?{...xe,target:await(e.prepareTarget?e.prepareTarget(xe.target):y0(xe.target,e.workflowPickerOptions))}:xe;return e.onRevise(Qe,be.revision,{command_id:Pe})},()=>{L("Saved; applies from the next run."),C(!1),V(['[data-action="edit"]'])})}}):e.definition?a.jsx(j0,{definition:e.definition,renderText:s,served:t,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}):null,ue?a.jsxs("div",{className:"af-auto__error",role:"alert","data-code":ne==null?void 0:ne.code,children:[a.jsx(de,{name:"error",size:14,className:"af-auto__btn-icon"}),a.jsxs("span",{className:"af-auto__error-text",children:[a.jsx("strong",{children:ue.title})," ",a.jsx("span",{children:ue.detail})]}),E?a.jsx("button",{type:"button",className:"af-auto__icon-btn af-auto__icon-btn--bare","data-action":"dismiss-error","aria-label":"Dismiss",title:"Dismiss",onClick:()=>j(null),children:a.jsx(de,{name:"x",size:12})}):null]}):null,oe.items.length||oe.waits.length?a.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:a.jsxs("ul",{children:[oe.items.map(q=>a.jsxs("li",{className:`af-auto__attention-item af-auto__attention-item--${q.kind}`,"data-cursor":q.cursor,children:[a.jsx("span",{className:`af-auto-badge af-auto-badge--${q.kind==="failure"?"failed":"notified"}`,children:q.kind==="failure"?"Failed":"Notified"})," ",a.jsx("strong",{children:q.title})," ",a.jsxs("span",{className:"af-auto-turn__muted",children:["#",q.index," · ",nu(q.at)]}),q.body?a.jsx("div",{className:"af-auto__attention-body",children:s(q.body)}):null]},q.cursor)),oe.waits.map(q=>a.jsxs("li",{className:"af-auto__attention-item af-auto__attention-item--wait",children:[a.jsx("span",{className:"af-auto-badge af-auto-badge--waiting","data-wait-kind":q.kind,children:vv[q.kind]??"Waiting for you"})," ",a.jsxs("span",{className:"af-auto-turn__muted",children:["#",q.index]}),q.prompt?a.jsx("div",{className:"af-auto__attention-body",children:s(q.prompt)}):null]},`${q.run_id}:${q.wait_key}`))]})}):null,K>0?a.jsx("button",{type:"button",className:"af-auto__btn af-auto__more","data-action":"load-more",disabled:n,onClick:e.onLoadMore,children:a.jsx(vn,{icon:"history",label:`Load earlier runs (${K} more)`})}):null,te.length?a.jsx("ol",{className:"af-auto__timeline","aria-label":"Runs",children:te.map(q=>{const be=`[data-index="${q.row.index}"]`;return a.jsx(M0,{view:q,busy:n,eventCard:T(q.row.run_id),task:typeof W=="string"?W:void 0,timeZone:t.time_zone,nowMs:e.nowMs,discuss:Y.discuss,renderText:s,renderTurn:e.renderTurn,onOpenWorkspace:e.onOpenWorkspace,onOpenResource:e.onOpenResource?xe=>{var Pe;j(null);try{Promise.resolve((Pe=e.onOpenResource)==null?void 0:Pe.call(e,xe)).catch(F)}catch(Qe){F(Qe)}}:void 0,discussOpen:R===q.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(xe,Pe,Qe)=>{j(null),e.onAnswerWait(xe,Pe,Qe).then(()=>L("Answer sent."),F)},onWaitError:xe=>j({status:0,code:"invalid_payload",message:xe}),onDiscussOpen:N,onDiscussCancel:()=>{N(null),V([`${be} [data-action="discuss"]`])},onDiscussSubmit:(xe,Pe)=>D(`discuss:${xe}:${Pe}`,Qe=>e.onDiscuss(xe,Pe,{request_id:Qe}),()=>{N(null),L("Discussion started in a new conversation."),V([`${be} [data-action="discuss"]`])})},q.row.run_id)})}):a.jsx("p",{className:"af-auto__empty",children:"No runs yet."})]})}function F0(e,t){return e==="email"||!Dj(t.when)?null:wv({...t}).trigger}function z0(e){return e==="daily"||e==="weekly"||e==="monthly"||e==="once"}function B0(e){var Q,_e;const t=y.useId(),n=y.useId(),s=y.useRef(null),o=y.useRef(null),l=y.useRef(e.onClose);l.current=e.onClose;const u=e.initialTools??ju((Q=e.target)==null?void 0:Q.input_data),[d,f]=y.useState({open:e.open,value:u});d.open!==e.open&&f({open:e.open,value:u});const m=d.value,p=ae=>f(Se=>({...Se,value:ae})),[g,_]=y.useState(e.initialPrompt??""),[v,C]=y.useState("every"),[x,k]=y.useState(xv),S=kv(v==="weekly"||v==="monthly"?v:"daily",x),[$,R]=y.useState(qh),[N,E]=y.useState(!1),[j,I]=y.useState(Xi),[L,z]=y.useState("24"),[V,Z]=y.useState("h"),[ie,F]=y.useState(""),[D,M]=y.useState(String(sl)),[J,B]=y.useState("independent"),[Y,te]=y.useState("auto"),[W,T]=y.useState(e.initialTitle??""),[K,ne]=y.useState(""),[ue,oe]=y.useState(""),[ve,Ne]=y.useState(""),[q,be]=y.useState([]),xe=y.useRef(null);xe.current||(xe.current=new _v(()=>(e.newRequestId??bv)())),y.useEffect(()=>{var Oe;if(!e.open)return;const ae=document.activeElement;(Oe=o.current)==null||Oe.focus();const Se=Fe=>{if(!Fe.defaultPrevented){if(Fe.key==="Escape"){Fe.preventDefault(),l.current();return}Rw(Fe,s.current,document.activeElement)}};return window.addEventListener("keydown",Se),()=>{window.removeEventListener("keydown",Se),ae&&typeof ae.focus=="function"&&ae.focus()}},[e.open]);const Pe=v==="once"?{kind:"once",at:ie}:v==="daily"||v==="weekly"||v==="monthly"?S:{kind:"every",amount:Number(L),unit:V},Qe={...v==="every"&&K?{startAt:K}:{},...v!=="once"&&ue.trim()?{count:Number(ue)}:{},...v!=="once"&&ve?{until:ve}:{}},He=jv(e.open?F0(v,{when:Pe,...Qe}):null,e.previewSchedule);if(!e.open)return null;const qe=Jh(e.emailStatus),ge=v==="email"&&qe,$e=v==="email"&&!qe?"every":v,st=$e==="daily"||$e==="weekly"||$e==="monthly",tt=ae=>C(ae),Lt={prompt:g,when:v==="once"?{kind:"once",at:ie}:st?S:{kind:"every",amount:Number(L),unit:V},...ge?{trigger:"email",email:{...$,usesModel:e.targetUsesModel!==!1}}:{},...qe&&N?{notifyEmail:!0}:{},...qe&&j.mode==="list"?{emailRecipients:j}:{},context:J,growingMaxTokens:Number(D),toolApproval:Y,title:W,...$e==="every"&&K?{startAt:K}:{},...($e==="every"||st)&&ue.trim()?{count:Number(ue)}:{},...($e==="every"||st)&&ve?{until:ve}:{}},ce=Fj(Lt),fe=e.busy===!0,H=e.error?Lo(e.error):null,le=ae=>`${n}-${ae}`,he=ae=>{ae.preventDefault();const Se=zj(Lt,{target:e.target,requestId:""});if(!Se.ok){be(Se.errors);return}be([]);const Oe=xe.current,Fe=e.availableTools===void 0?Se.body:{...Se.body,target:{...Se.body.target,input_data:Wh(Se.body.target.input_data||{},m)}},Ze=JSON.stringify(Fe),Le={...Fe,request_id:Oe.idFor(Ze)};Promise.resolve(e.onSubmit(Le)).then(()=>Oe.settle(Ze,{ok:!0}),Ke=>Oe.settle(Ze,{ok:!1,error:Ke}))};return a.jsx("div",{className:"af-appearance-overlay af-schedule-overlay",onClick:e.onClose,role:"presentation",children:a.jsxs("div",{ref:s,className:"af-appearance af-schedule",role:"dialog","aria-modal":"true","aria-labelledby":t,onClick:ae=>ae.stopPropagation(),children:[a.jsx("div",{className:"af-appearance__title",id:t,children:e.title??"Schedule a task"}),a.jsxs("form",{className:"af-schedule__form",onSubmit:he,"aria-busy":fe,children:[a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:"What"}),e.workflowPicker?a.jsx("div",{className:"af-schedule__picker",children:e.workflowPicker}):null,e.target?null:a.jsx("p",{className:"af-auto__hint",children:"Choose what to run."}),a.jsxs("label",{className:"af-auto__field",htmlFor:le("prompt"),children:[a.jsx("span",{children:"Task"}),a.jsx("textarea",{id:le("prompt"),ref:o,rows:3,value:g,onChange:ae=>_(ae.target.value),placeholder:"e.g. Check the price of ACME shares and notify me if it moved more than 2%.",required:!0})]})]}),a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:dt.legend}),a.jsxs("div",{className:"af-auto__row",role:"radiogroup","aria-label":"Schedule kind",children:[a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("kind"),value:"every",checked:$e==="every",onChange:()=>tt("every")})," ",dt.kind_every]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("kind"),value:"daily",checked:v==="daily",onChange:()=>tt("daily")})," ",dt.kind_daily]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("kind"),value:"weekly",checked:v==="weekly",onChange:()=>tt("weekly")})," ",dt.kind_weekly]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("kind"),value:"monthly",checked:v==="monthly",onChange:()=>tt("monthly")})," ",dt.kind_monthly]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("kind"),value:"once",checked:v==="once",onChange:()=>tt("once")})," ",dt.kind_once]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("kind"),value:"email",checked:ge,disabled:!qe,onChange:()=>tt("email")})," ",et.trigger_label]})]}),qe?null:a.jsx(mh,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),ge?a.jsx(w0,{value:{...$,usesModel:e.targetUsesModel!==!1},onChange:R,idBase:n}):st?a.jsx(Sv,{value:S,onChange:ae=>k(Se=>Zh(Se,ae)),idBase:n,disabled:fe}):$e==="every"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"af-auto__row af-schedule__presets",role:"group","aria-label":"Presets",children:Lj.map(ae=>ae.when.kind==="every"?a.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","aria-pressed":Number(L)===ae.when.amount&&V===ae.when.unit,onClick:()=>{ae.when.kind==="every"&&(z(String(ae.when.amount)),Z(ae.when.unit))},children:ae.label},ae.label):null)}),a.jsxs("div",{className:"af-auto__row",children:[a.jsx("span",{children:dt.every_label}),a.jsx("input",{type:"number",min:1,step:1,value:L,onChange:ae=>z(ae.target.value),"aria-label":"Interval amount"}),a.jsxs("select",{value:V,onChange:ae=>Z(ae.target.value),"aria-label":"Interval unit",children:[a.jsx("option",{value:"m",children:"minutes"}),a.jsx("option",{value:"h",children:"hours"}),a.jsx("option",{value:"d",children:"days"})]})]})]}):a.jsxs("label",{className:"af-auto__field",htmlFor:le("once"),children:[a.jsx("span",{children:dt.once_label}),a.jsx("input",{id:le("once"),type:"datetime-local",value:ie,onChange:ae=>F(ae.target.value)})]}),$e!=="email"?a.jsx(Nv,{state:He,onOpenPreferences:e.onOpenPreferences,showZone:z0($e)}):a.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":"true",children:ce?`Runs ${ce}.`:ge?"Incomplete email trigger.":dt.incomplete})]}),a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:"Context"}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("ctx"),value:"independent",checked:J==="independent",onChange:()=>B("independent")})," Independent — each run starts fresh"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("ctx"),value:"growing",checked:J==="growing",onChange:()=>B("growing")})," Growing — each run sees the previous runs"]}),J==="growing"?a.jsxs("label",{className:"af-auto__field",children:[a.jsx("span",{children:"Max growing context (tokens)"}),a.jsx("input",{type:"number",min:1,step:1,required:!0,disabled:fe,value:D,onChange:ae=>M(ae.target.value)}),a.jsx("span",{className:"af-auto__hint",children:uv})]}):null]}),a.jsxs("fieldset",{className:"af-auto__field","data-field":"tool-approval",children:[a.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?a.jsx(Cv,{availableTools:e.availableTools,value:m,onChange:p,disabled:fe}):null,a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("tools"),value:"auto",checked:Y==="auto",onChange:()=>te("auto")})," Run without asking"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:le("tools"),value:"ask",checked:Y==="ask",onChange:()=>te("ask")})," Ask me before each tool call (the run waits for you)"]}),ge?a.jsx("p",{className:"af-auto__hint","data-email-rule":"untrusted",children:et.untrusted_hint}):null,Y==="auto"?a.jsxs("p",{className:"af-schedule__consent","data-consent":"true",children:[Bj,e.targetTools&&e.targetTools.length?`: ${e.targetTools.join(", ")}.`:"."]}):a.jsx("p",{className:"af-auto__hint",children:"Each tool call waits for your approval in the automation's timeline."})]}),e.workspaces?a.jsx("div",{className:"af-auto__field","data-field":"workspaces",role:"group","aria-label":"Workspaces",children:e.workspaces}):null,a.jsxs("fieldset",{className:"af-auto__field","data-field":"email",children:[a.jsx("legend",{children:"Mailbox"}),qe?null:a.jsx(mh,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),a.jsx(v0,{notifyEmail:qe&&N,onNotifyEmailChange:E,recipients:qe?j:Xi,onRecipientsChange:I,disabled:!qe,idBase:n})]}),a.jsxs("fieldset",{className:"af-auto__field","data-field":"limits",children:[a.jsx("legend",{children:"Title and limits"}),a.jsxs("label",{className:"af-auto__field",htmlFor:le("title"),children:[a.jsx("span",{children:"Title"}),a.jsx("input",{id:le("title"),value:W,maxLength:120,onChange:ae=>T(ae.target.value),placeholder:"Defaults to the task's first line"})]}),$e==="every"||st?a.jsxs(a.Fragment,{children:[$e==="every"?a.jsxs("label",{className:"af-auto__field",htmlFor:le("start"),children:[a.jsx("span",{children:"First run at (UTC; empty = now)"}),a.jsx("input",{id:le("start"),type:"datetime-local",value:K,onChange:ae=>ne(ae.target.value)})]}):null,a.jsxs("label",{className:"af-auto__field",htmlFor:le("count"),children:[a.jsx("span",{children:"Stop after this many runs"}),a.jsx("input",{id:le("count"),type:"number",min:1,step:1,value:ue,onChange:ae=>oe(ae.target.value)})]}),a.jsxs("label",{className:"af-auto__field",htmlFor:le("until"),children:[a.jsx("span",{children:"Stop at (UTC)"}),a.jsx("input",{id:le("until"),type:"datetime-local",value:ve,onChange:ae=>Ne(ae.target.value)})]})]}):null]}),q.length?a.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:q.map(ae=>a.jsx("li",{children:ae},ae))}):null,H?a.jsxs("div",{className:"af-auto__error",role:"alert","data-code":(_e=e.error)==null?void 0:_e.code,children:[a.jsx("strong",{children:H.title})," ",a.jsx("span",{children:H.detail})]}):null,a.jsxs("div",{className:"af-appearance__actions af-auto__row",children:[a.jsx("button",{type:"button",className:"af-auto__btn",onClick:e.onClose,children:"Cancel"}),a.jsx("button",{type:"submit",className:"af-auto__btn af-auto__btn--primary",disabled:fe,children:"Create automation"})]})]})]})})}const ru=6e4,wh=60*ru,Xg=24*wh;function au(e){const t=Math.abs(e);return Number.isFinite(t)?t<ru?"<1 min":t<wh?`${Math.floor(t/ru)} min`:t<2*Xg?`${Math.floor(t/wh)} h`:`${Math.floor(t/Xg)} d`:""}function W0(e,t,n){return e.source_id==="schedule"?Aj(t,e.source_version):e.source_id==="manual"?"manual":ul(e)?"on new email":Hh(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function Jc(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function U0(e,t){var o;if(e.current_occurrence&&(((o=e.attention)==null?void 0:o.pending_waits)??0)>0){const l=e.last_occurrence&&e.last_occurrence.index===e.current_occurrence.index?Jc(e.last_occurrence.fired_at):null;return l===null?"":`waiting since ${au(Math.max(0,t-l))}`}if(e.current_occurrence)return"running now";const n=e.last_occurrence,s=Jc(n==null?void 0:n.finished_at)??Jc(n==null?void 0:n.fired_at);return s===null?"last never":`last ${au(Math.max(0,t-s))} ago`}function V0(e,t){const n=Jc(e.next_run_at);return n===null?null:n-t<ru?"next due now":`next in ${au(n-t)}`}function Dv(e,t){const n=W0(e.trigger,e),s=U0(e,t),o=V0(e,t);return{cadence:n,last:s,next:o,line:[n,s,o].filter(Boolean).join(" · ")}}const En={min:300,max:960,default:420,step:16,bigStep:64};function ou(e,t=En.min,n=En.max,s=En.default){return Number.isFinite(e)?Math.round(Math.min(n,Math.max(t,e))):Math.min(n,Math.max(t,s))}function G0(e,t,n,s=En.min,o=En.max,l="right"){const u=n?En.bigStep:En.step,d=l==="left"?"ArrowRight":"ArrowLeft",f=l==="left"?"ArrowLeft":"ArrowRight";return t===d?ou(e+u,s,o):t===f?ou(e-u,s,o):t==="Home"?s:t==="End"?o:null}function H0(e,t,n,s=En.min,o=En.max){return ou(n==="left"?e+t:e-t,s,o)}function K0(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 J0(e,t){return e===t?null:t}function Zi(e){return e.side==="left"?"left":"right"}function Zg(e,t,n){const s=e==null?null:typeof e=="string"?e:e[t]??null;if(!s)return null;const o=n.find(l=>l.id===s);return o&&Zi(o)===t?s:null}function q0(e){const t=String(e||"");if(!t)return null;const n=t.indexOf("#"),s=n<0?t:t.slice(0,n);return s?{id:s,nonce:n<0?"":t.slice(n+1)}:null}function Y0(e,t,n){return e.id===t||e.keepAlive==="always"||n.has(e.id)}function Q0(e){const t={widths:{},active:{}},n=String(e??"").trim();if(!n)return t;if(/^\d+(\.\d+)?$/.test(n))return{...t,legacyWidth:Number(n)};try{const s=JSON.parse(n);if(!s||typeof s!="object"||Array.isArray(s))return t;const o={};if(s.widths&&typeof s.widths=="object")for(const[d,f]of Object.entries(s.widths))typeof f=="number"&&Number.isFinite(f)&&(o[d]=f);const l={};if(s.active&&typeof s.active=="object")for(const d of["left","right"]){const f=s.active[d];(typeof f=="string"||f===null)&&(l[d]=f)}const u=typeof s.legacy=="number"&&Number.isFinite(s.legacy)?s.legacy:void 0;return u===void 0?{widths:o,active:l}:{widths:o,active:l,legacyWidth:u}}catch{return t}}function X0(e){return JSON.stringify({v:1,widths:e.widths,active:e.active,...e.legacyWidth!==void 0?{legacy:e.legacyWidth}:{}})}function ey(e,t,n){const s=t.minWidth??(n==null?void 0:n.min)??En.min,o=t.maxWidth??(n==null?void 0:n.max)??En.max,l=t.defaultWidth??(n==null?void 0:n.width)??En.default,u=e.widths[t.id]??e.legacyWidth;return ou(u??l,s,o,l)}function Z0(e,t,n,s){if(n)return null;const o=e.active[t];if(!o)return null;const l=s.find(u=>u.id===o);return l&&Zi(l)===t?o:null}function eN(e){if(e==="auto")return"var(--af-topbar-h, 0px)";if(typeof e=="number"&&Number.isFinite(e))return`${Math.max(0,Math.round(e))}px`}const Fv=y.createContext(void 0);function tN(e){const t=y.useContext(Fv);return t===void 0?a.jsx(a.Fragment,{children:e.children}):t===null?null:il.createPortal(e.children,t)}class ty extends yt.Component{constructor(){super(...arguments),this.state={error:null}}static getDerivedStateFromError(t){return{error:t instanceof Error?t:new Error(String(t))}}render(){const{error:t}=this.state;if(!t)return this.props.children;if(this.props.variant==="inline"){const n=`The ${this.props.label} panel's actions stopped: ${t.message||"unknown error"}`;return a.jsx("span",{className:"af-rail__error-inline",role:"img","aria-label":n,"data-af-tip":n,"data-panel-error":"actions",children:a.jsx(de,{name:"warning",size:16})})}return a.jsxs("div",{className:"af-rail__error",role:"alert","data-panel-error":"",children:[a.jsxs("p",{className:"af-rail__error-text",children:["The ",this.props.label," panel stopped: ",t.message||"unknown error"]}),a.jsx("button",{type:"button",className:"af-rail__error-retry",onClick:()=>this.setState({error:null}),children:"Try again"})]})}}function nN(e){if(!e||typeof window>"u")return{widths:{},active:{}};try{return Q0(window.localStorage.getItem(e))}catch{return{widths:{},active:{}}}}function ny(e,t){if(!(!e||typeof window>"u"))try{window.localStorage.setItem(e,X0(t))}catch{}}function sN(e){const{panel:t}=e,[n,s]=y.useState(null),o=e.mounted?t.content:null;return a.jsxs("section",{id:`${e.idBase}-panel-${t.id}`,role:"tabpanel","aria-labelledby":t.mode==="drawer"?void 0:`${e.idBase}-tab-${t.id}`,"aria-label":t.mode==="drawer"?t.label:void 0,className:"af-rail__section","data-panel":t.id,hidden:!e.open,children:[a.jsxs("header",{className:"af-rail__head",children:[a.jsx("h2",{className:"af-rail__title",children:t.label}),a.jsxs("span",{className:"af-rail__head-actions",children:[t.headerActions===void 0||t.headerActions===null?null:t.errorBoundary===!1?t.headerActions:a.jsx(ty,{label:t.label,variant:"inline",children:t.headerActions}),a.jsx("span",{className:"af-rail__head-slot",ref:s}),a.jsx("button",{type:"button",className:"af-rail__icon-btn","data-action":"collapse-panel","aria-label":`Collapse ${t.label}`,title:"Collapse",onClick:e.onCollapse,children:a.jsx(de,{name:e.overlay?"x":"chevronRight",size:16})})]})]}),a.jsx("div",{className:`af-rail__body${t.fill?" af-rail__body--fill":""}`,"data-fill":t.fill?"":void 0,children:a.jsx(Fv.Provider,{value:n,children:t.errorBoundary===!1?o:a.jsx(ty,{label:t.label,children:o})})})]})}function rN(e){const{side:t,panels:n,activeId:s,overlay:o,onActiveChange:l}=e,u=n.find(D=>D.id===s)||null,d=n.filter(D=>D.mode!=="drawer"),[f,m]=y.useState(()=>new Set(s?[s]:[])),p=y.useRef(null),g=y.useRef(null),_=y.useRef(null),v=y.useRef(null),C=u?e.width(u):En.default,x=y.useRef(C);x.current=C;const k=(u==null?void 0:u.minWidth)??En.min,S=(u==null?void 0:u.maxWidth)??En.max;y.useEffect(()=>{s&&m(D=>D.has(s)?D:new Set([...D,s]))},[s]);const $=u?u.id:null,R=y.useRef(l);R.current=l,y.useEffect(()=>{if(!o||!$)return;const D=M=>{M.key!=="Escape"||M.defaultPrevented||(M.preventDefault(),R.current(null))};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[o,$]),y.useEffect(()=>{var D,M,J;if(o)if($)!_.current&&typeof document<"u"&&(_.current=document.activeElement),(D=g.current)==null||D.focus({preventScroll:!0});else{const B=_.current;_.current=null;const Y=typeof document<"u"?document.activeElement:null;B&&(!Y||Y===document.body||(M=g.current)!=null&&M.contains(Y))&&((J=B.focus)==null||J.call(B))}},[o,$]);const N=D=>{var Y,te;const M=Array.from(((Y=p.current)==null?void 0:Y.querySelectorAll('[role="tab"]'))||[]),J=M.findIndex(W=>W===document.activeElement),B=K0(M.length,J<0?0:J,D.key);B!==null&&(D.preventDefault(),(te=M[B])==null||te.focus())},E=D=>{if(!u)return;const M=G0(x.current,D.key,D.shiftKey,k,S,t);M!==null&&(D.preventDefault(),e.setWidth(u,M,!0))},j=D=>{var M,J;D.button!==0&&D.pointerType==="mouse"||(v.current={startX:D.clientX,startW:x.current,pointerId:D.pointerId},(J=(M=D.currentTarget).setPointerCapture)==null||J.call(M,D.pointerId),D.preventDefault())},I=D=>{const M=v.current;!M||M.pointerId!==D.pointerId||!u||e.setWidth(u,H0(M.startW,D.clientX-M.startX,t,k,S),!1)},L=D=>{var J,B;const M=v.current;!M||M.pointerId!==D.pointerId||(v.current=null,(B=(J=D.currentTarget).releasePointerCapture)==null||B.call(J,D.pointerId),u&&e.setWidth(u,x.current,!0))},z=!!u,V=e.railLabelStyle==="vertical-text",Z=o&&e.top!==void 0,ie={"--af-rail-panel-width":`${C}px`,"--af-panel-w":`${C}px`,...e.top!==void 0?{"--af-drawers-top":e.top}:{}},F=d.length>0?a.jsx("div",{ref:p,className:"af-rail__rail",role:"tablist","aria-orientation":"vertical","aria-label":e.ariaLabel,onKeyDown:N,children:d.map(D=>{const M=D.id===s,J=`${M?`Collapse ${D.label}`:D.label}${D.hint?` · ${D.hint}`:""}`;return a.jsxs("button",{type:"button",role:"tab",id:`${e.idBase}-tab-${D.id}`,"aria-selected":M,"aria-controls":`${e.idBase}-panel-${D.id}`,"aria-label":D.label,title:J,className:`af-rail__tab${V?" af-rail__tab--text":""}${M?" is-active":""}`,"data-rail":D.id,onClick:B=>{_.current=B.currentTarget,l(J0(s,D.id))},children:[V?a.jsx("span",{className:"af-rail__vlabel","aria-hidden":"true",children:D.label}):a.jsx(de,{name:D.icon,size:19}),typeof D.badge=="number"&&D.badge>0?a.jsx("span",{className:"af-rail__badge","aria-hidden":"true",children:D.badge>99?"99+":D.badge}):D.badge===!0?a.jsx("span",{className:"af-rail__dot","aria-hidden":"true"}):null]},D.id)})}):null;return a.jsxs("div",{className:`af-rail${t==="left"?" af-rail--left":""}${z?" af-rail--open":" af-rail--collapsed"}${o?" af-rail--overlay":" af-rail--docked"}${Z?" af-rail--anchored":""}${F?"":" af-rail--no-rail"}${V?" af-rail--vertical-text":""}${e.className?` ${e.className}`:""}`,style:ie,"data-active":s||"","data-side":t,children:[t==="left"?F:null,o&&z?a.jsx("div",{className:"af-rail__backdrop","aria-hidden":"true",onClick:()=>l(null)}):null,a.jsxs("div",{className:"af-rail__panel-wrap",hidden:!z,style:!o&&z?{width:C}:void 0,children:[!o&&z?a.jsx("div",{className:"af-rail__resize",role:"separator","aria-orientation":"vertical","aria-label":`Resize the ${(u==null?void 0:u.label)||""} panel`,"aria-valuemin":k,"aria-valuemax":S,"aria-valuenow":C,tabIndex:0,title:"Drag to resize",onKeyDown:E,onPointerDown:j,onPointerMove:I,onPointerUp:L,onPointerCancel:L}):null,a.jsx("div",{ref:g,className:"af-rail__panel",role:o?"dialog":void 0,"aria-label":o?u==null?void 0:u.label:void 0,tabIndex:o?-1:void 0,children:n.map(D=>a.jsx(sN,{panel:D,idBase:e.idBase,open:D.id===s,mounted:Y0(D,s,f),overlay:o,side:t,onCollapse:()=>l(null)},D.id))})]}),t==="right"?F:null]})}function aN(e){const t=Hc(e.overlayBelow||Gc.md),n=e.overlay??t,s=e.idBase||"af-rail",{panels:o,onActiveChange:l,storageKey:u}=e,[d,f]=y.useState(()=>nN(u)),m=y.useRef(d);m.current=d;const p=y.useRef(e.onResize);p.current=e.onResize;const g=o.filter(j=>Zi(j)==="left"),_=o.filter(j=>Zi(j)==="right"),v=Zg(e.active,"left",o),C=Zg(e.active,"right",o),x=y.useCallback(j=>ey(d,j),[d]),k=y.useCallback((j,I,L)=>{var V;const z={...m.current,widths:{...m.current.widths,[j.id]:ey({widths:{[j.id]:I}},j)}};m.current=z,f(z),L&&(ny(u,z),(V=p.current)==null||V.call(p,j.id,z.widths[j.id]))},[u]),S=y.useRef(!1);y.useEffect(()=>{if(!S.current&&(S.current=!0,e.restoreActive!==!1))for(const j of["left","right"]){const I=j==="left"?v:C,L=Z0(m.current,j,n,o);!I&&L&&l(L,j)}},[]);const $=y.useRef(!1);y.useEffect(()=>{if(!$.current){$.current=!0;return}if(n||!u)return;const j={...m.current,active:{left:v,right:C}};m.current=j,ny(u,j)},[v,C,n,u]),y.useEffect(()=>{const j=q0(e.request);if(!j)return;const I=o.find(z=>z.id===j.id);if(!I)return;const L=Zi(I);(L==="left"?v:C)!==j.id&&l(j.id,L)},[e.request]);const R=n?eN(e.topOffset):void 0,N=e.railLabelStyle||"icon",E=(j,I,L)=>I.length?a.jsx(rN,{side:j,panels:I,activeId:L,onActiveChange:z=>l(z,j),overlay:n,width:x,setWidth:k,ariaLabel:g.length&&_.length?`${e.ariaLabel} (${j})`:e.ariaLabel,idBase:s,railLabelStyle:N,top:R,className:e.children===void 0?e.className:void 0}):null;return e.children===void 0&&!g.length?E("right",_,C)||a.jsx(a.Fragment,{}):a.jsxs("div",{className:`af-drawers${n?" af-drawers--overlay":""}${e.className?` ${e.className}`:""}`,children:[E("left",g,v),a.jsx("div",{className:"af-drawers__main",children:e.children}),E("right",_,C)]})}const zv=72;function oN(e,t=zv){const n=Math.max(1,Math.floor(t)),s=new Array(n).fill(0),o=e.length;if(!o)return s;const l=o/n;let u=0;for(let d=0;d<n;d+=1){const f=Math.floor(d*l),m=Math.max(f+1,Math.floor((d+1)*l));let p=0;for(let g=f;g<m&&g<o;g+=1){const _=Math.abs(Number(e[g])||0);_>p&&(p=_)}s[d]=p,p>u&&(u=p)}return u<=0?s:s.map(d=>d/u)}function Pc(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"--:--";const t=Math.floor(e),n=Math.floor(t/3600),s=Math.floor(t%3600/60),o=String(t%60).padStart(2,"0");return n>0?`${n}:${String(s).padStart(2,"0")}:${o}`:`${s}:${o}`}function iN(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function lN(e,t){const[n,s]=y.useState({peaks:t??null,note:""});return y.useEffect(()=>{if(t){s({peaks:t,note:""});return}let o=!0;s({peaks:null,note:""});const l=typeof window<"u"?window.AudioContext||window.webkitAudioContext:void 0;if(!e||!l||typeof fetch!="function"){s({peaks:null,note:"Waveform unavailable in this browser."});return}return(async()=>{let u=null;try{const d=await(await fetch(e)).arrayBuffer();u=new l;const f=await u.decodeAudioData(d);o&&s({peaks:oN(f.getChannelData(0)),note:""})}catch(d){o&&s({peaks:null,note:`Waveform unavailable: ${d instanceof Error?d.message:String(d)}`})}finally{u&&u.close().catch(()=>{})}})(),()=>{o=!1}},[e,t]),n}function Bv(e){const t=y.useRef(null),n=y.useRef(null),[s,o]=y.useState(!1),[l,u]=y.useState(0),[d,f]=y.useState(null),[m,p]=y.useState(""),{peaks:g,note:_}=lN(e.src,e.peaks),v=g??new Array(zv).fill(0),C=d&&d>0?Math.min(1,l/d):0,x=e.name?`Audio ${e.name}`:"Audio",k=y.useCallback(()=>{const N=t.current;N&&(N.paused?N.play().catch(E=>p(E instanceof Error?E.message:String(E))):N.pause())},[]),S=y.useCallback(N=>{const E=t.current;!E||!Number.isFinite(N)||(E.currentTime=N,u(N))},[]),$=N=>{var j;const E=(j=n.current)==null?void 0:j.getBoundingClientRect();!E||!d||S(iN(N-E.left,E.width,d))},R=N=>{if(!d)return;const E=N.key==="ArrowRight"||N.key==="ArrowUp"?5:N.key==="ArrowLeft"||N.key==="ArrowDown"?-5:0;E?(N.preventDefault(),S(Math.min(d,Math.max(0,l+E)))):N.key==="Home"?(N.preventDefault(),S(0)):N.key==="End"?(N.preventDefault(),S(d)):(N.key===" "||N.key==="Enter")&&(N.preventDefault(),k())};return a.jsxs("div",{className:`af-audio${e.className?` ${e.className}`:""}`,"data-playing":s?"true":"false",children:[a.jsx("audio",{ref:t,src:e.src,preload:"metadata",onPlay:()=>o(!0),onPause:()=>o(!1),onEnded:()=>o(!1),onTimeUpdate:N=>u(N.currentTarget.currentTime),onLoadedMetadata:N=>f(Number.isFinite(N.currentTarget.duration)?N.currentTarget.duration:null),onDurationChange:N=>f(Number.isFinite(N.currentTarget.duration)?N.currentTarget.duration:null),onError:()=>p("This audio cannot be played in this browser. Use Download to open it.")}),a.jsx("button",{type:"button",className:"af-audio__play","data-action":s?"pause-audio":"play-audio","aria-label":s?`Pause ${x}`:`Play ${x}`,title:s?"Pause":"Play",onClick:k,children:a.jsx(de,{name:s?"pause":"play",size:16})}),a.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(l),"aria-valuetext":`${Pc(l)} of ${Pc(d)}`,title:_||void 0,"data-waveform":g?"decoded":"flat",onKeyDown:R,onPointerDown:N=>{var E,j;(j=(E=N.currentTarget).setPointerCapture)==null||j.call(E,N.pointerId),$(N.clientX)},onPointerMove:N=>{N.buttons&1&&$(N.clientX)},children:a.jsx("svg",{viewBox:`0 0 ${v.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:v.map((N,E)=>{const j=Math.max(1.5,N*30),I=(E+.5)/v.length<=C;return a.jsx("rect",{className:I?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:E*2+.3,y:16-j/2,width:1.4,height:j,rx:.6},E)})})}),a.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[Pc(l)," / ",Pc(d)]}),m?a.jsx("p",{className:"af-audio__error",role:"alert",children:m}):null]})}const ka=e=>new Set(e.split(/\s+/).filter(Boolean)),cN=ka("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"),uN=ka("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"),dN=ka("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),fN=ka("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"),sy=ka("true false null yes no on off"),hN={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:cN},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:uN},shell:{line:["#"],strings:['"',"'"],keywords:dN},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:fN},data:{line:["#"],strings:['"',"'"],keywords:sy},json:{line:[],strings:['"'],keywords:sy},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:ka("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:ka("")}},mN={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 em(e){const t=String(e||"").trim().toLowerCase(),n=t.split("/").pop()||t;if(n==="dockerfile"||n==="makefile")return"shell";const s=n.lastIndexOf("."),o=s>=0?n.slice(s+1):n;return mN[o]||""}const pN=e=>e>="0"&&e<="9",gN=e=>/[A-Za-z_$]/.test(e),ry=e=>/[A-Za-z0-9_$]/.test(e);function Wv(e,t){const n=String(e??""),s=hN[t];if(!s)return n?[{kind:"plain",text:n}]:[];const o=[];let l="";const u=(f,m)=>{if(m){if(f==="plain"){l+=m;return}l&&o.push({kind:"plain",text:l}),l="",o.push({kind:f,text:m})}};let d=0;for(;d<n.length;){const f=n[d];if(s.line.find(p=>n.startsWith(p,d))){const p=n.indexOf(`
63
- `,d),g=p===-1?n.length:p;u("comment",n.slice(d,g)),d=g;continue}if(s.block&&n.startsWith(s.block[0],d)){const p=n.indexOf(s.block[1],d+s.block[0].length),g=p===-1?n.length:p+s.block[1].length;u("comment",n.slice(d,g)),d=g;continue}if(s.strings.includes(f)){const p=s.triple&&n.startsWith(f.repeat(3),d)?f.repeat(3):"";if(p){const v=n.indexOf(p,d+3),C=v===-1?n.length:v+3;u("string",n.slice(d,C)),d=C;continue}let g=d+1;for(;g<n.length&&n[g]!==f&&(f==="`"||n[g]!==`
64
- `);)g+=n[g]==="\\"?2:1;const _=Math.min(n.length,g+1);u("string",n.slice(d,_)),d=_;continue}if(pN(f)&&!(d>0&&ry(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(gN(f)){let p=d+1;for(;p<n.length&&ry(n[p]);)p+=1;const g=n.slice(d,p),_=t==="sql"?s.keywords.has(g.toLowerCase()):s.keywords.has(g);u(_?"keyword":"plain",g),d=p;continue}u("plain",f),d+=1}return l&&o.push({kind:"plain",text:l}),o}function Dc({text:e,language:t="",lineNumbers:n=!0,className:s,ariaLabel:o}){const l=em(t),u=Wv(e,l),d=n?String(e??"").split(`
65
- `).length:0;return a.jsx("pre",{className:`af-code${n?" af-code--numbered":""}${s?` ${s}`:""}`,"data-language":l||"text","aria-label":o,style:n?{"--af-code-gutter":`${String(d).length+1}ch`}:void 0,children:a.jsx("code",{children:n?yN(u).map((f,m)=>a.jsxs("span",{className:"af-code__line","data-line":m+1,children:[f.map((p,g)=>ay(p,g)),`
66
- `]},m)):u.map((f,m)=>ay(f,m))})})}function ay(e,t){return e.kind==="plain"?a.jsx(yt.Fragment,{children:e.text},t):a.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function yN(e){const t=[[]];for(const n of e)n.text.split(`
67
- `).forEach((o,l)=>{l>0&&t.push([]),o&&t[t.length-1].push({kind:n.kind,text:o})});return t}const Uv=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Wi=6e4,Ui=60*Wi,Fc=24*Ui;function hl(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)?hl(Number(t)):Date.parse(t)}function oy(e){return e<10?`0${e}`:String(e)}function iy(e,t){const n=hl(e);if(!Number.isFinite(n))return"";const s=new Date(n),o=s.getFullYear()===new Date(t).getFullYear();return`${Uv[s.getMonth()]} ${s.getDate()}${o?"":`, ${s.getFullYear()}`}`}function Mo(e){const t=hl(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${Uv[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${oy(n.getHours())}:${oy(n.getMinutes())}`}function $o(e,t){const n=hl(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const s=t-n;if(s<0){const l=-s;if(l<Wi)return"due now";if(l<Ui)return`in ${Math.round(l/Wi)} min`;if(l<Fc)return`in ${Math.round(l/Ui)} h`;const u=Math.round(l/Fc);return u<7?`in ${u} ${u===1?"day":"days"}`:iy(n,t)}if(s<Wi)return"just now";if(s<Ui)return`${Math.floor(s/Wi)} min ago`;if(s<Fc)return`${Math.floor(s/Ui)} h ago`;const o=Math.floor(s/Fc);return o===1?"yesterday":o<7?`${o} days ago`:iy(n,t)}const wN=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),vN=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),_N=new Set("mp4 m4v webm mov ogv mkv".split(" ")),bN=new Set("mts cts".split(" ")),xN=new Set(["video/mp2t"]),kN=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function SN(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function al(e,t=""){const n=SN(e),s=String(t||"").split(";",1)[0].trim().toLowerCase();return n==="md"||n==="markdown"||s==="text/markdown"?"markdown":n==="json"||s==="application/json"||s.endsWith("+json")?"json":n==="pdf"||s==="application/pdf"?"pdf":wN.has(n)?"image":vN.has(n)?"audio":_N.has(n)?"video":em(e)||bN.has(n)?"code":kN.has(n)?"text":s.startsWith("image/")&&s!=="image/svg+xml"?"image":s.startsWith("audio/")?"audio":s.startsWith("video/")&&!xN.has(s)?"video":s.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(s)?"code":"binary"}function iu(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function ml(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,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[s]}`}function jN(e){const t=e.kind??al(e.name,e.contentType),n=ml(e.sizeBytes),s=e.modified!==void 0?$o(e.modified,e.nowMs):"";return a.jsxs("section",{className:`af-file-viewer${e.className?` ${e.className}`:""}`,"aria-label":`Preview of ${e.name}`,"data-kind":t,children:[a.jsxs("header",{className:"af-file-viewer__head",children:[a.jsx(de,{name:"file",size:15}),a.jsxs("span",{className:"af-file-viewer__title",children:[a.jsx("strong",{className:"af-file-viewer__name",title:e.path||e.name,children:e.name}),n||s?a.jsxs("span",{className:"af-file-viewer__meta",children:[n?a.jsx("span",{"data-meta":"size",children:n}):null,n&&s?a.jsx("span",{"aria-hidden":"true",children:" · "}):null,s?a.jsx("time",{"data-meta":"modified",title:Mo(e.modified),dateTime:new Date(hl(e.modified)).toISOString(),children:s}):null]}):null]}),e.actions,e.onDownload?a.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:a.jsx(de,{name:"download",size:15})}):null,e.onClose?a.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:a.jsx(de,{name:"x",size:15})}):null]}),a.jsx("div",{className:"af-file-viewer__body",children:e.status==="loading"?a.jsx("p",{className:"af-file-viewer__muted",role:"status",children:"Loading preview…"}):e.status==="error"?a.jsx("p",{className:"af-file-viewer__error",role:"alert",children:e.error||"The preview could not be loaded."}):a.jsxs(a.Fragment,{children:[e.partialNote?a.jsx("p",{className:"af-file-viewer__muted",role:"status",children:e.partialNote}):null,a.jsx(NN,{kind:t,p:e})]})})]})}function NN({kind:e,p:t}){const n=t.text??"";switch(e){case"image":return t.url?a.jsx("img",{className:"af-file-viewer__image",src:t.url,alt:t.name}):a.jsx(Ri,{});case"audio":return t.url?a.jsx(Bv,{src:t.url,name:t.name}):a.jsx(Ri,{});case"video":return t.url?a.jsx("video",{className:"af-file-viewer__image af-file-viewer__video",src:t.url,controls:!0,playsInline:!0,preload:"metadata","aria-label":t.name}):a.jsx(Ri,{});case"pdf":return t.url?a.jsx("object",{className:"af-file-viewer__pdf",data:t.url,type:"application/pdf","aria-label":t.name,children:a.jsx("p",{className:"af-file-viewer__muted",children:"This browser cannot show PDFs inline. Use Download to open it."})}):a.jsx(Ri,{});case"markdown":return t.renderMarkdown?a.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):a.jsx(Dc,{text:n,language:""});case"json":{let s=n,o="";try{s=JSON.stringify(JSON.parse(n),null,2)}catch{o=t.partialNote?"":"Not valid JSON; shown as text."}return a.jsxs(a.Fragment,{children:[o?a.jsx("p",{className:"af-file-viewer__muted",children:o}):null,a.jsx(Dc,{text:s,language:"json"})]})}case"code":return a.jsx(Dc,{text:n,language:t.name});case"text":return a.jsx(Dc,{text:n,language:"",lineNumbers:!1});default:return a.jsx(Ri,{})}}function Ri(){return a.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 a.jsxs("section",{className:`af-settings-group${e.variant==="flat"?" af-settings-group--flat":""}${e.className?` ${e.className}`:""}`,"aria-labelledby":n,id:e.id,children:[a.jsxs("div",{className:"af-settings-group__head",children:[a.jsx("h3",{className:"af-settings-group__title",id:n,children:e.title}),e.aside?a.jsx("span",{className:"af-settings-group__aside",children:e.aside}):null]}),e.help?a.jsx("p",{className:"af-settings-group__help",children:e.help}):null,a.jsx("div",{className:"af-settings-group__rows",children:e.children})]})}function zr(e){const t=e.htmlFor?"label":"span";return a.jsxs("div",{className:`af-setting-row${e.stack?" af-setting-row--stack":""}${e.className?` ${e.className}`:""}`,"data-setting":e.setting,children:[a.jsxs("div",{className:"af-setting-row__label",children:[a.jsx(t,{className:"af-setting-row__name",...e.htmlFor?{htmlFor:e.htmlFor}:{},children:e.label}),e.help?a.jsx("span",{className:"af-setting-row__help",children:e.help}):null]}),e.children!==void 0||e.trailing?a.jsxs("div",{className:"af-setting-row__control",children:[e.children,e.trailing?a.jsx("span",{className:"af-setting-row__trailing",children:e.trailing}):null]}):null]})}function vh(e){const t=!!e.overrideSummary,n=y.useId(),s=t?`${e.overrideSummary}${e.overrideOwner?` — ${e.overrideOwner}`:""}`:`Gateway default${e.defaultSummary?` · ${e.defaultSummary}`:""}`;return a.jsxs("div",{className:"af-override","data-setting":e.setting,"data-overridden":t?"true":"false",children:[a.jsx(zr,{label:e.label,help:e.help,trailing:a.jsxs(a.Fragment,{children:[a.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?a.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:a.jsx("span",{className:"af-override__summary",title:s,children:s})}),a.jsx("div",{className:"af-override__editor",id:n,hidden:!e.open,children:e.open?e.children:null})]})}const ct={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=ct;function CN(e){return e==="any_except_denied"?An.postureAnyExceptDenied:An.postureAllowedOnly}function EN(e){return e==="any_except_denied"?An.postureAnyExceptDeniedHelp:An.postureAllowedOnlyHelp}function ly(e){return e==="ro"?An.accessRead:e==="deny"?An.accessDenied:An.accessReadWrite}function AN(e){return e==="gateway"?An.gatewayHelp:e==="account"?An.accountHelp:e==="session"?An.sessionHelp:An.runHelp}const cy={deny:0,ro:1,rw:2},Ef=["rw","ro","deny"];function $N(e){if(e===null)return{allowed:[...Ef],reasons:{}};const t=e==="deny"?An.capRefused:An.capReadOnly,n=Ef.filter(o=>cy[o]<=cy[e]),s={};for(const o of Ef)n.includes(o)||(s[o]=t);return{allowed:n,reasons:s}}function TN(e,t){const{policy:n}=t,s=t.effective;if(e==="gateway"?typeof n.summary!="string":!s)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 o=e!=="gateway"&&n.configured===!1,l=t.can_edit===!1,u=new Map(((s==null?void 0:s.folders)??[]).map(v=>[v.path,v.cap])),d=s,f=o?d.folders.map(v=>({path:v.path,mode:v.mode})):n.folders,m=o?d.posture:n.posture,p=o?d.default_mode??n.default_mode:n.default_mode,g=!o&&!l,_=f.map(v=>{const C=e==="gateway"?null:u.get(v.path)??null,{allowed:x,reasons:k}=$N(C);return{path:v.path,mode:v.mode,cap:C,allowed:x,reasons:k,builtin:!1,editable:g}});if(e==="gateway")for(const v of n.builtin_refused??[])_.push({path:v,mode:"deny",cap:null,allowed:[],reasons:{},builtin:!0,editable:!1});return{level:e,posture:m,following:o,rows:_,everythingElse:m==="any_except_denied"?{mode:p,editable:g}:null,canAdd:g,gatewayLine:e==="gateway"?null:`${An.gatewayPrefix} ${d.gateway_summary}`,summary:e==="gateway"?n.summary:d.summary,locked:l}}function RN(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function pl(e,t){const n={posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(s=>({path:s.path,mode:s.mode}))};return e==="gateway"?n:{configured:!0,...n}}function IN(e,t,n,s){return pl(e,{...t,folders:t.folders.map(o=>o.path===n?{path:n,mode:s}:o)})}function LN(e,t,n){return pl(e,{...t,posture:n})}function MN(e,t,n){return pl(e,{...t,default_mode:n})}function ON(e,t,n,s){const o=String(n).trim();return pl(e,{...t,folders:[...t.folders,{path:o,mode:RN(e,t.posture)}]})}function PN(e,t,n){return pl(e,{...t,folders:t.folders.filter(s=>s.path!==n)})}function DN(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(s=>({path:s.path,mode:s.mode}))}}function Vv(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function FN(e,t=Br){const n=Vv(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 zN(e="me",t=Br){return`${Vv(t)}/workspace/effective/${encodeURIComponent(e)}`}const _h=e=>e==="ro"||e==="rw"||e==="deny",Gv=e=>e==="ro"||e==="rw",Hv=e=>e==="allowed_only"||e==="any_except_denied",BN=e=>Array.isArray(e)&&e.every(t=>t&&typeof t.path=="string"&&_h(t.mode)),lu="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function WN(e,t){const n=e&&typeof e=="object"?e:{},s=n.policy&&typeof n.policy=="object"?n.policy:{};if("shared_workspace"in s||"shared_workspace"in n)throw new Error(lu);if(!(Hv(s.posture)&&Gv(s.default_mode)&&BN(s.folders)&&(t==="gateway"?typeof s.summary=="string":typeof s.configured=="boolean")&&(s.builtin_refused===void 0||Array.isArray(s.builtin_refused)&&s.builtin_refused.every(l=>typeof l=="string"))))throw new Error(`The gateway answered without a workspace policy (policy.posture, default_mode, folders, ${t==="gateway"?"summary":"configured"}). ${lu}`);return{...typeof s.account=="string"?{account:s.account}:{},...t==="gateway"?{summary:s.summary}:{configured:s.configured},posture:s.posture,default_mode:s.default_mode,folders:s.folders.map(l=>({path:l.path,mode:l.mode})),...Array.isArray(s.builtin_refused)?{builtin_refused:[...s.builtin_refused]}:{}}}function Kv(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(lu);if(!(Hv(t.posture)&&(Gv(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(s=>s&&typeof s.path=="string"&&_h(s.mode)&&_h(s.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${lu}`);return{posture:t.posture,default_mode:t.default_mode,folders:t.folders.map(s=>({path:s.path,mode:s.mode,cap:s.cap,source:s.source})),summary:t.summary,gateway_summary:t.gateway_summary}}function uy(e,t){const n=WN(e,t),s=e;return{policy:n,effective:t==="gateway"?null:Kv(s.effective),...typeof s.can_edit=="boolean"?{can_edit:s.can_edit}:{}}}function dy(e,t,n=Br){const s=FN(t,n);return{path:s,load:async()=>uy(await e(s,{method:"GET"}),t.level),save:async o=>uy(await e(s,{method:"PUT",body:o}),t.level)}}function bh(e,t="me",n=Br){const s=zN(t,n);return async(o,l)=>Kv(await e(s,{method:"POST",body:l?{workspace:o,session:l}:{workspace:o}}))}function tm(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 fy(e){const t=tm(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${An.notSaved}`}const UN=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function VN(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 nm(e){Io();const t=e.idPrefix||"af-workspace",[n,s]=y.useState(null),[o,l]=y.useState({}),[u,d]=y.useState(null),[f,m]=y.useState(""),[p,g]=y.useState(null),_=String(e.unavailableReason||"").trim(),v=e.level,C=e.level==="run"?VN(e.value,e.effective):e.state,x=e.level==="run"?e.effective:e.state,k=p&&p.base===x?p.value:C,S=k?TN(v,k):null,$=M=>{if(e.level==="run"){const J=e,B=M.configured===!1?null:{posture:M.posture,default_mode:M.default_mode,folders:M.folders};return Promise.resolve(J.onChange(B))}return e.save(M)};async function R(M,J){if(n!==null||_)return!1;s(M),d(null),l(B=>{const Y={...B};return delete Y[M],Y});try{const B=await $(J);return UN(B)&&g({base:x,value:B}),d(M),!0}catch(B){return l(Y=>({...Y,[M]:fy(B)})),!1}finally{s(null)}}const N=M=>o[M]?a.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:o[M]}):u===M?a.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:ct.saved}):null,E=(M,J)=>a.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":M,"data-af-tip":J,tabIndex:J?0:void 0,children:ly(M)}),j=(M,J,B,Y,te)=>a.jsx("span",{className:"af-workspace__access",role:"group","aria-label":M,"data-workspace":te,"data-access":J,children:B.map(W=>{const T=!!W.reason||!!_;return a.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":J===W.value?"true":"false","aria-disabled":T?"true":void 0,"data-af-tip":W.reason||void 0,"data-action":`${te}-${W.value}`,onClick:()=>T||n!==null||W.value===J?void 0:Y(W.value),children:W.text},W.value)})}),I=M=>{if(M.builtin)return E("deny",ct.builtinRefused);if(!M.editable||!k)return E(M.mode);const J=k.policy;return a.jsxs(a.Fragment,{children:[j(`${ct.accessLabel} ${M.path}`,M.mode,["rw","ro","deny"].map(B=>({value:B,text:ly(B),reason:M.reasons[B]})),B=>void R(M.path,IN(v,J,M.path,B)),"workspace-mode"),a.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${ct.remove} ${M.path}`,"data-af-tip":`${ct.remove} ${M.path}`,"aria-disabled":_||n!==null?"true":void 0,onClick:()=>_||n!==null?void 0:void R(M.path,PN(v,J,M.path)),children:a.jsx(de,{name:"x",size:16})})]})};async function L(M){if(!k||!S||!S.canAdd)return;const J=M.trim();J&&await R("add",ON(v,k.policy,J))&&m("")}async function z(){if(!e.choose||n!==null||_)return;let M;try{M=await e.choose()}catch(J){l(B=>({...B,add:fy(J)}));return}M&&await L(M)}const V=S?S.rows.filter(M=>M.mode!=="deny"):[],Z=S?S.rows.filter(M=>M.mode==="deny"):[],ie=M=>a.jsxs("li",{className:"af-workspace__row","data-workspace":M.builtin?"builtin":"row","data-path":M.path,"data-mode":M.mode,"data-cap":M.cap??void 0,children:[a.jsx("code",{className:"af-workspace__path",children:M.path}),a.jsx("span",{className:"af-workspace__controls",children:I(M)}),N(M.path)]},`${M.builtin?"builtin:":""}${M.path}`),F=v==="account"?ct.followGateway:ct.useDefault,D=v==="account"?ct.followGatewayHelp:ct.useDefaultHelp;return a.jsx(Vi,{id:t,className:`af-workspace af-workspace--${v}${e.className?` ${e.className}`:""}`,title:v==="gateway"?ct.gatewayTitle:ct.title,help:AN(v),children:e.loadError?a.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!S||!k?a.jsx("p",{className:"af-workspace__note","data-workspace":"loading",children:ct.loading}):a.jsxs("div",{className:"af-workspace__body","data-level":v,"data-following":S.following?"true":"false",children:[S.gatewayLine?a.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:S.gatewayLine}):null,_?a.jsx("p",{className:"af-workspace__note",id:`${t}-blocked`,"data-workspace":"blocked",children:_}):null,v!=="gateway"?a.jsxs("div",{className:"af-workspace__follow","data-workspace":"follow",children:[a.jsx(Wr,{variant:"row",label:F,description:D,checked:S.following,busy:n==="follow",unavailableReason:_||(S.locked?ct.locked:null),reasonVisible:!1,describedBy:_?`${t}-blocked`:void 0,action:v==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:M=>void R("follow",DN(k,M))}),N("follow")]}):null,a.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":S.posture,children:[S.following||S.locked?a.jsx("span",{className:"af-workspace__badge",children:CN(S.posture)}):j(ct.postureLabel,S.posture,[{value:"allowed_only",text:ct.postureAllowedOnly},{value:"any_except_denied",text:ct.postureAnyExceptDenied}],M=>void R("posture",LN(v,k.policy,M)),"workspace-posture"),a.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:EN(S.posture)}),N("posture")]}),a.jsxs("ul",{className:"af-workspace__list","aria-label":ct.title,"data-workspace":"list",children:[V.length?a.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:ct.allowedTitle}):null,V.map(ie),Z.length?a.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:ct.deniedTitle}):null,Z.map(ie),S.everythingElse?a.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":S.everythingElse.mode,children:[a.jsx("span",{className:"af-workspace__name",children:ct.everythingElse}),a.jsx("span",{className:"af-workspace__controls",children:S.everythingElse.editable?j(`${ct.accessLabel} ${ct.everythingElse}`,S.everythingElse.mode,[{value:"rw",text:ct.accessReadWrite},{value:"ro",text:ct.accessRead}],M=>void R("everything-else",MN(v,k.policy,M)),"workspace-default"):E(S.everythingElse.mode)}),N("everything-else")]}):null,S.canAdd?a.jsxs("li",{className:"af-workspace__add","data-workspace":"add",children:[a.jsx("input",{type:"text",className:"af-workspace__input","aria-label":ct.addPlaceholder,placeholder:ct.addPlaceholder,value:f,disabled:!!_||n==="add",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off",onChange:M=>m(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),L(f)):M.key==="Escape"&&(M.preventDefault(),m(""),l(J=>{const B={...J};return delete B.add,B}))}}),a.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!_||!f.trim()||n!==null,onClick:()=>void L(f),children:ct.add}),e.choose?a.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-choose",disabled:!!_||n!==null,onClick:()=>void z(),children:ct.choose}):null,N("add")]}):null]}),S.posture==="allowed_only"&&!V.length?a.jsx("p",{className:"af-workspace__note","data-workspace":"empty",children:ct.emptyAllowed}):null,v==="session"||v==="run"?a.jsx("p",{className:"af-workspace__note","data-workspace":"private",children:ct.privateNote}):null,a.jsx("p",{className:"af-workspace__effective","data-workspace":"effective",children:S.summary}),e.footer?a.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const Af=e=>`${Math.round(e*100)} %`,GN="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function HN(e){var j,I,L;const t=!!e.unavailableReason,n=e.outputSelectable??Vw(),s=y.useId(),[o,l]=y.useState({devices:[],labelled:!0}),[u,d]=y.useState({text:"",tone:"info"}),f=y.useRef(!0);y.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);const m=e.value,p=z=>e.onChange({...m,...z}),g=ba(m.reply_volume),_=m.reply_muted===!0,v=e.showMute!==!1||_,C=e.listDevices||Ow,x=y.useRef(C);x.current=C;const k=()=>{n&&x.current("audiooutput").then(z=>f.current&&l(z)).catch(()=>f.current&&l({devices:[],labelled:!1}))};y.useEffect(()=>{t||k()},[n,t,e.devicesKey]);const S=()=>{d({text:"Playing a short chime…",tone:"info"}),xS({deviceId:n&&m.output_device||"",volume:g}).then(()=>{if(!f.current)return;const z="Chime played. Heard nothing? Pick another output or raise the volume.";d({text:_?`${z} Replies are muted: unmute them to hear them.`:z,tone:"ok"})}).catch(z=>f.current&&d({text:`The speaker test failed: ${String((z==null?void 0:z.message)||z).replace(/\.$/,"")}.`,tone:"error"}))},$=m.output_device||"",R=[{value:"",label:"System default"},...o.devices.map(z=>({value:z.id,label:z.label})),...$&&!o.devices.some(z=>z.id===$)?[{value:$,label:"Saved speaker (not connected)"}]:[]],N=((j=e.labels)==null?void 0:j.device)||"Output device",E=((I=e.labels)==null?void 0:I.volume)||"Reply volume";return a.jsxs("div",{className:`af-voice-output${e.className?` ${e.className}`:""}`,"data-voice-output":!0,children:[a.jsx(zr,{label:N,setting:"output-device",help:n?void 0:GN,trailing:a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:t,onClick:S,children:((L=e.labels)==null?void 0:L.test)||"Test"}),children:a.jsx(bn,{ariaLabel:N,placeholder:"System default",value:n?$:"",options:R,disabled:t||!n,searchable:!1,onOpen:k,onChange:z=>p({output_device:z})})}),u.text?a.jsx("p",{className:`af-voice-note af-voice-note--${u.tone}`,role:"status","data-voice-note":"speaker",children:u.text}):null,a.jsxs(zr,{label:E,setting:"reply-volume",htmlFor:s,trailing:v?a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"mute-replies",disabled:t,onClick:()=>p({reply_muted:!_}),children:_?"Unmute":"Mute"}):void 0,children:[a.jsx("input",{id:s,className:"af-voice-range",type:"range",min:0,max:100,step:5,value:Math.round(g*100),disabled:t,"aria-valuetext":_?`Muted (${Af(g)})`:Af(g),onChange:z=>p({reply_volume:Number(z.currentTarget.value)/100})}),a.jsx("span",{className:"af-voice-range__value","data-voice-volume":_?"muted":"on",children:_?"Muted":Af(g)})]})]})}function KN(e){const[t,n]=y.useState(0),s=e==null?void 0:e.subscribe_level;return y.useEffect(()=>{if(!s){n(0);return}return s(o=>n(Math.min(1,Math.max(0,Number(o)||0))))},[s]),t}function Jv(e){const t=KN(e.level===void 0?e.source:null),n=Math.min(1,Math.max(0,e.level===void 0?t:Number(e.level)||0)),s=e.inline?"span":"div";return a.jsx(s,{className:`af-voice-meter${e.className?` ${e.className}`:""}`,"data-voice-meter":!0,"data-voice-meter-source":e.origin||"live",role:"meter","aria-label":e.label||"Microphone level","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(n*100),children:a.jsx("span",{className:"af-voice-meter__fill",style:{width:`${Math.round(n*100)}%`}})})}const $f=e=>`${Math.round(e*100)} %`;function sm(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function JN(e){var Z,ie,F;const t=!!e.unavailableReason,n=y.useId(),[s,o]=y.useState({devices:[],labelled:!0}),[l,u]=y.useState(""),[d,f]=y.useState({phase:"idle",message:"",tone:"info"}),[m,p]=y.useState(0),g=y.useRef(!0);y.useEffect(()=>(g.current=!0,()=>{g.current=!1}),[]);const _=Dw(),v=e.value,C=D=>e.onChange({...v,...D}),x=sm(v.input_gain),k=e.listDevices||Ow,S=y.useRef(k);S.current=k;const $=()=>{S.current("audioinput").then(D=>g.current&&o(D)).catch(()=>g.current&&o({devices:[],labelled:!1}))};y.useEffect(()=>{t||$()},[t]);const R=()=>{u(""),bS().then(()=>{var D;$(),(D=e.onDevicesChanged)==null||D.call(e)}).catch(D=>g.current&&u(tu(D)))},N=()=>{f({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),Bw({deviceId:v.input_device||"",ms:3e3,gain:x,onLevel:D=>g.current&&p(D)}).then(async({blob:D,peak:M})=>{var J,B,Y;if(g.current){if(M<zw){f({phase:"idle",message:"The microphone recorded silence. Pick another input, or raise its level in the system sound settings.",tone:"error"});return}f({phase:"playing",message:"Playing it back…",tone:"info"}),await Ww(D,{deviceId:((J=e.playOn)==null?void 0:J.deviceId)||"",volume:(B=e.playOn)==null?void 0:B.volume}),g.current&&(f({phase:"idle",message:`The microphone works (peak level ${$f(M)}).`,tone:"ok"}),$(),(Y=e.onDevicesChanged)==null||Y.call(e))}}).catch(D=>g.current&&f({phase:"idle",message:tu(D),tone:"error"}))},E=v.input_device||"",j=[{value:"",label:"System default"},...s.devices.map(D=>({value:D.id,label:D.label})),...E&&!s.devices.some(D=>D.id===E)?[{value:E,label:"Saved microphone (not connected)"}]:[]],I=d.phase!=="idle",L=d.phase==="recording",z=((Z=e.labels)==null?void 0:Z.device)||"Input device",V=((ie=e.labels)==null?void 0:ie.gain)||"Input level";return a.jsxs("div",{className:`af-voice-input${e.className?` ${e.className}`:""}`,"data-voice-input":!0,children:[a.jsx(zr,{label:z,setting:"input-device",trailing:a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:t||I,onClick:N,children:d.phase==="recording"?"Recording…":d.phase==="playing"?"Playing…":((F=e.labels)==null?void 0:F.test)||"Test"}),children:a.jsx(bn,{ariaLabel:z,placeholder:"System default",value:E,options:j,disabled:t,searchable:!1,onOpen:$,onChange:D=>C({input_device:D})})}),a.jsx(Jv,{source:L?null:e.levelSource,level:L?m:e.level,origin:L?"test":"live"}),d.message?a.jsx("p",{className:`af-voice-note af-voice-note--${d.tone}`,role:"status","data-voice-note":"microphone",children:d.message}):null,!s.labelled&&!t?a.jsxs("p",{className:"af-voice-note","data-voice-note":"labels",children:["Device names appear once the microphone is allowed."," ",a.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"show-device-names",onClick:R,children:"Show names"})]}):null,l?a.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:l}):null,_?a.jsxs(zr,{label:V,setting:"input-gain",htmlFor:n,help:"Raises a quiet microphone.",children:[a.jsx("input",{id:n,className:"af-voice-range",type:"range",min:50,max:150,step:10,value:Math.round(x*100),disabled:t,"aria-valuetext":$f(x),onChange:D=>C({input_gain:Number(D.currentTarget.value)/100})}),a.jsx("span",{className:"af-voice-range__value",children:$f(x)})]}):null]})}function qN(e){return{output_device_id:e.output_device||"",volume:ba(e.reply_volume),muted:e.reply_muted===!0,input_device_id:e.input_device||"",input_gain:sm(e.input_gain),capture_mode:Eo(e.capture_mode)}}const YN=["provider","model","voice","profile","speed","quality_preset","instructions"];function QN(e){const t={};for(const n of YN){const s=e[n];s!==void 0&&s!==""&&s!==null&&(t[n]=s)}return t}function XN(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 ZN=[{value:"",label:"Detect automatically"},...Object.keys(Hw).map(e=>({value:e,label:xa(e)}))],e1=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function t1(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function n1(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const s1=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],hy=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 r1(e){var oe,ve,Ne,q,be,xe,Pe,Qe,He,qe;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,s=e.rows||{},o=y.useRef(e.fetchCatalog);o.current=e.fetchCatalog;const l=y.useRef(e.fetchDefaults);l.current=e.fetchDefaults;const u=y.useRef(e.fetchLanguages);u.current=e.fetchLanguages;const[d,f]=y.useState({}),[m,p]=y.useState({value:null,failed:!1}),g=e.defaults!==void 0?{value:e.defaults,failed:!1}:m,_=e.defaults!==void 0,[v,C]=y.useState(""),[x,k]=y.useState(0),[S,$]=y.useState(null),R=e.outputSelectable??Vw(),N=e.value,E=e.nested?"flat":"card",j=ge=>e.onChange({...N,...ge}),I=ba(N.reply_volume),L=sm(N.input_gain),z=s.tts!==!1&&!e.ttsSlot,V=s.stt!==!1,Z=z||V||!!e.ttsSlot,ie=e.voiceLibrary||e.createVoice;y.useEffect(()=>{if(n)return;let ge=!0;return o.current().then($e=>ge&&f($e||{})).catch(()=>ge&&f({})),_||l.current().then($e=>ge&&p({value:$e||{},failed:!1})).catch(()=>ge&&p({value:null,failed:!0})),()=>{ge=!1}},[n,_]);const F=N.stt_provider||((ve=(oe=g.value)==null?void 0:oe.stt)!=null&&ve.configured?String(g.value.stt.provider||""):""),D=!!e.fetchLanguages;y.useEffect(()=>{const ge=u.current;if(n||!ge||s.microphone===!1)return;let $e=!0;return ge("stt",F||void 0).then(st=>$e&&$(Array.isArray(st)?st.map(tt=>String(tt).toLowerCase()).filter(Boolean):[])).catch(()=>$e&&$(null)),()=>{$e=!1}},[n,D,F,s.microphone]);const M=Pg(g.value,"tts",g.failed),J=Pg(g.value,"stt",g.failed),B=[(Ne=g.value)==null?void 0:Ne.tts,(q=g.value)==null?void 0:q.stt].map(ge=>ge&&!ge.configured?ge.note:"").filter(Boolean),Y=[(be=g.value)==null?void 0:be.tts,(xe=g.value)==null?void 0:xe.stt].map(ge=>{var $e;return ge&&ge.configured?String((($e=ge.hint)==null?void 0:$e.sentence)||"").trim():""}).filter(Boolean),te=!!((Qe=(Pe=d.controls)==null?void 0:Pe.quality_preset)!=null&&Qe.supported),W={deviceId:R&&N.output_device||"",volume:I},T=S&&S.length?[{value:"",label:"Detect automatically"},...S.map(ge=>({value:ge,label:xa(ge)}))]:[...ZN],K=N.stt_language||"";K&&!T.some(ge=>ge.value===K)&&T.push({value:K,label:`${xa(K)} (saved)`});const ne=Eo(N.capture_mode??((He=e.captureDefaults)==null?void 0:He.capture_mode)),ue=N.auto_send??((qe=e.captureDefaults)==null?void 0:qe.auto_send)??!1;return a.jsxs("div",{className:`af-voice-section${e.className?` ${e.className}`:""}`,children:[e.unavailableReason?a.jsx("p",{className:"af-settings-group__help",role:"status",children:e.unavailableReason}):null,Z?a.jsxs(Vi,{variant:E,title:"Engines",help:"Which engines speak and listen.",children:[e.ttsSlot?a.jsx("div",{className:"af-voice-section__tts-slot","data-voice-slot":"tts",children:e.ttsSlot}):null,z?a.jsx(vh,{label:"Text → speech",setting:"tts",defaultSummary:M,overrideSummary:t1(N),overrideOwner:t,open:v==="tts",onToggle:()=>C(v==="tts"?"":"tts"),onReset:()=>j({provider:"",model:"",voice:"",profile:""}),disabled:n,children:a.jsx(LS,{value:N,onChange:ge=>e.onChange({...N,...ge}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:ie,previewVoice:e.previewVoice?(ge,$e,st)=>e.previewVoice({...N,...ge},$e,st):void 0,previewOn:W,recordFrom:{deviceId:N.input_device||"",gain:L}})}):null,V?a.jsx(vh,{label:"Speech → text",setting:"stt",defaultSummary:J,overrideSummary:n1(N),overrideOwner:t,open:v==="stt",onToggle:()=>C(v==="stt"?"":"stt"),onReset:()=>j({stt_provider:"",stt_model:""}),disabled:n,children:a.jsx(_u,{value:{provider:N.stt_provider||"",model:N.stt_model||""},onChange:ge=>j({stt_provider:ge.provider,stt_model:ge.model}),fetchProviders:async()=>{const ge=await o.current();return hy(ge.stt_providers).map($e=>({name:$e}))},fetchModels:async ge=>{var st;const $e=await o.current(ge);return hy(((st=$e.stt_models_by_provider)==null?void 0:st[ge])||$e.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}):null,g.failed?a.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,B.map(ge=>a.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:ge},ge)),Y.map(ge=>a.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:ge},ge))]}):null,s.output!==!1?a.jsx(Vi,{variant:E,title:"Output",children:a.jsx(HN,{value:N,onChange:e.onChange,listDevices:e.listDevices,outputSelectable:R,showMute:s.mute===!0,unavailableReason:e.unavailableReason,devicesKey:x})}):null,s.microphone!==!1?a.jsxs(Vi,{variant:E,title:"Microphone",children:[a.jsx(JN,{value:N,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:W,onDevicesChanged:()=>k(ge=>ge+1),unavailableReason:e.unavailableReason}),a.jsx(zr,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:a.jsx(bn,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:K,options:T,disabled:n,searchable:!1,onChange:ge=>j({stt_language:ge})})}),s.capture===!0?a.jsxs(a.Fragment,{children:[a.jsx(zr,{label:"Microphone button",setting:"capture-mode",children:a.jsx(bn,{ariaLabel:"Microphone button",value:ne,options:e1,disabled:n,searchable:!1,onChange:ge=>j({capture_mode:ge==="toggle"?"toggle":"hold"})})}),a.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"auto-send",children:a.jsx(Wr,{label:"Send what you say automatically",description:"Off: what you say lands in the message box for you to review.",variant:"row",checked:ue,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ge=>j({auto_send:ge})})})]}):null]}):null,s.replies!==!1?a.jsxs(Vi,{variant:E,title:"Replies",children:[a.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:a.jsx(Wr,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:N.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:ge=>j({read_aloud:ge})})}),a.jsx(zr,{label:"Voice latency",setting:"latency",help:te?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:a.jsx(bn,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:te&&N.quality_preset||"",options:s1,disabled:n||!te,searchable:!1,onChange:ge=>j({quality_preset:ge})})})]}):null]})}const xh="@gateway-default";function a1(e){return[{value:xh,label:dt.time_zone_default.replace("{time_zone}",e.gateway_default)},...e.choices.map(t=>({value:t,label:t}))]}function o1(e){const t=e.block;if(!Array.isArray(t.choices)||typeof t.gateway_default!="string")throw new Error("AfTimeZonePicker: the preferences answer has no time_zone block (R16.1 preferences seam).");return a.jsxs("div",{className:"af-tz-picker","data-time-zone-preference":t.value??"",children:[a.jsxs("div",{className:"af-tz-picker__head",children:[a.jsx("label",{className:"af-tz-picker__label",htmlFor:e.id,children:t.label}),t.help?a.jsx(Zc,{content:t.help,children:a.jsx("span",{className:"af-tz-picker__help",tabIndex:0,"aria-label":t.help,children:"?"})}):null]}),a.jsxs("div",{className:"af-tz-picker__control",children:[a.jsx(bn,{id:e.id,value:t.value??xh,options:a1(t),searchable:!0,searchPlaceholder:dt.time_zone_search,ariaLabel:t.label,disabled:e.disabled,onChange:n=>e.onChange(n&&n!==xh?n:null)}),e.note?a.jsx("span",{className:`af-tz-picker__note ${e.note.ok?"is-ok":"is-error"}`,role:"status","aria-live":"polite",children:e.note.text}):null]})]})}const Ir={hold:"Hold to talk",toggle:"Tap to talk",recordingHold:"Recording — release to send",recordingToggle:"Recording — tap to stop",holdHint:"Hold the button while you speak — release to send.",unavailable:"Speech to text is not available here.",modeMismatch:"The microphone is set up for the other way of talking. Reload the page.",transcriptMismatch:"The microphone cannot deliver what you say here. Reload the page."};function i1(e){const[t,n]=y.useState(()=>Date.now());return y.useEffect(()=>{if(!e)return;n(Date.now());const s=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(s)},[e]),t}function l1(e){const{voice:t}=e,n=Eo(e.mode),s=t.voice_capture_mode&&t.voice_capture_mode!==n?"mode":e.onTranscript&&typeof t.add_transcript_listener!="function"?"transcript":"";y.useEffect(()=>{s==="mode"?console.error(`AfVoiceMicButton mode "${n}" needs useGatewayVoice({ capture_mode: "${n}" }) (the hook records in "${t.voice_capture_mode}" mode): pass the same voiceCaptureMode(prefs) to both.`):s==="transcript"&&console.error("AfVoiceMicButton onTranscript needs the voice returned by useGatewayVoice (add_transcript_listener).")},[s,n,t.voice_capture_mode]);const o=y.useRef(!1),l=y.useRef(0),u=y.useRef(!0),d=y.useRef(t.voice_ptt_recording);d.current=t.voice_ptt_recording;const f=y.useRef(t);f.current=t;const m=y.useRef(e.onTranscript);m.current=e.onTranscript;const[p,g]=y.useState(!1),_=!!e.onTranscript;y.useEffect(()=>(u.current=!0,()=>{var V,Z;u.current=!1,(o.current||d.current)&&((Z=(V=f.current).cancel_voice_ptt_recording)==null||Z.call(V)),o.current=!1}),[]),y.useEffect(()=>{if(!(!_||!t.add_transcript_listener))return t.add_transcript_listener((V,Z)=>{var ie;return(ie=m.current)==null?void 0:ie.call(m,V,Z)})},[t.add_transcript_listener,_]),y.useEffect(()=>{if(!p)return;const V=setTimeout(()=>g(!1),4e3);return()=>clearTimeout(V)},[p]);const v=s==="mode"?Ir.modeMismatch:s==="transcript"?Ir.transcriptMismatch:e.unavailableReason||(t.voice_ptt_supported?null:Ir.unavailable),C=t.voice_ptt_busy,x=t.voice_ptt_recording,k=()=>{const V=f.current;v||V.voice_ptt_busy||o.current||(o.current=!0,l.current=Date.now(),g(!1),V.start_voice_ptt_recording().then(()=>{var Z,ie;(!o.current||!u.current)&&((ie=(Z=f.current).cancel_voice_ptt_recording)==null||ie.call(Z))}))},S=()=>{var V,Z;if(o.current){if(o.current=!1,Date.now()-l.current<Uw){(Z=(V=f.current).cancel_voice_ptt_recording)==null||Z.call(V),u.current&&g(!0);return}f.current.stop_voice_ptt_recording()}},$=()=>{var V,Z;o.current&&(o.current=!1,(Z=(V=f.current).cancel_voice_ptt_recording)==null||Z.call(V))};y.useEffect(()=>{if(n==="hold")return window.addEventListener("pointerup",S),window.addEventListener("pointercancel",S),window.addEventListener("blur",$),()=>{window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",S),window.removeEventListener("blur",$)}},[n]);const R=()=>{const V=f.current;if(V.voice_ptt_recording){V.stop_voice_ptt_recording();return}v||V.voice_ptt_busy||(g(!1),V.start_voice_ptt_recording())},N=t.voice_ptt_since||0,E=i1(!!N),j=e.label||(n==="hold"?Ir.hold:Ir.toggle),I=x?n==="hold"?Ir.recordingHold:Ir.recordingToggle:j,L=x?`Recording… ${N?Mw(N,E):""}`.trim():C?_S(N||E,E,e.routeText||""):p?Ir.holdHint:"",z=n==="hold"?{onPointerDown:V=>{V.button===0&&k()},onPointerUp:S,onPointerCancel:S,onKeyDown:V=>{[" ","Enter"].includes(V.key)&&!V.repeat&&(V.preventDefault(),k())},onKeyUp:V=>{[" ","Enter"].includes(V.key)&&(V.preventDefault(),S())}}:{onClick:R};return a.jsxs("span",{className:`af-voice-mic${x?" af-voice-mic--recording":""}${e.className?` ${e.className}`:""}`,"data-voice-mic":!0,"data-mode":n,"data-voice-mic-error":s||void 0,children:[a.jsx("button",{type:"button",className:"af-voice-mic__button","data-action":"voice-mic","aria-label":I,"aria-pressed":x,title:v||I,disabled:!!v||C,...z,children:a.jsx(de,{name:C?"loader":"mic",size:15})}),x?a.jsx(Jv,{source:t,inline:!0,className:"af-voice-mic__meter"}):null,e.showStatus!==!1&&(L||v)?a.jsx("span",{role:"status",className:"af-voice-mic__status","data-voice-status":!0,children:L||v}):null]})}function c1(e,t=""){const n=y.useRef(e);n.current=e;const[s,o]=y.useState({value:null,failed:!1}),[l,u]=y.useState(0),d=!!e;y.useEffect(()=>{const m=n.current;if(!m){o(g=>g.value===null&&!g.failed?g:{value:null,failed:!1});return}let p=!0;return m().then(g=>p&&o({value:g||{},failed:!1})).catch(()=>p&&o({value:null,failed:!0})),()=>{p=!1}},[d,t,l]);const f=y.useCallback(()=>u(m=>m+1),[]);return{value:s.value,failed:s.failed,reload:f}}const qc=new Map,qv=()=>{try{return globalThis.localStorage||null}catch{return null}},Yv=e=>{try{const t=e?JSON.parse(e):null;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}};function Tf(e){var t;return Yv((t=qv())==null?void 0:t.getItem(e))}function u1(e,t){var s;const n=t&&typeof t=="object"?t:{};try{(s=qv())==null||s.setItem(e,JSON.stringify(n))}catch{}for(const o of Array.from(qc.get(e)||[]))o(n)}function d1(e){const[t,n]=y.useState(()=>({key:e,prefs:e?Tf(e):{}})),s=t.key===e?t:{key:e,prefs:e?Tf(e):{}};s!==t&&n(s),y.useEffect(()=>{var m;if(!e)return;const l=p=>n({key:e,prefs:p});let u=qc.get(e);u||qc.set(e,u=new Set),u.add(l);const d=p=>{p.key!==null&&p.key!==e||n({key:e,prefs:p.key===null?Tf(e):Yv(p.newValue)})},f=globalThis;return(m=f.addEventListener)==null||m.call(f,"storage",d),()=>{var p;u.delete(l),u.size||qc.delete(e),(p=f.removeEventListener)==null||p.call(f,"storage",d)}},[e]);const o=y.useCallback(l=>{e?u1(e,l):n({key:null,prefs:l||{}})},[e]);return[s.prefs,o]}function Au(e,t){const n=typeof e=="string"?e.trim().toLowerCase():"";if(n==="off"||n==="ask"||n==="auto")return n;if(n==="approve")return t==="entity"?"ask":t==="desktop"?"auto":void 0;if(n==="disabled"&&t==="desktop")return"off"}function xo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Qt(e){return typeof e=="string"?e.trim():""}function my(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}function f1(e){const t=xo(e),n=t==null?void 0:t.items,s=Qt(t==null?void 0:t.error);if(!Array.isArray(n))throw new Error(`The gateway's tool catalog has no items${s?`: ${s}`:""}.`);if(!n.length&&s)throw new Error(`The gateway could not list its tools: ${s}`);const o=xo(t==null?void 0:t.command_sandbox),l=Qt(o==null?void 0:o.sentence),u=new Set,d=[];for(const f of n){const m=xo(f),p=Qt(m==null?void 0:m.name);if(!m||!p||u.has(p))continue;u.add(p);const g=m.enabled!==!1&&m.available!==!1,_=Qt(m.approval_default).toLowerCase(),v=Au(m.default_approval,"desktop"),C=_?_==="auto"?"auto":"ask":v==="auto"?"auto":"ask",x=xo(m.risk),k=my(m.risk_rank)??my(x==null?void 0:x.rank),S=Qt(m.risk_tier)||Qt(x==null?void 0:x.tier),$=Qt(m.sandbox),R=$&&typeof m.sandboxed=="boolean"?{label:$,...l?{tooltip:l}:{},tone:m.sandboxed?"ok":Qt(o==null?void 0:o.state)==="unsandboxed"?"danger":"warn"}:void 0,N=Qt(m.why_disabled)||Qt(m.enable_gate);d.push({name:p,...Qt(m.description)?{description:Qt(m.description)}:{},...Qt(m.when_to_use)?{whenToUse:Qt(m.when_to_use)}:{},toolset:Qt(m.toolset)||"other",offered:g,gatewayDefault:g?C:"off",...g&&!_&&!v?{defaultUnserved:!0}:{},...k!==void 0?{riskRank:k}:{},...S?{riskTier:S}:{},...m.model_controlled_destination===!0?{modelControlledDestination:!0}:{},...m.risk_refiner!==void 0&&m.risk_refiner!==null?{refined:!0}:{},...!g&&N?{whyDisabled:N}:{},...Qt(m.approval_note)?{approvalNote:Qt(m.approval_note)}:{},...R?{state:R}:{}})}return d.sort((f,m)=>f.toolset===m.toolset?f.name.localeCompare(m.name):f.toolset.localeCompare(m.toolset)),d}function h1(e){const t=xo(e),n=Array.isArray(t==null?void 0:t.catalog_warnings)?t.catalog_warnings.map(Qt).filter(Boolean):[],s=Qt(t==null?void 0:t.error);return s&&Array.isArray(t==null?void 0:t.items)&&t.items.length?[s,...n]:n}function cu(e,t){if(!(!e||!Object.prototype.hasOwnProperty.call(e,t)))return Au(e[t])}function rm(e,t={}){const n={};for(const s of e){if(!s.offered){n[s.name]={mode:"off",source:"gateway",inherited:"off"};continue}const o=s.gatewayDefault,l=cu(t.app,s.name),u=cu(t.session,s.name);u!==void 0?n[s.name]={mode:u,source:"session",inherited:l??o}:l!==void 0?n[s.name]={mode:l,source:"app",inherited:o}:n[s.name]={mode:o,source:"gateway",inherited:o}}return n}function kh(e,t,n,s){const o={...e||{}};return t.offered?(n===s?delete o[t.name]:o[t.name]=n,o):(delete o[t.name],o)}const Qv=2;function Oo(e){return e.offered&&(e.riskRank??4)<=Qv&&e.modelControlledDestination!==!0}function m1(e,t,n,s){let o={...e||{}};const l=[];for(const u of t)if(u.offered){if(n==="auto"&&!Oo(u)){l.push(u.name);continue}o=kh(o,u,n,s[u.name]??u.gatewayDefault)}return{layer:o,skipped:l}}function Po(e,t={}){const n={},s={};for(const o of e){if(!o.offered)continue;const l=cu(t.app,o.name);l!==void 0&&l!==o.gatewayDefault&&(n[o.name]=l);const u=n[o.name]??o.gatewayDefault,d=cu(t.session,o.name);d!==void 0&&d!==u&&(s[o.name]=d)}return{app:n,session:s}}function uu(e,t={}){const n=Po(e,t);return Object.keys(n.app).length>0||Object.keys(n.session).length>0}function Yc(e,t={},n={}){const s=rm(e,t),o=Array.isArray(n.ceiling)?new Set(n.ceiling):null,l=[],u=[],d=[];for(const f of[...e].sort((m,p)=>m.name.localeCompare(p.name))){const m=o&&!o.has(f.name)?"off":s[f.name].mode;m!=="off"&&(l.push(f.name),m==="auto"?u.push(f.name):f.refined||d.push(f.name))}return{tools:l,allowed_tools:[...l],...uu(e,t)?{tool_policy:{auto_approve_tools:[...u],require_approval_tools:[...d]}}:{},approval:{auto:u,ask:d}}}function Xv(e,t){const n={...e||{}},s={...xo(n._runtime)||{}};return s.allowed_tools=[...t.allowed_tools],t.tool_policy?s.tool_policy={auto_approve_tools:[...t.tool_policy.auto_approve_tools],require_approval_tools:[...t.tool_policy.require_approval_tools]}:delete s.tool_policy,{...n,tools:[...t.tools],_runtime:s}}function p1(e){return{enabledTools:[...e.tools],autoApproveTools:[...e.approval.auto]}}const am="The gateway cannot store chat tool policies",g1="The gateway did not return a policy revision; refusing an unguarded write";class y1 extends Error{constructor(){super(`${am} (it does not advertise capabilities.session_tool_policy).`),this.code="unsupported",this.name="SessionToolPolicyUnsupportedError"}}class w1 extends Error{constructor(t){super(`${g1}${t?` (${t})`:""}.`),this.code="no_revision",this.name="SessionToolPolicyRevisionError"}}class v1 extends Error{constructor(t,n){super(t||"This chat's tool policy was changed elsewhere. Reload it and try again."),this.code="revision_conflict",this.name="SessionToolPolicyConflictError",typeof n=="number"&&(this.revision=n)}}const _n=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,rr=e=>typeof e=="string"?e.trim():"",No=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];function _1(e){const t=_n(e),n=_n(t==null?void 0:t.capabilities)??t,s=_n(n==null?void 0:n.session_tool_policy);return s?{supported:s.supported===!0,...typeof s.version=="number"?{version:s.version}:{},...rr(s.endpoint)?{endpoint:rr(s.endpoint)}:{},...Array.isArray(s.methods)?{methods:No(s.methods)}:{},...Array.isArray(s.approve)?{approve:No(s.approve)}:{},...Array.isArray(s.deny)?{deny:No(s.deny)}:{},...typeof s.ask=="boolean"?{ask:s.ask}:{},...rr(s.record)?{record:rr(s.record)}:{},...rr(s.reason)?{reason:rr(s.reason)}:{}}:null}const py=e=>{const t=_n(e);if(!t)return null;const n={};for(const[s,o]of Object.entries(t))typeof o=="string"&&(n[s]=o);return n};function gy(e){const t=_n(e),n=py(t==null?void 0:t.approve),s=py(t==null?void 0:t.deny);if(!t||typeof t.version!="number"||typeof t.revision!="number"||typeof t.session_id!="string"||!n||!s||!Array.isArray(t.ask))throw new Error("The gateway answered without a chat tool policy (policy.version, revision, session_id, approve, deny, ask).");const o=Array.isArray(t.clamped)?t.clamped.map(_n).filter(u=>!!u).map(u=>({selector:String(u.selector??""),name:String(u.name??""),reason:String(u.reason??"")})):void 0,l=_n(t.set_by);return{version:t.version,session_id:t.session_id,revision:t.revision,approve:n,deny:s,ask:No(t.ask),..."request"in t?{request:t.request}:{},...o?{clamped:o}:{},...l?{set_by:{...typeof l.tenant_id=="string"?{tenant_id:l.tenant_id}:{},...typeof l.user_id=="string"?{user_id:l.user_id}:{},...typeof l.client=="string"?{client:l.client}:{}}}:{},...typeof t.set_at=="string"?{set_at:t.set_at}:{}}}function Rf(e){const t=_n(e);if(!t)return;const n={};return typeof t.approve=="string"&&t.approve.trim()&&(n.approve=t.approve),typeof t.deny=="string"&&t.deny.trim()&&(n.deny=t.deny),n.approve||n.deny?n:void 0}function b1(e){const t=_n(e)??(e instanceof Error?e:void 0);if(!t)return null;const n=_n(t.body),s=_n(t.detail)??_n(n==null?void 0:n.detail)??n,o=rr(s==null?void 0:s.reason_code)||rr(t.reason_code);if(o!=="revision_conflict"&&!(t.status===409&&!o))return null;const l=s==null?void 0:s.revision;return new v1(rr(s==null?void 0:s.message),typeof l=="number"?l:void 0)}function x1(e,t,n,s={}){const o=String(t??"");if(!Sw.test(o))throw new Error(`A session id is 1-256 characters [A-Za-z0-9_.:-], not only dots, got ${JSON.stringify(o)}.`);const l=(n==null?void 0:n.supported)===!0,u=we(ak(o));let d,f;const m=v=>f?{...v,scope:f}:v,p=async(v,C,x="")=>{if(!l)throw new y1;if(n!=null&&n.methods&&!n.methods.includes(v))throw new Error(`${am} with ${v} (the gateway advertises ${n.methods.join(", ")}).`);try{return _n(await e(`${u}${x}`,C===void 0?{method:v}:{method:v,body:C}))}catch(k){throw b1(k)??k}},g=v=>s.client&&v.client===void 0?{...v,client:s.client}:v,_=v=>{const C=gy(v==null?void 0:v.policy);return d=C.revision,f=Rf(v==null?void 0:v.scope),m(C)};return{supported:l,sessionId:o,get revision(){return d},get scope(){return f},async get(){const v=await p("GET");if(!v||!("policy"in v))throw new Error("The gateway answered without `policy` for this chat.");const C=v.policy===null?null:gy(v.policy);return d=typeof v.revision=="number"?v.revision:C?C.revision:void 0,f=Rf(v.scope),C?m(C):null},replace:async v=>_(await p("PUT",g(v))),merge:async v=>_(await p("POST",g(v))),async reset(v){if(v!==void 0&&!Number.isInteger(v))throw new Error(`reset(ifRevision) takes an integer revision, got ${JSON.stringify(v)}.`);const C=await p("DELETE",void 0,v===void 0?"":`?if_revision=${v}`);return d=typeof(C==null?void 0:C.revision)=="number"?C.revision:void 0,f=Rf(C==null?void 0:C.scope),{...d===void 0?{}:{revision:d},...f?{scope:f}:{}}}}}function k1(e,t,n={}){var g;const s=new Set,o=new Set,l=new Set,u=new Set(t.filter(_=>_.offered).map(_=>_.name)),d=_=>e&&Object.prototype.hasOwnProperty.call(e,_)?Au(e[_]):void 0;for(const _ of u){const v=d(_);v==="auto"?s.add(_):v==="off"?o.add(_):v==="ask"&&l.add(_)}const f=n.base,m={};if(f){for(const[x,k]of Object.entries(f.approve))!u.has(x)&&k==="tool"&&s.add(x);for(const[x,k]of Object.entries(f.deny))!u.has(x)&&k==="tool"&&o.add(x);for(const x of f.ask)u.has(x)||l.add(x);for(const[x,k]of Object.entries(f.approve)){if(!u.has(x)||k==="tool")continue;(d(x)??((g=n.inherited)==null?void 0:g[x]))==="ask"&&l.add(x)}const _=_n(f.request),v=_n(_==null?void 0:_.approve),C=_n(_==null?void 0:_.deny);Array.isArray(v==null?void 0:v.kinds)&&v.kinds.length&&(m.approve={kinds:No(v.kinds)}),(v==null?void 0:v.all)===!0&&(m.approve={...m.approve||{},all:!0}),typeof(v==null?void 0:v.max_risk_rank)=="number"&&(m.approve={...m.approve||{},max_risk_rank:v.max_risk_rank}),Array.isArray(C==null?void 0:C.kinds)&&C.kinds.length&&(m.deny={kinds:No(C.kinds)})}const p=_=>[..._].sort();return{approve:{tools:p(s),...m.approve||{}},deny:{tools:p(o),...m.deny||{}},ask:p(l)}}function S1(e){var t,n,s,o,l,u,d,f,m,p;return!((n=(t=e.approve)==null?void 0:t.tools)!=null&&n.length)&&!((o=(s=e.approve)==null?void 0:s.kinds)!=null&&o.length)&&((l=e.approve)==null?void 0:l.all)!==!0&&!((d=(u=e.deny)==null?void 0:u.tools)!=null&&d.length)&&!((m=(f=e.deny)==null?void 0:f.kinds)!=null&&m.length)&&!((p=e.ask)!=null&&p.length)}function j1(e,t){const n={};if(!e)return n;const s=new Set(t.filter(o=>o.offered).map(o=>o.name));for(const o of Object.keys(e.approve))s.has(o)&&(n[o]="auto");for(const o of e.ask)s.has(o)&&(n[o]="ask");for(const o of Object.keys(e.deny))s.has(o)&&(n[o]="off");return n}function N1(e){return((e==null?void 0:e.clamped)||[]).map(t=>`Not covered: ${t.name}${t.selector&&t.selector!=="tools"?` (${t.selector})`:""} (${t.reason})`)}const C1={off:"Off",ask:"Ask",auto:"Auto",on:"On"},E1={app:"Use the gateway's",session:"Use my defaults"},A1="Off = denied for every run of this chat, automations included",$1="The gateway did not say where this policy applies",yy={app:"this app",session:"this chat"},wy=`Auto for a whole group reaches the tools that read or make changes (risk ${Qv} or lower) and whose destination the assistant does not choose. Set the others to Auto one at a time.`;function T1(e){const t=e.split("_");return t.map((n,s)=>s<t.length-1?a.jsxs(yt.Fragment,{children:[n,"_",a.jsx("wbr",{})]},s):a.jsx(yt.Fragment,{children:n},s))}function vy(e){var o,l;if(!e)return"";const t=((o=e.set_by)==null?void 0:o.user_id)||"",n=((l=e.set_by)==null?void 0:l.client)||"",s=Mo(e.set_at);return!t&&!s?"":`Set${t?` by ${t}`:""}${n?` (${n})`:""}${s?` on ${s}`:""}`}function R1(e){var M,J,B,Y,te;const t={...C1,...e.labels||{}},n=e.disabled===!0,s=e.allowListOnly===!0,o=e.value||{},[l,u]=y.useState(""),[d,f]=y.useState(!1),m=W=>{var T;return W.offered?((T=e.inherited)==null?void 0:T[W.name])??W.gatewayDefault:"off"},p=W=>{if(!W.offered)return"off";const T=o[W.name];return T==="off"||T==="ask"||T==="auto"?T:m(W)},g=y.useMemo(()=>{const W={};for(const T of e.catalog)W[T.name]=m(T);return W},[e.catalog,e.inherited]),_=y.useMemo(()=>{const W=l.trim().toLowerCase(),T=new Map;for(const K of e.catalog){if(W&&![K.name,K.description||"",K.toolset].some(ue=>ue.toLowerCase().includes(W)))continue;const ne=T.get(K.toolset)||[];ne.push(K),T.set(K.toolset,ne)}return[...T.entries()].sort(([K],[ne])=>K==="other"?1:ne==="other"?-1:K.localeCompare(ne)).map(([K,ne])=>({toolset:K,items:[...ne].sort((ue,oe)=>ue.offered===oe.offered?ue.name.localeCompare(oe.name):ue.offered?-1:1)}))},[e.catalog,l]),v=W=>{n||e.onChange(W)},C=W=>{const T=m(W);return T!=="off"?T:W.gatewayDefault!=="off"?W.gatewayDefault:"ask"},x=(W,T)=>v(kh(o,W,T,m(W))),k=(W,T)=>{if(T==="on"){let K=o;for(const ne of W)ne.offered&&p(ne)==="off"&&(K=kh(K,ne,C(ne),m(ne)));v(K);return}v(m1(o,W,T,g).layer)},S=e.catalog.filter(W=>W.offered),$={auto:0,ask:0};for(const W of S){const T=p(W);T==="auto"?$.auto+=1:T==="ask"&&($.ask+=1)}const R=$.auto+$.ask,N=W=>{if(!W.offered||!Object.prototype.hasOwnProperty.call(o,W.name))return!1;const T=o[W.name];return(T==="off"||T==="ask"||T==="auto")&&T!==m(W)},E=e.catalog.filter(N).map(W=>W.name),j=$k(e.toolMode,e.toolModeLabel,e.toolModeDetail),I=e.scope??((M=e.policy)==null?void 0:M.scope)??null,L=s?["off","on"]:["off","ask","auto"],z=W=>t[W],V=a.jsxs("div",{className:`af-tool-modes${e.className?` ${e.className}`:""}`,"data-layer":e.layer,"data-allowlist":s?"true":void 0,children:[j?a.jsxs("div",{className:`af-tool-policy__mode is-${j.tone}`,children:[a.jsx("div",{className:"af-tool-policy__mode-badge",children:"Tool mode"}),a.jsx("div",{className:"af-tool-policy__mode-value",children:j.label}),a.jsx("div",{className:"af-tool-policy__mode-detail",children:j.detail})]}):null,e.note?a.jsx("div",{className:"af-tool-policy__note",children:e.note}):null,(J=e.warnings)!=null&&J.length?a.jsx("div",{className:"af-tool-modes__warnings",role:"status","data-catalog-warnings":"",children:e.warnings.map((W,T)=>a.jsxs("div",{children:["Gateway warning: ",W]},T))}):null,a.jsxs("div",{className:"af-tool-modes__top",children:[a.jsx("input",{type:"search",className:"af-tool-modes__search",placeholder:"Search tools","aria-label":"Search tools",value:l,onChange:W=>u(W.target.value)}),a.jsx("span",{className:"af-tool-modes__count","data-tool-count":"",children:s?`${R} of ${S.length} tools on`:`${R} of ${S.length} tools on · ${$.auto} run without asking · ${$.ask} ask first`}),e.onReset&&Object.keys(o).length?a.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"reset-layer",disabled:n,onClick:e.onReset,children:E1[e.layer]}):null,e.storage?a.jsx("span",{className:"af-tool-modes__saved","data-storage":e.storage.kind,children:e.storage.where}):e.savedWhere?a.jsx("span",{className:"af-tool-modes__saved",children:e.savedWhere}):null]}),(B=e.storage)!=null&&B.note?a.jsx("div",{className:"af-tool-modes__warnings",role:"status","data-storage-note":e.storage.kind,children:e.storage.note}):null,e.layer==="session"&&((Y=e.storage)==null?void 0:Y.kind)==="gateway"?a.jsx("div",{className:"af-tool-modes__policy","data-session-off-help":"",children:A1}):null,((te=e.storage)==null?void 0:te.kind)==="gateway"||e.policy?a.jsx("div",{className:"af-tool-modes__policy","data-policy-scope":I?"served":"unsaid",children:I?a.jsxs(a.Fragment,{children:[I.approve?a.jsxs("div",{children:["Approve applies to: ",I.approve]}):null,I.deny?a.jsxs("div",{children:["Deny applies to: ",I.deny]}):null]}):$1}):null,e.policy?a.jsxs("div",{className:"af-tool-modes__policy","data-session-policy":e.policy.revision,children:[vy(e.policy)?a.jsx("div",{"data-policy-set":"",children:vy(e.policy)}):null,N1(e.policy).map((W,T)=>a.jsx("div",{"data-policy-clamped":"",children:W},T))]}):null,e.catalog.length?null:a.jsx("div",{className:"af-tool-policy__empty",children:"The gateway offers no tools."}),e.catalog.length&&!_.length?a.jsx("div",{className:"af-tool-policy__empty",children:"No tools match the search."}):null,_.map(W=>{const T=W.items.filter(oe=>oe.offered),K=new Set(T.map(oe=>s?p(oe)==="off"?"off":"on":p(oe))),ne=K.size===1?[...K][0]:void 0,ue=s?[]:T.filter(oe=>!Oo(oe));return a.jsxs("section",{className:"af-tool-modes__group","data-toolset":W.toolset,children:[a.jsxs("div",{className:"af-tool-modes__group-head",children:[a.jsx("span",{className:"af-tool-modes__group-name",children:W.toolset}),T.length?a.jsx("span",{className:"af-tool-modes__group-state","data-group-state":ne??"mixed",children:ne?z(ne):"Mixed"}):null,a.jsx("div",{className:"af-tool-modes__seg",role:"group","aria-label":`All ${W.toolset} tools`,children:L.map(oe=>a.jsx("button",{type:"button",className:`af-tool-modes__seg-btn${ne===oe?" is-active":""}`,"aria-pressed":ne===oe,"data-group-mode":`${W.toolset}:${oe}`,disabled:n||!T.length||oe==="auto"&&ue.length===T.length,title:oe==="auto"&&ue.length?wy:void 0,onClick:()=>k(W.items,oe),children:z(oe)},oe))})]}),ue.length?a.jsxs("div",{className:"af-tool-modes__cap","data-bulk-cap":W.toolset,children:[wy," ",ue.length===1?"1 tool here stays":`${ue.length} tools here stay`," as it is: ",ue.map(oe=>oe.name).join(", "),"."]}):null,W.items.map(oe=>{const ve=p(oe),Ne=s&&ve!=="off"?"on":ve,q=N(oe),be=m(oe);return a.jsxs("div",{className:`af-tool-mode-row${oe.offered?"":" is-unavailable"}`,"data-tool":oe.name,"data-mode":ve,"data-overridden":q?"true":"false",children:[a.jsxs("div",{className:"af-tool-mode-row__meta",children:[a.jsxs("div",{className:"af-tool-row__title",children:[a.jsx("span",{className:"af-tool-row__name",children:T1(oe.name)}),oe.riskTier?a.jsx("span",{className:"af-tool-row__badge","data-risk":oe.riskRank??"",title:oe.riskRank!==void 0?`Risk ${oe.riskRank}`:void 0,children:oe.riskTier}):null,q?a.jsxs("span",{className:"af-tool-mode-row__default","data-default-chip":oe.name,title:e.layer==="app"||be===oe.gatewayDefault?"The gateway's default":"Your default for this app",children:["Default: ",s?be==="off"?t.off:t.on:z(be)]}):null]}),oe.state?a.jsx("div",{className:"af-tool-row__state-line",children:a.jsx(Zc,{content:oe.state.tooltip||"",children:a.jsx("span",{className:`af-tool-row__state${oe.state.tone?` is-${oe.state.tone}`:""}`,"data-tool-state":oe.name,tabIndex:oe.state.tooltip?0:void 0,"aria-label":oe.state.tooltip?`${oe.state.label}. ${oe.state.tooltip}`:void 0,children:oe.state.label})})}):null,oe.description?a.jsx("div",{className:"af-tool-row__desc",children:oe.description}):null,oe.whenToUse?a.jsx("div",{className:"af-tool-row__hint",children:oe.whenToUse}):null,oe.offered&&oe.defaultUnserved?a.jsx("div",{className:"af-tool-mode-row__why","data-default-unserved":oe.name,children:"The gateway did not say whether this tool asks first; Ask is assumed."}):null,oe.offered?null:a.jsx("div",{className:"af-tool-mode-row__why","data-why-disabled":oe.name,children:oe.whyDisabled?`Not offered by the gateway: ${oe.whyDisabled}`:"Not offered by the gateway."})]}),a.jsx("div",{className:"af-tool-modes__seg",role:"group","aria-label":`Mode for ${oe.name}`,children:L.map(xe=>a.jsx("button",{type:"button",className:`af-tool-modes__seg-btn${Ne===xe?" is-active":""}`,"aria-pressed":Ne===xe,"data-tool-mode":`${oe.name}:${xe}`,disabled:n||!oe.offered,onClick:()=>x(oe,xe==="on"?C(oe):xe),children:z(xe)},xe))})]},oe.name)})]},W.toolset)})]});if(e.rowLabel===void 0)return V;const Z=e.layer==="session"&&S.some(W=>m(W)!==W.gatewayDefault),ie=E.length?`${E.length} tool${E.length===1?"":"s"} changed`:Z?"Your defaults":"",F=E.length?yy[e.layer]:yy.app,D=e.open??d;return a.jsx(vh,{label:e.rowLabel,help:e.rowHelp,defaultSummary:s?`${R} of ${S.length} tools on`:`${R} tools on, ${$.auto} without asking`,overrideSummary:ie,overrideOwner:F,open:D,onToggle:e.onToggle??(()=>f(W=>!W)),disabled:n,setting:`tools-${e.layer}`,children:V})}const Zv="Saved in this browser",I1="Saved for this chat on the gateway",L1=`${am}, so this chat's tool choices are kept in this browser.`,M1=100;function If(e,t,n){const s=e&&typeof e=="object"?e:{},o={};for(const[l,u]of Object.entries(s)){const d=Au(u,t);l.trim()&&d?o[l.trim()]=d:l.trim()&&(n==null||n.push(l.trim()))}return o}function O1(e,t={}){const n=String(e||"").trim();if(!n)throw new Error("createToolLayerStore needs the gateway identity (toolIdentityKey).");const s=()=>{if(t.storage!==void 0)return t.storage;try{return globalThis.localStorage??null}catch{return null}},o=E=>{var j;try{const I=(j=s())==null?void 0:j.getItem(E);return I?JSON.parse(I):void 0}catch{return}},l=(E,j)=>{try{const I=s();if(!I)return;j===null?I.removeItem(E):I.setItem(E,JSON.stringify(j))}catch{}},u=`af.tools.sessions.${n}`,d=E=>{const j=String(E||"").trim();if(!j)throw new Error("The app layer needs the app's interface id.");return`af.tools.app.${j}.${n}`},f=E=>{const j=String(E||"").trim();if(!j)throw new Error("The session layer needs a session id.");return`af.tools.session.${n}.${j}`},m=`af.tools.session.${n}.`,p=()=>{var L;const E=o(u);if(Array.isArray(E))return E.filter(z=>typeof z=="string"&&!!z);const j=s(),I=[];try{const z=typeof(j==null?void 0:j.length)=="number"?j.length:0;for(let V=0;V<z;V+=1){const Z=(L=j==null?void 0:j.key)==null?void 0:L.call(j,V);Z&&Z.startsWith(m)&&I.push(Z.slice(m.length))}}catch{}return I},g=E=>{var L,z;const j=[],I=If((L=o(E))==null?void 0:L.modes,t.dialect,j);return j.length&&((z=t.onDropped)==null||z.call(t,E,j)),I},_=new Map,v=new Map,C=(E,j)=>{const I=E.revision;return typeof I=="number"?I:j?j.revision:void 0},x=E=>{const j=_.get(E);if(j===void 0)throw new w1(v.has(E)?"the last read carried none":"load this chat's policy before saving it");return j},k=E=>({kind:"browser",where:Zv,...E?{note:E}:{}}),S=E=>{var I;const j=((I=t.sessionPolicy)==null?void 0:I.call(t,E))??null;return(j==null?void 0:j.supported)===!0?{client:j,storage:{kind:"gateway",where:I1}}:{client:null,storage:k(j?L1:void 0)}},$=(E,j,I,L,z,V)=>(z===void 0?_.delete(E):_.set(E,z),v.set(E,I),{storage:j,layer:j1(I,L),policy:I,...V?{scope:V}:{}}),R=(E,j)=>E.scope??(j==null?void 0:j.scope),N={identityKey:n,appKey:d,sessionKey:f,readApp:E=>g(d(E)),writeApp(E,j){const I=If(j);l(d(E),Object.keys(I).length?{modes:I}:null)},readSession:E=>g(f(E)),writeSession(E,j){const I=String(E||"").trim(),L=If(j),z=!Object.keys(L).length;l(f(I),z?null:{modes:L});const V=p().filter(Z=>Z!==I);z||V.unshift(I);for(const Z of V.splice(M1))l(f(Z),null);l(u,V.length?V:null)},sessions:p,sessionStorage:E=>S(E).storage,async loadSession(E,j){const{client:I,storage:L}=S(E);if(!I)return{storage:L,layer:N.readSession(E),policy:null};const z=await I.get();return $(E,L,z,j,C(I,z),R(I,z))},async saveSession(E,j,I,L={}){const{client:z,storage:V}=S(E);if(!z)return N.writeSession(E,j),{storage:V,layer:N.readSession(E),policy:null};const Z=k1(j,I,{base:v.get(E)??null,inherited:L.inherited});if(S1(Z))return N.resetSession(E);const ie=await z.replace({...Z,if_revision:x(E)});return $(E,V,ie,I,C(z,ie),R(z,ie))},async resetSession(E){const{client:j,storage:I}=S(E);if(!j)return N.writeSession(E,null),{storage:I,layer:{},policy:null};const L=await j.reset(x(E));return $(E,I,null,[],typeof L.revision=="number"?L.revision:C(j,null),R(j,null))}};return N}function e_(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 P1(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function D1(e){const t=String(e.role||"message").trim()||"message",n=String(e.title||"").trim(),s=String(e.ts||"").trim(),o=[t];return n&&o.push(n),s&&o.push(s),o.join(" · ")}function F1(e){return e.endsWith(`
68
- `)?e:`${e}
69
- `}function z1(e){return String(e||"").trimStart().startsWith("```")}function B1(e,t){const s=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=D1(o);s.push(`## ${l}`,"");const u=String(o.content||""),d=e_(u);d!==null&&!z1(u)?s.push("```json",P1(d).trimEnd(),"```",""):s.push(F1(u).trimEnd(),""),s.push("---","")}for(;s.length&&!s[s.length-1].trim();)s.pop();return s.length&&s[s.length-1]==="---"&&s.pop(),`${s.join(`
70
- `).trimEnd()}
71
- `}async function gl(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 s=document.createElement("textarea");s.value=t,s.style.position="fixed",s.style.left="-9999px",document.body.appendChild(s),s.select();const o=document.execCommand("copy")===!0;return document.body.removeChild(s),o}catch{return!1}}function W1(e){const t=String(e.filename||"").trim()||"export.txt",n=String(e.text||""),s=String(e.mime),o=new Blob([n],{type:s}),l=URL.createObjectURL(o),u=document.createElement("a");u.href=l,u.download=t,document.body.appendChild(u),u.click(),u.remove(),window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}const U1=3,V1=Number.MAX_SAFE_INTEGER;function t_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function n_(e){return Array.isArray(e)}function G1(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ko({kind:e,children:t}){return a.jsx("span",{className:`pc-json-token ${e}`,children:t})}function H1(e){const t=JSON.stringify(e.value),n=t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t"),[s,o]=y.useState(!n||e.expansionMode==="unfolded");return y.useEffect(()=>{n&&o(e.expansionMode==="unfolded")},[n,e.expansionMode,e.expansionVersion]),n?a.jsxs("span",{className:`pc-json-string ${s?"open":"collapsed"}`,children:[a.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>o(l=>!l),"aria-label":s?"Collapse string value":"Expand string value","aria-expanded":s,children:s?"▾":"▸"}),s?a.jsx("span",{className:"pc-json-token string pc-json-string__value",children:t}):a.jsxs("button",{type:"button",className:"pc-json-string__preview",onClick:()=>o(!0),"aria-label":"Expand string value",children:[a.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:t}),a.jsx("span",{className:"pc-json-string__suffix",children:"(...)"})]})]}):a.jsx(ko,{kind:"string",children:t})}function K1(e,t,n){return e===null?a.jsx(ko,{kind:"null",children:"null"}):typeof e=="string"?a.jsx(H1,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?a.jsx(ko,{kind:"number",children:String(e)}):typeof e=="boolean"?a.jsx(ko,{kind:"boolean",children:e?"true":"false"}):a.jsx(ko,{kind:"string",children:JSON.stringify(String(e))})}function J1(e){return n_(e)?e.length===1?"1 item":`${e.length} items`:t_(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function s_(e){const{label:t,value:n,depth:s,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:d}=e,f=s*14,m=t_(n),p=n_(n),g=m||p,_=s<o,[v,C]=y.useState(_);y.useEffect(()=>{C(_)},[_,u]);const x=t?a.jsxs(a.Fragment,{children:[a.jsx(ko,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[x,K1(n,l,u),d?",":""]});const k=p?"[":"{",S=p?"]":"}",$=J1(n),R=v?`${k}`:`${k}…${S}${$?` (${$})`:""}`,N=p?n.map((E,j)=>({key:String(j),label:void 0,value:E})):Object.entries(n).map(([E,j])=>({key:E,label:E,value:j}));return a.jsxs("details",{className:"pc-json-viewer__details",open:v,onToggle:E=>C(E.currentTarget.open),children:[a.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[x,a.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:v?"▾":"▸"}),a.jsx("span",{className:"pc-json-viewer__punct",children:R}),!v&&d?a.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),v?a.jsx("div",{className:"pc-json-viewer__children",children:N.length===0?a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[a.jsx("span",{className:"pc-json-viewer__punct",children:S}),d?",":""]}):a.jsxs(a.Fragment,{children:[N.map((E,j)=>{const I=j===N.length-1;return a.jsx(s_,{label:E.label,value:E.value,depth:s+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!I},`${s}:${t||"root"}:${E.key}`)}),a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[a.jsx("span",{className:"pc-json-viewer__punct",children:S}),d?",":""]})]})}):null]})}function q1(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 Co(e){const{value:t,className:n,showCopy:s=!0}=e,[o,l]=y.useState({mode:"folded",version:0}),[u,d]=y.useState("idle"),f=typeof e.collapseAfterDepth=="number"&&(Number.isFinite(e.collapseAfterDepth)||e.collapseAfterDepth===1/0)&&e.collapseAfterDepth>=0?e.collapseAfterDepth===1/0?Number.MAX_SAFE_INTEGER:Math.trunc(e.collapseAfterDepth):U1,m=o.mode==="unfolded"?V1:f,p=y.useMemo(()=>typeof t=="string"?q1(t):t,[t]),g=y.useMemo(()=>G1(t),[t]),_=["pc-json-viewer",n].filter(Boolean).join(" ");y.useEffect(()=>{l(C=>({mode:"folded",version:C.version+1}))},[p]);const v=()=>{l(C=>({mode:C.mode==="unfolded"?"folded":"unfolded",version:C.version+1}))};return a.jsxs("div",{className:_,children:[a.jsxs("div",{className:"pc-json-viewer__toolbar",children:[a.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:v,"aria-expanded":o.mode==="unfolded",children:o.mode==="unfolded"?"Fold all":"Unfold all"}),s?a.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__copy",onClick:()=>void gl(g).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]}),a.jsx("div",{className:"pc-json-viewer__tree",role:"tree","aria-label":"JSON viewer",children:a.jsx(s_,{value:p,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Y1({code:e,lang:t}){const[n,s]=y.useState("idle"),o=y.useRef(null);y.useEffect(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);const l=Wv(e,em(t));return a.jsxs("div",{className:"pc-md_codeblock",children:[a.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 gl(e);s(u?"copied":"failed"),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>s("idle"),900)},children:a.jsx(de,{name:n==="copied"?"check":"copy",size:14})}),a.jsx("pre",{className:"pc-md_pre",children:a.jsx("code",{className:t?`language-${t}`:void 0,children:l.map((u,d)=>u.kind==="plain"?a.jsx(yt.Fragment,{children:u.text},d):a.jsx("span",{className:`af-code__${u.kind}`,children:u.text},d))})})]})}function Ii(e,t){const n=String(e??"");if(!t||!t.needles.length)return[n];const s=[],o=n.toLowerCase();let l=0;for(;l<n.length;){let u=-1,d="";for(let p=0;p<t.needlesLower.length;p++){const g=t.needlesLower[p];if(!g)continue;const _=o.indexOf(g,l);if(_===-1)continue;const v=t.needles[p]||"";v&&(u===-1||_<u||_===u&&v.length>d.length)&&(u=_,d=v)}if(u===-1||!d){s.push(n.slice(l));break}u>l&&s.push(n.slice(l,u));const f=t.hits===0&&t.id?t.id:void 0,m=n.slice(u,u+d.length);s.push(a.jsx("span",{id:f,className:t.className,children:m},`hl:${t.hits}`)),t.hits+=1,l=u+d.length}return s}function r_(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Sh="http://same-origin.invalid/";function Q1(e){try{const t=new URL(e,Sh);return t.protocol==="http:"&&t.origin===new URL(Sh).origin}catch{return!1}}function a_(e){const t=String(e||"").trim();return r_(t)??(t&&Q1(t)?t:void 0)}let ya=null;function X1(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 s=n??Sh;let o,l;try{o=new URL(s).origin,l=new URL(t,s)}catch{return!1}return l.protocol!=="http:"&&l.protocol!=="https:"?!1:l.origin===o}function o_(e,t,n){return a.jsx("a",{className:"pc-md_link pc-md_image_link",href:t,target:"_blank",rel:"noopener noreferrer",children:`image: ${n||t}`},e)}function _y(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function ar(e,t){const n=[],s=String(e??"");let o=0,l="";const u=()=>{if(l){for(const d of Ii(l,t))n.push(d);l=""}};for(;o<s.length;){const d=s[o];if(d==="!"&&s[o+1]==="["){const f=s.indexOf("]",o+2);if(f!==-1&&s[f+1]==="("){const m=s.indexOf(")",f+2);if(m!==-1){const p=s.slice(o+2,f),g=a_(s.slice(f+2,m));if(g&&ya&&!ya(g)){u(),n.push(o_(`img:${o}`,g,p)),o=m+1;continue}if(g){u(),n.push(a.jsxs("span",{className:"pc-md_image_inline",children:[a.jsx("img",{className:"pc-md_img",src:g,alt:p,loading:"lazy"}),p?a.jsx("span",{className:"pc-md_img_caption",children:t?Ii(p,t):p}):null]},`img:${o}`)),o=m+1;continue}}}}if(d==="["){const f=s.indexOf("]",o+1);if(f!==-1&&s[f+1]==="("){const m=s.indexOf(")",f+2);if(m!==-1){const p=s.slice(o+1,f),g=r_(s.slice(f+2,m));if(g){u(),n.push(a.jsx("a",{className:"pc-md_link",href:g,target:g.startsWith("#")?void 0:"_blank",rel:"noreferrer",children:ar(p,t)},`link:${o}`)),o=m+1;continue}}}}if(d==="`"){const f=s.indexOf("`",o+1);if(f!==-1){u();const m=s.slice(o+1,f);n.push(a.jsx("code",{children:t?Ii(m,t):m},`code:${o}`)),o=f+1;continue}}if(d==="_"&&!_y(s[o-1])){const f=s[o+1]==="_"?"__":"_",m=f.length;if(s[o+m]&&!/\s/.test(s[o+m])&&s[o+m]!=="_"){let p=s.indexOf(f,o+m);for(;p!==-1&&(/\s/.test(s[p-1]||" ")||_y(s[p+m])||m===1&&s[p+1]==="_");)p=s.indexOf(f,p+1);if(p!==-1&&p>o+m){u();const g=s.slice(o+m,p),_=ar(g,t);n.push(m===2?a.jsx("strong",{children:_},`ubold:${o}`):a.jsx("em",{children:_},`uem:${o}`)),o=p+m;continue}}}if(d==="*"&&s[o+1]==="*"){const f=s.indexOf("**",o+2);if(f!==-1){u();const m=s.slice(o+2,f);n.push(a.jsx("strong",{children:t?Ii(m,t):m},`bold:${o}`)),o=f+2;continue}}if(d==="*"&&s[o+1]!=="*"){const f=s.indexOf("*",o+1);if(f!==-1){u();const m=s.slice(o+1,f);n.push(a.jsx("em",{children:t?Ii(m,t):m},`em:${o}`)),o=f+1;continue}}l+=d,o+=1}return u(),n}function Z1(e){return String(e??"").replace(/\r\n/g,`
72
- `).replace(/\r/g,`
73
- `).split(`
74
- `)}function Qc(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 eC(e){const t=[];for(const o of e){const l=Qc(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}const n=[],s=[];for(const o of t){for(;s.length>0&&o.indent<s[s.length-1].indent;)s.pop();let l=s.length>0?s[s.length-1]:null;if(l&&o.indent>l.indent){const u=l.node.items,d=u[u.length-1];if(d){const f={ordered:o.ordered,start:o.start,items:[]};d.children.push(f),s.push({indent:o.indent,node:f}),l=s[s.length-1]}}else if(l&&l.node.ordered!==o.ordered){s.pop();const u=s.length>0?s[s.length-1]:null,d={ordered:o.ordered,start:o.start,items:[]};if(u){const f=u.node.items,m=f[f.length-1];m?m.children.push(d):u.node.items.push({content:"",children:[d]})}else n.push(d);s.push({indent:o.indent,node:d}),l=s[s.length-1]}if(!l){const u={ordered:o.ordered,start:o.start,items:[]};n.push(u),s.push({indent:o.indent,node:u}),l=s[s.length-1]}l.node.items.push({content:o.content,children:[]})}return n}function i_(e,t,n){const s=e.items.map((o,l)=>a.jsxs("li",{children:[ar(o.content,t),o.children.map((u,d)=>i_(u,t,`${n}:${l}:${d}`))]},`${n}:li:${l}`));return e.ordered?a.jsx("ol",{className:"pc-md_ol",start:e.start!==1?e.start:void 0,children:s},n):a.jsx("ul",{className:"pc-md_ul",children:s},n)}function tC(e,t,n){return eC(e).map((s,o)=>i_(s,t,`${n}:${o}`))}function by(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 xy(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(s=>String(s??"").trim());return n.length<2?!1:n.every(s=>/^:?-{3,}:?$/.test(s))}const ky=/^(#{1,5})\s+(.*)$/;function Sy(e){return e.trim().startsWith("```")}function jy(e){return e.trimStart().startsWith(">")}function l_(e){const t=ya;ya=e.images==="link"?e.inlineImage||X1:null;try{return nC(e)}finally{ya=t}}function nC({text:e,className:t,highlight:n,highlights:s,highlightClassName:o,highlightId:l}){const u=Z1(e),d=[],f=[];Array.isArray(s)&&f.push(...s),typeof n=="string"&&n.trim()&&f.push(n);const m=Array.from(new Set(f.map(v=>String(v??"").trim()).filter(Boolean))).filter(v=>v.length>=4),p=m.length?{needles:m,needlesLower:m.map(v=>v.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let g=0;for(;g<u.length;){const v=String(u[g]??"");if(!v.trim()){g+=1;continue}const C=v.trim();if(/^([-_*])(\s*\1){2,}$/.test(C)){d.push(a.jsx("hr",{className:"pc-md_hr"},`hr:${g}`)),g+=1;continue}const x=v.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(x){const $=a_(x[2]||"");if($&&ya&&!ya($)){d.push(a.jsx("p",{className:"pc-md_p",children:o_(`img:${g}`,$,x[1]||"")},`p:${g}`)),g+=1;continue}if($){const R=x[1]||"";d.push(a.jsxs("figure",{className:"pc-md_figure",children:[a.jsx("img",{className:"pc-md_img",src:$,alt:R,loading:"lazy"}),R?a.jsx("figcaption",{children:ar(R,p)}):null]},`figure:${g}`)),g+=1;continue}}if(Sy(v)){const R=v.trim().replace(/```/g,"").trim(),N=[];for(g+=1;g<u.length&&!String(u[g]??"").trim().startsWith("```");)N.push(String(u[g]??"")),g+=1;g<u.length&&(g+=1);const E=N.join(`
75
- `);d.push(a.jsx(Y1,{code:E,lang:R},`pre:${g}`));continue}const k=v.match(ky);if(k){const $=k[1].length,R=k[2]||"",N=ar(R,p);$===1?d.push(a.jsx("h1",{children:N},`h1:${g}`)):$===2?d.push(a.jsx("h2",{children:N},`h2:${g}`)):$===3?d.push(a.jsx("h3",{children:N},`h3:${g}`)):$===4?d.push(a.jsx("h4",{children:N},`h4:${g}`)):d.push(a.jsx("h5",{children:N},`h5:${g}`)),g+=1;continue}if(jy(v)){const $=[];for(;g<u.length&&String(u[g]??"").trimStart().startsWith(">");){const N=String(u[g]??"").trimStart();$.push(N.replace(/^>\s?/,"")),g+=1}d.push(a.jsx("blockquote",{className:"pc-md_quote",children:$.map((R,N)=>a.jsxs(yt.Fragment,{children:[ar(R,p),N<$.length-1?a.jsx("br",{}):null]},`q:${g}:${N}`))},`quote:${g}`));continue}if(v.includes("|")&&g+1<u.length&&xy(String(u[g+1]??""))){const $=by(v),R=Math.max(1,$.length),N=[];for(g+=2;g<u.length;){const E=String(u[g]??"");if(!E.trim()||!E.includes("|"))break;const j=by(E),I=[];for(let L=0;L<R;L++)I.push(j[L]??"");N.push(I),g+=1}d.push(a.jsx("div",{className:"pc-md_table_wrap",children:a.jsxs("table",{className:"pc-md_table",children:[a.jsx("thead",{children:a.jsx("tr",{children:$.slice(0,R).map((E,j)=>a.jsx("th",{children:ar(E,p)},`th:${g}:${j}`))})}),a.jsx("tbody",{children:N.map((E,j)=>a.jsx("tr",{children:E.map((I,L)=>a.jsx("td",{children:ar(I,p)},`td:${g}:${j}:${L}`))},`tr:${g}:${j}`))})]})},`table:${g}`));continue}if(Qc(v)){const $=[];for(;g<u.length;){const R=String(u[g]??"");if(!R.trim()||R.trimStart().startsWith("```"))break;if(Qc(R)||/^\s{2,}\S/.test(R)){$.push(R),g+=1;continue}break}d.push(a.jsx(yt.Fragment,{children:tC($,p,`list:${g}`)},`list:${g}`));continue}const S=[];for(;g<u.length&&String(u[g]??"").trim()&&!(S.length>0&&Qc(String(u[g]??"")));){const $=String(u[g]??"");if(S.length>0&&(ky.test($)||Sy($)||jy($))||S.length>0&&$.includes("|")&&g+1<u.length&&xy(String(u[g+1]??"")))break;S.push($),g+=1}d.push(a.jsx("p",{className:"pc-md_p",children:S.map(($,R)=>a.jsxs(yt.Fragment,{children:[ar($,p),R<S.length-1?a.jsx("br",{}):null]},`pl:${g}:${R}`))},`p:${g}`))}const _=["pc-md",t].filter(Boolean).join(" ");return a.jsx("div",{className:_,children:d})}function c_(e){const t=String(e.text??""),n=y.useMemo(()=>e_(t),[t]),s=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?a.jsx("div",{className:s,children:a.jsx(Co,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?a.jsx("div",{className:s,children:e.renderMarkdown(t)}):a.jsx("div",{className:s,children:a.jsx(l_,{text:t,images:e.images,inlineImage:e.inlineImage})})}const sC=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),rC=new Set(["application/pdf","application/json","text/plain","text/markdown","text/csv","text/tab-separated-values","text/x-python","text/javascript","application/javascript","text/css","text/x-c","text/x-shellscript","text/x-typescript","image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","video/mp4","video/webm","video/quicktime","audio/mpeg","audio/mp4","audio/aac","audio/wav","audio/x-wav","audio/ogg","audio/webm","audio/flac"]);function u_(e){const t=String(e??"");if(!t.trim())return!1;try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/",s=new URL(t,n).protocol;return s==="blob:"||s==="data:"}catch{return!0}}function aC(e,t){const n=String(t||"").split("/").pop()||"",s=n.lastIndexOf(".");if(s>0&&sC.has(n.slice(s+1).toLowerCase()))return!1;const o=String(e||"").split(";",1)[0].trim().toLowerCase();return!o||o==="text/html"||o.includes("xml")?!1:rC.has(o)}function oC(e){const t=n=>!!n&&(!u_(n)||aC(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}const du=1024*1024,iC="1 MiB",lC=25*1024*1024,d_=(e,t)=>`${we(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function f_(e){const t=e.headers.get("content-range"),n=t?Number(t.split("/")[1]):NaN;if(Number.isFinite(n))return n;const s=Number(e.headers.get("content-length"));return e.status===200&&Number.isFinite(s)&&e.headers.has("content-length")?s:void 0}async function cC(e,t,n){var m;const s=new TextDecoder;let o="",l=0;const u=(m=e.body)==null?void 0:m.getReader();if(u){for(;l<t;){const{done:p,value:g}=await u.read();if(p)break;const _=g.subarray(0,t-l);l+=_.length,o+=s.decode(_,{stream:!0})}await u.cancel().catch(()=>{})}else o=(await e.text()).slice(0,t),l=o.length;const d=f_(e)??n,f=d!==void 0?d>l:l>=t;return{text:o,received:l,total:d,partial:f}}function h_(e){return`Showing the first ${iC} of ${e!==void 0?ml(e):"a file of unknown size"}; download for the rest.`}function uC(e){try{return decodeURIComponent(e)}catch{return e}}function dC(e,t,n){const s=`${we(`runs/${encodeURIComponent(t)}/workspace`)}/content?`,o=n.split("/").slice(0,-1),l=f=>{if(/^[a-z][a-z0-9+.-]*:/i.test(f)||f.startsWith("/")||f.startsWith("#"))return null;const m=[...o];for(const p of f.split(/[?#]/,1)[0].split("/"))if(!(!p||p==="."))if(p===".."){if(!m.length)return null;m.pop()}else m.push(uC(p));return m.length?d_(t,m.join("/")):null},u=f=>{let m="",p=0;for(;p<f.length;){if(f[p]==="!"&&f[p+1]==="["){const g=f.indexOf("]",p+2);if(g!==-1&&f[g+1]==="("){const _=f.indexOf(")",g+2);if(_!==-1){const v=f.slice(p+2,g),C=f.slice(g+2,_).trim(),x=C.startsWith(s)?C:l(C);m+=x?`![${v}](${x})`:`[image: ${v||C}](${C})`,p=_+1;continue}}}m+=f[p],p+=1}return m};let d=!1;return e.split(`
76
- `).map(f=>/^\s*(```|~~~)/.test(f)?(d=!d,f):d?f:u(f)).join(`
77
- `)}function fC(e,t,n,s){const[o,l]=y.useState({status:"idle"});return y.useEffect(()=>{if(!n||!t){l({status:"idle"});return}const u=new AbortController;let d="";const f=al(n.name);if(f==="binary"){l({status:"ready",kind:"binary",contentType:"",partial:!1});return}if((f==="image"||f==="audio"||f==="video"||f==="pdf")&&typeof n.size_bytes=="number"&&n.size_bytes>lC){l({status:"error",kind:f,message:`Too large to preview (${ml(n.size_bytes)}); use Download.`});return}l({status:"loading",kind:f});const m=iu(f);return(async()=>{var p;try{const g=await e(d_(t,n.path),{signal:u.signal,...m?{headers:{Range:`bytes=0-${du-1}`}}:{}});if(!g.ok)throw new Error(`Preview failed (HTTP ${g.status}): ${await g.text().catch(()=>"")||g.statusText||"no reason given"}`);const _=g.headers.get("content-type")||"",v=al(n.name,_);if(iu(v)){const C=await cC(g,du,n.size_bytes);if(u.signal.aborted)return;l({status:"ready",kind:v,contentType:_,text:v==="markdown"?dC(C.text,t,n.path):C.text,partial:C.partial,total:C.total});return}if(v==="image"||v==="audio"||v==="video"||v==="pdf"){const C=await g.blob();if(u.signal.aborted)return;d=URL.createObjectURL(C.type?C:new Blob([C],{type:v==="pdf"?"application/pdf":_})),l({status:"ready",kind:v,contentType:_,url:d,partial:!1});return}await((p=g.body)==null?void 0:p.cancel().catch(()=>{})),u.signal.aborted||l({status:"ready",kind:"binary",contentType:_,partial:!1})}catch(g){u.signal.aborted||l({status:"error",kind:f,message:String((g==null?void 0:g.message)||g)})}})(),()=>{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,s]),o}function om(e){const{markdownImages:t,inlineImage:n,renderMarkdown:s,...o}=e;return a.jsx(jN,{...o,nowMs:e.nowMs??Date.now(),renderMarkdown:s||(l=>a.jsx(l_,{text:l,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}function hC(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:h_(e.total)}:{}}}function Gi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Or(e){return typeof e=="string"?e.trim():""}function mC(e){var o;const t=Gi(e);if(!t)return null;const n=Gi(t.sandbox);if(n&&Or(n.kind))return n;const s=Gi((o=Gi(t.output))==null?void 0:o.sandbox);return s&&Or(s.kind)?s:null}function Ny(e){const t=mC(e);if(!t)return null;const n=Or(t.kind),s=Or(t.label)||n,o=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:s,line:`Sandbox: ${s} — refused`,rows:[],builtinRefused:0};const l=[],u=Or(t.private_workspace);u&&l.push({path:u,mode:"Read & write",private:!0});for(const f of Array.isArray(t.allowed)?t.allowed:[]){const m=Gi(f),p=Or(m==null?void 0:m.path);p&&l.push({path:p,mode:Or(m==null?void 0:m.mode)==="ro"?"Read-only":"Read & write"})}for(const f of Array.isArray(t.refused)?t.refused:[]){const m=Or(f);m&&l.push({path:m,mode:"Refused"})}if(n==="unsandboxed")return{state:"unsandboxed",kind:n,label:s,line:`Sandbox: ${s}`,rows:[],builtinRefused:0};const d=l.length;return{state:"sandboxed",kind:n,label:s,line:`Sandbox: ${s} · ${d} ${d===1?"workspace":"workspaces"} enforced`,rows:l,builtinRefused:o}}function pC({sandbox:e,className:t}){return e?a.jsxs("div",{className:`pc-tool-sandbox is-${e.state}${t?` ${t}`:""}`,"data-sandbox-kind":e.kind,children:[a.jsx("div",{className:"pc-tool-sandbox__line",children:e.line}),e.rows.length?a.jsxs("ul",{className:"pc-tool-sandbox__rows","aria-label":"Workspaces the sandbox enforced",children:[e.rows.map((n,s)=>a.jsxs("li",{children:[a.jsx("code",{children:n.path}),a.jsx("span",{className:"pc-tool-sandbox__mode",children:n.private?`${n.mode} · this run's folder`:n.mode})]},`${n.mode}:${n.path}:${s}`)),e.builtinRefused?a.jsxs("li",{className:"pc-tool-sandbox__builtin",children:[e.builtinRefused," built-in protected ",e.builtinRefused===1?"folder":"folders"," refused"]}):null]}):null]}):null}const Lf=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,Fn=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"";function gC(e){const t=Fn(e==null?void 0:e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=Lf(e==null?void 0:e.policy),s=Lf(n==null?void 0:n.set_by),o=Fn(s==null?void 0:s.user_id)||Fn(s==null?void 0:s.client),l=typeof(n==null?void 0:n.revision)=="number"?n.revision:void 0,u={decision:t,...Fn(e==null?void 0:e.source)?{source:Fn(e==null?void 0:e.source)}:{},...l!==void 0?{revision:l}:{},...o?{setBy:o}:{},...Fn(n==null?void 0:n.set_at)?{setAt:Fn(n==null?void 0:n.set_at)}:{}},d=(Array.isArray(e==null?void 0:e.tool_calls)?e.tool_calls:[]).map(f=>Lf(f)).filter(f=>!!(f&&Fn(f.call_id))).map(f=>({callId:Fn(f.call_id),name:Fn(f.name),...Fn(f.matched)?{matched:Fn(f.matched)}:{}}));return d.length?{provenance:u,calls:d}:null}function fu(e){if(e.decision==="denied")return"Denied by this chat's policy";const t=e.setAt?Mo(e.setAt):"",s=[e.setBy?`set by ${e.setBy}`:"",t?`at ${t}`:""].filter(Boolean).join(" ");return`Allowed by this chat's policy${s?` (${s})`:""}`}function Cy(e){const t=new Map;for(const n of e||[]){const s=Fn(n==null?void 0:n.name);if(!s)continue;const o=Fn(n==null?void 0:n.reason).replace(/_/g," ")||"not stored";t.set(o,[...t.get(o)||[],s])}return t.size?`Not covered: ${[...t].map(([n,s])=>`${s.join(", ")} (${n})`).join("; ")}`:""}function m_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function p_(e){const t=m_(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};const n=Object.entries(t),o=["command","query","url","file_path","path","pattern","name"].map(l=>n.find(([u])=>u===l)).find(Boolean)||n[0];return o?{label:o[0].replace(/_/g," "),value:typeof o[1]=="string"?o[1]:JSON.stringify(o[1])??""}:{label:"",value:""}}function g_({tool:e,showCopy:t=!0}){const[n,s]=y.useState(!1),o=m_(e.arguments),l=p_(e.arguments),u=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.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,f={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},m=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,p=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o):null;return a.jsxs("details",{className:`pc-tool-activity pc-tool-activity--${e.status}`,children:[a.jsxs("summary",{className:"pc-tool-activity__summary",children:[a.jsx("span",{className:"pc-tool-activity__state-icon","aria-hidden":"true",children:a.jsx(de,{name:e.status==="completed"?"check":e.status==="failed"?"x":e.status==="waiting"?"warning":"loader",size:15})}),a.jsx("strong",{children:e.name}),a.jsx("span",{className:"pc-tool-activity__preview",title:l.value,children:l.value?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"pc-tool-activity__key",children:l.label}),u]}):"No parameters"}),a.jsx("span",{className:"pc-tool-activity__status",children:f[e.status]}),e.policy?a.jsx("span",{className:"pc-tool-activity__policy","data-policy":e.policy.decision,title:fu(e.policy),children:e.policy.decision==="denied"?"Denied by this chat's policy":"Allowed by this chat's policy"}):null,Number.isFinite(m)&&m>=0?a.jsxs("span",{className:"pc-tool-activity__duration",children:[(m/1e3).toFixed(1),"s"]}):null,a.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:a.jsx(de,{name:"chevronRight",size:13})}),e.error?a.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:d}):null]}),a.jsxs("div",{className:"pc-tool-activity__detail",children:[e.policy?a.jsxs("p",{className:"pc-tool-activity__policy-line","data-policy":e.policy.decision,children:[fu(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,a.jsx(pC,{sandbox:e.sandbox}),e.error?a.jsxs(a.Fragment,{children:[a.jsx("h4",{children:"Error"}),a.jsx("pre",{className:"pc-tool-activity__output",children:e.error})]}):null,a.jsxs("div",{className:"pc-tool-activity__detail-heading",children:[a.jsx("h4",{children:"Parameters"}),t?a.jsxs("button",{type:"button",onClick:async()=>s(await gl(JSON.stringify(e,null,2))),children:[a.jsx(de,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?a.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([g,_])=>a.jsxs(yt.Fragment,{children:[a.jsx("dt",{children:g}),a.jsx("dd",{children:_&&typeof _=="object"?a.jsx(Co,{value:_}):a.jsx("code",{children:typeof _=="string"?_:JSON.stringify(_)})})]},g))}):e.arguments===void 0?a.jsx("p",{children:"Arguments are unavailable in this ledger."}):a.jsx(Co,{value:o}),e.output!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("h4",{children:"Result"}),typeof e.output=="string"?a.jsx("pre",{className:"pc-tool-activity__output",children:e.output}):a.jsx("div",{className:"pc-tool-activity__output",children:a.jsx(Co,{value:e.output})})]}):null]})]})}function im({tools:e,showCopy:t}){const n=s=>e.filter(o=>o.status===s).length;return a.jsxs("section",{className:"pc-tool-group","aria-label":"Tool activity",children:[a.jsxs("div",{className:"pc-tool-group__heading",children:[a.jsx(de,{name:"terminal",size:14}),a.jsx("strong",{children:"Tools"}),a.jsxs("span",{children:[e.length," ",e.length===1?"call":"calls"]}),a.jsx("div",{}),n("running")?a.jsxs("span",{className:"pc-tool-group__running",children:[n("running")," running"]}):null,n("waiting")?a.jsxs("span",{className:"pc-tool-group__waiting",children:[n("waiting")," need approval"]}):null,n("failed")?a.jsxs("span",{className:"pc-tool-group__failed",children:[n("failed")," failed"]}):null,n("completed")?a.jsxs("span",{className:"pc-tool-group__completed",children:[n("completed")," done"]}):null]}),e.map(s=>a.jsx(g_,{tool:s,showCopy:t},s.id))]})}const cn="not reported",Cn=e=>e===void 0?cn:Math.round(e).toLocaleString(),zn=e=>{if(e===void 0)return cn;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`},y_=e=>e===void 0?cn:`${Math.round(e).toLocaleString()} tok/s`,yC=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",wa=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,wC=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function vC(e){const t=new Map;for(const n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,s])=>s>1?`${n} ×${s}`:n).join(" · ")}function hu(e){const t=[],n=(e.models||[]).map(wC),s=e.providers||[];return(n.length||s.length)&&t.push([n.join(", ")||"model not reported",s.join(", ")].filter(Boolean).join(" · ")),t.push("From the run ledger; summed across this turn and its child runs."),t}function _C(e){const t=e.modelCalls||[],n=[],s=[{label:"Input",value:Cn(e.inputTokens)},{label:"Output",value:Cn(e.outputTokens)}];if(e.reasoningTokens!==void 0&&s.push({label:"Reasoning",value:Cn(e.reasoningTokens),hint:"part of output"}),s.push({label:"Total",value:Cn(e.totalTokens)}),n.push({heading:`Usage · ${wa(e.llmCalls,"model call")}`,rows:s}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,d=[{label:"Reused from cache",value:`${Cn(l)}${l+u?` (${yC(l,l+u)})`:""}`},{label:"Newly processed",value:Cn(e.fedTokens)},{label:"Outcome",value:vC(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||cn},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||cn}];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:cn}]});const o=t.filter(l=>l.inputTokens!==void 0);return o.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${Cn(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Cn(o[0].inputTokens)} → ${Cn(o[o.length-1].inputTokens)} tokens`}],note:"Each call re-sends the conversation, so the input total counts the context once per call."}),t.length>1&&n.push({heading:"Per call",table:{columns:["#","Input","Cached","New","Output","Cache"],rows:t.map((l,u)=>[String(u+1),Cn(l.inputTokens),l.cachedTokens===void 0?"—":Cn(l.cachedTokens),l.fedTokens===void 0?"—":Cn(l.fedTokens),Cn(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?cn:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:hu(e)}}function zc(e,t,n,s){if(e===void 0)return cn;const o=[zn(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${s}${n!==void 0?` at ${y_(n)}`:""}`),o.join(" · ")}function bC(e){var m,p,g;const t=e.modelCalls||[],n=[],s=e.durationMs,o=[{label:"Wall clock",value:zn(s)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?cn:`${zn(e.genTimeMs)} · ${wa(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${zn(e.toolTimeMs)} · ${wa(e.toolBatches||0,"batch","batches")}`:e.toolCalls?cn:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),s!==void 0&&e.genTimeMs!==void 0){const _=s-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:_>=0?zn(_):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:o});const l=[],u=e.ttftCalls||0,d=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?l.push({label:u&&u===d?"Prefill (TTFT)":"Prefill",value:zc(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?l.push({label:"Prefill",value:zc(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${zn(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${y_(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:cn}),e.cachedTokens&&(e.promptPhaseMs??e.prefillMs)!==void 0&&l.push({label:"Restored",value:`${e.cachedTokens.toLocaleString()} tok from cache`,hint:"not recomputed"}),l.push({label:"Generation",value:e.generationPhaseMs!==void 0?zc(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):zc(e.decodeMs,e.outputTokens,e.generationTokensPerSecond,"tok")}),e.measuredSpeedCalls&&e.measuredSpeedCalls!==e.llmCalls&&l.push({label:"Speeds from",value:`${e.measuredSpeedCalls} of ${e.llmCalls} calls`}),n.push({heading:"Model",rows:l});const f=e.speculation;if(f){const _=(f.draftKinds||[]).map(C=>C.toUpperCase()).join(", "),v=[{label:"Mode",value:`${f.used?"on":"off"}${_?` · ${_}`:""}${(m=f.modes)!=null&&m.length?` (${f.modes.join(", ")})`:""}`,hint:f.calls!==e.llmCalls||f.used!==f.calls?`used on ${f.used} of ${e.llmCalls} calls`:void 0},{label:"Acceptance",value:f.acceptanceRate===void 0?cn:`${Math.round(f.acceptanceRate*100)}% · ${Cn(f.acceptedTokens)} of ${Cn(f.draftedTokens)} drafted`}];((p=f.draftLengths)!=null&&p.length||f.rounds!==void 0)&&v.push({label:"Draft length",value:`${(g=f.draftLengths)!=null&&g.length?`${f.draftLengths.join("/")} tok/round`:cn}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:v})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${zn(e.toolTimeMs)} · ${wa(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${zn(e.slowestToolBatch.ms)} · ${w_(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((_,v)=>[String(v+1),_.promptMs===void 0?"—":`${zn(_.promptMs)}${_.promptSource==="rate"?"*":""}`,_.promptNewTokensPerSecond===void 0?"—":Math.round(_.promptNewTokensPerSecond).toLocaleString(),_.generationMs===void 0?"—":zn(_.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:s===void 0?cn:`${zn(s)} wall clock`,sections:n,footer:hu(e)}}function w_(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${wa(e.calls,"call")} (${e.tools.join(", ")})`}function xC(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:hu(e)};const s=[{label:"Succeeded",value:(e.toolCalls-(e.toolsFailed||0)).toLocaleString()},{label:"Failed",value:(e.toolsFailed||0).toLocaleString()}];e.toolsRunning&&s.push({label:"Running",value:e.toolsRunning.toLocaleString()}),e.toolsWaiting&&s.push({label:"Awaiting approval",value:e.toolsWaiting.toLocaleString(),hint:"not run yet — not a failure"}),t.push({heading:"Outcome",rows:s});const o=Object.entries(e.toolBreakdown||{}).sort((d,f)=>f[1].calls-d[1].calls||d[0].localeCompare(f[0]));o.length&&t.push({heading:"By tool",table:{columns:["Tool","Calls","Failed","Time"],rows:o.map(([d,f])=>[d,f.calls.toLocaleString(),f.failed.toLocaleString(),f.ms!==void 0?`${zn(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":cn])},note:o.some(([,d])=>d.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});const l=o.filter(([,d])=>d.errors&&Object.keys(d.errors).length);l.length&&t.push({heading:"Failures",rows:l.map(([d,f])=>({label:d,value:Object.entries(f.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?cn:`${zn(e.toolTimeMs)} · ${wa(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${zn(e.slowestToolBatch.ms)} · ${w_(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:`${wa(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:hu(e)}}function Mf(e,t){return e==="tokens"?_C(t):e==="time"?bC(t):xC(t)}function kC(e){const t=e.detail;return a.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:[a.jsxs("div",{className:"pc-stat-detail-head",children:[a.jsx("span",{className:"pc-stat-detail-title",children:t.title}),a.jsx("span",{className:"pc-stat-detail-headline",children:t.headline})]}),t.sections.map(n=>{var s;return a.jsxs("div",{className:"pc-stat-detail-section",children:[a.jsx("div",{className:"pc-stat-detail-heading",children:n.heading}),(s=n.rows)!=null&&s.length?a.jsx("dl",{className:"pc-stat-detail-rows",children:n.rows.map(o=>a.jsxs(yt.Fragment,{children:[a.jsx("dt",{children:o.label}),a.jsxs("dd",{children:[a.jsx("span",{className:o.value===cn?"pc-stat-detail-value pc-stat-detail-value--absent":"pc-stat-detail-value",children:o.value}),o.hint?a.jsx("span",{className:"pc-stat-detail-hint",children:o.hint}):null]})]},o.label))}):null,n.table?a.jsxs("table",{className:"pc-stat-detail-table",children:[a.jsx("thead",{children:a.jsx("tr",{children:n.table.columns.map(o=>a.jsx("th",{scope:"col",children:o},o))})}),a.jsx("tbody",{children:n.table.rows.map((o,l)=>a.jsx("tr",{children:o.map((u,d)=>a.jsx("td",{children:u},d))},l))})]}):null,n.note?a.jsx("p",{className:"pc-stat-detail-note",children:n.note}):null]},n.heading)}),a.jsx("div",{className:"pc-stat-detail-foot",children:t.footer.map(n=>a.jsx("div",{children:n},n))})]})}const tr=8;function SC(e){const[t,n]=y.useState(!!e.defaultOpen),[s,o]=y.useState(null),l=y.useRef(null),u=y.useRef(null),d=y.useRef(null),f=`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]),g=y.useCallback(()=>{m(),d.current=window.setTimeout(()=>n(!1),120)},[m]);y.useEffect(()=>m,[m]),y.useLayoutEffect(()=>{if(!t){o(null);return}const x=()=>{const k=l.current,S=u.current;if(!k||!S)return;const $=k.getBoundingClientRect(),R=S.offsetWidth,N=S.offsetHeight,E=window.innerWidth,j=window.innerHeight,I=$.top-tr-N,L=$.bottom+tr,z=I>=tr?I:L+N<=j-tr?L:Math.max(tr,j-tr-N),V=Math.min(Math.max(tr,$.left),Math.max(tr,E-tr-R));o({top:z,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=k=>{k.key==="Escape"&&n(!1)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t]);const _=typeof e.onClick=="function",v=_?"button":"span",C=t?a.jsx(kC,{detail:e.detail,id:f,panelRef:u,onMouseEnter:m,onMouseLeave:g,style:{position:"fixed",top:(s==null?void 0:s.top)??0,left:(s==null?void 0:s.left)??0,visibility:s?"visible":"hidden"}}):null;return a.jsxs(a.Fragment,{children:[a.jsxs(v,{ref:l,..._?{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?f:void 0,"data-stat-kind":e.detail.kind,onMouseEnter:p,onMouseLeave:g,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?a.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:e.icon}):null,a.jsx("span",{className:"pc-chat-stat-label",children:e.label})]}),C&&typeof document<"u"?il.createPortal(C,document.body):C]})}function jC(e){const t=e.totalTokens!==void 0?Mf("tokens",e):null,n=Mf("tools",e),s=e.durationMs!==void 0?Mf("time",e):null;return[...t?[{label:`${e.totalTokens.toLocaleString()} tokens`,detail:t}]:[],{label:`${e.toolCalls} ${e.toolCalls===1?"tool":"tools"}`,detail:n},...e.changedFiles.length?[{label:`${e.changedFiles.length} ${e.changedFiles.length===1?"file":"files"} changed`,title:e.changedFiles.join(`
78
- `)}]:[],...s?[{label:`${(e.durationMs/1e3).toFixed(e.durationMs<1e4?1:0)}s`,detail:s}]:[]]}function NC(e){const t=String(e.role||"").trim().toLowerCase()||"system",n=String(e.kind||"").trim().toLowerCase(),s=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()||(s==="error"?"Error":s==="warn"?"Warning":"System"),icon:s==="error"?"error":s==="warn"?"warning":"info",variant:s==="error"?"error":s==="warn"?"warn":"status"}}const CC=new Set(["blob:","data:","http:","https:"]);function mu(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return CC.has(new URL(t,n).protocol)?t:void 0}catch{return}}function v_(e,t){return u_(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function EC({item:e,onOpen:t,markdown:n}){const[s,o]=y.useState(!1),l=mu(e.src),u=String(e.name||e.label||"").trim()||"File",d=oC({href:e.href?mu(e.href):void 0,src:l,contentType:e.contentType,name:e.name||e.label}),f=al(u,e.contentType),m=iu(f),p=typeof e.text=="string";if(!l&&!d&&!p)return null;const g=ml(e.size),_=String(e.label||"").trim()||u;return a.jsxs("figure",{className:"pc-chat-media__item pc-chat-media__item--file","data-file-kind":f,children:[a.jsxs("div",{className:"pc-chat-media__file-row",children:[a.jsx(de,{name:"file",size:14}),a.jsx("span",{className:"pc-chat-media__file-name",title:u,children:_}),g?a.jsx("span",{className:"pc-chat-media__file-size",children:g}):null,t?a.jsx("button",{type:"button",className:"pc-chat-media__file-open","data-action":"open-file",onClick:()=>t({...e,src:l||"",...d?{href:d}:{href:void 0}}),children:"Open"}):a.jsx("button",{type:"button",className:"pc-chat-media__file-open","data-action":"toggle-file","aria-expanded":s,onClick:()=>o(v=>!v),children:s?"Close":"Open"}),d?a.jsx("a",{className:"pc-chat-media__link",...v_(d,String(e.name||"").trim()||_),children:"Raw file"}):null]}),s&&!t?a.jsx(om,{className:"pc-chat-media__viewer",name:u,kind:f,contentType:e.contentType,sizeBytes:e.size,status:m&&!p?"error":"ready",error:m&&!p?d?"No preview text was supplied for this file; open the raw file.":"No preview text was supplied for this file.":void 0,markdownImages:n.images||"link",...n.inlineImage?{inlineImage:n.inlineImage}:{},...n.renderMarkdown?{renderMarkdown:n.renderMarkdown}:{},...p?{text:e.text}:{},...l&&!m?{url:l}:{},onClose:()=>o(!1)}):null]})}function AC({item:e,onOpenFile:t,markdown:n}){const[s,o]=y.useState(!1);if(e.kind==="file")return a.jsx(EC,{item:e,onOpen:t,markdown:n||{}});const l=mu(e.src),u=e.href?mu(e.href):void 0,d=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!d||!l&&!u)return null;const f=d==="image"?"Image":d==="video"?"Video":"Audio",m=String(e.label||"").trim()||`Generated ${f.toLowerCase()}`,p=()=>o(!0);return a.jsxs("figure",{className:`pc-chat-media__item pc-chat-media__item--${d}`,children:[l&&d==="image"?a.jsx("img",{className:"pc-chat-media__image",src:l,alt:m,loading:"lazy",onError:p}):null,l&&d==="video"?a.jsx("video",{className:"pc-chat-media__video",src:l,controls:!0,playsInline:!0,preload:"metadata","aria-label":m,onError:p}):null,l&&d==="audio"?a.jsx(Bv,{className:"pc-chat-media__audio",src:l,name:m}):null,d==="audio"&&String(e.transcript||"").trim()?a.jsxs("details",{className:"pc-chat-media__transcript",children:[a.jsx("summary",{children:"Transcript"}),a.jsx("p",{className:"pc-chat-media__transcript-text",children:String(e.transcript).trim()})]}):null,s?a.jsxs("div",{className:"pc-chat-media__error",role:"note",children:[f," could not be decoded by this browser",u?"; open the raw file with the link.":"."]}):null,u?a.jsx("figcaption",{className:"pc-chat-media__caption",children:a.jsx("a",{className:"pc-chat-media__link",...v_(u,String(e.name||"").trim()||m),children:m})}):null]})}function __(e){var j,I;const t=e.message,n=y.useMemo(()=>NC(t),[t.kind,t.level,t.role,t.title]),s=String(t.ts||"").trim(),o=y.useMemo(()=>{if(!s)return"";const L=new Date(s);return Number.isFinite(L.getTime())?L.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""},[s]),[l,u]=y.useState("idle"),d=y.useRef(null);y.useEffect(()=>()=>{d.current!==null&&window.clearTimeout(d.current)},[]);const f=t.live,m=!f&&typeof e.onSpeakToggle=="function"&&n.variant==="assistant"&&!!String(t.content||"").trim(),p=m&&((j=e.getSpeakState)==null?void 0:j.call(e,t))||"idle",g=p==="loading"?"loader":p==="playing"?"pause":"speaker",_=p==="loading"?"Generating audio…":p==="playing"?"Pause":p==="paused"?"Resume":"Speak (TTS)",v=e.showCopy!==!1,C=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],x=t.statistics,k=t.stats,S=y.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(k)?k:x?jC(x):[],[e.stats,k,x]),$=Array.isArray(t.media)?t.media:[],R=String(f?f.reasoning||"":t.reasoning||""),N=!!String(t.content||"").trim();if(t.toolActivity)return a.jsx(g_,{tool:t.toolActivity,showCopy:e.showCopy});const E=e.renderFooter?e.renderFooter(t):null;if(((I=e.variant)==null?void 0:I.call(e,t))==="hint"||t.kind==="tool_policy_decision"){const L=String(t.level||"").trim().toLowerCase();return a.jsxs("div",{className:["pc-chat-hint",L==="warn"||L==="error"?`pc-chat-hint--${L}`:"",e.className].filter(Boolean).join(" "),role:"note","data-variant":"hint",children:[a.jsx("span",{className:"pc-chat-hint__text",children:String(t.content||"")}),E!=null&&E!==!1?a.jsx("div",{className:"pc-chat-footer",children:E}):null]})}return a.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,f?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...f?{"aria-busy":!0}:{},children:[a.jsxs("div",{className:"pc-chat-header",children:[a.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:a.jsx(de,{name:n.icon,size:14})}),a.jsx("span",{className:"pc-chat-role",children:n.label}),f?a.jsxs("span",{className:"pc-chat-live-indicator",title:f.label?`Pending: ${f.label}`:"The reply is still being written",children:[a.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),f.label||"streaming"]}):null,f!=null&&f.caption?a.jsx("span",{className:"pc-chat-live-caption",children:f.caption}):null,a.jsx("span",{className:"pc-chat-header-spacer"}),o?a.jsx("span",{className:"pc-chat-time",children:o}):null,a.jsxs("div",{className:"pc-chat-header-actions",children:[m?a.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":_,title:_,onClick:()=>{var L;return(L=e.onSpeakToggle)==null?void 0:L.call(e,t)},children:a.jsx(de,{name:g,size:22,className:p==="loading"?"pc-chat-speak-spinner":void 0})}):null,v?a.jsx("button",{className:`pc-chat-icon-btn ${l!=="idle"?`pc-chat-icon-btn--${l}`:""}`.trim(),type:"button","aria-label":"Copy message",title:l==="idle"?"Copy":l==="copied"?"Copied":"Copy failed",onClick:async()=>{const L=await gl(String(t.content||""));u(L?"copied":"failed"),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>u("idle"),900)},children:a.jsx(de,{name:"copy",size:22})}):null]})]}),R.trim()?a.jsxs("details",{className:"pc-chat-thinking",children:[a.jsx("summary",{children:"Thinking"}),a.jsx("div",{className:"pc-chat-thinking-body",children:R})]}):null,N||!f&&!$.length?a.jsx("div",{className:"pc-chat-body",children:a.jsx(c_,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,$.length?a.jsx("div",{className:"pc-chat-media",children:$.slice(0,24).map((L,z)=>a.jsx(AC,{item:L,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},L.id||`${L.kind}:${L.src}:${z}`))}):null,C.length?a.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:C.slice(0,24).map((L,z)=>{const V=String(L.label||"").trim()||"attachment",Z=String(L.target||"").trim(),ie=String(L.title||"").trim(),F=!!L.disabled||typeof L.onClick!="function";return a.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:ie||V,onClick:F?void 0:L.onClick,disabled:F,children:[a.jsx(de,{name:"paperclip",size:14}),Z?a.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${Z}`,children:Z}):null,a.jsx("span",{className:"pc-chat-attachment-name",children:V})]},L.id||`${V}:${z}`)})}):null,S.length?a.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:S.slice(0,12).map((L,z)=>{const V=String(L.label||"").trim();if(!V)return null;if(L.detail)return a.jsx(SC,{label:V,detail:L.detail,icon:L.icon,onClick:L.onClick},L.id||`${V}:${z}`);const Z=String(L.title||"").trim(),ie=typeof L.onClick=="function",F=ie?"button":"span";return a.jsxs(F,{...ie?{type:"button"}:{},className:["pc-chat-stat",ie?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:Z||void 0,onClick:ie?()=>{var D;return(D=L.onClick)==null?void 0:D.call(L)}:void 0,children:[L.icon?a.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:L.icon}):null,a.jsx("span",{className:"pc-chat-stat-label",children:V})]},L.id||`${V}:${z}`)})}):null,E!=null&&E!==!1?a.jsx("div",{className:"pc-chat-footer",children:E}):null]})}function $C(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function b_(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,s=y.useRef(null),o=y.useRef(null),[l,u]=y.useState(!0),d=y.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=y.useMemo(()=>{var g;const p=[];for(const _ of d){const v=p[p.length-1];_.toolActivity&&((g=v==null?void 0:v[0])!=null&&g.toolActivity)&&v[0].runId===_.runId?v.push(_):p.push([_])}return p},[d]);y.useEffect(()=>{if(!n)return;const p=s.current;if(!p)return;const g=()=>{u($C(p,t))};return p.addEventListener("scroll",g,{passive:!0}),g(),()=>p.removeEventListener("scroll",g)},[n,t]);const m=y.useMemo(()=>{let p=0;for(const g of d)if(p+=String(g.content??"").length,Array.isArray(g.media))for(const _ of g.media)p+=String((_==null?void 0:_.src)??"").length+1;return`${d.length}:${p}:${String(e.afterKey??"")}`},[d,e.afterKey]);return y.useEffect(()=>{if(!n||!l)return;const p=s.current;p&&(p.scrollTop=p.scrollHeight)},[n,l,m]),y.useEffect(()=>{if(!n)return;const p=s.current;if(!p)return;const g=()=>{l&&(p.scrollTop=p.scrollHeight)};return p.addEventListener("load",g,!0),p.addEventListener("loadedmetadata",g,!0),()=>{p.removeEventListener("load",g,!0),p.removeEventListener("loadedmetadata",g,!0)}},[n,l]),a.jsxs("div",{ref:s,className:["pc-chat-thread",e.className].filter(Boolean).join(" "),children:[d.length?null:e.empty||null,f.map((p,g)=>{var C;const _=p[0],v=String(_.id||"")||String(_.ts||"")+":"+String(_.role||"")+":"+g;return _.toolActivity?a.jsx(im,{tools:p.map(x=>x.toolActivity),showCopy:(C=e.messageProps)==null?void 0:C.showCopy},v):a.jsx(__,{message:_,...e.messageProps||{}},v)}),e.after,a.jsx("div",{ref:o})]})}const x_=yt.forwardRef(function(t,n){const s=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):3,o=!!t.disabled,l=!!t.busy,u=!o&&!l&&!!String(t.value||"").trim();return a.jsxs("div",{className:["pc-composer",t.className].filter(Boolean).join(" "),children:[t.leading,a.jsx("textarea",{ref:n,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:d=>t.onChange(d.target.value),rows:s,style:{"--pc-composer-rows":String(s)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message",disabled:o,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:d=>{d.key!=="Enter"||d.shiftKey||d.nativeEvent.isComposing||d.keyCode===229||(d.preventDefault(),u&&t.onSubmit())}}),a.jsxs("div",{className:"pc-composer__row",children:[a.jsx("div",{className:"pc-composer__actions",children:t.actions}),a.jsx("button",{type:"button",className:t.sendButtonClassName||"pc-btn",disabled:!u,onClick:()=>t.onSubmit(),children:l?t.busyLabel||"Thinking…":t.sendLabel||"Send"})]}),t.overlay]})});function Hi(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function Ey(e){var s;const t=e==null?void 0:e.items;if(!t||!t.length)return null;let n=0;for(let o=0;o<t.length;o+=1)((s=t[o])==null?void 0:s.kind)==="file"&&(n+=1);return n>0?n:null}function Ay(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function lm(e){const t=[],n=[],s=e==null?void 0:e.items;if(s&&s.length){for(let l=0;l<s.length;l+=1){const u=s[l];if(!u||u.kind!=="file")continue;const d=typeof u.webkitGetAsEntry=="function"?u.webkitGetAsEntry():null,f=typeof u.getAsFile=="function"?u.getAsFile():null;d!=null&&d.isDirectory?n.push(d.name||(f==null?void 0:f.name)||"folder"):f&&t.push(f)}return{files:t,folders:n}}const o=e==null?void 0:e.files;if(o)for(let l=0;l<o.length;l+=1)o[l]&&t.push(o[l]);return{files:t,folders:n}}function k_(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 TC={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Li(e){return String(e).padStart(2,"0")}function RC(e,t,n){const s=String(e||"").trim();if(s&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(s))return s;const o=TC[String(t||"").toLowerCase()]||s.split(".").pop()||"bin",l=`${n.getFullYear()}-${Li(n.getMonth()+1)}-${Li(n.getDate())} at ${Li(n.getHours())}.${Li(n.getMinutes())}.${Li(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!s?"Pasted image":"Pasted file"} ${l}.${o}`}function S_(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:s}=lm(e);return s.map(o=>{const l=RC(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class IC{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 Ki="llm.delta",vo="llm.delta_end";function LC(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ha(e){return typeof e=="string"&&e.trim()!==""}function MC(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function j_(e){return"reason"in e}function N_(e,t){const n=LC(e),s=n==null?void 0:n.kind,o=t||(typeof s=="string"&&s?s:n&&"reason"in n?vo:Ki),l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(t!==void 0&&t!==Ki&&t!==vo&&l(`unknown event name ${JSON.stringify(t)}`),!n)return l("the payload is not an object");s!==void 0&&s!==Ki&&s!==vo&&l(`unknown kind ${JSON.stringify(s)}`),s!==void 0&&t!==void 0&&s!==t&&l(`kind ${JSON.stringify(s)} does not match the event name`),ha(n.run_id)||l("run_id is missing"),ha(n.call_id)||l("call_id is missing"),MC(n.seq)||l("seq is not a non-negative integer");const u=t||s?(t||s)===vo:"reason"in n;n.root_run_id!==void 0&&!ha(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ha(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const d={run_id:n.run_id,...ha(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ha(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))||l(`unknown reason ${JSON.stringify(n.reason)}`),n.detail!==void 0&&n.detail!==null&&typeof n.detail!="string"&&l("detail is not a string"),{kind:vo,...d,reason:n.reason,...ha(n.detail)?{detail:n.detail}:{}}):(typeof n.text!="string"&&l("text is not a string"),n.channel!=="content"&&n.channel!=="reasoning"&&l(`unknown channel ${JSON.stringify(n.channel)}`),typeof n.snapshot!="boolean"&&l("snapshot is not a boolean"),{kind:Ki,...d,text:n.text,channel:n.channel,snapshot:n.snapshot})}function C_(e,t){if(e!==Ki&&e!==vo)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 N_(n,e)}function OC(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 PC={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 DC(e){return`This reply is not streamed: ${e?PC[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const cm=e=>we(`runs/${encodeURIComponent(e)}/workspace`);function FC(e){return cm(e)}function zC(e,t){return`${cm(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function E_(e,t){return`${cm(e)}/content?${new URLSearchParams({path:t})}`}async function Do(e,t){let n="";try{const s=await e.text();try{const o=JSON.parse(s),l=(o==null?void 0:o.detail)??(o==null?void 0:o.error)??(o==null?void 0:o.message);n=typeof l=="string"?l:l&&typeof l.message=="string"?l.message:s}catch{n=s}}catch{n=""}return new Error(`${t} (HTTP ${e.status}): ${n.trim()||e.statusText||"no reason given"}`)}function BC(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:null,s=u=>{throw new Error(`Unexpected /workspace/files response from the gateway: ${u}.`)};if(!n)return s("not an object");Array.isArray(n.entries)||s("no `entries` list"),typeof n.truncated!="boolean"&&s("no `truncated` flag");const o=n.entries.map((u,d)=>{const f=u&&typeof u=="object"?u:{};return(typeof f.name!="string"||typeof f.path!="string"||f.type!=="file"&&f.type!=="dir")&&s(`entry ${d+1} lacks a name, path or file/dir type`),f}),l=n.hidden&&typeof n.hidden=="object"&&!Array.isArray(n.hidden)?n.hidden:void 0;return{path:typeof n.path=="string"?n.path:t,entries:o,truncated:n.truncated,...l?{hidden:l}:{}}}async function WC(e,t,n){const s=await e(FC(t),{signal:n});if(!s.ok)throw await Do(s,"The workspace is not available");const o=await s.json();if(!o||typeof o.workspace_root!="string"||typeof o.exists!="boolean")throw new Error("Unexpected /workspace response from the gateway: no `workspace_root` / `exists`.");return o}async function UC(e,t,n,s){const o=await e(zC(t,n),{signal:s});if(!o.ok)throw await Do(o,"The folder could not be listed");return BC(await o.json(),n)}async function VC(e,t,n,s){const o=await e(E_(t,n),{signal:s});if(!o.ok)throw await Do(o,"The file could not be read");return await o.blob()}async function GC(e,t,n,s){const o=await WC(e,t,s);return{where:o,listing:o.exists?await UC(e,t,n,s):null}}function HC(e){const t=String(e||"").split("/").filter(Boolean),n=[{label:"Workspace",path:""}];return t.forEach((s,o)=>n.push({label:s,path:t.slice(0,o+1).join("/")})),n}function pu(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,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n<10?n.toFixed(1):Math.round(n)} ${t[s]}`}function KC(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function JC(e){const t=e.hidden||{},n=Number(t.blocked||0)+Number(t.outside_links||0)+Number(t.other||0),s=[];return n>0&&s.push(`${n} ${n===1?"entry":"entries"} hidden by the gateway's workspace rules`),e.truncated&&s.push("the list is truncated"),s.join("; ")}const qC=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function YC(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return qC.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 A_(e,t,n){const s=n==="open"?YC(e.type):{mode:"download"},o=s.mode==="open"&&s.type!==e.type?new Blob([e],{type:s.type}):e,l=URL.createObjectURL(o);if(s.mode==="open")window.open(l,"_blank","noopener");else{const u=document.createElement("a");u.href=l,u.download=t,document.body.appendChild(u),u.click(),u.remove()}window.setTimeout(()=>URL.revokeObjectURL(l),6e4)}async function QC(e,t,n){const s=await e(Qx(t),{signal:n.signal});if(!s.ok)throw await Do(s,`${n.name} could not be read`);A_(await s.blob(),n.name,n.mode??"open")}function XC(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function ZC(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 eE(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function um(e){var ie;const{fetchGateway:t,runId:n}=e,[s,o]=y.useState({runId:n,path:""}),l=s.runId===n?s.path:"",[u,d]=y.useState(null),[f,m]=y.useState(""),[p,g]=y.useState(""),[_,v]=y.useState(!!n),[C,x]=y.useState(""),[k,S]=y.useState(!1),[$,R]=y.useState(0),[N,E]=y.useState(null),j=N&&N.runId===n&&!e.onSelectFile?N.entry:null,I=fC(t,n,j,`${e.refreshKey??""}:${$}`);y.useEffect(()=>{if(!n)return;const F=new AbortController;return v(!0),m(""),(async()=>{try{const D=await GC(t,n,l,F.signal);F.signal.aborted||d({runId:n,...D})}catch(D){F.signal.aborted||m(String((D==null?void 0:D.message)||D))}finally{F.signal.aborted||v(!1)}})(),()=>F.abort()},[t,n,l,$,e.refreshKey]),y.useEffect(()=>g(""),[n]);const L=u&&u.runId===n?u:null,z=y.useCallback(async F=>{x(F.path),m("");try{A_(await VC(t,n,F.path),F.name,"download")}catch(D){m(String((D==null?void 0:D.message)||D))}finally{x("")}},[t,n]),V=(L==null?void 0:L.where.workspace_root)||"",Z=e.nowMs??Date.now();return a.jsx(tE,{title:e.title,note:e.note,where:(L==null?void 0:L.where)??null,path:l,listing:(L==null?void 0:L.listing)??null,error:f,notice:p,loading:_,fileBusy:C,selectedPath:e.onSelectFile?e.selectedPath:j==null?void 0:j.path,className:e.className,nowMs:Z,openingFolder:k,onNavigate:F=>{E(null),o({runId:n,path:F})},onRefresh:()=>R(F=>F+1),onFile:F=>void z(F),onSelectFile:e.onSelectFile??(F=>E({runId:n,entry:F})),onClose:e.onClose,onCopyPath:V?()=>{(e.copyText||eE)(V).then(F=>g(F?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&ZC(L==null?void 0:L.where)?()=>{S(!0),g(""),e.onOpenFolder().then(()=>g("Folder opened on this machine.")).catch(F=>g(`Open folder failed: ${String((F==null?void 0:F.message)||F)}`)).finally(()=>S(!1))}:void 0,preview:j?a.jsx(om,{name:j.name,path:j.path,sizeBytes:j.size_bytes,modified:j.mtime,nowMs:Z,...hC(I),actions:(ie=e.fileActions)==null?void 0:ie.call(e,j),onDownload:()=>void z(j),onClose:()=>E(null)}):null})}function tE(e){var l,u,d,f;const t=e.listing?JC(e.listing):"",n=(u=(l=e.where)==null?void 0:l.host)==null?void 0:u.hostname,s=((d=e.where)==null?void 0:d.workspace_root)||"",o=e.nowMs??Date.now();return a.jsxs("section",{className:`pc-ws${e.className?` ${e.className}`:""}`,"aria-label":e.title,"data-workspace-root":s||void 0,children:[a.jsxs("header",{className:"pc-ws__head",children:[a.jsxs("span",{className:"pc-ws__title",children:[a.jsx(de,{name:"folder",size:15})," ",e.title]}),a.jsx("span",{className:"pc-ws__spacer"}),a.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:a.jsx(de,{name:"refresh",size:14})}),e.onClose?a.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:a.jsx(de,{name:"x",size:14})}):null]}),e.where?a.jsxs("div",{className:"pc-ws__root",children:[a.jsx("span",{className:"pc-ws__root-name",title:s,"data-root-name":"true",children:XC(s)}),e.onOpenFolder?a.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:a.jsx(de,{name:"folder",size:14})}):null,e.onCopyPath?a.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:a.jsx(de,{name:"copy",size:14})}):null,n&&((f=e.where.host)==null?void 0:f.caller_is_this_machine)!==!0?a.jsxs("span",{className:"pc-ws__muted",children:[" on ",n]}):null]}):null,e.note?a.jsx("div",{className:"pc-ws__muted",children:e.note}):null,e.notice?a.jsx("div",{className:"pc-ws__muted",role:"status",children:e.notice}):null,e.error?a.jsx("div",{className:"pc-ws__error",role:"alert",children:e.error}):null,e.preview?a.jsx("div",{className:"pc-ws__preview",children:e.preview}):a.jsxs(a.Fragment,{children:[a.jsx("nav",{className:"pc-ws__crumbs","aria-label":"Folder",children:HC(e.path).map((m,p,g)=>p===g.length-1?a.jsx("span",{"aria-current":"page",children:m.label},m.path):a.jsxs(yt.Fragment,{children:[a.jsx("button",{type:"button",className:"pc-ws__crumb",onClick:()=>e.onNavigate(m.path),children:m.label}),a.jsx("span",{className:"pc-ws__muted",children:" / "})]},m.path))}),e.loading&&!e.listing?a.jsx("div",{className:"pc-ws__muted",role:"status",children:"Loading…"}):null,e.where&&!e.where.exists?a.jsx("div",{className:"pc-ws__muted",children:"The folder does not exist yet: nothing has been written."}):null,e.listing?e.listing.entries.length?a.jsx("ul",{className:"pc-ws__entries",children:KC(e.listing.entries).map(m=>a.jsx("li",{className:`pc-ws__entry${e.selectedPath===m.path?" is-selected":""}`,"data-type":m.type,"data-path":m.path,children:m.type==="dir"?a.jsxs("button",{type:"button",className:"pc-ws__name","data-action":"open-dir",onClick:()=>e.onNavigate(m.path),children:[a.jsx(de,{name:"folder",size:14})," ",a.jsxs("span",{className:"pc-ws__label",children:[m.name,"/"]})]}):a.jsxs(a.Fragment,{children:[e.onSelectFile?a.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:[a.jsx(de,{name:"file",size:14})," ",a.jsx("span",{className:"pc-ws__label",children:m.name})]}):a.jsxs("span",{className:"pc-ws__name",children:[a.jsx(de,{name:"file",size:14})," ",a.jsx("span",{className:"pc-ws__label",children:m.name})]}),a.jsxs("span",{className:"pc-ws__meta",children:[a.jsx("span",{className:"pc-ws__size",children:pu(m.size_bytes)}),m.mtime!==void 0&&$o(m.mtime,o)?a.jsx("time",{className:"pc-ws__time",title:Mo(m.mtime),"data-meta":"modified",children:$o(m.mtime,o)}):null]}),e.onFile?a.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:a.jsx(de,{name:"download",size:14})}):null]})},m.path))}):a.jsx("div",{className:"pc-ws__muted",children:"This folder is empty."}):null,t?a.jsx("div",{className:"pc-ws__muted","data-hidden-note":"true",children:t}):null]})]})}const nE={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},$_="docs";function sE(e){return we(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Of(e){return`${String(e||"app")}-docs-assistant:${Fr()}`}function rE(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}),{...nE,session_id:e.sessionId,kind:$_,input_data:t}}function T_(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 aE(e){const t=e&&typeof e=="object"?e:{},n=d=>typeof d=="number"&&Number.isFinite(d)&&d>0?Math.trunc(d):0,s=n(t.dropped_messages);if(!s)return"";const o=n(t.replayed_messages),l=n(t.dropped_tokens),u=n(t.max_tokens);return`Earlier messages not replayed: ${s.toLocaleString("en-US")}${l?` (~${l.toLocaleString("en-US")} tokens)`:""}. The model read the newest ${o.toLocaleString("en-US")} message${o===1?"":"s"}`+(u?` (history window: the most recent ${u.toLocaleString("en-US")} tokens of whole messages).`:".")}async function*oE(e,t){const n=e.getReader(),s=new TextDecoder;let o="";const l=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",l,{once:!0});try{for(;;){const{value:u,done:d}=await n.read();if(d)break;o+=s.decode(u,{stream:!0}).replace(/\r\n/g,`
79
- `);let f=o.indexOf(`
80
-
81
- `);for(;f>=0;){const m=o.slice(0,f);o=o.slice(f+2);let p="message";const g=[];for(const _ of m.split(`
82
- `))_.startsWith("event:")?p=_.slice(6).trim():_.startsWith("data:")&&g.push(_.slice(5).replace(/^ /,""));g.length&&(yield{event:p,data:g.join(`
83
- `)}),f=o.indexOf(`
84
-
85
- `)}}}finally{t==null||t.removeEventListener("abort",l)}}function iE(e,t){return new Promise((n,s)=>{if(t.aborted)return s(new DOMException("Aborted","AbortError"));const o=setTimeout(()=>{t.removeEventListener("abort",l),n()},e),l=()=>{clearTimeout(o),s(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",l,{once:!0})})}async function Dr(e,t){if(!e.ok)throw await Do(e,t);return e.json()}function lE(e){const t=e.pollMs??1e3,n=e.timeoutMs??18e4;let s=null;return async(o,l)=>{var C;const{fetchGateway:u,source:d}=e;if(s===null){const x=await u(sE(d.app),{signal:l.signal,headers:{Accept:"application/json"}}),k=await Dr(x,`The ${d.name} documentation could not be read, so nothing was asked`),S=typeof(k==null?void 0:k.text)=="string"?k.text:"";if(!S.trim())throw new Error(`The gateway returned an empty ${d.name} documentation corpus, so nothing was asked.`);s=S}const f=String(s),m=[];for(const x of l.files||[]){const k=new FormData;k.append("session_id",l.sessionId),k.append("file",x,x.name||"upload.bin"),k.append("filename",x.name||"upload.bin"),x.type&&k.append("content_type",x.type);const S=await Dr(await u(we("attachments/upload"),{method:"POST",body:k,signal:l.signal}),`"${x.name}" could not be attached`),$=S==null?void 0:S.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 Dr(await u(we("runs/start"),{method:"POST",signal:l.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(rE({question:o,docs:f,appName:d.name,sessionId:l.sessionId,attachments:m}))}),"The docs-qa workflow could not start"),g=String((p==null?void 0:p.run_id)||"");if(!g)throw new Error("The gateway did not return a run id for the docs-qa workflow.");const _=new AbortController,v=()=>_.abort();l.signal.addEventListener("abort",v,{once:!0}),l.onText&&(async()=>{var x;try{const k=await u(we(`runs/${encodeURIComponent(g)}/ledger/stream?after=0`),{signal:_.signal,headers:{Accept:"text/event-stream"}});if(!k.ok||!k.body)return;let S="",$="";for await(const R of oE(k.body,_.signal)){const N=C_(R.event,R.data);!N||j_(N)||N.channel!=="content"||N.run_id!==g||(N.call_id!==S&&(S=N.call_id,$=""),$=N.snapshot?N.text:$+N.text,(x=l.onText)==null||x.call(l,$))}}catch{}})();try{const x=Date.now()+n;for(;;){await iE(t,l.signal);const k=await Dr(await u(we(`runs/${encodeURIComponent(g)}`),{signal:l.signal}),"The docs-qa run could not be read"),S=String((k==null?void 0:k.status)||"").toLowerCase();if(S==="completed"){(C=l.onHistory)==null||C.call(l,(k==null?void 0:k.session_history)??null);const $=T_(k);if(!$)throw new Error(`The docs-qa run ${g} completed without an answer.`);return $}if(S==="failed"||S==="cancelled"){const $=k==null?void 0:k.error,R=typeof $=="string"?$:typeof($==null?void 0:$.message)=="string"?$.message:"";throw new Error(`The docs-qa run ${S}${R?`: ${R}`:""}.`)}if(S==="waiting")throw new Error(`The docs-qa run ${g} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=x)throw new Error(`The docs-qa run ${g} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{l.signal.removeEventListener("abort",v),_.abort()}}}async function cE(e,t,n={}){const s=new URLSearchParams({root_only:"true",kind:$_,limit:"500",include_ledger_len:"false"}),o=await Dr(await e(we(`runs?${s}`),{signal:n.signal}),"The docs assistant history could not be read"),l=`${String(t||"app")}-docs-assistant:`,u=new Map;for(const f of Array.isArray(o==null?void 0:o.items)?o.items:[]){const m=String((f==null?void 0:f.session_id)||"");if(!m.startsWith(l)||!(f!=null&&f.run_id))continue;const p=u.get(m)||{runs:[],updatedAt:""};p.runs.push({id:String(f.run_id),created:String(f.created_at||"")});const g=String(f.updated_at||f.created_at||"");g>p.updatedAt&&(p.updatedAt=g),u.set(m,p)}const d=[...u.entries()].sort((f,m)=>f[1].updatedAt<m[1].updatedAt?1:-1).slice(0,n.max??20);return Promise.all(d.map(async([f,m])=>{var _;const p=m.runs.sort((v,C)=>v.created<C.created?-1:1).map(v=>v.id);let g="";try{const v=await Dr(await e(we(`runs/${encodeURIComponent(p[0])}/input_data`),{signal:n.signal}),"");g=String(((_=v==null?void 0:v.input_data)==null?void 0:_.prompt)||"").trim()}catch{g=""}return{sessionId:f,title:g||"Untitled question",updatedAt:m.updatedAt,runIds:p}}))}async function uE(e,t,n,s){var l;const o=[];for(const u of t.runIds){const[d,f]=await Promise.all([Dr(await e(we(`runs/${encodeURIComponent(u)}/input_data`),{signal:s}),"A past question could not be read"),Dr(await e(we(`runs/${encodeURIComponent(u)}`),{signal:s}),"A past answer could not be read")]),m=String(((l=d==null?void 0:d.input_data)==null?void 0:l.prompt)||"").trim();m&&o.push({id:`u-${u}`,role:"user",content:m,ts:String((f==null?void 0:f.created_at)||"")||void 0});const p=T_(f),g=String((f==null?void 0:f.status)||"").toLowerCase();o.push(p?{id:`a-${u}`,role:"assistant",title:n,content:p,ts:String((f==null?void 0:f.updated_at)||"")||void 0}:{id:`a-${u}`,role:"assistant",title:n,level:"warn",content:g==="completed"?"This answer was empty.":`No answer: the run is ${g||"unknown"}.`})}return o}function dE(e){const[t,n]=y.useState(null);return e.state==="loading"?a.jsx("div",{className:"pc-docs-history__note",role:"status",children:"Loading past conversations…"}):e.state==="error"?a.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?a.jsx("ul",{className:"pc-docs-history","aria-label":"Past conversations",children:e.items.map(s=>a.jsx("li",{className:`pc-docs-history__row${s.sessionId===e.activeSessionId?" is-active":""}`,children:t===s.sessionId?a.jsxs("div",{className:"pc-docs-history__confirm",children:[a.jsx("span",{children:"Archive this conversation? It stays in the gateway; it leaves this list."}),a.jsx("button",{type:"button",className:"pc-docs-history__btn pc-docs-history__btn--danger",onClick:()=>{n(null),e.onArchive(s)},children:"Archive"}),a.jsx("button",{type:"button",className:"pc-docs-history__btn",onClick:()=>n(null),children:"Cancel"})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button",className:"pc-docs-history__open",onClick:()=>e.onOpen(s),title:s.title,children:[a.jsx("span",{className:"pc-docs-history__title",children:s.title}),a.jsxs("span",{className:"pc-docs-history__meta",children:[$o(s.updatedAt,e.nowMs),s.runIds.length>1?` · ${s.runIds.length} questions`:""]})]}),a.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":`Archive "${s.title}"`,"data-af-tip":`Archive "${s.title}" (kept, hidden)`,onClick:()=>n(s.sessionId),children:a.jsx(de,{name:"archive",size:16})})]})},s.sessionId))}):a.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const fE=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function hE(e){const t=y.useRef(null),[n,s]=y.useState(!1),o=!!e.blockedNotice,l=!!e.busy,u=e.files||[],d=typeof e.onAddFiles=="function"&&!o,f=a.jsxs("div",{className:"pc-docs-assistant__empty",children:[a.jsxs("p",{className:"pc-docs-assistant__empty-text",children:["Ask anything about ",e.source.name,"."]}),e.suggestions&&e.suggestions.length?a.jsx("div",{className:"pc-docs-assistant__suggestions",children:e.suggestions.map(m=>a.jsx("button",{type:"button",className:"pc-docs-assistant__suggestion",disabled:l||o,onClick:()=>{var p;return(p=e.onSuggestion)==null?void 0:p.call(e,m)},children:m},m))}):null]});return a.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:m=>{var p;!d||!Hi((p=m.dataTransfer)==null?void 0:p.types)||(m.preventDefault(),s(!0))},onDragLeave:()=>s(!1),onDrop:m=>{var g,_;if(!d)return;m.preventDefault(),s(!1);const p=lm(m.dataTransfer);p.files.length&&((g=e.onAddFiles)==null||g.call(e,p.files)),p.folders.length&&((_=e.onNotice)==null||_.call(e,k_(p.folders)))},children:[a.jsx(b_,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:f,messageProps:{showCopy:!0}}),o?a.jsx("div",{className:"pc-docs-assistant__blocked",role:"status",children:e.blockedNotice}):null,e.notice?a.jsx("div",{className:"pc-docs-assistant__notice",role:"status",children:e.notice}):null,a.jsx("div",{className:"pc-docs-assistant__composer",children:a.jsx(x_,{value:e.draft,onChange:e.onDraftChange,onSubmit:e.onSend,placeholder:e.placeholder||`Ask about ${e.source.name}…`,ariaLabel:`Question about ${e.source.name}`,disabled:o,busy:l,rows:1,sendLabel:"Send",busyLabel:"Answering…",onPaste:m=>{var g;if(!d)return;const p=S_(m.clipboardData);p.length&&(m.preventDefault(),(g=e.onAddFiles)==null||g.call(e,p))},leading:u.length?a.jsx("div",{className:"pc-chat-attachments pc-docs-assistant__files",role:"list","aria-label":"Attached files",children:u.map(m=>a.jsxs("span",{role:"listitem",className:"pc-chat-attachment-chip",children:[a.jsx(de,{name:"paperclip",size:14}),a.jsx("span",{className:"pc-chat-attachment-name",children:m.name}),e.onRemoveFile&&!l?a.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:a.jsx(de,{name:"x",size:12})}):null]},m.id))}):null,actions:a.jsxs(a.Fragment,{children:[d?a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Attach files","data-af-tip":"Attach files to your question",disabled:l,onClick:()=>{var m;return(m=t.current)==null?void 0:m.click()},children:a.jsx(de,{name:"paperclip",size:16})}),a.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:m=>{var g;const p=Array.from(m.currentTarget.files||[]);m.currentTarget.value="",p.length&&((g=e.onAddFiles)==null||g.call(e,p))}})]}):null,l&&e.onStop?a.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"Stop","data-af-tip":"Stop the answer",onClick:e.onStop,children:a.jsx(de,{name:"stop",size:14})}):null]})})}),a.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 Bc(){return new Date().toISOString()}function mE(e){Io();const{source:t}=e,n=y.useRef(e.fetchGateway);n.current=e.fetchGateway;const s=y.useMemo(()=>e.ask||lE({fetchGateway:(F,D)=>n.current(F,D),source:t}),[e.ask,t.app,t.name]),o=y.useRef(Of(t.app)),[l,u]=y.useState([]),d=y.useRef(l);d.current=l;const[f,m]=y.useState(""),[p,g]=y.useState([]),[_,v]=y.useState(!1),[C,x]=y.useState(""),k=y.useRef(null),[S,$]=y.useState(!1),[R,N]=y.useState({state:"loading",items:[]});y.useEffect(()=>()=>{var F;return(F=k.current)==null?void 0:F.abort()},[]);const E=y.useCallback(async()=>{N(F=>({...F,state:"loading"}));try{const F=await cE((D,M)=>n.current(D,M),t.app);N({state:"ready",items:F})}catch(F){N({state:"error",items:[],error:String((F==null?void 0:F.message)||F)})}},[t.app]),j=y.useCallback(async F=>{var D;(D=k.current)==null||D.abort(),N(M=>({...M,state:"loading"}));try{const M=await uE((J,B)=>n.current(J,B),F,t.name);o.current=F.sessionId,u(M),x(""),$(!1),N(J=>({...J,state:"ready"}))}catch(M){N(J=>({...J,state:"error",error:String((M==null?void 0:M.message)||M)}))}},[t.name]),I=y.useCallback(async F=>{try{const D=await n.current(we(`sessions/${encodeURIComponent(F.sessionId)}/archive`),{method:"POST"});if(!D.ok)throw await Do(D,"The conversation could not be archived");o.current===F.sessionId&&(o.current=Of(t.app),u([])),N(M=>({...M,items:M.items.filter(J=>J.sessionId!==F.sessionId)}))}catch(D){N(M=>({...M,state:"error",error:String((D==null?void 0:D.message)||D)}))}},[t.app]);y.useEffect(()=>{var F;e.connected||(F=k.current)==null||F.abort()},[e.connected]),y.useEffect(()=>()=>{for(const F of p)F.preview&&URL.revokeObjectURL(F.preview)},[]);const L=y.useCallback(F=>{x(""),g(D=>[...D,...F.map(M=>({id:Fr(),file:M,preview:fE.test(M.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(M):void 0}))])},[]),z=y.useCallback(async F=>{const D=String(F||"").trim();if(!D||_||!e.connected)return;const M=p;m(""),g([]),x("");const J=M.filter(ue=>ue.preview).map(ue=>({kind:"image",src:ue.preview,label:ue.file.name})),B=M.map(ue=>({id:ue.id,label:ue.file.name,title:ue.file.name,disabled:!0})),Y={id:`u-${Fr()}`,role:"user",content:D,ts:Bc(),...J.length?{media:J}:{},...B.length?{attachments:B}:{}},te=`a-${Fr()}`,W=[...d.current,Y],T={id:te,role:"assistant",title:t.name,content:"",ts:Bc(),live:{callId:te,reasoning:"",label:"answering"}};u([...W,T]),v(!0);const K=new AbortController;k.current=K;const ne=ue=>u([...W,ue]);try{const ue=await s(D,{signal:K.signal,sessionId:o.current,files:M.map(oe=>oe.file),onText:oe=>{K.signal.aborted||ne({...T,content:oe,live:{callId:te,reasoning:"",label:"streaming"}})},onHistory:oe=>x(aE(oe))});K.signal.aborted||ne({id:te,role:"assistant",title:t.name,content:ue,ts:Bc()})}catch(ue){const oe=K.signal.aborted;ne({id:te,role:"assistant",title:t.name,level:oe?"warn":"error",content:oe?"Stopped. Nothing more will be shown for this question.":String((ue==null?void 0:ue.message)||ue||"The docs assistant failed."),ts:Bc()})}finally{k.current===K&&(k.current=null),v(!1)}},[s,_,p,e.connected,t.name]),V=()=>{var F;(F=k.current)==null||F.abort(),o.current=Of(t.app),u([]),g([]),m(""),x("")},Z=a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:`pc-docs-assistant__icon-btn${S?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":S,disabled:!e.connected||_,onClick:()=>{const F=!S;$(F),F&&E()},children:a.jsx(de,{name:"history",size:16})}),a.jsx("button",{type:"button",className:"pc-docs-assistant__icon-btn","aria-label":"New conversation","data-af-tip":"Start a new conversation",disabled:!l.length&&!f&&!p.length&&!S,onClick:()=>{V(),$(!1)},children:a.jsx(de,{name:"compose",size:16})})]}),ie=a.jsxs(a.Fragment,{children:[S?a.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:a.jsx(dE,{items:R.items,state:R.state,error:R.error,nowMs:Date.now(),activeSessionId:o.current,onOpen:F=>void j(F),onArchive:F=>void I(F)})}):null,a.jsx("div",{hidden:S,style:{display:S?"none":"contents"},children:a.jsx(hE,{source:t,messages:l,draft:f,onDraftChange:m,onSend:()=>void z(f),onStop:()=>{var F;return(F=k.current)==null?void 0:F.abort()},busy:_,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:p.map(F=>({id:F.id,name:F.file.name})),onAddFiles:L,onNotice:x,onRemoveFile:F=>g(D=>{const M=D.find(J=>J.id===F);return M!=null&&M.preview&&URL.revokeObjectURL(M.preview),D.filter(J=>J.id!==F)}),notice:C,suggestions:e.suggestions,onSuggestion:F=>void z(F),placeholder:e.placeholder})})]});return{headerActions:Z,body:ie}}function pE(e){const{headerActions:t,body:n}=mE(e);return a.jsxs("div",{className:"pc-docs-assistant-panel",children:[a.jsx(tN,{children:t}),n]})}function gE(e,t,n){const{id:s,label:o,mode:l,side:u,defaultWidth:d,...f}=n;return{id:s||"docs",label:o||"Docs assistant",icon:"book",mode:l||"drawer",side:u||"right",keepAlive:"always",defaultWidth:d??420,content:a.jsx(pE,{source:e,fetchGateway:t,...f})}}const $y="replay_view_v1",yE=["version","root_run_id","workflow","session_id","status","display_status","cursor","interaction","open_waits","usage","warnings"],Ty=["runs","messages","activities","artifacts"],R_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function I_(e){return e==null?"None":e===!0?"True":e===!1?"False":String(e)}function wE(e){const t=typeof e=="boolean"?Number(e):e;if(typeof t=="number"&&Number.isInteger(t)){const n=String(Math.abs(t));return t<0?`-${n.padStart(11,"0")}`:n.padStart(12,"0")}return I_(e)}function Ry(e,t){if(e===t)return 0;const n=Math.min(e.length,t.length);for(let s=0;s<n;s+=1){const o=e.charCodeAt(s),l=t.charCodeAt(s);if(o===l)continue;const u=d=>d>=55296&&d<=57343;return u(o)||u(l)?(e.codePointAt(s)??o)-(t.codePointAt(s)??l):o-l}return e.length-t.length}function jh(e,t){return I_(e==="runs"?t.run_id:t.id)}function Nh(e,t){return[(Array.isArray(t.order)&&t.order.length?t.order:[]).map(wE),jh(e,t)]}function L_(e,t){const n=Math.min(e[0].length,t[0].length);for(let s=0;s<n;s+=1){const o=Ry(e[0][s],t[0][s]);if(o)return o}return e[0].length!==t[0].length?e[0].length-t[0].length:Ry(e[1],t[1])}function vE(e,t){return L_(Nh("messages",e),Nh("messages",t))}function Ch(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return e===t||e==null&&t==null;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,s)=>Ch(n,t[s]));if(e&&t&&typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),s=Object.keys(t);return n.length===s.length&&n.every(o=>R_(t,o)&&Ch(e[o],t[o]))}return!1}function _E(e,t){const n=e&&Object.keys(e).length?{...e}:Object.fromEntries(Ty.map(s=>[s,[]]));for(const s of yE)R_(t,s)&&(n[s]=t[s]);for(const s of Ty){const o=t[s],l=Array.isArray(n[s])&&n[s].length?n[s]:[];if(!Array.isArray(o)||!o.length){n[s]=l;continue}const u=[...l],d=new Map(u.map((m,p)=>[jh(s,m),p]));let f=!1;for(const m of o){const p=jh(s,m),g=d.get(p);g===void 0?(d.set(p,u.length),u.push(m),f=!0):(Ch(u[g].order??null,m.order??null)||(f=!0),u[g]=m)}if(f){const m=u.map(p=>({it:p,key:Nh(s,p)}));m.sort((p,g)=>L_(p.key,g.key)),n[s]=m.map(p=>p.it)}else n[s]=u}return n}let bE=class{constructor(){this.lastEventId="",this.buffer="",this.event="",this.data=[],this.pendingCr=!1}push(t){const n=[];let s=t;for(this.pendingCr&&s.startsWith(`
86
- `)&&(s=s.slice(1)),this.pendingCr=!1,this.buffer+=s;;){const o=/\r\n|\n|\r/.exec(this.buffer);if(!o)break;if(o[0]==="\r"&&o.index===this.buffer.length-1){const u=this.buffer.slice(0,o.index);this.buffer="",this.pendingCr=!0,this.line(u,n);break}const l=this.buffer.slice(0,o.index);this.buffer=this.buffer.slice(o.index+o[0].length),this.line(l,n)}return n}line(t,n){if(t===""){this.data.length&&n.push({event:this.event||"message",data:this.data.join(`
87
- `),...this.id!==void 0?{id:this.id}:{}}),this.event="",this.data=[],this.id=void 0;return}if(t.startsWith(":"))return;const s=t.indexOf(":"),o=s<0?t:t.slice(0,s);let l=s<0?"":t.slice(s+1);l.startsWith(" ")&&(l=l.slice(1)),o==="event"?this.event=l:o==="data"?this.data.push(l):o==="id"&&!l.includes("\0")&&(this.id=l,this.lastEventId=l)}};class xE{constructor(){this.view=null,this.lastEventId=null,this.terminal=!1}adopt(t,n){var s,o,l;return this.view&&Iy((s=t.cursor)==null?void 0:s.runs,(o=this.view.cursor)==null?void 0:o.runs)?!1:(this.view=t,this.lastEventId=kE(n)||((l=t.cursor)==null?void 0:l.token)||null,!0)}apply(t){var o,l,u,d;if(t.event==="done")return this.terminal=!0,"done";if(t.event!=="view"&&t.event!=="delta")return"ignored";const n=JSON.parse(t.data);if(t.event==="view")return this.view=n,this.lastEventId=t.id||((o=this.view.cursor)==null?void 0:o.token)||null,"view";if(!this.view)throw new Error("replay view: a delta arrived before any view (reconnect without Last-Event-ID).");const s=t.id||((l=n.cursor)==null?void 0:l.token)||null;return s&&s===this.lastEventId?"duplicate":Iy((u=n.cursor)==null?void 0:u.runs,(d=this.view.cursor)==null?void 0:d.runs)?"stale":(this.view=_E(this.view,n),this.lastEventId=s,"delta")}}function kE(e){return String(e||"").trim().replace(/^W\//,"").replace(/^"|"$/g,"")}function Iy(e,t){if(!e||!t)return!1;let n=!1;for(const[s,o]of Object.entries(t)){const l=e[s];if(typeof l!="number"){o>0&&(n=!0);continue}if(l>o)return!1;l<o&&(n=!0)}for(const[s,o]of Object.entries(e))if(!(s in t)&&o>0)return!1;return n}class SE extends Error{constructor(t,n){super(`This gateway does not serve the replay view (GET runs/{id}/view answered ${t}${n?`: ${n}`:""}); AbstractGateway 0.17.0 or later serves it.`),this.name="ReplayViewUnavailableError",this.status=t}}async function Ly(e){let t="";try{const s=await e.text();try{const o=JSON.parse(s);t=typeof o.detail=="string"?o.detail:s}catch{t=s}}catch{t=""}if(e.status===405||e.status===404&&t.trim()==="Not Found")return new SE(e.status,t.trim());const n=new Error(t||`Gateway answered ${e.status}`);return n.status=e.status,n.detail=t,n}const My=e=>`runs/${encodeURIComponent(e)}/view`;function jE(e){const t=e.fetch;return{...e.advertised!==void 0?{advertised:e.advertised}:{},async getView(n,s={}){const o={Accept:"application/json"};s.ifNoneMatch&&(o["If-None-Match"]=s.ifNoneMatch);const l=s.at?`?at=${encodeURIComponent(s.at)}`:"",u=await t(`${My(n)}${l}`,{method:"GET",headers:o,...s.signal?{signal:s.signal}:{}}),d=u.headers.get("etag");if(u.status===304)return{notModified:!0,etag:d,bytes:0};if(!u.ok)throw await Ly(u);const f=new Uint8Array(await u.arrayBuffer()),m=JSON.parse(new TextDecoder().decode(f));if((m==null?void 0:m.version)!==$y)throw new Error(`Unsupported replay view version ${JSON.stringify(m==null?void 0:m.version)} (this client reads ${$y}).`);return{notModified:!1,view:m,etag:d,bytes:f.byteLength}},async streamView(n,s){var p;const o={Accept:"text/event-stream"};s.lastEventId&&(o["Last-Event-ID"]=s.lastEventId);const l=await t(`${My(n)}/stream`,{method:"GET",headers:o,signal:s.signal});if(!l.ok)throw await Ly(l);if(!l.body)throw new Error("The replay view stream has no body.");(p=s.onOpen)==null||p.call(s);const u=new bE,d=new TextDecoder,f=l.body.getReader();let m=0;try{for(;;){const{done:g,value:_}=await f.read();if(g)break;m+=_.byteLength;for(const v of u.push(d.decode(_,{stream:!0})))if(s.onFrame(v),v.event==="done")return{bytes:m}}for(const g of u.push(d.decode()))s.onFrame(g)}finally{try{await f.cancel()}catch{}}return{bytes:m}}}}const Xe=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"",Sa=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,Oy=new Set(["completed","failed","cancelled"]),NE=new Set(["write_file","create_file","save_file","edit_file","update_file","replace_in_file","delete_file","remove_file","move_file","rename_file","copy_file"]);function M_(e){const t={...e.details||{}};e.kind==="tool_approval"&&(t.kind="tool_approval",t.tool_calls=Array.isArray(e.tool_calls)?e.tool_calls:[]);const n=e.kind==="ask_user"?"user":e.kind==="event"?"event":"tool_approval",s={wait_key:e.wait_key,reason:n,details:t};return e.prompt!=null&&(s.prompt=e.prompt),Array.isArray(e.choices)&&(s.choices=e.choices),typeof e.allow_free_text=="boolean"&&(s.allow_free_text=e.allow_free_text),{runId:e.run_id,wait:s,...e.step_id?{stepId:e.step_id}:{},kind:e.kind,...e.command?{command:e.command}:{}}}function CE(e,t){const n=Xe(e.status||t.status).toLowerCase();return n==="completed"?"completed":n==="waiting"?"waiting":n==="running"||n==="started"||n==="pending"?"running":"failed"}function EE(e){const t=Sa(e.policy_decision),n=Xe(t==null?void 0:t.decision);if(n!=="auto_approved"&&n!=="denied")return;const s=Sa(t==null?void 0:t.set_by),o=Xe(s==null?void 0:s.user_id)||Xe(s==null?void 0:s.client);return{decision:n,...Xe(e.decided_by)?{source:Xe(e.decided_by)}:{},...Xe(e.matched)?{matched:Xe(e.matched)}:{},...typeof(t==null?void 0:t.revision)=="number"?{revision:t.revision}:{},...o?{setBy:o}:{},...Xe(t==null?void 0:t.set_at)?{setAt:Xe(t==null?void 0:t.set_at)}:{}}}function AE(e,t){if(typeof e.error=="string"&&e.error.trim())return e.error.trim();const n=Sa(e.error);if(n)return Xe(n.message)||Xe(n.detail)||JSON.stringify(n);if(t==="denied")return"Denied";if(t==="cancelled")return"Cancelled"}function O_(e){return(Array.isArray(e.tool_calls)?e.tool_calls:[]).map((n,s)=>{const o=CE(n,e),l=Xe(n.status||e.status).toLowerCase(),u=EE(n),d=o==="failed"?AE(n,l):void 0;return{id:`${e.id}:${Xe(n.id)||s}`,runId:e.run_id,name:Xe(n.name)||"tool",...n.arguments!==void 0?{arguments:n.arguments}:{},...n.output!==void 0?{output:n.output}:{},status:o,...o==="completed"?{success:!0}:o==="failed"?{success:!1}:{},...d?{error:d}:{},...Xe(e.started_at)?{startedAt:Xe(e.started_at)}:{},...Xe(e.ended_at)?{endedAt:Xe(e.ended_at)}:{},...Xe(n.id)?{callId:Xe(n.id)}:{},...u?{policy:u}:{}}})}function P_(e){return{id:`tool:${e.id}`,role:"system",kind:"tool_activity",title:"Tool activity",runId:e.runId,toolActivity:e,content:JSON.stringify({tool:e.name,status:e.status,arguments:e.arguments,output:e.output,error:e.error},null,2),ts:e.endedAt||e.startedAt}}function $E(e){const t=Xe(e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=Sa(e.policy),s=Sa(n==null?void 0:n.set_by),o=Xe(s==null?void 0:s.user_id)||Xe(s==null?void 0:s.client),l={decision:t,...Xe(e.source)?{source:Xe(e.source)}:{},...typeof(n==null?void 0:n.revision)=="number"?{revision:n.revision}:{},...o?{setBy:o}:{},...Xe(n==null?void 0:n.set_at)?{setAt:Xe(n==null?void 0:n.set_at)}:{}};return{id:`policy:${e.id}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",runId:e.run_id,content:fu(l),ts:Xe(e.started_at)||void 0}}function TE(e){const t=Sa(e.usage)||{},n=new Set;let s=0,o=0,l=1/0,u=-1/0;for(const m of e.activities||[]){const p=Date.parse(Xe(m.started_at)),g=Date.parse(Xe(m.ended_at));if(Number.isFinite(p)&&(l=Math.min(l,p)),Number.isFinite(g)&&(u=Math.max(u,g)),m.kind==="llm"&&(o+=1),m.kind==="tool")for(const _ of m.tool_calls||[]){if(s+=1,Xe(_.status)!=="completed"||!NE.has(Xe(_.name)))continue;const v=Sa(_.arguments)||{},C=Xe(v.destination)||Xe(v.destination_path)||Xe(v.file_path)||Xe(v.path)||Xe(v.filename);C&&n.add(C)}}const d=m=>typeof m=="number"&&Number.isFinite(m)?m:void 0,f={llmCalls:d(t.llm_calls)??o,toolCalls:s,changedFiles:[...n]};return d(t.input_tokens)!==void 0&&(f.inputTokens=d(t.input_tokens)),d(t.output_tokens)!==void 0&&(f.outputTokens=d(t.output_tokens)),d(t.total_tokens)!==void 0&&(f.totalTokens=d(t.total_tokens)),Number.isFinite(l)&&Number.isFinite(u)&&(f.durationMs=Math.max(0,u-l)),f}function RE(e,t){const n=Array.isArray(e.order)&&typeof e.order[0]=="string"&&e.order[0]?e.order[0]:void 0,s=Xe(e.level).toLowerCase();return{id:e.id,role:e.role,kind:e.kind,content:e.text,runId:e.run_id,...n?{ts:n}:{},...e.role==="system"?{title:"Workflow",level:s==="error"?"error":s==="warn"||s==="warning"?"warn":"info"}:{},...Array.isArray(e.artifact_ids)&&e.artifact_ids.length?{artifactIds:[...e.artifact_ids]}:{},...t?{statistics:t}:{}}}function D_(e){const t=e.root_run_id,n=TE(e),s=e.interaction?M_(e.interaction):null,o=e.interaction?`${e.interaction.run_id}:${e.interaction.step_id||""}:question`:"",l=(e.messages||[]).find(v=>v.id===`${t}:final`),u=l?l.repeats||l.id:"",d=[];for(const v of e.messages||[])v.kind==="final"&&v.repeats||v.kind==="question"&&v.id===o||d.push({order:v.order,id:v.id,message:RE(v,v.id===u?n:void 0)});const f=[],m=[],p=[];for(const v of e.activities||[])if(v.kind==="tool"){const C=O_(v);f.push(...C),C.forEach((x,k)=>d.push({order:[...v.order||[],k],id:`${v.id}:${k}`,message:P_(x)}))}else if(v.kind==="tool_policy"){const C=$E(v);C&&d.push({order:v.order,id:v.id,message:C})}else if(v.kind==="llm")for(const C of v.step_ids||[])(Oy.has(v.status)?p:m).push(`${v.run_id}:${C}`);d.sort((v,C)=>vE(v,C));const g=new Map((e.runs||[]).map(v=>[v.run_id,Xe(v.status).toLowerCase()])),_=Xe(e.status).toLowerCase()||"unknown";return{messages:d.map(v=>v.message),tools:f,interaction:Oy.has(_)?null:s,status:_,displayStatus:Xe(e.display_status),openLlmCalls:m,endedLlmCalls:p,runStatus:g,statistics:n}}const mt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Xc=e=>Array.isArray(e)?e.map(mt):[],rt=e=>typeof e=="string"?e:"",Mi=e=>rt(e.runtime_call_id||e.call_uid),nr=e=>rt(e.call_id||e.id);function F_(e,t){const n=t.record,s=mt(n.effect);if(s.type!=="tool_calls")return[];const o=mt(n.result),l=Xc(mt(s.payload).tool_calls),u=l.length||n.status!=="waiting"?l:Xc(mt(mt(o.wait).details).tool_calls),d=Xc(o.results),f=u.length?u:d,m=[];return f.forEach((p,g)=>{let _=Mi(p)?d.filter(j=>Mi(j)===Mi(p)):[];!_.length&&nr(p)&&u.filter(j=>nr(j)===nr(p)).length===1&&(_=d.filter(j=>nr(j)===nr(p)));const v=u.length?_.length===1?_[0]:u.length===d.length?d[g]:{}:p,C=Mi(p)||Mi(v)||`${rt(n.idempotency_key)||rt(n.step_id)||t.cursor}:${g}`,x=`${t.runId}:${C}`,k=e.get(x),S=rt(p.name||v.name)||(k==null?void 0:k.name);if(!S)return;const $=n.status==="completed"||n.status==="failed",R=n.status==="failed"||v.success===!1||!!v.error,N=p.arguments??v.arguments??(k==null?void 0:k.arguments),E={...k,id:x,runId:t.runId,name:S,arguments:N,status:$?R?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof v.success=="boolean"?{success:v.success}:{},...v.output!==void 0||v.result!==void 0?{output:v.output??v.result}:{},...v.error?{error:String(v.error)}:{},...Ny(v)?{sandbox:Ny(v)}:{},...nr(p)||nr(v)?{callId:nr(p)||nr(v)}:{},startedAt:(k==null?void 0:k.startedAt)||rt(n.started_at)||void 0,endedAt:$&&rt(n.ended_at)||(k==null?void 0:k.endedAt)};k&&["completed","failed"].includes(k.status)&&!$||(e.set(x,E),m.push(E))}),m}function _o(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Ps(e,t){for(const n of t){const s=e==null?void 0:e[n];if(s==null||s===""||typeof s=="boolean")continue;const o=Number(s);if(Number.isFinite(o)&&o>=0)return Math.trunc(o)}}function z_(e){if(typeof e=="string")try{return mt(JSON.parse(e))}catch{return{}}return mt(e)}function fo(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function IE(e){return Ps(e,["reasoning_tokens","thinking_tokens"])??Ps(mt(e.completion_tokens_details),["reasoning_tokens"])??Ps(mt(e.output_tokens_details),["reasoning_tokens"])}function LE(e){const t=mt(typeof e=="string"&&e.trim().startsWith("{")?z_(e):e);return rt(t.error_class)}function ME(e){const t=new Map;for(const n of e){const s=n.record;if(mt(s.effect).type!=="emit_event")continue;const o=mt(s.result);if(rt(o.name)!=="abstract.progress")continue;const l=mt(o.payload);if(rt(l.kind)!=="llm"||!rt(l.step_id))continue;const u=`${rt(l.run_id)||n.runId}:${rt(l.step_id)}`,d=t.get(u)||{},f=_o(l.ttft_s);f!==void 0&&(d.ttftS=f),d.provider=d.provider||rt(l.provider)||void 0,d.model=d.model||rt(l.model)||void 0,t.set(u,d)}return t}function el(e){var x,k,S,$;const t=new Map,n=new Set,s=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,u=-1/0,d=!1,f=0,m=0,p=0;const g=ME(e),_=[],v=new Set;for(const R of e){const N=R.record,E=`${R.runId}:${N.step_id||R.cursor}:${N.status}`;if(n.has(E))continue;n.add(E);for(const q of[N.started_at,N.ended_at]){const be=Date.parse(rt(q));Number.isFinite(be)&&(l=Math.min(l,be),u=Math.max(u,be))}for(const q of F_(t,R))q.status==="waiting"&&v.add(q.id);if(mt(N.effect).type!=="llm_call"||N.status!=="completed")continue;o.llmCalls+=1;const j=mt(N.result),I=mt(j.output),L=mt(j.usage||j.token_usage||j.tokens||I.usage||I.token_usage||I.tokens),z=Ps(L,["input_tokens","prompt_tokens","prompt","input","in"]),V=Ps(L,["output_tokens","completion_tokens","completion","output","out"]),Z=Ps(L,["total_tokens","total"])??(z!==void 0||V!==void 0?(z||0)+(V||0):void 0);Z!==void 0&&(z===void 0||V===void 0||z+V!==Z)&&(d=!0),z!==void 0&&(o.inputTokens=(o.inputTokens||0)+z),V!==void 0&&(o.outputTokens=(o.outputTokens||0)+V),Z!==void 0&&(o.totalTokens=(o.totalTokens||0)+Z);const ie=_o(j.gen_time??I.gen_time);ie!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+ie,o.timedCalls=(o.timedCalls||0)+1);const F=mt(j.metadata||I.metadata),D=mt(F.performance),M=_o(D.prompt_tokens_per_second),J=_o(D.generation_tokens_per_second),B=mt(F.prompt_cache),Y=_o(B.cached_tokens),te=_o(B.fed_tokens);if(M!==void 0||J!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,M!==void 0&&M>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+M,z!==void 0)){const q=z/M*1e3;o.prefillMs=(o.prefillMs||0)+q,te!==void 0&&(f+=te,m+=q)}J!==void 0&&J>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+J,V!==void 0&&(o.decodeMs=(o.decodeMs||0)+V/J*1e3))}if(Y!==void 0||te!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(Y||0),o.fedTokens=(o.fedTokens||0)+(te||0);const q=rt(B.outcome);if(q){const be=o.cacheOutcomes||[];be.includes(q)||be.push(q),o.cacheOutcomes=be}}const W=rt(N.step_id)||void 0,T=W&&g.get(`${R.runId}:${W}`)||{},K=mt(j.route),ne={runId:R.runId};W&&(ne.stepId=W),rt(N.started_at)&&(ne.startedAt=rt(N.started_at));const ue=rt(j.model||I.model)||rt(K.model)||T.model,oe=rt(K.provider)||rt(mt(F._provider_request).provider)||T.provider||rt(j.provider);ue&&(ne.model=ue),oe&&(ne.provider=oe),ue&&(o.models=fo(o.models,ue)),oe&&(o.providers=fo(o.providers,oe)),(Z===void 0||z!==void 0&&V!==void 0&&z+V===Z)&&(z!==void 0&&(ne.inputTokens=z),V!==void 0&&(ne.outputTokens=V)),Z!==void 0&&(ne.totalTokens=Z);const ve=IE(L);ve!==void 0&&(ne.reasoningTokens=ve,o.reasoningTokens=(o.reasoningTokens||0)+ve),Y!==void 0&&(ne.cachedTokens=Y),te!==void 0&&(ne.fedTokens=te),rt(B.outcome)&&(ne.cacheOutcome=rt(B.outcome)),rt(B.backend)&&(ne.cacheBackend=rt(B.backend),o.cacheBackends=fo(o.cacheBackends,ne.cacheBackend)),ie!==void 0&&(ne.genTimeMs=ie),M!==void 0&&M>0&&(ne.promptTokensPerSecond=M),J!==void 0&&J>0&&(ne.generationTokensPerSecond=J),T.ttftS!==void 0?(ne.ttftMs=T.ttftS*1e3,ne.promptMs=ne.ttftMs,ne.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+ne.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):ne.promptTokensPerSecond!==void 0&&z!==void 0&&(ne.promptMs=z/ne.promptTokensPerSecond*1e3,ne.promptSource="rate"),ne.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+ne.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,te!==void 0&&ne.promptMs>0&&(ne.promptNewTokensPerSecond=te/(ne.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+te,p+=ne.promptMs)),ne.ttftMs!==void 0&&ie!==void 0&&ie>=ne.ttftMs?ne.generationMs=ie-ne.ttftMs:ne.generationTokensPerSecond!==void 0&&V!==void 0&&(ne.generationMs=V/ne.generationTokensPerSecond*1e3),ne.generationMs!==void 0&&V!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+ne.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+V);const Ne=mt(F.speculation);if(Object.keys(Ne).length){const q={};rt(Ne.mode)&&(q.mode=rt(Ne.mode)),typeof Ne.used=="boolean"&&(q.used=Ne.used),rt(Ne.draft_kind)&&(q.draftKind=rt(Ne.draft_kind));const be=Ps(Ne,["accepted_tokens"]),xe=Ps(Ne,["drafted_tokens"]),Pe=Ps(Ne,["rounds"]),Qe=Ps(Ne,["num_draft_tokens"]);be!==void 0&&(q.acceptedTokens=be),xe!==void 0&&(q.draftedTokens=xe),be!==void 0&&xe&&(q.acceptanceRate=be/xe),Pe!==void 0&&(q.rounds=Pe),Qe!==void 0&&(q.draftLength=Qe),ne.speculation=q;const He=o.speculation||(o.speculation={calls:0,used:0});He.calls+=1,q.used&&(He.used+=1),q.mode&&(He.modes=fo(He.modes,q.mode)),q.draftKind&&(He.draftKinds=fo(He.draftKinds,q.draftKind)),be!==void 0&&xe!==void 0&&(He.acceptedTokens=(He.acceptedTokens||0)+be,He.draftedTokens=(He.draftedTokens||0)+xe),Pe!==void 0&&(He.rounds=(He.rounds||0)+Pe),Qe!==void 0&&(He.draftLengths=fo(He.draftLengths,Qe))}_.push(ne)}_.length&&(_.every(R=>R.startedAt)&&_.sort((R,N)=>Date.parse(R.startedAt)-Date.parse(N.startedAt)),o.modelCalls=_),p>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(p/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(x=o.speculation)!=null&&x.draftedTokens&&(o.speculation.acceptanceRate=(o.speculation.acceptedTokens||0)/o.speculation.draftedTokens),o.measuredSpeedCalls&&(o.promptTokensPerSecond!==void 0&&(o.promptTokensPerSecond/=o.measuredSpeedCalls),o.generationTokensPerSecond!==void 0&&(o.generationTokensPerSecond/=o.measuredSpeedCalls)),m>0&&(o.prefillNewTokens=f,o.prefillNewTokensPerSecond=f/(m/1e3));const C=new Map;for(const R of t.values()){if(R.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(R.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(R.status))continue;o.toolCalls+=1;const N=R.status==="failed";N&&(o.toolsFailed=(o.toolsFailed||0)+1);const E=o.toolBreakdown||(o.toolBreakdown={}),j=E[R.name]||(E[R.name]={calls:0,failed:0});if(j.calls+=1,N){j.failed+=1;const Z=LE(R.output);Z&&((j.errors||(j.errors={}))[Z]=(((k=j.errors)==null?void 0:k[Z])||0)+1)}const I=Date.parse(rt(R.startedAt)),L=Date.parse(rt(R.endedAt));if(Number.isFinite(I)&&Number.isFinite(L)&&L>=I){const Z=`${R.runId}|${R.startedAt}|${R.endedAt}`,ie=C.get(Z)||{ms:L-I,calls:0,names:new Map,waited:!1};ie.calls+=1,ie.names.set(R.name,(ie.names.get(R.name)||0)+1),v.has(R.id)&&(ie.waited=!0),C.set(Z,ie)}if(R.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(R.name))continue;const z=z_(R.arguments),V=rt(z.destination||z.destination_path||z.file_path||z.path||z.filename);V&&s.add(V)}for(const R of C.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+R.ms,R.waited&&(o.toolTimeIncludesApproval=!0);const N=[...R.names.keys()].sort();(!o.slowestToolBatch||R.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:R.ms,calls:R.calls,tools:N});const E=(S=o.toolBreakdown)==null?void 0:S[N[0]];if(N.length===1&&E)E.ms=(E.ms||0)+R.ms;else for(const j of N){const I=($=o.toolBreakdown)==null?void 0:$[j];I&&(I.sharedBatches=(I.sharedBatches||0)+1)}}return o.changedFiles=[...s],d&&(delete o.inputTokens,delete o.outputTokens),Number.isFinite(l)&&Number.isFinite(u)&&(o.durationMs=Math.max(0,u-l)),{tools:[...t.values()],statistics:o}}function OE(e){const t=mt(mt(e).ledgers);return Object.entries(t).flatMap(([n,s])=>Xc(mt(s).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(mt(o.record)).length?mt(o.record):o})))}const Pf=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};function PE(e){var S,$,R,N;const t=e.view||null,n=t?D_(t):null,{tools:s,statistics:o}=n?{tools:n.tools,statistics:n.statistics}:el(e.records),l={toolCalls:o.toolCalls,totalTokens:o.totalTokens,startedAt:String(((S=e.run)==null?void 0:S.created_at)||"")||void 0},u=(E,j,I)=>({...l,label:E,detail:j,tone:I});if(e.loading)return u("Loading conversation","Restoring saved activity","neutral");if(["completed","failed","cancelled"].includes(e.status))return u(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")&&((n?!1:!(($=e.records)!=null&&$.length))||!!e.error))return u(e.connection==="reconnecting"?"Reconnecting":"Disconnected",String(e.error||"Live activity is unavailable"),"waiting");if(e.status==="paused"||((R=e.run)==null?void 0:R.paused)===!0)return u("Paused","Resume when you’re ready","waiting");const d=Pf((N=e.interaction)==null?void 0:N.wait),f=Pf(d.details),m=f.kind==="tool_approval"||f.mode==="approval_required",p=m&&e.toolApprovalGranted===!0;if(m&&!p)return u("Approval needed","Review the tool requests below","waiting");if(!m&&["user","ask_user"].includes(d.reason))return u("Your answer is needed",String(d.prompt||"The workflow has a question for you"),"waiting");if(!m&&(d.reason==="event"||String(d.wait_key||"").startsWith("evt:")))return u("Waiting for an event",String(d.prompt||"Listening for the workflow’s trigger"),"waiting");const g=s.filter(E=>{var j;return E.status==="running"||p&&E.status==="waiting"&&E.runId===((j=e.interaction)==null?void 0:j.runId)});if(g.length)return u(g.length===1?"Running a tool":`Running ${g.length} tools`,[...new Set(g.map(E=>E.name))].join(" · "),"working");const _=new Map;for(const E of e.records){const j=`${E.runId}:${E.record.step_id||E.record.idempotency_key||E.cursor}`,I=_.get(j);I&&["completed","failed"].includes(String(I.record.status))||_.set(j,E)}if(n!=null&&n.openLlmCalls.length||[..._.values()].reverse().find(E=>Pf(E.record.effect).type==="llm_call"&&["started","running"].includes(String(E.record.status))))return u("Thinking","Generating the next response","working");const C=e.displayStatus.trim(),x=!/^(completed|complete|done|finished|ready|success|succeeded|failed|running|working|waiting|thinking|idle|paused|stopped|cancelled)$/i.test(C)&&!C.startsWith("{")?C:"",k=s[s.length-1];return u(e.status==="idle"?"Ready":"Working",x||(k?`Last tool: ${k.name} · ${k.status==="failed"?"failed":k.status==="completed"?"done":"waiting"}`:"Following the workflow"),e.status==="idle"?"neutral":"working")}const DE=3;function Py(e){return`${Math.round(e).toLocaleString("en-US")} bytes`}function dm(e,t){if(!t||!(t>0)||e.size<=t)return null;let n=pu(e.size),s=pu(t);return n===s&&(n=Py(e.size),s=Py(t)),`${e.name||"This file"} is ${n}; the gateway accepts files up to ${s}.`}function FE(e){return`Upload failed: ${String(e||"").replace(/^[a-z_]*upload failed:?\s*/i,"").trim()||"the gateway did not say why"}`}async function zE(e,t,n){let s=0;const o=Array.from({length:Math.max(1,Math.min(Math.floor(t)||1,e.length))},async()=>{for(;s<e.length;){const l=e[s];s+=1,await n(l)}});await Promise.all(o)}const gu=e=>`${e} ${e===1?"file":"files"}`;function Dy(e,t){const n=[];return e&&n.push(`${gu(e)} attached`),t&&n.push(`${gu(t)} could not be attached`),n.join(", ")}function B_(e){const t=e.filter(o=>o.state==="queued"||o.state==="uploading").length;if(t)return`Wait for ${gu(t)} to finish uploading.`;const n=e.filter(o=>o.state==="failed"||o.state==="refused");if(!n.length)return null;const s=n.some(o=>o.state==="failed");return n.length===1?`"${n[0].name}" was not attached. ${s?"Retry or remove":"Remove"} it before sending.`:`${gu(n.length)} were not attached. ${s?"Retry or remove":"Remove"} them before sending.`}function BE(e){const[t,n]=y.useState([]),[s,o]=y.useState(""),l=y.useRef(e);l.current=e;const u=y.useRef(new Set),d=y.useRef(0),f=y.useRef(!0);y.useEffect(()=>(f.current=!0,()=>{f.current=!1,d.current+=1}),[]);const m=(S,$)=>n(R=>R.map(N=>N.id===S?{...N,...$}:N)),p=async S=>{const $=d.current,R=j=>!f.current||d.current!==$||u.current.has(j);let N=0,E=0;await zE(S,l.current.concurrency??DE,async j=>{if(!(R(j.id)||!j.file)){m(j.id,{state:"uploading",error:void 0});try{const I=await l.current.upload(j.file);if(R(j.id))return;m(j.id,{state:"attached",ref:I,error:void 0}),N+=1}catch(I){if(R(j.id))return;m(j.id,{state:"failed",error:FE(I instanceof Error?I.message:String(I??""))}),E+=1}}}),f.current&&d.current===$&&(N||E)&&o(Dy(N,E))},g=S=>{if(!S.length)return[];const{maxBytes:$,thumbnail:R}=l.current,N=S.map(j=>{const I=dm(j,$),L=R==null?void 0:R(j);return{id:Fr(),file:j,name:j.name||"Untitled file",size:j.size,state:I?"refused":"queued",...I?{error:I}:{},...L?{thumbnailUrl:L}:{}}});n(j=>[...j,...N]);const E=N.filter(j=>j.state==="refused").length;return E&&o(Dy(0,E)),p(N.filter(j=>j.state==="queued")),N.map(j=>j.id)},_=S=>{const $=t.find(N=>N.id===S);if(!$||$.state!=="failed")return;const R={...$,state:"queued",error:void 0};n(N=>N.map(E=>E.id===S?R:E)),p([R])},v=S=>{u.current.add(S),n($=>$.filter(R=>R.id!==S))},C=()=>{d.current+=1,n([])},x=y.useMemo(()=>t.map(({id:S,name:$,size:R,state:N,thumbnailUrl:E,error:j})=>({id:S,name:$,size:R,state:N,...E?{thumbnailUrl:E}:{},...j?{error:j}:{}})),[t]),k=y.useMemo(()=>t.filter(S=>S.state==="attached").map(S=>S.ref),[t]);return{items:x,attached:k,add:g,remove:v,retry:_,clear:C,sendBlock:B_(x),announcement:s}}const WE=new Set(["blob:","data:","http:","https:"]);function UE(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return WE.has(new URL(t,n).protocol)?t:void 0}catch{return}}function VE(e){const t=typeof e.size=="number"?pu(e.size):"";if(e.state==="queued")return{meta:`Waiting${t?` · ${t}`:""}`,state:"waiting to upload"};if(e.state==="uploading")return{meta:`Uploading${t?` · ${t}`:""}`,state:"uploading"};if(e.state==="attached")return{meta:t,state:"attached"};const n=String(e.error||"").trim()||(e.state==="refused"?"Refused":"Upload failed");return{meta:n,state:`not attached: ${n}`}}function GE(e){const t=Array.isArray(e.items)?e.items:[];return t.length?a.jsx("div",{className:"pc-attachment-chips",role:"list","aria-label":"Attached files",children:t.map(n=>{const s=n.state==="queued"||n.state==="uploading",{meta:o,state:l}=VE(n),u=UE(n.thumbnailUrl);return a.jsxs("div",{role:"listitem",tabIndex:0,className:`pc-attachment-chip is-${n.state}`,"data-state":n.state,"aria-label":`${n.name}, ${l}`,"aria-busy":s||void 0,children:[a.jsx("span",{className:"pc-attachment-chip__icon","aria-hidden":"true",children:u?a.jsx("img",{className:"pc-attachment-chip__thumb",src:u,alt:"",loading:"lazy"}):s?a.jsx("span",{className:"pc-attachment-chip__spinner"}):n.state==="attached"?a.jsx(de,{name:"paperclip",size:13}):a.jsx(de,{name:"warning",size:13})}),a.jsxs("span",{className:"pc-attachment-chip__body",children:[a.jsx("span",{className:"pc-attachment-chip__name",title:n.name,children:n.name}),o?a.jsx("span",{className:"pc-attachment-chip__meta",children:o}):null]}),n.state==="failed"&&e.onRetry?a.jsxs("button",{type:"button",className:"pc-attachment-chip__action pc-attachment-chip__retry","data-action":"retry","aria-label":`Retry ${n.name}`,title:"Retry upload",disabled:e.disabled,onClick:()=>{var d;return(d=e.onRetry)==null?void 0:d.call(e,n.id)},children:[a.jsx(de,{name:"refresh",size:12}),a.jsx("span",{children:"Retry"})]}):null,e.onRemove?a.jsx("button",{type:"button",className:"pc-attachment-chip__action","data-action":"remove","aria-label":`Remove ${n.name}`,title:`Remove ${n.name}`,disabled:e.disabled,onClick:()=>{var d;return(d=e.onRemove)==null?void 0:d.call(e,n.id)},children:a.jsx(de,{name:"x",size:12})}):null]},n.id)})}):null}function HE(e,t){var n,s;if(e.kind==="ask-user"){if(t.kind==="choice"||t.kind==="free-text")return e.onSubmit(t.answer);if(t.kind==="skip"&&e.onSkip)return e.onSkip();throw new Error("Invalid submission for ask-user interaction")}if(e.kind==="tool-approval"){if(t.kind==="approve")return e.onApprove();if(t.kind==="deny")return e.onDeny();if(t.kind==="approve-all"&&e.onApproveAll)return e.onApproveAll();if(t.kind==="approve-session"&&e.onApproveForSession)return e.onApproveForSession();if(t.kind==="deny-chat"){const o=(n=e.denyOptions)==null?void 0:n.find(l=>l.key===t.key);if(o)return o.onDeny()}if(t.kind==="approve-kind"){const o=(s=e.approveKinds)==null?void 0:s.find(l=>l.kind===t.toolset);if(o)return o.onApprove()}throw new Error("Invalid submission for tool-approval interaction")}if(t.kind==="event")return e.onSend(t.payload);throw new Error("Invalid submission for event-wait interaction")}const Ji={deny:"Deny",allowOnce:"Allow once",allowForChat:"Allow for this chat",allowAll:"Allow all enabled tools",allowKindForChat:e=>`Allow all ${e} tools for this chat`,allowForRun:"Allow for this run",localChatPolicyNote:"Allowed for this chat in this browser only — the gateway cannot store chat policies.",localRunPolicyNote:"Allowed until this run ends, in this browser only — the gateway cannot store chat policies.",denyToolForChat:e=>`Always deny ${e} in this chat`,denyKindForChat:e=>`Always deny ${e} tools in this chat`,denyForChatNote:"Always deny applies to every run of this chat, automations and runs that read other people's text included, until the policy is reset; a request shown before it is refused even if approved later.",noScopeNote:"The gateway did not say where this grant applies.",unavailablePolicyNote:e=>`Allow for this chat is unavailable: ${e||"the gateway's capabilities could not be read."} Allow once still works.`,decideLater:"Decide later",submit:"Submit",skip:"Continue without answering",keepWaiting:"Keep waiting",sendEvent:"Send event"};function Fy(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function KE(e){return a.jsxs("div",{className:"pc-workflow-interaction__error",role:"alert",children:[a.jsxs("span",{children:["Could not complete that action: ",e.message]}),a.jsx("button",{type:"button",className:"pc-workflow-interaction__retry",onClick:e.onRetry,disabled:e.disabled,children:"Try again"})]})}const ks=Ji;function JE(e){var ie,F,D;const t=e.interaction,n=e.variant==="card",[s,o]=y.useState(""),[l,u]=y.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[d,f]=y.useState(null),[m,p]=y.useState(!1),[g,_]=y.useState(""),[v,C]=y.useState(null),x=`${t.kind}:${t.id}`,k=y.useRef(x),S=y.useRef(!1),$=y.useRef(!1),R=y.useRef(!0),N=y.useRef(0);k.current!==x&&(k.current=x,S.current=!1,$.current=!1,N.current+=1);const E=!!e.disabled||d!==null||m||S.current||$.current,j=async(M,J)=>{var te;if(e.disabled||S.current||$.current)return;const B=x,Y=++N.current;S.current=!0,C(null),_(""),f(M);try{const W=await J();if(!R.current||k.current!==B||N.current!==Y)return;$.current=!0,p(!0);const T=W&&typeof W=="object"&&typeof W.outcomeNote=="string"?String(W.outcomeNote):"";_(`Response sent. Waiting for the workflow to continue.${T?` ${T}`:""}`)}catch(W){if(!R.current||k.current!==B||N.current!==Y)return;C({submission:M,message:Fy(W)}),_("The action failed. You can try again."),(te=e.onError)==null||te.call(e,W)}finally{if(!R.current||k.current!==B||N.current!==Y)return;S.current=!1,f(null)}},I=async M=>{var B;if(e.disabled||S.current||$.current)return;const J=x;try{if(await M(),!R.current||k.current!==J)return;C(null),_(t.kind==="tool-approval"?"Left for later. Nothing was sent; the run keeps waiting for this decision.":"Left for later. Nothing was sent; the run keeps waiting for your answer.")}catch(Y){if(!R.current||k.current!==J)return;_(`Could not leave this for later: ${Fy(Y)}`),(B=e.onError)==null||B.call(e,Y)}};y.useEffect(()=>{o(""),u(t.kind==="event-wait"&&t.initialPayload||""),C(null),f(null),p(!1),_("")},[x]),y.useEffect(()=>(R.current=!0,()=>{R.current=!1,N.current+=1,S.current=!1}),[]);const L=()=>{v&&j(v.submission,()=>HE(t,v.submission))},z=t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required"),V=(M,J)=>M?a.jsx("button",{type:"button",className:"pc-workflow-interaction__defer","data-decision":"defer",disabled:E,onClick:()=>void I(M),children:J}):null;let Z;if(t.kind==="ask-user")Z=a.jsxs("div",{className:"pc-workflow-interaction__body",children:[a.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(ie=t.choices)!=null&&ie.length?a.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(M=>a.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice","data-decision":"choice",disabled:E||M.disabled,onClick:()=>void j({kind:"choice",answer:M.id},()=>t.onSubmit(M.id)),children:[a.jsx("span",{children:M.label}),M.description?a.jsx("small",{children:M.description}):null]},M.id))}):null,t.allowFreeText!==!1?a.jsxs("div",{className:"pc-workflow-interaction__entry",children:[a.jsx("textarea",{"aria-label":"Response",value:s,onChange:M=>o(M.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:n?1:2,disabled:E,onKeyDown:M=>{M.key!=="Enter"||M.shiftKey||M.nativeEvent.isComposing||M.keyCode===229||(M.preventDefault(),s.trim()&&j({kind:"free-text",answer:s},()=>t.onSubmit(s)))}},`${x}:text`),a.jsx("button",{type:"button",className:"pc-btn","data-decision":"submit",disabled:E||!s.trim(),onClick:()=>void j({kind:"free-text",answer:s},()=>t.onSubmit(s)),children:(d==null?void 0:d.kind)==="free-text"?"Sending…":t.submitLabel||ks.submit})]}):null,t.onSkip||t.onDefer?a.jsxs("div",{className:"pc-workflow-interaction__buttons pc-workflow-interaction__buttons--secondary",children:[V(t.onDefer,t.deferLabel||ks.keepWaiting),t.onSkip?a.jsx("button",{type:"button",className:"pc-workflow-interaction__skip","data-decision":"skip",disabled:E,onClick:()=>void j({kind:"skip"},t.onSkip),children:(d==null?void 0:d.kind)==="skip"?"Continuing…":t.skipLabel||ks.skip}):null]}):null]});else if(t.kind==="tool-approval"){const M=String(t.disabledReason||"").trim(),J=E||!!M;Z=a.jsxs("div",{className:"pc-workflow-interaction__body",children:[a.jsxs("div",{className:"pc-workflow-interaction__prompt",children:["Allow ",a.jsx("strong",{children:t.toolName})," to run?"]}),t.detail?n?a.jsxs("details",{className:"pc-workflow-interaction__review",children:[a.jsx("summary",{children:"Review"}),a.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail})]}):a.jsx("div",{className:"pc-workflow-interaction__detail",children:t.detail}):null,a.jsxs("div",{className:"pc-workflow-interaction__buttons",children:[V(t.onDefer,t.deferLabel||ks.decideLater),a.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:E,onClick:()=>void j({kind:"deny"},t.onDeny),children:(d==null?void 0:d.kind)==="deny"?"Denying…":t.denyLabel||ks.deny}),a.jsx("button",{type:"button",className:"pc-btn","data-decision":"approve",disabled:E,onClick:()=>void j({kind:"approve"},t.onApprove),children:(d==null?void 0:d.kind)==="approve"?"Allowing…":t.approveLabel||ks.allowOnce}),t.onApproveForSession?a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session","data-decision":"approve-session",disabled:J,title:M||void 0,onClick:()=>void j({kind:"approve-session"},t.onApproveForSession),children:(d==null?void 0:d.kind)==="approve-session"?"Allowing…":t.approveForSessionLabel||ks.allowForChat}):null,(t.approveKinds||[]).map(B=>a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session pc-workflow-interaction__allow-kind","data-decision":"approve-kind","data-kind":B.kind,disabled:J,title:M||void 0,onClick:()=>void j({kind:"approve-kind",toolset:B.kind},B.onApprove),children:(d==null?void 0:d.kind)==="approve-kind"&&d.toolset===B.kind?"Allowing…":B.label||ks.allowKindForChat(B.kind)},B.kind)),t.onApproveAll?a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all","data-decision":"approve-all",disabled:J,title:M||void 0,onClick:()=>void j({kind:"approve-all"},t.onApproveAll),children:(d==null?void 0:d.kind)==="approve-all"?"Allowing…":t.approveAllLabel||ks.allowAll}):null]}),t.remember?a.jsxs("label",{className:"pc-workflow-interaction__remember",children:[a.jsx("input",{type:"checkbox",checked:t.remember.checked,disabled:E,onChange:B=>t.remember.onChange(B.target.checked)}),a.jsx("span",{children:t.remember.label})]}):null,t.deniedNote?a.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note","data-denied-note":"",children:t.deniedNote}):null,(F=t.denyOptions)!=null&&F.length?a.jsxs("details",{className:"pc-workflow-interaction__more","data-more":"",children:[a.jsx("summary",{children:"More"}),a.jsx("p",{className:"pc-workflow-interaction__scope",children:ks.denyForChatNote}),a.jsx("div",{className:"pc-workflow-interaction__buttons",children:t.denyOptions.map(B=>a.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny-chat","data-key":B.key,disabled:E,onClick:()=>void j({kind:"deny-chat",key:B.key},B.onDeny),children:(d==null?void 0:d.kind)==="deny-chat"&&d.key===B.key?"Denying…":B.label},B.key))})]}):null,t.policySummary?a.jsx("p",{className:"pc-workflow-interaction__scope","data-policy-summary":"",children:t.policySummary}):null,t.scopeNote?a.jsx("p",{className:"pc-workflow-interaction__scope-note",role:"note","data-scope-note":"",children:t.scopeNote}):null,t.notCovered?a.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note","data-not-covered":"",children:t.notCovered}):null,M&&(t.onApproveAll||t.onApproveForSession||(D=t.approveKinds)!=null&&D.length)?a.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note",children:M}):null,!M&&t.onApproveForSession&&t.approveForSessionDescription?a.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveForSessionDescription}):null,!M&&t.onApproveAll&&t.approveAllDescription?a.jsx("p",{className:"pc-workflow-interaction__scope",children:t.approveAllDescription}):null]})}else Z=a.jsxs("div",{className:"pc-workflow-interaction__body",children:[a.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),a.jsxs("label",{className:"pc-workflow-interaction__entry",children:[a.jsx("span",{children:t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload")}),a.jsx("textarea",{value:l,onChange:M=>u(M.target.value),placeholder:t.payloadPlaceholder||"Enter payload",rows:n?1:2,"aria-label":t.payloadLabel||(t.eventName?`Payload for ${t.eventName}`:"Event payload"),disabled:E},`${x}:payload`)]}),a.jsx("div",{className:"pc-workflow-interaction__buttons",children:a.jsx("button",{type:"button",className:"pc-btn","data-decision":"send-event",disabled:E,onClick:()=>void j({kind:"event",payload:l},()=>t.onSend(l)),children:(d==null?void 0:d.kind)==="event"?"Sending…":t.sendLabel||ks.sendEvent})})]});return a.jsxs("section",{className:["pc-workflow-interaction",n?"pc-workflow-interaction--card":""].filter(Boolean).join(" "),"data-variant":n?"card":"panel","aria-labelledby":`pc-workflow-interaction-${x}`,children:[a.jsxs("div",{className:"pc-workflow-interaction__heading",children:[a.jsx(de,{name:t.kind==="tool-approval"?"warning":t.kind==="event-wait"?"history":"info",size:n?14:16}),a.jsxs("div",{children:[a.jsx("h3",{tabIndex:-1,id:`pc-workflow-interaction-${x}`,children:z}),t.description?a.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),Z,v?a.jsx(KE,{message:v.message,onRetry:L,disabled:E}):null,a.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:g})]})}function ho(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function qE(e){var le;Io();const[t,n]=y.useState(!1),[s,o]=y.useState(!1),[l,u]=y.useState(!1),[d,f]=y.useState(null),[m,p]=y.useState(()=>{var he,Q;return((Q=(he=e.steer)==null?void 0:he.modes)==null?void 0:Q[0])||"guide"}),[g,_]=y.useState(null),[v,C]=y.useState("idle"),x=y.useRef(null),k=y.useRef(!0),S=y.useRef(!1),$=y.useRef(!1),R=y.useRef(!1),N=y.useRef(0),E=y.useRef(0),j=y.useRef(0);y.useEffect(()=>(k.current=!0,()=>{var he;k.current=!1,N.current+=1,E.current+=1,j.current+=1,S.current=!1,$.current=!1,R.current=!1,(he=x.current)==null||he.abort(),x.current=null}),[]);const I=!!e.blockedNotice,L=!!e.disabled||I,z=!!e.busy||t,V=t||!!e.busy&&!e.sendWhileBusy,Z=e.stopState||null,ie=(Z==null?void 0:Z.phase)==="stopping",F=e.steer&&typeof e.steer.onSteer=="function"?e.steer:null,D=F?(le=F.modes)!=null&&le.length?F.modes:["guide"]:[],M=D.includes(m)?m:D[0]||"guide",J=!!F&&!!e.busy,B=Array.isArray(e.attachmentItems)?e.attachmentItems:[];y.useEffect(()=>{_(null)},[!!e.busy]);const Y=typeof e.onFiles=="function",te=y.useRef(null),[W,T]=y.useState(null),[K,ne]=y.useState(""),ue=y.useRef(e.onFiles);ue.current=e.onFiles;const oe=y.useRef(L);oe.current=L;const ve=async(he,Q)=>{const _e=ue.current;if(_e){if(oe.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(Q.length)f({action:"attach",message:k_(Q)});else if(he.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(he.length){ne(`Attaching ${he.length} ${he.length===1?"file":"files"}…`);try{await _e(he)}catch(ae){k.current&&f({action:"attach",message:ho(ae)})}}}},Ne=y.useRef(ve);Ne.current=ve,y.useEffect(()=>{if(!Y||typeof window>"u")return;const he=new IC;let Q=0;const _e=De=>!!(te.current&&De instanceof Node&&te.current.contains(De)),ae=()=>{he.reset(),Q&&window.clearInterval(Q),Q=0,T(null)},Se=()=>{Q||(Q=window.setInterval(()=>{he.active(Date.now())||ae()},250))},Oe=De=>{var jt;if(!Hi((jt=De.dataTransfer)==null?void 0:jt.types))return;he.enter(Date.now());const pt=_e(De.target),St=Ey(De.dataTransfer);T(Pt=>Pt&&Pt.over===pt&&Pt.count===(St??Pt.count)?Pt:{count:St??(Pt==null?void 0:Pt.count)??null,over:pt}),Se()},Fe=De=>{var St;if(!Hi((St=De.dataTransfer)==null?void 0:St.types))return;De.preventDefault(),he.over(Date.now());const pt=_e(De.target);De.dataTransfer&&(De.dataTransfer.dropEffect=pt&&!oe.current?"copy":"none"),T(jt=>jt&&jt.over===pt?jt:{count:(jt==null?void 0:jt.count)??Ey(De.dataTransfer),over:pt}),Se()},Ze=De=>{var pt;Hi((pt=De.dataTransfer)==null?void 0:pt.types)&&(he.leave(Date.now())||ae())},Le=De=>{var Ss;if(!Hi((Ss=De.dataTransfer)==null?void 0:Ss.types))return;const pt=_e(De.target),St=De.defaultPrevented&&!pt;if(De.preventDefault(),ae(),St)return;if(!pt){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:jt,folders:Pt}=lm(De.dataTransfer);Ne.current(jt,Pt)},Ke=De=>{De.key==="Escape"&&he.depth>0&&ae()};return window.addEventListener("dragenter",Oe),window.addEventListener("dragover",Fe),window.addEventListener("dragleave",Ze),window.addEventListener("drop",Le),window.addEventListener("dragend",ae),window.addEventListener("blur",ae),window.addEventListener("keydown",Ke),()=>{window.removeEventListener("dragenter",Oe),window.removeEventListener("dragover",Fe),window.removeEventListener("dragleave",Ze),window.removeEventListener("drop",Le),window.removeEventListener("dragend",ae),window.removeEventListener("blur",ae),window.removeEventListener("keydown",Ke),Q&&window.clearInterval(Q)}},[Y]);const q=he=>{if(!Y||L)return;const Q=S_(he.clipboardData);Q.length&&(he.preventDefault(),ve(Q,[]))},be=W?a.jsxs("div",{className:["pc-workflow-chat__dropzone",W.over?"is-over":"",L?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[a.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:a.jsx(de,{name:"paperclip",size:18})}),a.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[a.jsx("strong",{children:L?"Attachments are unavailable right now":Ay(W.count)}),L?null:a.jsx("span",{children:W.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,xe=W?L?"Attachments are unavailable right now":Ay(W.count):K,Pe=async he=>{if(!F)return;const Q=M,_e=++N.current;S.current=!0,f(null),_(null),n(!0);try{const ae=await F.onSteer(he,Q);if(!k.current||N.current!==_e)return;if(!(ae!=null&&ae.accepted)&&!(ae!=null&&ae.duplicate)){f({action:"steer",message:"the gateway did not accept this message (accepted=false)."});return}_({mode:Q,...typeof ae.seq=="number"?{seq:ae.seq}:{},duplicate:!!ae.duplicate}),e.onDraftChange("")}catch(ae){k.current&&N.current===_e&&f({action:"steer",message:ho(ae)})}finally{k.current&&N.current===_e&&(S.current=!1,n(!1))}},Qe=async()=>{const he=String(e.draft||"");if(L||S.current||!he.trim())return;if(J)return void Pe(he);if(!e.sendWhileBusy&&e.busy)return;const Q=B.length?B_(B):null;if(Q){f({action:"send",message:Q});return}const _e=++N.current,ae=new AbortController;x.current=ae,S.current=!0,f(null),_(null),n(!0);try{await e.onSend(he,{signal:ae.signal})}catch(Se){k.current&&N.current===_e&&!ae.signal.aborted&&f({action:"send",message:ho(Se)})}finally{x.current===ae&&(x.current=null),k.current&&N.current===_e&&(S.current=!1,n(!1))}},He=async()=>{if(L||$.current||!e.onCancel)return;const he=++E.current;$.current=!0,f(null),o(!0);const _e=x.current||new AbortController;_e.abort(new DOMException("Stopped by the user","AbortError"));try{await e.onCancel(_e.signal)}catch(ae){k.current&&E.current===he&&f({action:"cancel",message:ho(ae)})}finally{k.current&&E.current===he&&($.current=!1,o(!1))}},qe=async()=>{if(L||R.current||!e.onAttach)return;const he=++j.current;R.current=!0,f(null),u(!0);try{await e.onAttach()}catch(Q){k.current&&j.current===he&&f({action:"attach",message:ho(Q)})}finally{k.current&&j.current===he&&(R.current=!1,u(!1))}},ge=()=>{d&&((d.action==="send"||d.action==="steer")&&Qe(),d.action==="cancel"&&He(),d.action==="attach"&&qe())},$e=e.toolbar||null,st=he=>B1((Array.isArray(e.messages)?e.messages:[]).filter(Q=>!Q.toolActivity&&!Q.live&&String(Q.content||"").trim()),he?{heading:he}:void 0),tt=async he=>{if(!L){f(null);try{await he()}catch(Q){k.current&&f({action:"toolbar",message:ho(Q)})}}},Lt=async()=>{const he=await gl(st());k.current&&(C(he?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>k.current&&C("idle"),1200))},ce=$e?a.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[$e.onNewSession?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:L,onClick:()=>void tt($e.onNewSession),children:[a.jsx(de,{name:"plus",size:14}),a.jsx("span",{children:"New chat"})]}):null,$e.onClear?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:L,onClick:()=>void tt($e.onClear),children:[a.jsx(de,{name:"trash",size:14}),a.jsx("span",{children:"Clear"})]}):null,$e.copyTranscript?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"copy",onClick:()=>void Lt(),children:[a.jsx(de,{name:v==="copied"?"check":"copy",size:14}),a.jsx("span",{children:v==="copied"?"Copied":v==="failed"?"Copy failed":"Copy"})]}):null,$e.exportTranscript?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const he=$e.exportTranscript;W1({filename:he.filename,text:st(he.heading),mime:"text/markdown;charset=utf-8"})},children:[a.jsx(de,{name:"download",size:14}),a.jsx("span",{children:"Export"})]}):null]}):null,fe=M==="queue"?"Queue":"Steer",H=g?g.mode==="queue"?`Queued for the next turn${typeof g.seq=="number"?` (seq ${g.seq})`:""}.`:`${g.duplicate?"Already queued":"Queued"}${typeof g.seq=="number"?` (seq ${g.seq})`:""}. ${F!=null&&F.parked?"The run is waiting: your guidance delivers at its next wake (steers do not wake runs).":"Delivers at the run's next loop boundary."}`:"";return a.jsxs("section",{ref:te,className:["pc-workflow-chat",W?"pc-workflow-chat--dragging":"",W!=null&&W.over?"pc-workflow-chat--drag-over":"",e.className].filter(Boolean).join(" "),"aria-label":"Workflow chat","data-stream-replies":e.streamReplies||"gateway_default",children:[e.header||ce?a.jsxs("header",{className:["pc-workflow-chat__header",ce?"pc-workflow-chat__header--toolbar":""].filter(Boolean).join(" "),children:[e.header?a.jsx("div",{className:"pc-workflow-chat__header-main",children:e.header}):null,ce]}):null,a.jsx("div",{className:"pc-workflow-chat__transcript",children:a.jsx(b_,{messages:Array.isArray(e.messages)?e.messages:[],empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:a.jsxs(a.Fragment,{children:[e.interaction?a.jsx(JE,{interaction:e.interaction,disabled:L}):null,I?a.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${I?"blocked":""}`})}),d?a.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[a.jsxs("span",{children:["Could not"," ",d.action==="send"?"send this message":d.action==="steer"?M==="queue"?"queue this message":"steer the run":d.action==="attach"?"attach a file":d.action==="toolbar"?"complete that action":"stop the run",": ",d.message]}),d.action!=="toolbar"?a.jsx("button",{type:"button",onClick:ge,disabled:L,children:"Try again"}):null]}):null,a.jsxs("div",{className:"pc-workflow-chat__composer",children:[a.jsx(x_,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void Qe(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:L,busy:J?t:V,sendLabel:J?fe:e.sendLabel,busyLabel:J?M==="queue"?"Queueing…":"Steering…":e.busyLabel,rows:2,leading:e.attachments||B.length?a.jsxs("div",{className:"pc-workflow-chat__attachments",children:[B.length?a.jsx(GE,{items:B,onRemove:e.onRemoveAttachment,onRetry:e.onRetryAttachment,disabled:L}):null,e.attachments]}):null,overlay:be,onPaste:Y?q:void 0,actions:a.jsxs(a.Fragment,{children:[e.onAttach?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","aria-label":"Attach file","data-af-tip":"Attach a file",disabled:L||l,onClick:()=>void qe(),children:[a.jsx(de,{name:"paperclip",size:16}),a.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,J&&D.length>1?a.jsx("span",{className:"pc-workflow-chat__steer-modes",role:"group","aria-label":"While the run is busy",children:D.map(he=>a.jsx("button",{type:"button",className:"pc-workflow-chat__steer-mode","data-steer-mode":he,"aria-pressed":M===he,disabled:L||t,onClick:()=>p(he),children:he==="queue"?"Queue next turn":"Guide this run"},he))}):null,z&&e.onCancel?a.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:L||s||ie,onClick:()=>void He(),children:[a.jsx(de,{name:"x",size:14}),a.jsx("span",{children:s||ie?"Stopping…":"Stop"})]}):Z?a.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${Z.phase}`,role:"status","aria-live":"polite",children:Z.label}):null]})}),F?a.jsx("div",{className:"pc-workflow-chat__steer-status",role:"status","aria-live":"polite",children:H}):null,Y?a.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:xe}):null]}),e.footer?a.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function YE(e){return e.toolApprovalGranted?null:e.interaction}const Df={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function Ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Te(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function qi(e){return Array.isArray(e)?e:[]}function QE(e){const t=Ue(e);return!!(t&&(t.code==="revision_conflict"||t.reason_code==="revision_conflict"||t.status===409||t.name==="SessionToolPolicyConflict"))}function Dn(e){return Te(e==null?void 0:e.status).toLowerCase()||"unknown"}function _t(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Ls(e){const t=Ue(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function XE(e){const t=Ue(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Ff(e){const t=n=>{if(Array.isArray(n))return n.map(t);const s=Ue(n);if(!s)return n;const o={};for(const l of Object.keys(s).sort())o[l]=t(s[l]);return o};try{return JSON.stringify(t(e))}catch{return"[unserializable]"}}function Eh(e){if(typeof e=="string")return e.trim();const t=Ue(e);if(!t)return"";for(const n of["answer","response","message","text","content","output"]){const s=t[n];if(typeof s=="string"&&s.trim())return s.trim()}return""}function mo(e){const t=Eh(e);if(t)return t;if(!Ue(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function zy(e){if(!e)return"";for(const s of["prompt","request","task","message","query","input"]){const o=Te(e[s]);if(o)return o}const t=Ue(e.context);for(const s of["task","message"]){const o=Te(t==null?void 0:t[s]);if(o)return o}const n=qi(t==null?void 0:t.messages);for(let s=n.length-1;s>=0;s-=1){const o=Ue(n[s]);if(Te(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=Te(o==null?void 0:o.content);if(l)return l}return""}function W_(e){const t=Ue(e.result);return Ue(t==null?void 0:t.wait)}function zf(e){return e?Te(e.reason)==="subworkflow"||Te(e.wait_key).startsWith("subworkflow:"):!1}function By(e,t){return!!(e&&e.runId===t.runId&&Te(e.wait.wait_key)===Te(t.wait.wait_key))}function Ah(e){return Ue(e.effect)||{}}function ZE(e,t){return Te(e.run_id)||t}function Wy(e){return Te(e.ended_at)||Te(e.started_at)||void 0}function Uy(e){const t=new Set,n=m=>{const p=Te(m);p&&t.add(p)},s=Ue(e.result);n(s==null?void 0:s.sub_run_id),n(s==null?void 0:s.subRunId),n(s==null?void 0:s.child_run_id);const o=Ah(e),l=Ue(o.payload);Te(o.type)==="start_subworkflow"&&(n(l==null?void 0:l.sub_run_id),n(l==null?void 0:l.subRunId),n(l==null?void 0:l.child_run_id));const u=W_(e),d=Ue(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 f=Te(u==null?void 0:u.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}const Bf=new WeakMap,eA=/^(live|live-end|stream-unavailable):/;function tA(e){return!!(e&&typeof e=="object"&&e.name==="ReplayViewUnavailableError")}function Vy(e){const t=String(e||""),n=t.indexOf("~");return n<0?"":t.slice(n+1)}class nA{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Df},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0,this.sessionToolPolicy=null,this.sessionPolicyUnavailableReason="",this.sessionPolicyState=null,this.sessionPolicyClamped=[],this.toolPolicyByCall=new Map,this.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds=new Set,this.viewTerminalRuns=new Set,this.viewStreamEnded=!1;const s=n.liveRenderIntervalMs??60;if(typeof s!="number"||!Number.isFinite(s)||s<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(n.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=s,this.sessionToolPolicy=n.sessionToolPolicy||null,this.sessionToolPolicy||(this.sessionPolicyUnavailableReason=Te(n.sessionToolPolicyUnavailableReason)),this.snapshot=this.withSessionPolicy({...Df})}sessionPolicyMode(){var t;return((t=this.sessionToolPolicy)==null?void 0:t.supported)===!0?"gateway":!this.sessionToolPolicy&&this.sessionPolicyUnavailableReason?"unavailable":"local-fallback"}sessionPolicyStatus(){const t=this.sessionPolicyMode();return{mode:t,...t==="unavailable"?{reason:this.sessionPolicyUnavailableReason}:{},clamped:this.sessionPolicyClamped,policy:this.sessionPolicyState}}setSessionToolPolicyClient(t,n={}){const s=t?"":Te(n.reason);if(t===this.sessionToolPolicy&&s===this.sessionPolicyUnavailableReason)return;const o=!!(t&&this.sessionToolPolicy&&t.sessionId===this.sessionToolPolicy.sessionId);this.sessionToolPolicy=t,this.sessionPolicyUnavailableReason=s,o||(this.sessionPolicyState=null,this.sessionPolicyClamped=[]),this.set({...this.snapshot})}gatewayPolicy(){const t=this.sessionToolPolicy;if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);if(!t||t.supported!==!0)throw new Error("This gateway cannot store chat tool policies (session_tool_policy is not supported).");return t}adoptSessionPolicy(t){var n,s;this.sessionPolicyState=t,this.sessionPolicyClamped=Array.isArray(t==null?void 0:t.clamped)?t.clamped.filter(o=>o&&typeof o=="object"):[],this.set({...this.snapshot}),(s=(n=this.options).onSessionPolicy)==null||s.call(n,t,this.sessionPolicyClamped)}async loadSessionPolicy(){const t=await this.gatewayPolicy().get();return this.adoptSessionPolicy(t),t}requireRootSession(t){var s,o;const n=Te((s=this.snapshot.run)==null?void 0:s.session_id)||Te((o=this.runStates.get(this.rootRunId))==null?void 0:o.session_id);if(!n)throw new Error("This chat's session is not known yet: the policy is written to the root run's session.");if(n!==t.sessionId)throw new Error(`The tool policy client is bound to session ${t.sessionId}, but this chat's root run belongs to session ${n}: the policy is written to the root run's session.`)}async currentRevision(t){var o;if(typeof((o=this.sessionPolicyState)==null?void 0:o.revision)=="number")return this.sessionPolicyState.revision;const n=await this.loadSessionPolicy();if(typeof(n==null?void 0:n.revision)=="number")return n.revision;const s=t.revision;return typeof s=="number"?s:void 0}async policyWriteError(t){if(QE(t))return await this.loadSessionPolicy().catch(()=>null),new Error("Someone changed this chat's policy; re-read it before deciding again (it was refreshed).");const n=t instanceof Error?t.message:String(t);return new Error(`This chat's policy was not changed: ${n}`)}requireTarget(t){const n=this.requireInteraction();if(_t(this.snapshot.status))throw new Error("This run has already ended.");if(n.runId!==t.runId||Te(n.wait.wait_key)!==t.waitKey||t.stepId!==void 0&&n.stepId!==t.stepId)throw new Error("This approval request has changed. Review the current request before deciding.");if(!this.isToolApproval(n))throw new Error("This is not a tool approval request.");return n}async writeThenAnswer(t,n,s,o=[]){this.requireTarget(t);const l=this.gatewayPolicy();this.requireRootSession(l);const u=[...new Set(o.map(m=>Te(m)).filter(Boolean))];let d={};if(n.deny){const m=await this.currentRevision(l);if(typeof m!="number")throw new Error("This chat's policy was not changed: the gateway did not return a policy revision to guard the deny with.");d={if_revision:m}}let f;try{f=await l.merge({...n,...u.length?{ask:u}:{},...d,client:n.client||"panel-chat"})}catch(m){throw await this.policyWriteError(m)}this.sessionToolPolicy===l&&this.adoptSessionPolicy(f);try{await this.approve(s,t)}catch(m){const p=m instanceof Error?m.message:String(m);throw new Error(`This chat's tool policy was saved, but this request was not answered: ${p} The policy does not answer requests that were already waiting.`)}return f}async approveAllForSession(t,n={}){const s=this.sessionPolicyMode();if(s==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);return s!=="gateway"?(await this.allowAllToolsForRun(t),null):this.writeThenAnswer(t,{approve:{all:!0,...typeof n.maxRiskRank=="number"?{max_risk_rank:n.maxRiskRank}:{}}},!0,n.ask)}approveKindForSession(t,n,s={}){return this.writeThenAnswer(t,{approve:{kinds:[n]}},!0,s.ask)}denyKindForSession(t,n,s={}){return this.writeThenAnswer(t,{deny:{kinds:[n]}},!1,s.ask)}denyToolForSession(t,n,s={}){return this.writeThenAnswer(t,{deny:{tools:[n]}},!1,s.ask)}async resetSessionPolicy(){if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason}`);if(this.sessionPolicyMode()!=="gateway"){this.revokeToolApproval();return}const t=this.gatewayPolicy();this.requireRootSession(t);const n=await this.currentRevision(t);if(typeof n!="number")throw new Error("This chat's policy was not reset: the gateway did not return a policy revision to guard the reset with.");try{await t.reset(n)}catch(s){throw await this.policyWriteError(s)}this.adoptSessionPolicy(null)}withSessionPolicy(t){const n=this.sessionPolicyMode(),{sessionPolicyReason:s,...o}=t;return{...o,sessionPolicyMode:n,...n==="unavailable"?{sessionPolicyReason:this.sessionPolicyUnavailableReason}:{},sessionPolicy:this.sessionPolicyState,sessionPolicyClamped:this.sessionPolicyClamped}}withSource(t){const{source:n,sourceReason:s,...o}=t;return this.source?{...o,source:this.source.source,...this.source.reason?{sourceReason:this.source.reason}:{}}:o}subscribe(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}getSnapshot(){return this.snapshot}reset(){var t;this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.approvalEpoch+=1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps.clear(),this.forcedStop=null,this.generation+=1,(t=this.controller)==null||t.abort(),this.controller=null,this.rootRunId="",this.cursors.clear(),this.seenRecords.clear(),this.seenMessages.clear(),this.watchedRuns.clear(),this.childCatchUpAttempts.clear(),this.runStates.clear(),this.historicalRuns.clear(),this.historicalRunFailures.clear(),this.commandIds.clear(),this.toolActivities.clear(),this.toolPolicyByCall.clear(),this.historicalEvidence.clear(),this.approvedWaits.clear(),this.grantedToolWaits.clear(),this.resolvedWaits.clear(),this.liveReplies.clear(),this.closedLiveCalls.clear(),this.shownLiveCalls.clear(),this.liveDirty.clear(),this.lastLiveRender=-1/0,this.liveRenderTimer&&(clearTimeout(this.liveRenderTimer),this.liveRenderTimer=null),this.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds.clear(),this.viewTerminalRuns.clear(),this.viewStreamEnded=!1,this.set({...Df})}dispose(){this.reset(),this.subscribers.clear()}async load(t){const n=Te(t);if(this.reset(),!n)return;const s=++this.generation,o=new AbortController;this.controller=o,this.rootRunId=n,this.set({...this.snapshot,loading:!0,status:"loading",error:null,connection:"connecting"});try{if(await this.loadView(n,s,o.signal)||!this.live(s))return;this.set({...this.snapshot});const[l,u]=await Promise.all([this.transport.getRun(n,o.signal),this.transport.getHistory(n,o.signal)]);if(!this.live(s))return;const d=Ue(l),f=Ue(d==null?void 0:d.waiting),m=Dn(d);if(await this.ingestHistory(u,n,s),!this.live(s))return;if(this.set({...this.snapshot,run:d,status:m,loading:!1,...f&&!_t(m)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),d&&this.updateRunState(n,d),f)for(const p of Uy({result:{wait:f}}))p!==n&&this.catchUpAndWatch(p,s);await this.catchUpAndWatch(n,s),this.pollRootLifecycle(n,s)}catch(l){!o.signal.aborted&&this.live(s)&&this.fail(l)}}async sendCommand(t,n={}){var p,g;t==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const s=Te(n.wait_key),o=t==="resume"?s?this.interactionRunId()||this.rootRunId:this.rootRunId:t==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!o)throw new Error("No workflow run is loaded");const l=t==="resume"&&s&&((p=this.snapshot.interaction)==null?void 0:p.stepId)||"",u=`${o}\0${t}\0${l}\0${Ff(n)}`;let d=this.commandIds.get(u);d||(d=this.newCommandId(),this.commandIds.set(u,d));const f=this.generation,m=(g=this.controller)==null?void 0:g.signal;try{const _=await this.transport.submitCommand({command_id:d,run_id:o,type:t,payload:n,...this.options.clientId?{client_id:this.options.clientId}:{}},m);if(!this.live(f))return _;const v=Ue(_);if(v&&v.accepted===!1)throw t==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Te(v.detail)||"Gateway did not accept the command");return this.commandIds.delete(u),this.viewFold?["pause","resume","cancel"].includes(t)&&this.refreshViewRun(f):o===this.rootRunId&&["pause","resume","cancel"].includes(t)&&this.refreshRunState(o,f),_}catch(_){throw this.live(f)&&this.fail(_,!1),_}}resume(t,n){const s=this.requireInteraction();if(n&&(s.runId!==n.runId||Te(s.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&s.stepId!==n.stepId))throw new Error("This question has changed. Review the current question before answering.");return this.sendCommand("resume",{wait_key:Te(s.wait.wait_key),payload:{response:t}})}answerEvent(t,n){const s=this.requireInteraction();if(n&&(s.runId!==n.runId||Te(s.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&s.stepId!==n.stepId))throw new Error("This wait has changed. Review the current one before answering.");if(!s.command)throw new Error("This wait has no resume command (it does not come from the replay view): send the event instead.");return this.sendCommand("resume",{wait_key:Te(s.wait.wait_key),payload:t})}approve(t,n){const s=this.requireInteraction();if(_t(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(s.runId!==n.runId||Te(s.wait.wait_key)!==n.waitKey||n.stepId!==void 0&&s.stepId!==n.stepId))throw new Error("This approval request has changed. Review the current request before deciding.");if(t&&this.toolApprovalPolicy&&!this.toolCallsMatch(s,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 o=this.generation;return this.sendCommand("resume",{wait_key:Te(s.wait.wait_key),payload:{approved:!!t}}).then(l=>{if(!this.live(o))return l;const u=this.occurrenceKey(s);return this.approvedWaits.add(u),t&&this.isToolApproval(s)&&!this.grantedToolWaits.has(u)&&(this.grantedToolWaits.add(u),this.set({...this.snapshot})),l})}async approveWithPolicyChange(t,n){const s=this.generation,o=this.approvalEpoch;if(!this.isToolApproval(this.requireInteraction()))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(s)||o!==this.approvalEpoch||this.toolApprovalStopped||_t(this.snapshot.status))&&n()}async allowAllToolsForRun(t){const n=this.generation,s=this.approvalEpoch,o=this.requireInteraction();if(!this.isToolApproval(o))throw new Error("This is not a tool approval request.");await this.approve(!0,t),!(!this.live(n)||s!==this.approvalEpoch||_t(this.snapshot.status))&&(this.approvedWaits.add(`${t.runId}:${t.waitKey}${o.stepId?`:${o.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(t){Ff(t)!==Ff(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}:${Te(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&zf(t.wait)&&!zf(n.wait)?n:n&&By(n,t)&&t.stepId===void 0&&n.stepId!==void 0?{...t,stepId:n.stepId}:t}adoptDurableWait(t,n){const s=Ue(n.waiting);if(!s||Dn(n)!=="waiting"||zf(s)||_t(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Te(s.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:s}),l=this.snapshot.interaction;l&&By(l,o)&&l.stepId===o.stepId||this.set({...this.snapshot,interaction:o})}coveredByStandingPermission(t,n){var s;return t.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!t.autoApproveTools||_t(t.status)||((s=t.run)==null?void 0:s.paused)===!0||t.status==="paused"||!n||!this.isToolApproval(n)||this.toolApprovalPolicy&&(!this.toolCallsMatch(n,this.toolApprovalPolicy.enabledTools)||!this.toolCallsMatch(n,this.toolApprovalPolicy.autoApproveTools))?!1:!!Te(n.wait.wait_key)}present(t){const n=t.interaction,s=n?this.occurrenceKey(n):"",o=!!(n&&this.isToolApproval(n)&&(this.grantedToolWaits.has(s)||!this.approvedWaits.has(s)&&this.coveredByStandingPermission({...t,loading:!1},n)));if(!o&&!this.snapshot.toolApprovalGranted&&!t.toolApprovalGranted)return t.toolApprovalGranted===!1?t:{...t,toolApprovalGranted:!1};let l=!1;const u=t.messages.map(d=>{var p;const f=d.toolActivity;if(!f||((p=this.toolActivities.get(f.id))==null?void 0:p.status)!=="waiting")return d;const m=o&&f.runId===(n==null?void 0:n.runId)?"running":"waiting";return f.status===m?d:(l=!0,this.toolMessage({...f,status:m}))});return{...t,toolApprovalGranted:o,...l?{messages:u}:{}}}toolCallsMatch(t,n){var o;const s=qi((o=Ue(t.wait.details))==null?void 0:o.tool_calls);return s.length>0&&s.every(l=>{var d;const u=Te((d=Ue(l))==null?void 0:d.name);return!!u&&n.includes(u)})}isToolApproval(t){const n=Ue(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:Te(t.wait.wait_key),stepId:t.stepId},s=this.occurrenceKey(t);if(this.approvedWaits.has(s))return;this.approvedWaits.add(s),this.grantedToolWaits.add(s);const o=this.generation,l=this.approvalEpoch;this.approve(!0,n).catch(u=>{if(this.live(o)){if(this.grantedToolWaits.delete(s),l!==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(!Te(this.snapshot.interaction.wait.wait_key))throw new Error("The workflow wait has no wait_key");return this.snapshot.interaction}interactionRunId(){var t;return((t=this.snapshot.interaction)==null?void 0:t.runId)||""}live(t){var n;return t===this.generation&&!((n=this.controller)!=null&&n.signal.aborted)}set(t){this.snapshot=this.present(this.withSource(this.withSessionPolicy(t)));for(const n of this.subscribers)n();this.autoApproveCurrentWait()}async loadView(t,n,s){const o=this.transport.replayView,l=p=>(this.live(n)&&(this.source={source:"ledger_fold",reason:p}),!1);if(!o)return l("this app's transport does not read the replay view");if(o.advertised===!1)return l("the gateway does not advertise the replay view");const u=Bf.get(o);if(typeof u=="string")return l(u);let d,f;try{[d,f]=await Promise.all([o.getView(t,{signal:s}),this.transport.getRun(t,s)])}catch(p){if(!tA(p))throw p;const g=p instanceof Error?p.message:"the gateway does not serve the replay view";return Bf.set(o,g),l(g)}if(Bf.set(o,!0),!this.live(n))return!0;if(d.notModified)throw new Error("The gateway answered 304 to a replay view read without If-None-Match.");this.source={source:"replay_view"},this.viewRun=Ue(f);const m=new xE;return m.adopt(d.view,d.etag),this.viewFold=m,this.viewDigest=Vy(m.lastEventId),this.adoptView(),this.followView(t,n),this.followLiveReplies(t,n),!0}adoptView(){var m,p,g;const t=(m=this.viewFold)==null?void 0:m.view;if(!t)return;const n=D_(t);this.toolActivities=new Map(n.tools.map(_=>[_.id,_]));for(const _ of n.endedLlmCalls)this.closedLiveCalls.has(_)||this.closeLiveReply(_);for(const _ of t.messages||[])_.role!=="assistant"||this.viewAssistantIds.has(_.id)||(this.viewAssistantIds.add(_.id),this.closeLiveRepliesOfRun(_.run_id));for(const[_,v]of n.runStatus)!_t(v)||this.viewTerminalRuns.has(_)||(this.viewTerminalRuns.add(_),this.endLiveRepliesOfRun(_,v));this.openLlmSteps=new Set(n.openLlmCalls);const s=_t(n.status),o=this.snapshot.messages.filter(_=>eA.test(String(_.id||""))),l={...this.viewRun||{},run_id:t.root_run_id,status:n.status,...t.session_id?{session_id:t.session_id}:{}};let u=n.interaction;const d=this.snapshot.interaction;if(u&&d&&d.runId===u.runId&&Te(d.wait.wait_key)===Te(u.wait.wait_key)&&d.stepId!==u.stepId&&(d.stepId===void 0||u.stepId===void 0)){const{stepId:_,...v}=u;u=d.stepId===void 0?v:{...v,stepId:d.stepId}}this.set({...this.snapshot,view:t,run:l,status:n.status,displayStatus:s?"":n.displayStatus,messages:[...n.messages,...o],interaction:u,loading:!1,...s?{autoApproveTools:!1}:{}}),(this.stopRequested||this.forcedStop)&&this.recomputeStop();const f=Vy((p=this.viewFold)==null?void 0:p.lastEventId);f!==this.viewDigest&&Object.keys(((g=t.cursor)==null?void 0:g.runs)||{}).length<=32&&(this.viewDigest=f,this.refreshViewRun(this.generation))}async followView(t,n){const s=this.transport.replayView,o=this.viewFold;if(!s||!o)return;let l=0;for(;this.live(n)&&this.viewFold===o&&!o.terminal;){this.set({...this.snapshot,connection:l?"reconnecting":"connecting"});try{if(await s.streamView(t,{lastEventId:o.lastEventId,signal:this.controller.signal,onOpen:()=>{this.live(n)&&this.set({...this.snapshot,connection:"connected",error:null})},onFrame:u=>{if(!this.live(n)||this.viewFold!==o)return;l=0;const d=o.apply(u);(d==="view"||d==="delta")&&this.adoptView()}}),!this.live(n))return;if(o.terminal)break;l+=1}catch(u){if(!this.live(n))return;if(l+=1,this.fail(u,!1),Ls(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(l>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(l-1)))}if(this.viewStreamEnded=!0,!(!this.live(n)||this.viewFold!==o)){if(o.terminal||_t(this.snapshot.status)){this.set({...this.snapshot,connection:"disconnected"});return}this.set({...this.snapshot,connection:"disconnected",error:this.snapshot.error||"Replay view stream reconnect limit reached. Reconnect the workflow to continue."})}}async followLiveReplies(t,n){var o,l,u;let s=0;try{for(;this.live(n)&&this.viewFold&&!this.viewStreamEnded&&!_t(this.snapshot.status);){const d=Number((u=(l=(o=this.viewFold.view)==null?void 0:o.cursor)==null?void 0:l.runs)==null?void 0:u[t])||0;this.dropLiveRepliesVia(t);try{if(await this.transport.streamLedger(t,d,()=>{},this.controller.signal,void 0,f=>{this.live(n)&&(s=0,this.ingestDelta(t,f))}),!this.live(n))return;s+=1}catch(f){if(!this.live(n))return;if(s+=1,Ls(f)){this.fail(f);return}}if(s>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(s-1)))}}finally{this.live(n)&&this.closeLiveRepliesVia(t)}}async refreshView(t){var l;const n=this.transport.replayView,s=this.viewFold;if(!n||!s)return;const o=await n.getView(this.rootRunId,{ifNoneMatch:s.lastEventId?`"${s.lastEventId}"`:null,signal:(l=this.controller)==null?void 0:l.signal});!this.live(t)||this.viewFold!==s||o.notModified||s.adopt(o.view,o.etag)&&this.adoptView()}async refreshViewRun(t){var n;try{const s=Ue(await this.transport.getRun(this.rootRunId,(n=this.controller)==null?void 0:n.signal));if(!s||!this.live(t)||!this.viewFold)return;this.viewRun=s,this.adoptView()}catch(s){this.live(t)&&this.fail(s,!1)}}async catchUpAndWatch(t,n){var s;if(!(!this.live(n)||this.watchedRuns.has(t))){this.watchedRuns.add(t);try{if(t!==this.rootRunId)try{const o=Ue(await this.transport.getRun(t,(s=this.controller)==null?void 0:s.signal));if(!this.live(n))return;o&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(Ls(o))throw o;this.fail(o,!1)}if(await this.catchUp(t,n),!this.live(n)||_t(Dn(this.runStates.get(t)||null)))return;this.childCatchUpAttempts.delete(t),this.watch(t,n)}catch(o){if(!this.live(n))return;if(this.watchedRuns.delete(t),t===this.rootRunId)throw o;if(Ls(o)){this.fail(o);return}const l=(this.childCatchUpAttempts.get(t)||0)+1;if(this.childCatchUpAttempts.set(t,l),this.fail(o,!1),l>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(l-1))),this.live(n)&&this.catchUpAndWatch(t,n)}}}async catchUp(t,n){var s;for(let o=0;o<100&&this.live(n);o+=1){const l=this.cursors.get(t)||0,u=await this.transport.getLedger(t,l,(s=this.controller)==null?void 0:s.signal);if(!this.live(n))return;const d=Ue(u),f=Array.isArray(u)?u:qi(d==null?void 0:d.items);for(const p of f)this.ingestItem(t,p);const m=Number(d==null?void 0:d.next_after);if(!f.length||!Number.isFinite(m)||m<=l)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 o;let s=0;for(;this.live(n)&&!_t(Dn(this.runStates.get(t)||null));){const l=this.cursors.get(t)||0;this.set({...this.snapshot,connection:s?"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,l,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 f=Ue(await this.transport.getRun(t,(o=this.controller)==null?void 0:o.signal));if(!this.live(n))return;f&&this.updateRunState(t,f),s+=1}catch(u){if(!this.live(n))return;if(s+=1,this.fail(u,!1),Ls(u)){this.set({...this.snapshot,connection:"disconnected"});return}}if(s>=5||!this.live(n))break;await this.waitForRetry(Math.min(2e3,150*2**(s-1)))}if(this.live(n)){if(_t(Dn(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,s){const o=Ue(t);if(!o)return;const l=Ue(o.session),u=qi(l==null?void 0:l.turns).map(Ue).filter(m=>!!m);if(await this.hydrateHistoricalSessionRuns(u,n,s),!this.live(s))return;for(const m of u){const p=Te(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=zy(Ue(o.input_data));m&&this.addMessage({id:d,role:"user",content:m})}const f=Ue(o.ledgers);if(f)for(const[m,p]of Object.entries(f)){const g=Ue(p);for(const _ of qi(g==null?void 0:g.items))this.ingestItem(m,_)}}ingestSessionTurn(t,n,s){if(!t)return;const o=Te(t.run_id)||n,l=Ue(t.input_data)||Ue(t.input)||{},u=Te(t.prompt)||zy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:Te(t.created_at)||void 0});const d=this.historicalRunFailures.get(o);if(d){const g=Te(t.answer)||Eh(t.output),_=d.missing?"is unavailable because the run no longer exists":"could not be restored",v=g?` Saved reply (not verified as the final result): ${g}`:"";this.addMessage({id:`history:${o}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${_}.${v}`});return}const m=(s&&_t(Dn(s))?mo(s.output):"")||(s?Te(t.answer)||Eh(t.output):""),p=this.historicalEvidence.get(o);for(const g of(p==null?void 0:p.tools)||[])this.upsertTool(g);m&&this.addRunAssistantMessage(o,{id:`final:${o}`,role:"assistant",content:m,runId:o,statistics:p==null?void 0:p.statistics,ts:Te(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,s){const o=[...new Set(t.map(f=>Te(f.run_id)).filter(f=>f&&f!==n&&!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)))];if(!o.length||!this.live(s))return;let l=0,u=!1;const d=async()=>{var f,m,p;for(;!u&&this.live(s);){const g=o[l++];if(!g)return;try{const _=Ue(await this.transport.getRun(g,(f=this.controller)==null?void 0:f.signal));if(!this.live(s))return;if(_){this.historicalRuns.set(g,_);try{const v=await this.transport.getHistory(g,(m=this.controller)==null?void 0:m.signal);if(!this.live(s))return;this.historicalEvidence.set(g,el(OE(v)))}catch(v){if(!this.live(s))return;if(Ls(v))throw v;this.fail(new Error(`Earlier turn activity could not be restored: ${v instanceof Error?v.message:String(v)}`),!1)}}else this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(_){if(!this.live(s))return;const v=XE(_)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:v,detail:_ instanceof Error?_.message:Te((p=Ue(_))==null?void 0:p.detail)||"request failed"}),Ls(_)&&(u=!0,this.fail(_))}}};if(await Promise.all(Array.from({length:Math.min(4,o.length)},()=>d())),u&&this.live(s))for(const f of o)!this.historicalRuns.has(f)&&!this.historicalRunFailures.has(f)&&(this.historicalRuns.set(f,null),this.historicalRunFailures.set(f,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(t,n){const s=Ue(n),o=Ue(s==null?void 0:s.record)||s;if(!o)return;const l=ZE(o,t),u=Number(s==null?void 0:s.cursor),d=Number.isFinite(u)&&u>0?u:(this.cursors.get(l)||0)+1,f=`${l}:${d}`;if(!this.seenRecords.has(f)){if(this.seenRecords.add(f),this.cursors.set(l,Math.max(this.cursors.get(l)||0,d)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:d,record:o,runId:l}]}),this.foldRecord(l,o,f),this.snapshot.messages.some(m=>m.id===`final:${this.rootRunId}`)){const m=el(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 Uy(o))m!==l&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,s){var p,g,_;const o=Ah(n),l=Te(o.type).toLowerCase(),u=Ue(n.result),d=Te(n.status).toLowerCase(),f=Wy(n);if(this.foldStopEvidence(t,n,l,d),["llm_call","tool_calls"].includes(l)&&["started","running"].includes(d)){const v=Date.parse(f||"");(!Number.isFinite(v)||v>=this.displayStatusAt)&&(Number.isFinite(v)&&(this.displayStatusAt=v),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(l==="answer_user"&&d==="completed"){const v=mo(u)||mo(Ue(o.payload));v&&this.addRunAssistantMessage(t,{id:`answer:${t}:${s}`,role:"assistant",content:v,ts:f})}if(l==="emit_event"&&d==="completed"){const v=Ue(o.payload)||{},C=Ue(u),x=Te(v.name)||Te(C==null?void 0:C.name),k=v.payload!==void 0?v.payload:C==null?void 0:C.payload;if(["abstract.message","abstractcode.message"].includes(x)){const S=mo(k);if(S){const $=Te((p=Ue(k))==null?void 0:p.level).toLowerCase(),R=$==="error"?"error":["warn","warning"].includes($)?"warn":"info";this.addMessage({id:`event:${t}:${s}`,role:"system",title:"Workflow",content:S,level:R,ts:f})}}if(["abstract.status","abstractcode.status"].includes(x)){const S=Ue(k),$=S?S.status??S.text??S.value:k,R=Date.parse(f||"");!_t(this.snapshot.status)&&typeof $=="string"&&(!Number.isFinite(R)||R>=this.displayStatusAt)&&(Number.isFinite(R)&&(this.displayStatusAt=R),this.set({...this.snapshot,displayStatus:$.trim()}))}if(x==="abstract.tool_policy_decision"){const S=gC(Ue(k));if(S){this.addMessage({id:`policy:${t}:${s}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",content:fu(S.provenance),ts:f});for(const $ of S.calls){const R={...S.provenance,...$.matched?{matched:$.matched}:{}};this.toolPolicyByCall.set(`${t}:${$.callId}`,R);for(const N of this.toolActivities.values())N.runId===t&&N.callId===$.callId&&this.upsertTool(N)}}}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(x)){const S=mo(k);S&&this.addMessage({id:`event:${t}:${s}`,role:"system",title:"Tool activity",content:S,ts:f})}}const m=W_(n);if(d==="waiting"&&m&&!_t(this.snapshot.status)&&!_t(Dn(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Te(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...Te(n.step_id)?{stepId:Te(n.step_id)}:{}})})),l==="tool_calls")for(const v of F_(this.toolActivities,{runId:t,cursor:this.cursors.get(t)||0,record:n}))this.upsertTool(v);if(l==="resume"&&(u==null?void 0:u.resumed)===!0){const v=Te((g=Ue(o.payload))==null?void 0:g.wait_key);v&&this.resolvedWaits.add(`${t}:${v}`),((_=this.snapshot.interaction)==null?void 0:_.runId)===t&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(t,this.generation))}}foldStopEvidence(t,n,s,o){let l=!1;if(s==="llm_call"){const u=Te(n.step_id);if(u){const d=`${t}:${u}`;o==="started"?(this.openLlmSteps.add(d),l=!0):["completed","failed","cancelled","waiting"].includes(o)&&(l=this.openLlmSteps.delete(d)||l),["completed","failed","cancelled"].includes(o)&&this.closeLiveReply(d)}}if(s==="emit_event"&&o==="completed"){const u=Ue(Ah(n).payload)||{},d=Ue(n.result),f=Te(u.name)||Te(d==null?void 0:d.name),m=Ue(u.payload!==void 0?u.payload:d==null?void 0:d.payload);f==="abstract.status"&&Te(m==null?void 0:m.killed_by)==="kill_switch"&&(this.forcedStop=m,l=!0)}l&&this.recomputeStop()}recomputeStop(){let t=null;this.forcedStop?t={phase:"forced",label:Te(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 s=500,o=null;for(;this.live(t)&&((n=this.snapshot.stop)==null?void 0:n.phase)==="stopping";){if(await this.waitForRetry(s),!this.live(t))return;const l=this.viewFold?[]:[this.rootRunId,...[...this.watchedRuns].filter(d=>d!==this.rootRunId)];let u=!1;if(this.viewFold)try{await this.refreshView(t)}catch(d){u=!0,this.live(t)&&(this.fail(d,!1),o=this.snapshot.error)}for(const d of l)try{await this.catchUp(d,t)}catch(f){u=!0,this.live(t)&&(this.fail(f,!1),o=this.snapshot.error)}!u&&o&&this.snapshot.error===o&&(this.set({...this.snapshot,error:null}),o=null),s=Math.min(5e3,s*2)}}finally{this.generation===t&&(this.stopFollowing=!1)}}}addMessage(t){const n=Te(t.id)||`${t.role}:${t.content}:${t.ts||""}`;this.seenMessages.has(n)||(this.seenMessages.add(n),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...t,id:n}]}))}toolMessage(t){const n=t.callId?this.toolPolicyByCall.get(`${t.runId}:${t.callId}`):void 0;return P_(n?{...t,policy:n}:t)}upsertTool(t){const n=this.toolMessage(t),s=this.snapshot.messages.findIndex(l=>l.id===n.id);if(s<0){this.addMessage(n);return}const o=[...this.snapshot.messages];o[s]=n,this.set({...this.snapshot,messages:o})}addRunAssistantMessage(t,n){this.closeLiveRepliesOfRun(t);const s=`answer:${t}:`,o=`final:${t}`;this.snapshot.messages.some(l=>l.role==="assistant"&&l.content===n.content&&(l.id===o||String(l.id||"").startsWith(s)))||this.addMessage(n)}ingestDelta(t,n){let s;try{s=N_(n)}catch(f){this.fail(f,!1);return}const o=`${s.run_id}:${s.call_id}`;if(j_(s)){if(s.reason==="unavailable"){this.noteStreamUnavailable(s);return}if(s.reason==="cancelled"&&s.detail==="reinvoked"){this.closeLiveReply(o,"restarted");return}this.closeLiveReply(o,s.reason==="completed"?void 0:s.reason);return}if(this.closedLiveCalls.has(o)||this.runEnded(s.run_id)||this.runEnded(this.rootRunId))return;const l=this.liveReplies.get(o)||{runId:s.run_id,callId:s.call_id,nodeId:s.node_id||"",via:t,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},u=s.channel==="reasoning"?"reasoning":"text",d=l.seq[s.channel];if(s.snapshot){if(s.seq<d)return;l[u]=s.text}else{if(s.seq<=d)return;l[u]+=s.text}l.seq[s.channel]=s.seq,l.via=t,this.liveReplies.set(o,l),this.liveDirty.add(o),this.scheduleLiveRender()}runEnded(t){var s,o;const n=(s=this.viewFold)==null?void 0:s.view;return n?_t(String(((o=n.runs.find(l=>l.run_id===t))==null?void 0:o.status)||""))||t===this.rootRunId&&_t(String(n.status||"")):_t(Dn(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 s=this.liveReplies.get(n);if(!s)continue;const o=this.liveMessage(s),l=t.findIndex(u=>u.id===o.id);l<0?t.push(o):t[l]=o,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 s=this.liveReplies.get(t);if(!s){n==="restarted"&&this.shownLiveCalls.has(t)&&this.addMessage(this.restartNote(t));return}this.liveReplies.delete(t),this.liveDirty.delete(t);const o=`live:${s.runId}:${s.callId}`,l=this.snapshot.messages.findIndex(d=>d.id===o);if(l<0)return;const u=[...this.snapshot.messages];if(n==="restarted"){const d=this.restartNote(t);this.seenMessages.add(String(d.id)),u[l]=d}else if(n){const d=`live-end:${s.runId}:${s.callId}`;this.seenMessages.add(d),u[l]={id:d,role:"system",level:"warn",title:"Reply",runId:s.runId,content:n==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else u.splice(l,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:DC(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 s of[...this.liveReplies.values()])(s.via===t||s.runId===t)&&this.closeLiveReply(`${s.runId}:${s.callId}`,n)}endLiveRepliesOfRun(t,n){const s=n==="failed"||n==="cancelled"?n:void 0;if(t===this.rootRunId){for(const o of[...this.liveReplies.values()])this.closeLiveReply(`${o.runId}:${o.callId}`,s);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(t,s);for(const o of[...this.closedLiveCalls])o.startsWith(`${t}:`)&&this.closedLiveCalls.delete(o);for(const o of[...this.shownLiveCalls])o.startsWith(`${t}:`)&&this.shownLiveCalls.delete(o)}dropLiveRepliesVia(t){const n=new Set;for(const[s,o]of this.liveReplies)o.via===t&&(this.liveReplies.delete(s),this.liveDirty.delete(s),n.add(`live:${o.runId}:${o.callId}`));n.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(s=>!n.has(String(s.id)))})}fail(t,n=!0){var s,o,l;Ls(t)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(o=(s=this.options).onAuthError)==null||o.call(s,t)),this.set({...this.snapshot,error:t instanceof Error?t.message:Te((l=Ue(t))==null?void 0:l.detail)||String(t),...Ls(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 s=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(t,n){var l;if(this.runStates.set(t,n),_t(Dn(n))&&this.endLiveRepliesOfRun(t,Dn(n)),t!==this.rootRunId){_t(Dn(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const s=Dn(n),o=_t(s);if(o){const u=mo(n.output);u&&this.upsertFinal(t,u,Wy(n))}this.set({...this.snapshot,run:n,status:s,...o?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),o||this.adoptDurableWait(t,n),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(t,n,s){this.closeLiveRepliesOfRun(t);const o=`final:${t}`;this.seenMessages.add(o);const l={id:o,role:"assistant",content:n,ts:s,runId:t,statistics:el(this.snapshot.records).statistics},u=this.snapshot.messages.findIndex(f=>f.id===o||String(f.id||"").startsWith(`answer:${t}:`)&&f.content===n);if(u<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,l]});return}const d=[...this.snapshot.messages];d[u]=l,this.set({...this.snapshot,messages:d})}async refreshRunState(t,n){var s;try{const o=Ue(await this.transport.getRun(t,(s=this.controller)==null?void 0:s.signal));o&&this.live(n)&&this.updateRunState(t,o)}catch(o){this.live(n)&&this.fail(o,!1)}}async pollRootLifecycle(t,n){var s;for(;this.live(n)&&this.rootRunId===t&&!_t(Dn(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||_t(Dn(this.runStates.get(t)||null)))return;try{const o=Ue(await this.transport.getRun(t,(s=this.controller)==null?void 0:s.signal));o&&this.live(n)&&this.rootRunId===t&&this.updateRunState(t,o)}catch(o){if(!this.live(n))return;if(Ls(o)){this.fail(o);return}this.fail(o,!1)}}}waitForRetry(t){var o;const n=(o=this.controller)==null?void 0:o.signal;if(!n||n.aborted)return Promise.resolve();const s=n;return new Promise(l=>{const u=setTimeout(f,t),d=()=>{clearTimeout(u),f()};function f(){s.removeEventListener("abort",d),l()}s.addEventListener("abort",d,{once:!0})})}}function sA(e){const t=y.useMemo(()=>new nA(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(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),s=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||!s){t.reset();return}return t.load(s),()=>t.reset()},[t,s,e.enabled]),{controller:t,snapshot:n}}function ma(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function yn(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Gy(e){return["session","workflow","run","global"].includes(e)?e:null}function Mr(e){return{scope:yn(e==null?void 0:e.scope).toLowerCase(),name:yn(e==null?void 0:e.name)||yn(e==null?void 0:e.event_name),scopeId:yn(e==null?void 0:e.scope_id)||yn(e==null?void 0:e.scopeId),sessionId:yn(e==null?void 0:e.session_id)||yn(e==null?void 0:e.sessionId),workflowId:yn(e==null?void 0:e.workflow_id)||yn(e==null?void 0:e.workflowId),runId:yn(e==null?void 0:e.run_id)||yn(e==null?void 0:e.runId)}}function rA(e,t){const n=e.wait,s=yn(n.wait_key),o=[Mr(n),Mr(ma(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,d=ma(u.result),f=ma(d==null?void 0:d.wait),m=ma(u.effect),p=ma(m==null?void 0:m.payload);yn(f==null?void 0:f.wait_key)!==s&&yn(p==null?void 0:p.wait_key)!==s||o.push(Mr(u),Mr(p),Mr(ma(p==null?void 0:p.details)),Mr(f),Mr(ma(f==null?void 0:f.details)))}return o}function Wf(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function U_(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function aA(e,t,n){if(!n)return null;const s=`evt:${t}:${n}:`;if(!e.startsWith(s))return null;const o=e.slice(s.length);return o?U_(t,n,o):null}function oA(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const s=yn(e.wait.wait_key),o=/^evt:(session|workflow|run|global):/.exec(s);if(!o)return{target:null,error:"The gateway did not provide a canonical event wait key."};const l=Gy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=rA(e,Array.isArray(t)?t:[]),d=new Map;for(const _ of u){const v=Gy(_.scope);if(!v||!_.name)continue;if(v!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const C=`evt:${v}:`,x=`:${_.name}`;if(!s.startsWith(C)||!s.endsWith(x)||s.length<=C.length+x.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const k=s.slice(C.length,-x.length),S=Wf(v,_);if(S&&S!==k)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const $=U_(v,k,_.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 f=new Set;l==="run"&&f.add(e.runId),l==="global"&&f.add("global");for(const _ of u){const v=Wf(l,_);v&&f.add(v)}if(yn(n==null?void 0:n.run_id)===e.runId){const _=Mr(n||null),v=Wf(l,_);v&&f.add(v)}const p=[...f].map(_=>aA(s,l,_)).filter(_=>!!_),g=new Map(p.map(_=>[`${_.scope}\0${_.scopeId}\0${_.name}`,_]));return g.size===1?{target:[...g.values()][0]}:g.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}function iA(e){return a.jsx(c_,{text:e,images:"link"})}const lA={trigger:"Trigger",answer:"Automation"};function V_(e,t){return a.jsx(__,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:lA[e.kind],runId:e.runId},images:"link"})}const cA={renderText:iA,renderTurn:V_};function uA(e){const{fetchGateway:t,messageProps:n,...s}=e,o=s.onOpenResource??(t?l=>QC(t,l.url,{name:l.name}):void 0);return a.jsx(D0,{...s,onOpenResource:o,...cA,renderTurn:l=>V_(l,n)})}function dA(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function fA(e,t,n={}){var m;if(!e)return null;const s=dA(e)?M_(e):e,o=s.wait,l=`${s.runId}:${o.wait_key}:${s.stepId||""}`,u=o.details||{};if(u.mode==="approval_required"||u.kind==="tool_approval"){const p=Array.isArray(u.tool_calls)?u.tool_calls:[],g={runId:s.runId,waitKey:String(o.wait_key||""),stepId:s.stepId},_=[...new Set(p.map(j=>String((j==null?void 0:j.name)||"tool")))],v=n.onPermissionsAll,C=n.onAllowForSession,x=String(n.approveAllScope||"").trim(),k=((m=n.remember)==null?void 0:m.call(n,_))||void 0,S=Ji,$=C?{approveForSessionLabel:S.allowForChat,approveForSessionDescription:"Allow for this chat approves this batch and the enabled tools for the rest of this chat. Unchecked tools stay unavailable; questions still need your answer.",onApproveForSession:async()=>{let j;await t.approveWithPolicyChange(g,()=>{j=C()}),j&&await j.catch(I=>{throw new Error(`This batch was allowed, but "Allow for this chat" could not be turned on: ${I instanceof Error?I.message:String(I)}`)})}}:{};let R=$,N=[];const E=n.sessionPolicy;if(E){const j=t.approveAllForSession,I=t.approveKindForSession,L=t.denyToolForSession,z=t.denyKindForSession,V=t.sessionPolicyStatus;if(typeof j!="function"||typeof I!="function"||typeof L!="function"||typeof z!="function"||typeof V!="function")throw new Error("presentInteraction: sessionPolicy needs a WorkflowSessionController (approveAllForSession, approveKindForSession, denyToolForSession, denyKindForSession, sessionPolicyStatus).");const Z=V.call(t),ie=E.ask?[...E.ask]:void 0,F=(B,Y)=>{var W;const te=String(((W=B==null?void 0:B.scope)==null?void 0:W[Y])||"").trim();return te?`Applies: ${te}`:S.noScopeNote},D=B=>({outcomeNote:[Cy(B==null?void 0:B.clamped),F(B,"approve")].filter(Boolean).join(" ")}),M=B=>({outcomeNote:`${S.denyForChatNote} ${F(B,"deny")}`}),J=Cy(Z.clamped);if(Z.mode==="unavailable")R={scopeNote:S.unavailablePolicyNote(Z.reason||"")};else if(Z.mode==="gateway"){const B=[...new Set(p.map(T=>{var K;return String((T==null?void 0:T.toolset)||"").trim()||String(((K=E.toolsetOf)==null?void 0:K.call(E,String((T==null?void 0:T.name)||"")))||"").trim()}).filter(Boolean))],Y=(ie||[]).map(T=>String(T).trim()).filter(Boolean),te=Y.length?`Tools set to Ask keep asking: ${Y.join(", ")}.`:"Nothing is set to Ask, so tools that reach destinations the model picks (fetch_url, browser_probe, send_email) are included.",W=Z.policy;N=W?_.filter(T=>Object.prototype.hasOwnProperty.call(W.deny||{},T)):[],R={approveForSessionLabel:S.allowForChat,approveForSessionDescription:`Allow for this chat (and Allow all <toolset> tools for this chat) approves this batch and stores a policy for this chat on the gateway: later tool calls of every run of this chat run without asking, until the policy is reset. ${te} Tools the gateway does not authorize stay uncovered.`,onApproveForSession:async()=>D(await j.call(t,g,{...E.maxRiskRank!==void 0?{maxRiskRank:E.maxRiskRank}:{},...ie?{ask:ie}:{}})),approveKinds:B.map(T=>({kind:T,label:S.allowKindForChat(T),onApprove:async()=>D(await I.call(t,g,T,ie?{ask:ie}:{}))})),denyOptions:[..._.map(T=>({key:`tool:${T}`,label:S.denyToolForChat(T),onDeny:async()=>M(await L.call(t,g,T,ie?{ask:ie}:{}))})),...B.map(T=>({key:`kind:${T}`,label:S.denyKindForChat(T),onDeny:async()=>M(await z.call(t,g,T,ie?{ask:ie}:{}))}))],...N.length?{deniedNote:`Denied by this chat's policy: ${N.join(", ")}. The gateway refuses ${N.length===1?"it":"them"} even if allowed once.`}:{},...W?{policySummary:`This chat's policy: ${Object.keys(W.approve||{}).length} tools allowed without asking, ${Object.keys(W.deny||{}).length} denied. ${F(W,"approve")}`}:{},...J?{notCovered:J}:{}}}else R=C?{...$,scopeNote:S.localChatPolicyNote}:{approveForSessionLabel:S.allowForRun,onApproveForSession:async()=>{await j.call(t,g,{})},scopeNote:S.localRunPolicyNote}}return{id:l,kind:"tool-approval",title:`${p.length||"Requested"} ${p.length===1?"action needs":"actions need"} permission`,toolName:_.join(", ")||"the requested tools",description:"Review the targets below. Allow once approves this batch only.",detail:a.jsxs("div",{className:"pc-approval-summary",children:[a.jsx(im,{tools:p.map((j,I)=>({id:String((j==null?void 0:j.call_id)||(j==null?void 0:j.id)||I),runId:s.runId,name:(j==null?void 0:j.name)||"Tool",arguments:j==null?void 0:j.arguments,status:"waiting"}))}),a.jsxs("details",{children:[a.jsx("summary",{children:"Review full tool arguments (JSON)"}),a.jsx(Co,{value:p.length?p:u})]})]}),approveLabel:Ji.allowOnce,denyLabel:Ji.deny,approveAllLabel:v?Ji.allowAll:void 0,approveAllDescription:v?`Sets permissions: all${x?` ${x}`:""}, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.`:void 0,...R,...n.approveAllDisabledReason?{disabledReason:n.approveAllDisabledReason}:{},...k?{remember:k}:{},...n.onDefer?{onDefer:n.onDefer}:{},onApproveAll:v?async()=>{await t.approveWithPolicyChange(g,()=>{v()})}:void 0,onApprove:async()=>(await t.approve(!0,g),N.length?{outcomeNote:`The gateway refuses ${N.join(", ")}: denied by this chat's policy.`}:void 0),onDeny:async()=>{await t.approve(!1,g)}}}const d={runId:s.runId,waitKey:String(o.wait_key||""),stepId:s.stepId};if(o.reason==="user"||o.reason==="ask_user")return{id:l,kind:"ask-user",title:"A question for you",prompt:String(o.prompt||u.prompt||"How would you like to continue?"),allowFreeText:o.allow_free_text!==!1,choices:(Array.isArray(o.choices)?o.choices:[]).map(p=>typeof p=="object"&&p!==null?{id:String(p.value??p.id??p.label),label:String(p.label??p.text??p.value??p.id),description:p.description}:{id:String(p),label:String(p)}),onSubmit:async p=>{await t.resume(p,d)},...n.allowSkip?{onSkip:async()=>{await t.resume("",d)}}:{},...n.onDefer?{onDefer:n.onDefer}:{}};const f=String(o.wait_key||"");if(o.reason==="event"||f.startsWith("evt:")){if(s.command){const C=t.answerEvent;if(typeof C!="function")throw new Error("presentInteraction: an event wait from the replay view needs a WorkflowSessionController (answerEvent).");const x={runId:s.runId,waitKey:f,stepId:s.stepId};return{id:l,kind:"event-wait",title:"Waiting for your input",eventName:f,prompt:String(o.prompt||"This workflow is waiting for an event."),description:Array.isArray(o.choices)&&o.choices.length?`Expected: ${o.choices.map(k=>String(typeof k=="object"&&k!==null?k.label??k.value??"":k)).join(", ")}`:"The data you send resumes this wait.",initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send",onSend:async k=>{await C.call(t,JSON.parse(k||"{}"),x)}}}const g=oA(s,n.records||[],n.currentRun??null),_=g.target,v=(_==null?void 0:_.name)||"";return{id:l,kind:"event-wait",title:_?"Waiting for an event":"Event routing unavailable",eventName:v,prompt:String(o.prompt||`This workflow will continue when “${v||"its trigger"}” arrives.`),description:_?"You can also send the expected event here.":`This event cannot be sent safely. ${g.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async C=>{if(!_)throw new Error(g.error);const x=JSON.parse(C||"{}"),k={name:_.name,scope:_.scope,payload:x};_.scope==="session"?k.session_id=_.scopeId:_.scope==="workflow"?k.workflow_id=_.scopeId:_.scope==="run"&&(k.run_id=_.scopeId),await t.emitEvent(k)}}}return null}class G_{constructor(){zt(this,"_buffer","");zt(this,"_current",{data_lines:[]})}push(t,n){for(this._buffer+=t;;){const s=this._buffer.indexOf(`
88
- `);if(s===-1)return;const o=this._buffer.slice(0,s);this._buffer=this._buffer.slice(s+1);const l=o.endsWith("\r")?o.slice(0,-1):o;if(l.startsWith(":"))continue;if(l===""){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(`
89
- `)};n(m)}this._current={data_lines:[]};continue}const u=l.indexOf(":"),d=u===-1?l:l.slice(0,u),f=u===-1?"":l.slice(u+1).trimStart();d==="id"?this._current.id=f:d==="event"?this._current.event=f:d==="data"&&this._current.data_lines.push(f)}}}function ft(e){var s;const t=(e||"").trim(),n={};t&&(n.Authorization=`Bearer ${t}`);try{const o=(s=document.cookie.split(";").map(l=>l.trim()).find(l=>l.startsWith("abstractcode_gateway_csrf=")))==null?void 0:s.slice(26);o&&(n["X-AbstractCode-CSRF"]=decodeURIComponent(o))}catch{}return n}function hA(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 mA(e){var t;try{if(String(e.headers.get("content-type")||"").toLowerCase().includes("application/json")){const o=await e.json().catch(()=>null);if(o&&typeof o=="object"){const l=o.detail;if(typeof l=="string"&&l.trim())return l.trim();const u=(t=o.error)==null?void 0:t.message;if(typeof u=="string"&&u.trim())return u.trim();try{const d=JSON.stringify(o);if(d&&d!=="{}")return d}catch{}}}const s=await e.text();return s!=null&&s.trim()?s.trim():`${e.status}`}catch{return`${e.status}`}}class H_ extends Error{constructor(n,s){super(n);zt(this,"status");zt(this,"retry_after_s");zt(this,"body_text");this.name="GatewayHttpError",this.status=Number.isFinite(Number(s.status))?Number(s.status):0,this.retry_after_s=s.retry_after_s,this.body_text=s.body_text}}async function ht(e,t){const n=await mA(e);throw new H_(`${t}: ${n}`,{status:e.status,retry_after_s:hA(e),body_text:n})}class pA{constructor(t){zt(this,"_cfg");this._cfg={...t,base_url:(t.base_url||"").trim()}}async start_run(t,n,s){const o=String((s==null?void 0:s.bundle_id)||"").trim(),l=(s==null?void 0:s.session_id)===null||(s==null?void 0:s.session_id)===void 0?"":String(s.session_id||"").trim(),u=String(t||"").trim(),d={input_data:n||{}};o&&(d.bundle_id=o),u&&(d.flow_id=u),l&&(d.session_id=l);const f=await fetch(ut(this._cfg.base_url.trim(),we("runs/start")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(d)});if(!f.ok)return await ht(f,"start_run failed");const m=await f.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 s=await fetch(ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(n)}`)),{headers:{...ft(this._cfg.auth_token)}});return s.ok?await s.json():await ht(s,"get_run failed")}async get_run_history_bundle(t,n){const s=String(t||"").trim();if(!s)throw new Error("get_run_history_bundle: run_id is required");const o=new URLSearchParams;(n==null?void 0:n.include_subruns)===!1&&o.set("include_subruns","false"),(n==null?void 0:n.include_session)===!0&&o.set("include_session","true"),typeof(n==null?void 0:n.session_turn_limit)=="number"&&Number.isFinite(n.session_turn_limit)&&o.set("session_turn_limit",String(Math.max(1,Math.trunc(n.session_turn_limit)))),n!=null&&n.ledger_mode&&o.set("ledger_mode",String(n.ledger_mode)),typeof(n==null?void 0:n.ledger_max_items)=="number"&&Number.isFinite(n.ledger_max_items)&&o.set("ledger_max_items",String(Math.max(0,Math.trunc(n.ledger_max_items))));const l=ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(s)}/history_bundle?${o.toString()}`)),u=await fetch(l,{headers:{...ft(this._cfg.auth_token)}});return u.ok?await u.json():await ht(u,"get_run_history_bundle failed")}async list_runs(t){const n=new URLSearchParams,s=typeof(t==null?void 0:t.limit)=="number"?t.limit:50;n.set("limit",String(s));const o=String((t==null?void 0:t.status)||"").trim();o&&n.set("status",o);const l=String((t==null?void 0:t.workflow_id)||"").trim();l&&n.set("workflow_id",l);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=ut(this._cfg.base_url.trim(),we(`runs?${n.toString()}`)),f=await fetch(d,{headers:{...ft(this._cfg.auth_token)}});return f.ok?await f.json():await ht(f,"list_runs failed")}async get_ledger(t,n){const s=String(t||"").trim();if(!s)throw new Error("get_ledger: run_id is required");const o=Number((n==null?void 0:n.after)||0),l=Number((n==null?void 0:n.limit)||0),u=ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(s)}/ledger?after=${encodeURIComponent(String(o))}&limit=${encodeURIComponent(String(l))}`)),d=await fetch(u,{headers:{...ft(this._cfg.auth_token)}});if(!d.ok)return await ht(d,"get_ledger failed");const f=await d.json(),m=Array.isArray(f==null?void 0:f.items)?f.items:[],p=typeof(f==null?void 0:f.next_after)=="number"?f.next_after:o;return{items:m,next_after:p}}async stream_ledger(t,n){var C;const s=String(t||"").trim();if(!s)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 o=Number((n==null?void 0:n.after)||0),l=n.on_step,u=n.signal,d=ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(s)}/ledger/stream?after=${encodeURIComponent(String(o))}`)),f=await fetch(d,{headers:{Accept:"text/event-stream",...ft(this._cfg.auth_token)},signal:u});if(!f.ok)return await ht(f,"stream_ledger failed");if(!f.body)throw new Error("stream_ledger: response body is missing");(C=n.on_open)==null||C.call(n);const m=f.body.getReader(),p=new TextDecoder("utf-8"),g=new G_,_=n.on_delta,v=n.on_delta_error;for(;;){const{value:x,done:k}=await m.read();if(k)return;const S=p.decode(x,{stream:!0});g.push(S,$=>{if(_&&v){const R=$.event||"message",N=$.data??"";let E;try{E=C_(R,N)}catch(j){v(j instanceof Error?j:new Error(String(j)),{event:R,data:N});return}if(E){_(E);return}}if(!($.event!=="step"||!$.data))try{const R=JSON.parse($.data);R&&typeof R.cursor=="number"&&R.record&&l(R)}catch{}})}}async list_bundles(){const t=await fetch(ut(this._cfg.base_url.trim(),we("bundles")),{headers:{...ft(this._cfg.auth_token)}});return t.ok?await t.json():await ht(t,"list_bundles failed")}async reload_bundles(){const t=await fetch(ut(this._cfg.base_url.trim(),we("bundles/reload")),{method:"POST",headers:{...ft(this._cfg.auth_token)}});return t.ok?await t.json():await ht(t,"reload_bundles failed")}async upload_bundle(t,n){const s=(n==null?void 0:n.overwrite)===!0,o=(n==null?void 0:n.reload)!==!1,l=new FormData;l.set("overwrite",s?"true":"false"),l.set("reload",o?"true":"false"),l.set("file",t,t.name||"upload.flow");const u=await fetch(ut(this._cfg.base_url.trim(),we("bundles/upload")),{method:"POST",headers:{...ft(this._cfg.auth_token)},body:l});return u.ok?await u.json():await ht(u,"upload_bundle failed")}async discovery_tools(){const t=await fetch(ut(this._cfg.base_url.trim(),we("discovery/tools")),{headers:{...ft(this._cfg.auth_token)}});return t.ok?await t.json():await ht(t,"discovery_tools failed")}async discovery_providers(t){const n=(t==null?void 0:t.include_models)===!0,s=ut(this._cfg.base_url.trim(),we(`discovery/providers?include_models=${encodeURIComponent(String(n))}`)),o=await fetch(s,{headers:{...ft(this._cfg.auth_token)}});return o.ok?await o.json():await ht(o,"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 s=await fetch(ut(this._cfg.base_url.trim(),we(`discovery/providers/${encodeURIComponent(n)}/models`)),{headers:{...ft(this._cfg.auth_token)}});return s.ok?await s.json():await ht(s,"discovery_provider_models failed")}async discovery_model_capabilities(t,n=""){const s=String(t||"").trim();if(!s)throw new Error("discovery_model_capabilities: model_name is required");const o=new URLSearchParams({model_name:s});n.trim()&&o.set("provider",n.trim());const l=ut(this._cfg.base_url.trim(),we(`discovery/models/capabilities?${o}`)),u=await fetch(l,{headers:{...ft(this._cfg.auth_token)}});return u.ok?await u.json():await ht(u,"discovery_model_capabilities failed")}async workspace_policy(){const t=await fetch(ut(this._cfg.base_url.trim(),we("workspace/policy")),{headers:{...ft(this._cfg.auth_token)}});return t.ok?await t.json():await ht(t,"workspace_policy failed")}async files_search(t,n){const s=String(t||"").trim(),o=typeof(n==null?void 0:n.limit)=="number"&&Number.isFinite(n.limit)?Math.max(1,Math.trunc(n.limit)):20,l=new URLSearchParams;l.set("query",s),l.set("limit",String(o));const u=n==null?void 0:n.scope;if(u&&typeof u=="object"){const m=String(u.workspace_root||"").trim();m&&l.set("workspace_root",m)}const d=ut(this._cfg.base_url.trim(),we(`files/search?${l.toString()}`)),f=await fetch(d,{headers:{...ft(this._cfg.auth_token)},signal:n==null?void 0:n.signal});return f.ok?await f.json():await ht(f,"files_search failed")}async list_run_artifacts(t,n){const s=String(t||"").trim();if(!s)throw new Error("list_run_artifacts: run_id is required");const o=typeof(n==null?void 0:n.limit)=="number"?n.limit:200,l=ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(s)}/artifacts?limit=${encodeURIComponent(String(o))}`)),u=await fetch(l,{headers:{...ft(this._cfg.auth_token)}});return u.ok?await u.json():await ht(u,"list_run_artifacts failed")}async get_run_artifact_blob(t,n,s){const o=String(t||"").trim(),l=String(n||"").trim();if(!o)throw new Error("get_run_artifact_blob: run_id is required");if(!l)throw new Error("get_run_artifact_blob: artifact_id is required");const u=ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(l)}/content`)),d=await fetch(u,{headers:{...ft(this._cfg.auth_token)}});if(!d.ok)return await ht(d,"get_run_artifact_blob failed");const f=await d.blob(),m=typeof(s==null?void 0:s.max_bytes)=="number"&&Number.isFinite(s.max_bytes)?Math.max(0,Math.trunc(s.max_bytes)):0;if(m>0&&f.size>m)throw new Error(`Artifact too large (${f.size} bytes > ${m} bytes)`);const p=String(d.headers.get("content-type")||"").trim()||"application/octet-stream";return{blob:f,content_type:p}}async get_run_artifact_text(t,n,s){const{blob:o}=await this.get_run_artifact_blob(t,n,s);return await o.text()}async attachments_ingest(t,n,s){const o=String(t||"").trim(),l=String(n||"").trim();if(!o)throw new Error("attachments_ingest: session_id is required");if(!l)throw new Error("attachments_ingest: path is required");const u={session_id:o,path:l},d=s==null?void 0:s.scope;if(d&&typeof d=="object"){const _=String(d.workspace_root||"").trim();_&&(u.workspace_root=_)}const f=await fetch(ut(this._cfg.base_url.trim(),we("attachments/ingest")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(u)});if(!f.ok)return await ht(f,"attachments_ingest failed");const m=await f.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,s){const o=String(t||"").trim();if(!o)throw new Error("attachments_upload: session_id is required");if(!n)throw new Error("attachments_upload: file is required");const l=String((s==null?void 0:s.filename)||"").trim()||String((n==null?void 0:n.name)||"").trim()||"upload.bin",u=String((s==null?void 0:s.content_type)||"").trim()||String((n==null?void 0:n.type)||"").trim(),d=new FormData;d.append("session_id",o),d.append("file",n,l),d.append("filename",l),u&&d.append("content_type",u);const f=await fetch(ut(this._cfg.base_url.trim(),we("attachments/upload")),{method:"POST",headers:{...ft(this._cfg.auth_token)},body:d});if(!f.ok)return await ht(f,"attachments_upload failed");const m=await f.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 s=String(t||"").trim();if(!s)throw new Error("audio_transcribe: run_id is required");const o={audio_artifact:n==null?void 0:n.audio_artifact,request_id:(n==null?void 0:n.request_id)||void 0},l=(n==null?void 0:n.language)===null||(n==null?void 0:n.language)===void 0?"":String(n.language||"").trim();l&&(o.language=l),n!=null&&n.provider&&(o.provider=String(n.provider)),n!=null&&n.provider&&(n!=null&&n.model)&&(o.model=String(n.model));const u=await fetch(ut(this._cfg.base_url.trim(),we(`runs/${encodeURIComponent(s)}/audio/transcribe`)),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(o)});return u.ok?await u.json():await ht(u,"audio_transcribe 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:{}},s=String((t==null?void 0:t.ts)||"").trim();s&&(n.ts=s);const o=String((t==null?void 0:t.client_id)||"").trim();o&&(n.client_id=o);const l=await fetch(ut(this._cfg.base_url.trim(),we("commands")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(n)});return l.ok?await l.json():await ht(l,"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)||"")},s=String((t==null?void 0:t.active_run_id)||"").trim();s&&(n.active_run_id=s);const o=String((t==null?void 0:t.workflow_id)||"").trim();o&&(n.workflow_id=o);const l=String((t==null?void 0:t.client)||"").trim();l&&(n.client=l);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 f=String((t==null?void 0:t.url)||"").trim();f&&(n.url=f);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 g=String((t==null?void 0:t.template)||"").trim();g&&(n.template=g);const _=t==null?void 0:t.context;_&&typeof _=="object"&&(n.context=_);const v=await fetch(ut(this._cfg.base_url.trim(),we("bugs/report")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(n)});return v.ok?await v.json():await ht(v,"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)||"")},s=String((t==null?void 0:t.active_run_id)||"").trim();s&&(n.active_run_id=s);const o=String((t==null?void 0:t.workflow_id)||"").trim();o&&(n.workflow_id=o);const l=String((t==null?void 0:t.client)||"").trim();l&&(n.client=l);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 f=String((t==null?void 0:t.url)||"").trim();f&&(n.url=f);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 g=String((t==null?void 0:t.template)||"").trim();g&&(n.template=g);const _=t==null?void 0:t.context;_&&typeof _=="object"&&(n.context=_);const v=await fetch(ut(this._cfg.base_url.trim(),we("features/report")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(n)});return v.ok?await v.json():await ht(v,"feature_report_create failed")}async prompt_cache_stats(t,n){const s=String(t||"").trim(),o=String(n||"").trim();if(!s||!o)throw new Error("prompt_cache_stats: provider and model are required");const l=ut(this._cfg.base_url.trim(),we(`prompt_cache/stats?provider=${encodeURIComponent(s)}&model=${encodeURIComponent(o)}`)),u=await fetch(l,{headers:{...ft(this._cfg.auth_token)}});return u.ok?await u.json():await ht(u,"prompt_cache_stats failed")}async prompt_cache_capabilities(t,n){const s=String(t||"").trim(),o=String(n||"").trim();if(!s||!o)throw new Error("prompt_cache_capabilities: provider and model are required");const l=ut(this._cfg.base_url.trim(),we(`prompt_cache/capabilities?provider=${encodeURIComponent(s)}&model=${encodeURIComponent(o)}`)),u=await fetch(l,{headers:{...ft(this._cfg.auth_token)}});return u.ok?await u.json():await ht(u,"prompt_cache_capabilities failed")}async prompt_cache_saved(t,n){const s=String(t||"").trim(),o=String(n||"").trim();if(!s||!o)throw new Error("prompt_cache_saved: provider and model are required");const l=ut(this._cfg.base_url.trim(),we(`prompt_cache/saved?provider=${encodeURIComponent(s)}&model=${encodeURIComponent(o)}`)),u=await fetch(l,{headers:{...ft(this._cfg.auth_token)}});return u.ok?await u.json():await ht(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()},s=(t==null?void 0:t.key)===null||(t==null?void 0:t.key)===void 0?"":String(t.key||"").trim();s&&(n.key=s);const o=await fetch(ut(this._cfg.base_url.trim(),we("prompt_cache/clear")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(n)});return o.ok?await o.json():await ht(o,"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)},s=await fetch(ut(this._cfg.base_url.trim(),we("prompt_cache/save")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(n)});return s.ok?await s.json():await ht(s,"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)},s=await fetch(ut(this._cfg.base_url.trim(),we("prompt_cache/load")),{method:"POST",headers:{"Content-Type":"application/json",...ft(this._cfg.auth_token)},body:JSON.stringify(n)});return s.ok?await s.json():await ht(s,"prompt_cache_load failed")}}function $u(){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 ot(e,t={}){var o;if(!e.startsWith(`${Br}/`))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[l,u]of Object.entries($u()))n.set(l,u);const s=await fetch(e,{...t,headers:n,credentials:"same-origin"});if(!s.ok){const l=await s.text();let u=l;try{const d=JSON.parse(l);u=typeof d.detail=="string"?d.detail:typeof((o=d.detail)==null?void 0:o.message)=="string"?d.detail.message:JSON.stringify(d.detail||d)}catch{}throw new H_(u||`Gateway request failed (${s.status})`,{status:s.status,body_text:l})}if(s.status!==204)return s.json()}const Ur=new pA({base_url:""});function At(e){return e instanceof Error?e.message:String(e)}function va(){return Fr()}async function gA(e,t,n){const{blob:s}=await Ur.get_run_artifact_blob(e,t),o=URL.createObjectURL(s),l=document.createElement("a");l.href=o,l.download=n.replace(/[\\/]/g,"_")||"artifact",l.click(),window.setTimeout(()=>URL.revokeObjectURL(o),1e3)}const yA={app:"code",name:"AbstractCode"},wA=["How do I change the model?","Where are my files and generated outputs?","How do I schedule an automation?"],vA=(e,t={})=>{const n=new Headers(t.headers||{}),s=String(t.method||"GET").toUpperCase();if(s!=="GET"&&s!=="HEAD")for(const[o,l]of Object.entries($u()))n.set(o,l);return fetch(e,{...t,headers:n,credentials:"same-origin"})};function _A(e){return gE(yA,vA,{connected:e,suggestions:wA,placeholder:"Ask about AbstractCode…"})}function To({children:e}){return a.jsxs("p",{className:"code-history-empty code-loading-status",role:"status",children:[a.jsx("span",{className:"code-loading-spinner","aria-hidden":"true"}),e]})}function bA(e,t,n,s){const o=y.useRef(null);y.useEffect(()=>{var d,f;if(!t)return;if(e){o.current=document.activeElement||null;const m=s(),p=window.setTimeout(()=>m==null?void 0:m.focus(),0);return()=>window.clearTimeout(p)}const l=n(),u=document.activeElement;o.current&&(!u||u===document.body||l&&l.contains(u))&&((f=(d=o.current).focus)==null||f.call(d)),o.current=null},[e,t])}function xA(e,t){return t?"drawers":e?"overlay":"docked"}function kA(e,t){return t==="drawers"?e:!1}function SA(e){return e.key!=="Escape"||e.defaultPrevented||e.overlayOpen?null:e.sidebarOpen?"sidebar":null}function jA(e=typeof document<"u"?document:void 0){return!!(e!=null&&e.querySelector('[role="dialog"], [role="alertdialog"]'))}function NA(e){const t=Number.parseFloat(String(e??"").trim());return Number.isFinite(t)&&t>0}let Oi=null;function CA(){var s;if(Oi)return Oi;if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const e=document.documentElement,t=()=>{const o=NA(getComputedStyle(e).getPropertyValue("--keyboard-inset"));o&&e.dataset.keyboard!=="open"?e.dataset.keyboard="open":!o&&e.dataset.keyboard&&delete e.dataset.keyboard},n=new MutationObserver(t);return n.observe(e,{attributes:!0,attributeFilter:["style"]}),(s=window.visualViewport)==null||s.addEventListener("resize",t),t(),Oi=()=>{var o;n.disconnect(),(o=window.visualViewport)==null||o.removeEventListener("resize",t),Oi=null},Oi}function EA(e){const t=e.isDrawer&&!e.open;return a.jsx("aside",{className:"code-sidebar","aria-label":"Conversations",...t?{inert:""}:{},children:e.children})}const Tu=(e,t)=>ot(e,{method:t.method,...t.body!==void 0?{body:JSON.stringify(t.body)}:{}}),Ru="Connect to your gateway to change workspaces.";function K_(e,t,n,s){const[o,l]=y.useState(null),[u,d]=y.useState(null),f=t?t.level==="session"?`session:${t.session}`:"account":"";y.useEffect(()=>{if(l(null),d(null),!e||!t)return;let p=!0;return dy(n,t).load().then(g=>p&&l(g)).catch(g=>p&&d(`Could not read the workspaces: ${At(g)}`)),()=>{p=!1}},[e,f,n,s]);const m=y.useCallback(async p=>{if(!t)throw new Error(Ru);const g=await dy(n,t).save(p);return l(g),g},[f,n]);return{state:o,error:u,save:m}}function J_(e){return e.automation?a.jsx(RA,{...e,automation:e.automation}):a.jsx(AA,{...e})}function AA({connected:e,sessionId:t,onOpenDefaults:n,refreshKey:s,request:o=Tu}){const l=K_(e,t?{level:"session",session:t}:null,o,s),u=e?t?null:"Open a conversation to choose its workspaces.":Ru;return a.jsxs(a.Fragment,{children:[a.jsx(nm,{level:"session",idPrefix:"code-workspace-session",state:l.state,save:l.save,loadError:u??l.error,unavailableReason:u}),n?a.jsx("p",{className:"code-default-workspaces",children:a.jsx("button",{type:"button",className:"code-text-button","data-action":"open-default-workspaces",onClick:n,disabled:!e,children:"My default workspaces"})}):null]})}function $A({open:e,onClose:t,connected:n,onChanged:s,request:o=Tu}){const l=K_(n&&e,e?{level:"account"}:null,o),u=n?null:Ru,d=y.useCallback(async f=>{const m=await l.save(f);return s==null||s(),m},[l,s]);return a.jsx(Gk,{open:e,onClose:t,title:"My default workspaces",size:"narrow",children:a.jsx(nm,{level:"account",idPrefix:"code-workspace-account",state:l.state,save:d,loadError:u??l.error,unavailableReason:u})})}function TA(e,t,n,s){const[o,l]=y.useState(null),[u,d]=y.useState(null),f=JSON.stringify(t);y.useEffect(()=>{if(d(null),!e){l(null);return}let p=!0;return bh(s)(t).then(g=>p&&l(g)).catch(g=>p&&d(`Could not read the workspaces: ${tm(g)||At(g)}`)),()=>{p=!1}},[e,f,s]);const m=y.useCallback(async p=>{const g=await bh(s)(p);l(g),n(p)},[s,n]);return{effective:o,error:u,onChange:m}}function RA({connected:e,automation:t,idPrefix:n="code-workspace-automation",request:s=Tu}){const o=TA(e,t.value,t.onChange,s),l=e?null:Ru;return a.jsx(nm,{level:"run",idPrefix:n,value:t.value,effective:o.effective,onChange:o.onChange,loadError:l??o.error,unavailableReason:l})}const q_="abstractcode.sidebar.panels",Pi={automations:!0,conversations:!0};function IA(e){try{const t=e==null?void 0:e.getItem(q_);if(!t)return{...Pi};const n=JSON.parse(t);if(!n||typeof n!="object")return{...Pi};const s=n;return{automations:typeof s.automations=="boolean"?s.automations:Pi.automations,conversations:typeof s.conversations=="boolean"?s.conversations:Pi.conversations}}catch{return{...Pi}}}function LA(e,t){try{t==null||t.setItem(q_,JSON.stringify(e))}catch{}}function MA(e,t){return{...e,[t]:!e[t]}}function yu(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function OA(){const[e,t]=y.useState(()=>IA(yu())),n=y.useCallback(s=>{t(o=>{const l=MA(o,s);return LA(l,yu()),l})},[]);return[e,n]}const fm=e=>({toggle:`code-panel-${e}-toggle`,region:`code-panel-${e}`});function Y_(e){const t=fm(e.panel);return a.jsxs("div",{className:"code-panel-header",children:[a.jsxs("button",{type:"button",className:"code-panel-toggle",id:t.toggle,"aria-expanded":e.open,"aria-controls":t.region,onClick:e.onToggle,children:[a.jsx(de,{name:"chevronDown",size:14}),a.jsx("span",{children:e.label})]}),e.actions?a.jsx("span",{className:"code-panel-actions",children:e.actions}):null]})}function PA(e){return a.jsx("div",{className:"code-sidebar-lists","data-automations":e.panels.automations?"open":"closed","data-conversations":e.panels.conversations?"open":"closed",children:e.children})}function DA(e){const t=fm("conversations");return a.jsxs("section",{className:"code-panel code-conversations","data-open":e.open?"true":"false",children:[a.jsx(Y_,{panel:"conversations",label:"Conversations",open:e.open,onToggle:e.onToggle,actions:e.actions}),a.jsx("nav",{className:"code-sessions",id:t.region,"aria-labelledby":t.toggle,hidden:!e.open,children:e.children})]})}function FA(e){return e.split("/").filter(Boolean).pop()||"Gateway managed"}const Q_="abstractcode.sidebar.archived",Hy={automations:!1,conversations:!1};function zA(e){try{const t=e==null?void 0:e.getItem(Q_),n=t?JSON.parse(t):null;return!n||typeof n!="object"?{...Hy}:{automations:n.automations===!0,conversations:n.conversations===!0}}catch{return{...Hy}}}function BA(){const[e,t]=y.useState(()=>zA(yu())),n=y.useCallback(s=>{t(o=>{var u;const l={...o,[s]:!o[s]};try{(u=yu())==null||u.setItem(Q_,JSON.stringify(l))}catch{}return l})},[]);return[e,n]}function X_(e){const t=y.useRef(null),n=y.useRef(!1);if(y.useEffect(()=>{var o,l;!e.open||!n.current||(n.current=!1,(l=(o=t.current)==null?void 0:o.scrollIntoView)==null||l.call(o,{block:"nearest",behavior:"smooth"}))},[e.open]),!(e.count>0))return null;const s=`code-archived-${e.list}`;return a.jsxs("div",{className:"code-archived","data-list":e.list,"data-open":e.open?"true":"false",children:[a.jsxs("button",{type:"button",className:"code-archived-toggle","aria-expanded":e.open,"aria-controls":s,onClick:()=>{n.current=!0,e.onToggle()},children:[a.jsxs("span",{children:["Archived · ",e.count]}),a.jsx(de,{name:"chevronDown",size:12})]}),e.open?a.jsx("ul",{ref:t,className:"code-archived-list",id:s,"aria-label":`Archived ${e.list}`,children:e.children}):null]})}function Z_(e){return a.jsxs("li",{className:"code-archived-row","data-id":e.id,children:[a.jsxs("button",{type:"button",className:"code-archived-name",title:e.title,onClick:e.onOpen,children:[a.jsx("strong",{children:e.title}),e.meta?a.jsx("small",{children:e.meta}):null]}),a.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?a.jsx(de,{name:"loader",size:12}):a.jsx(de,{name:"archive",size:12}),a.jsx("span",{children:"Unarchive"})]}),e.error?a.jsx("p",{className:"code-inline-error",role:"alert",children:e.error}):null]})}const WA="Archive this conversation? It stays searchable and auditable; it just leaves this list.";function UA(e){const t=y.useRef(null);return y.useEffect(()=>{var n;(n=t.current)==null||n.focus({preventScroll:!0})},[]),a.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:[a.jsx("p",{children:WA}),a.jsxs("span",{className:"code-archive-confirm-actions",children:[a.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?a.jsx(de,{name:"loader",size:12}):a.jsx(de,{name:"archive",size:12}),a.jsx("span",{children:"Archive"})]}),a.jsx("button",{type:"button",className:"code-subtle-button","data-action":"cancel-archive",disabled:e.busy,onClick:e.onCancel,children:"Cancel"})]}),e.error?a.jsx("p",{className:"code-inline-error",role:"alert",children:e.error}):null]})}const VA="abstractcode.agent.v1";function hm(e){return!!(e!=null&&e.interfaces.some(t=>[VA,"abstractassistant.agent.v1"].includes(t)))}function gt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function $h(e){return Array.isArray(e)?e:[]}function ze(e){return typeof e!="string"?void 0:e.trim()||void 0}function GA(e){return $h(e).flatMap(t=>{const n=ze(t);return n?[n]:[]})}function tl(e,t=0){if(typeof e!="number"||!Number.isFinite(e))return;const n=Math.trunc(e);return n>=t?n:void 0}function mm(e,t){if(Array.isArray(e))return e;const n=gt(e);if(!n)return[];for(const s of t)if(Array.isArray(n[s]))return n[s];return[]}function eb(e){const t=gt(e);return t?{...t}:void 0}function Ky(e){const t=eb(e.input_schema??e.inputSchema??e.inputs_schema);if(t)return t;const n=gt(e.inputs);if(n&&("properties"in n||"type"in n||"$schema"in n))return{...n}}function HA(e){const t=ze(e.bundle_version??e.bundleVersion??e.version);if(t)return t;const n=ze(e.bundle_ref??e.bundleRef);if(!n)return;const s=n.lastIndexOf("@");return s>0&&s<n.length-1?n.slice(s+1):void 0}function KA(e,t,n){return e?`${e}${t?`@${t}`:""}:${n}`:n}function Jy(e,t,n){var d;const s=gt(e),o=ze((s==null?void 0:s.default_bundle_id)??(s==null?void 0:s.defaultBundleId)),l=mm(e,["items","bundles"]),u=[];for(const f of l){const m=gt(f);if(!m)continue;const p=gt(m.actions);if((p==null?void 0:p.can_run)===!1)continue;const g=(d=ze(m.status))==null?void 0:d.toLowerCase();if(m.is_draft===!0||m.is_published===!1||m.version_channel==="draft"||g&&!["published","deprecated"].includes(g)||!n.includeDeprecated&&(g==="deprecated"||g==="deleted"||g==="disabled"))continue;const _=ze(m.bundle_id??m.bundleId??m.id),v=HA(m);if(v&&/(?:^|[.\-])draft(?:[.\-]|$)/i.test(v))continue;const C=ze(m.default_entrypoint??m.defaultEntrypoint),x=t==="private"&&(m.is_default===!0||m.isDefault===!0||!!_&&_===o);for(const k of $h(m.entrypoints)){const S=gt(k);if(!S||!n.includeDeprecated&&(S.deprecated===!0||S.enabled===!1))continue;const $=ze(S.flow_id??S.flowId??S.id);if(!$)continue;const R=GA(S.interfaces??S.interface_ids??S.interfaceIds);if(n.interfaceId&&!R.includes(n.interfaceId))continue;const N=ze(S.workflow_id??S.workflowId)??KA(_,v,$),E=C?C===$:$h(m.entrypoints).length===1;u.push({id:`${t}:${N}`,workflowId:N,..._?{bundleId:_}:{},...v?{bundleVersion:v}:{},flowId:$,name:ze(S.name??S.title)??$,description:ze(S.description)??"",interfaces:R,...Ky(S)?{inputSchema:Ky(S)}:{},registryScope:t,isPreferredVersion:t==="tenant_catalog"?m.is_default===!0||m.default_version===v:m.latest_published_version===v,...x&&E?{isDefault:!0}:{}})}}return u}function JA(e,t,n={}){const s=[...Jy(e,"private",n),...Jy(t,"tenant_catalog",n)],o=new Map;for(const l of s)o.set(l.id,l);return[...o.values()].sort((l,u)=>+!!u.isDefault-+!!l.isDefault||l.name.localeCompare(u.name)||l.id.localeCompare(u.id))}function qA(e){const t=gt(e);if(!t)return;const n=gt(t.workflow_selection??t.workflowSelection);if(n)return n;const s=gt(t._runtime),o=gt((s==null?void 0:s.workflow_policy)??(s==null?void 0:s.workflowPolicy));if(o)return o;const l=gt(t.input_data??t.inputData),u=gt(l==null?void 0:l._runtime);return gt((u==null?void 0:u.workflow_policy)??(u==null?void 0:u.workflowPolicy))}function YA(e,t){const n=qA(t.inputData);if(n){const l=ze(n.registry_scope??n.registryScope),u=ze(n.bundle_id??n.bundleId),d=ze(n.bundle_version??n.bundleVersion),f=ze(n.flow_id??n.flowId);if((l==="private"||l==="tenant_catalog")&&u&&f){const m=e.filter(p=>(p.registryScope??"private")===l&&p.bundleId===u&&p.flowId===f&&(!d||p.bundleVersion===d));if(m.length===1)return m[0]}return}const s=ze(t.runWorkflowId);if(!s)return;const o=e.filter(l=>(l.registryScope??"private")==="private"&&l.workflowId===s);return o.length===1?o[0]:void 0}function QA(e){const t=gt(e)??{},n=gt(t.policy)??t,s=tl(n.max_attachment_bytes??n.maxAttachmentBytes,1);return{raw:{...n},...s!==void 0?{maxAttachmentBytes:s}:{}}}function qy(e,t){const n=ze(e.sandbox);if(!n||typeof e.sandboxed!="boolean")return;const s=ze(t==null?void 0:t.sentence),o=e.sandboxed?"ok":ze(t==null?void 0:t.state)==="unsandboxed"?"danger":"warn";return{label:n,...s?{tooltip:s}:{},tone:o}}function XA(e){var l;const t=mm(e,["items","tools"]),n=gt((l=gt(e))==null?void 0:l.command_sandbox),s=new Set,o=[];for(const u of t){const d=gt(u);if(!d)continue;const f=ze(d.name??d.tool_name??d.id);if(!f||s.has(f))continue;s.add(f);const m=d.enabled!==!1&&d.served_disabled!==!0&&d.servedDisabled!==!0,p=tl(d.risk_rank??d.riskRank),g=eb(d.input_schema??d.inputSchema??d.parameters);o.push({name:f,description:ze(d.description)??"",...ze(d.toolset)?{toolset:ze(d.toolset)}:{},...ze(d.tier)?{tier:ze(d.tier)}:{},...ze(d.approval_default??d.default_approval??d.approvalDefault??d.defaultApproval??d.approval)?{approval:ze(d.approval_default??d.default_approval??d.approvalDefault??d.defaultApproval??d.approval)}:{},...p!==void 0?{riskRank:p}:{},enabled:m,servedDisabled:!m,...ze(d.enable_gate??d.enableGate)?{enableGate:ze(d.enable_gate??d.enableGate)}:{},...ze(d.why_disabled??d.whyDisabled)?{whyDisabled:ze(d.why_disabled??d.whyDisabled)}:{},...g?{inputSchema:g}:{},...qy(d,n)?{sandboxState:qy(d,n)}:{},raw:{...d}})}return o.sort((u,d)=>u.name.localeCompare(d.name))}function ZA(e){var s;const t=(s=ze(e.status??e.state))==null?void 0:s.toLowerCase();return ze(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 Yy={waiting:4,running:3,failed:2,done:1,unknown:0};function po(e){return ze(e.updated_at??e.updatedAt??e.finished_at??e.finishedAt??e.created_at??e.createdAt)}function go(e){if(!e)return Number.NEGATIVE_INFINITY;const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function Qy(e){var u;const t=ze(e);if(t)return t;const n=gt(e);if(!n)return;const s=ze(n.prompt);if(s)return s;const o=gt(n.input_data??n.inputData),l=["prompt","request","task","message","query","input"].map(d=>ze(o==null?void 0:o[d])).find(Boolean);return l||ze((u=gt(o==null?void 0:o.context))==null?void 0:u.task)}function wu(e,t={}){const n=gt(e),s=(n==null?void 0:n.has_more)===!0||(n==null?void 0:n.hasMore)===!0,o=mm(e,["items","runs"]),l=new Map;o.forEach((d,f)=>{const m=gt(d);if(!m||ze(m.parent_run_id??m.parentRunId))return;const p=ze(m.session_id??m.sessionId),g=ze(m.run_id??m.runId??m.id);if(!p||!g)return;const _=l.get(p)??[];_.push({run:m,index:f}),l.set(p,_)});const u=[];for(const[d,f]of l){const m=[...f].sort((x,k)=>go(po(k.run))-go(po(x.run))||x.index-k.index),p=[...f].sort((x,k)=>{const S=ze(x.run.created_at??x.run.createdAt)??po(x.run),$=ze(k.run.created_at??k.run.createdAt)??po(k.run);return go(S)-go($)||x.index-k.index}),g=m.flatMap(({run:x})=>{const k=ze(x.run_id??x.runId??x.id);return k?[k]:[]});if(!g.length)continue;let _="unknown";for(const{run:x}of f){const k=ZA(x);Yy[k]>Yy[_]&&(_=k)}let v;for(const{run:x}of p){const k=ze(x.run_id??x.runId??x.id);if(v=(k?Qy(t[k]):void 0)??Qy(x),v)break}let C=0;for(const{run:x}of f){const k=x.tool_calls;C=typeof k=="number"&&Number.isFinite(k)&&C!==void 0?C+k:void 0}u.push({sessionId:d,state:_,...po(m[0].run)?{updatedAt:po(m[0].run)}:{},firstRunId:ze(p[0].run.run_id??p[0].run.runId??p[0].run.id),latestRunId:g[0],runIds:g,turnCount:f.length,...C!==void 0?{toolCalls:C}:{},...v?{prompt:v}:{},truncated:s})}return u.sort((d,f)=>go(f.updatedAt)-go(d.updatedAt)||d.sessionId.localeCompare(f.sessionId))}function vu(e){return e?{...e}:{}}function Di(e){if(e!==void 0)return e.flatMap(t=>{const n=ze(t);return n?[n]:[]})}function e$(e,t,n){var x,k,S,$,R,N,E;const s=(j,I)=>{var L,z;!hm(t.workflow)&&!((z=gt((L=t.inputSchema)==null?void 0:L.properties))!=null&&z[j])||I!==void 0&&n&&(e[j]=I)},o=ze((x=t.model)==null?void 0:x.provider),l=ze((k=t.model)==null?void 0:k.model);if(!!o!=!!l)throw new Error("Choose both a provider and a model, or use the workflow / Gateway defaults.");s("provider",o),s("model",l),t.tools!==void 0&&s("tools",Di(t.tools)??[]);const u=Di(t.skills);u!=null&&u.length&&(e.skills=u);const d=ze((S=t.workspace)==null?void 0:S.root);d!==void 0&&(e.workspace_root=d),s("system",ze(t.system));const f=vu(gt(e._runtime)),m=(j,I)=>{I!==void 0&&n&&(f[j]=I)};if(m("provider",o),m("model",l),m("thinking",ze(t.reasoning)),m("speculation",t.speculation),t.streamReplies!==void 0&&m("stream",OC(t.streamReplies).stream),m("system_prompt_extra",ze(t.systemPromptExtra)),t.tools!==void 0){const j=Di(t.tools)??[],I=Array.isArray(f.allowed_tools)?f.allowed_tools:null;f.allowed_tools=I?j.filter(L=>I.includes(L)):j}if(t.review!==void 0&&t.reviewCapable!==!1){m("review_mode",t.review.enabled);const j=t.review.enabled?tl(t.review.maxRounds,1):void 0;m("review_max_rounds",j)}const p=Di(($=t.toolPolicy)==null?void 0:$.autoApproveTools),g=Di((R=t.toolPolicy)==null?void 0:R.requireApprovalTools);(((p==null?void 0:p.length)??0)>0||((g==null?void 0:g.length)??0)>0)&&m("tool_policy",{...p!=null&&p.length?{auto_approve_tools:p}:{},...g!=null&&g.length?{require_approval_tools:g}:{}}),t.promptCache!==void 0&&m("prompt_cache",t.promptCache),Object.keys(f).length&&(e._runtime=f);const _=vu(gt(e._limits)),v=tl((N=t.limits)==null?void 0:N.maxIterations,1),C=tl((E=t.limits)==null?void 0:E.maxTokens,1);v!==void 0&&n&&(_.max_iterations=v),C!==void 0&&n&&(_.max_tokens=C),Object.keys(_).length&&(e._limits=_),s("max_iterations",v),t.gatingMode==="auto"&&s("gating_mode","auto")}function t$(e){var s;const t=vu(e.schemaInputs),n=hm(e.workflow);if(e.promptProperty){const o=ze(e.promptProperty);o&&((s=e.prompt)!=null&&s.trim())&&(t[o]=e.prompt)}if(n){const o=e.prompt??"";t.prompt=o;const l=vu(gt(t.context));l.task=o,delete l.messages,delete l.media;const u=(e.attachments??[]).map(d=>({...d}));u.length?l.attachments=u:delete l.attachments,t.use_context=!1,delete t.attachments,delete t.media,t.context=l,t.use_session_history=e.useSessionHistory??!0}return e$(t,e,!0),t}function n$(e){const t=e.last_notification;if(!t||typeof t!="object")return null;const n=t;return n.status!=="failed"||typeof n.text!="string"||!n.text?null:{text:n.text,at:typeof n.at=="string"&&n.at?n.at:null}}function s$(e,t){const n=e?Date.parse(e):NaN;return Number.isNaN(n)?"":`${au(Math.max(0,t-n))} ago`}function tb(e){const t=n$(e.summary);if(!t)return null;const n=s$(t.at,e.nowMs);return a.jsxs("small",{className:`code-notif-line ${e.className??""}`.trim(),"data-field":"last-notification","data-status":"failed",children:[a.jsx(Fk,{tone:"error",size:"sm",className:"code-notif-pill",title:t.at?`${t.text}
90
- ${nu(t.at)}`:t.text,children:t.text}),n?a.jsx("span",{className:"code-notif-time",children:n}):null]})}const Xy=(e,t,n)=>`${e} ${e===1?t:n}`;function nb(e,t={}){const n=e.updatedAt?new Date(e.updatedAt):null,o=[n&&Number.isFinite(n.getTime())?n.toLocaleDateString(t.locale,{month:"short",day:"numeric",...t.timeZone?{timeZone:t.timeZone}:{}}):"Saved conversation",Xy(e.turnCount,"turn","turns")];return typeof e.toolCalls=="number"&&e.toolCalls>0&&o.push(Xy(e.toolCalls,"tool","tools")),o.join(" · ")}function sb(e){return e.prompt||`Conversation ${e.sessionId.slice(0,8)}`}function r$(e){const{item:t}=e,n=sb(t);return a.jsxs("div",{className:`code-session-item${e.confirm?" is-confirming":""}`,"data-item-id":t.sessionId,children:[a.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:[a.jsxs("span",{children:[a.jsx("strong",{className:"code-card-title",children:n}),a.jsx("small",{className:"code-card-meta","data-field":"meta",children:nb(t)})]}),t.state==="running"||t.state==="waiting"?a.jsx("span",{className:`code-status-dot ${t.state==="running"?"is-working":"is-waiting"}`,title:t.state}):null]}),e.onAskArchive?a.jsx(Bh,{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 rb(e){return e.attention.pending_waits>0}function ab(){return a.jsx("span",{className:"code-waiting-badge","data-field":"waiting",children:"waiting for you"})}function ob(e){const t=Ao(e.summary,[],e.busy).active;return a.jsx(Wr,{className:`${e.className??""}${e.iconOnly?" code-switch-icon-only":""}`.trim()||void 0,variant:e.variant??"sm",action:"active",label:e.iconOnly?a.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
91
- ${rl("active",e.summary)}`:rl("active",e.summary),onChange:()=>e.onToggle()})}function a$(e,t){const n=Dv(e,t);return{first:[n.cadence,n.last].filter(Boolean).join(" · "),second:n.next||"",scheduled:e.trigger.source_id==="schedule"}}function o$(e){const t=e.summary,n=a$(t,e.nowMs),s=rb(t);return a.jsxs("div",{className:`code-card code-auto-card${e.selected?" is-selected":""}`,"data-automation-id":t.automation_id,"data-status":t.status,children:[a.jsxs("button",{type:"button",className:"code-card-main","aria-current":e.selected?"page":void 0,title:`${t.title}
92
- ${[n.first,n.second].filter(Boolean).join(" · ")}`,onClick:e.onSelect,children:[a.jsx("strong",{className:"code-card-title",children:t.title}),s?a.jsx(ab,{}):null,a.jsxs("small",{className:"code-card-meta","data-field":"timing",children:[n.scheduled?a.jsx(de,{name:"refresh",size:12,className:"code-card-cadence-icon"}):null,a.jsx("span",{className:"code-card-part",children:n.first})]})]}),a.jsxs("div",{className:"code-card-line2",children:[a.jsx("small",{className:"code-card-meta","data-field":"next",children:n.second}),a.jsx(ob,{className:"code-card-switch",iconOnly:!0,summary:t,busy:e.busy,onToggle:e.onToggleActive})]}),a.jsx(tb,{summary:t,nowMs:e.nowMs,className:"code-card-notif"})]})}const i$="runs?root_only=true&archived_only=true&include_ledger_len=false&include_metrics=true&limit=200",l$=e=>`sessions/${encodeURIComponent(e)}/archive`,c$=e=>`sessions/${encodeURIComponent(e)}/unarchive`;async function u$(e,t=ot){return t(we(l$(e)),{method:"POST",body:"{}"})}function d$(e,t){const n=e.findIndex(o=>o.sessionId===t),s=e.filter(o=>o.sessionId!==t);return s.length?n<0?s[0]:s[Math.min(n,s.length-1)]:null}function Zy(e){const t=e==null?void 0:e.archived_sessions;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function f$(e){const t=e.request??ot,[n,s]=y.useState(null),[o,l]=y.useState(""),[u,d]=y.useState(""),[f,m]=y.useState(null);return y.useEffect(()=>{if(!e.enabled)return;const p=new AbortController;return l(""),t(we(i$),{signal:p.signal}).then(async g=>{if(p.signal.aborted)return;const _=wu(g);s(_);const v={};await Promise.all(_.filter(C=>!C.prompt).slice(0,50).map(async C=>{try{v[C.firstRunId]=await t(we(`runs/${encodeURIComponent(C.firstRunId)}/input_data`),{signal:p.signal})}catch{}})),!p.signal.aborted&&Object.keys(v).length&&s(wu(g,v))}).catch(g=>!p.signal.aborted&&l(`Archived conversations unavailable: ${At(g)}`)),()=>p.abort()},[e.enabled,e.revision]),o?a.jsx("li",{className:"code-inline-error",role:"alert",children:o}):n?a.jsx(a.Fragment,{children:n.map(p=>a.jsx(Z_,{id:p.sessionId,title:sb(p),meta:nb(p),busy:u===p.sessionId,error:(f==null?void 0:f.id)===p.sessionId?f.message:void 0,onOpen:()=>e.onOpen(p),onUnarchive:()=>{d(p.sessionId),m(null),t(we(c$(p.sessionId)),{method:"POST",body:"{}"}).then(()=>{s(g=>(g||[]).filter(_=>_.sessionId!==p.sessionId)),e.onUnarchived(p)}).catch(g=>m({id:p.sessionId,message:`Not unarchived: ${At(g)}`})).finally(()=>d(""))}},p.sessionId))}):a.jsx("li",{children:a.jsx(To,{children:"Loading archived conversations…"})})}const Un=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},h$=["context","messages","attachments","media"];function m$(e){return h$.includes(e)}function p$(e,t){const n=Un(t);return Object.fromEntries(Object.keys(Un(e.properties)).flatMap(s=>["_runtime","_limits"].includes(s)||m$(s)||!Object.prototype.hasOwnProperty.call(n,s)?[]:[[s,structuredClone(n[s])]]))}function ew(e){if(!e)return;const t=Un(e.input_data_schema||e.input_schema||e.schema||e),n=Object.fromEntries(Object.entries(Un(t.properties)).map(([s,o])=>[s,{...Un(o)}]));for(const s of Array.isArray(e.inputs)?e.inputs:[])s!=null&&s.id&&(n[s.id]={...Un(s.schema),...n[s.id],...s.type?{"x-abstract-type":s.type}:{},...s.label?{title:s.label}:{},...Object.prototype.hasOwnProperty.call(s,"default")?{default:s.default}:{}});for(const[s,o]of Object.entries(Un(e.defaults)))n[s]={...n[s],default:o};return{...t,properties:n}}function g$(e,t){var m;const n=Un(t).nodes;if(!Array.isArray(n))throw new Error("The workflow input declarations could not be verified. Please retry.");const s=n.find(p=>{var g;return(((g=p==null?void 0:p.data)==null?void 0:g.nodeType)||(p==null?void 0:p.type))==="on_flow_start"});if(!s||!Array.isArray((m=s.data)==null?void 0:m.outputs))throw new Error("The workflow start inputs could not be verified. Please retry.");const o=s.data.outputs.filter(p=>typeof(p==null?void 0:p.id)=="string"&&p.id&&p.type!=="execution"&&!["exec","exec-out"].includes(p.id)),l=new Set(o.map(p=>p.id)),u=new Set((Array.isArray(e.required)?e.required:[]).filter(p=>!l.has(p))),d={...e.properties},f=Un(s.data.pinDefaults);for(const p of o)p.required===!0&&u.add(p.id),d[p.id]={...Un(d[p.id]),...Un(p.schema),...p.type?{"x-abstract-type":p.type}:{},...p.label?{title:p.label}:{},...Object.prototype.hasOwnProperty.call(f,p.id)?{default:structuredClone(f[p.id])}:{}};return{...e,properties:d,required:[...u]}}function sr(e){return Object.fromEntries(Object.entries((e==null?void 0:e.properties)||{}).flatMap(([t,n])=>Object.prototype.hasOwnProperty.call(Un(n),"default")?[[t,structuredClone(Un(n).default)]]:[]))}function y$(e){const t=Array.isArray(e.type)?e.type.find(s=>s!=="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 w$(e){const t=(e==null?void 0:e.properties)||{},n=o=>{const l=t[o];return l&&(l.type==="string"||Array.isArray(l.type)&&l.type.includes("string")||!l.type&&l["x-abstract-type"]==="string")},s=Object.keys(t).filter(o=>{var l;return((l=t[o])==null?void 0:l["x-abstract-role"])==="prompt"&&n(o)});return s.length?s.length===1?s[0]:void 0:["prompt","request","task","message","query","input"].find(n)}function Uf(e,t){var o,l,u;if(!e)return[];const n={...sr(e),...t},s=[];for(const d of Array.isArray(e.required)?e.required:[])n[d]===void 0&&s.push(`${((l=(o=e.properties)==null?void 0:o[d])==null?void 0:l.title)||d} is required.`);for(const[d,f]of Object.entries(n)){const m=(u=e.properties)==null?void 0:u[d];if(!m||f===void 0)continue;const p=m.title||d;Array.isArray(m.enum)&&!m.enum.some(C=>JSON.stringify(C)===JSON.stringify(f))&&s.push(`${p} must be one of the available choices.`);const g=Array.isArray(m.type)?m.type:m.type?[m.type]:[];if(f===null&&(g.includes("null")||!g.length))continue;const _=Array.isArray(f)?"array":f===null?"null":typeof f,v=g.includes(_)?_:_==="number"&&g.includes("integer")?"integer":g[0];(v==="number"||v==="integer")&&(typeof f!="number"||!Number.isFinite(f)||v==="integer"&&!Number.isInteger(f))&&s.push(`${p} must be ${v==="integer"?"a whole number":"a number"}.`),typeof f=="number"&&m.minimum!==void 0&&f<m.minimum&&s.push(`${p} must be at least ${m.minimum}.`),typeof f=="number"&&m.maximum!==void 0&&f>m.maximum&&s.push(`${p} must be at most ${m.maximum}.`),v==="string"&&typeof f!="string"&&s.push(`${p} must be text.`),typeof f=="string"&&m.minLength!==void 0&&f.length<m.minLength&&s.push(`${p} must contain at least ${m.minLength} characters.`),v==="boolean"&&typeof f!="boolean"&&s.push(`${p} must be true or false.`),v==="array"&&!Array.isArray(f)&&s.push(`${p} must be a JSON array.`),v==="object"&&(f===null||typeof f!="object"||Array.isArray(f))&&s.push(`${p} must be a JSON object.`)}return s}function ib(e){const t=(e==null?void 0:e.properties)||{},n=[];for(const[s,o]of Object.entries(t)){const l=Un(o);if(!(s==="provider"||s.endsWith("_provider")||String(l["x-abstract-type"]||"").startsWith("provider")))continue;const u=String(l["x-abstract-type"]||""),d=s.replace("provider","model"),f=Object.keys(t).filter(v=>{var C;return((C=t[v])==null?void 0:C["x-abstract-type"])===u.replace(/^provider/,"model")}),m=d!==s&&t[d]?d:f.length===1?f[0]:"";if(!m)continue;const p=s==="provider"?"":s.startsWith("provider_")?s.slice(9):s.endsWith("_provider")?s.slice(0,-9):u.replace(/^provider_?/,""),g=p&&p!=="text"?`${p}_`:"",_=[`${g}reasoning`,`${g}thinking`,`${g}reasoning_effort`,`reasoning_${p}`,`thinking_${p}`].find(v=>t[v]);n.push({provider:s,model:m,reasoning:_,title:g?g.replace(/_/g," ").trim():"Text model"})}return n}const So=uk(e=>ot(e));function v$(e){try{const t=jw(e);return t?{provider:t.provider,model:t.model}:void 0}catch{return}}function _$(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 So;const s=e==="voice_provider",o=we(n?`vision/provider_models?task=${n}`:s?"audio/speech/models?compact=true":"audio/music/models?task=text_to_music"),l=n?`${o}&providers_only=true`:we(s?"voice/voices?providers_only=true&compact=true":"audio/music/providers?task=text_to_music"),u=d=>Array.isArray(d)?d.map(f=>typeof f=="string"?f:f.id||f.name).filter(Boolean):[];return{fetchProviders:async()=>{const d=await ot(l);if(d.error)throw new Error(d.error);return u(d.providers||d.available_providers||d.items).map(f=>({name:f}))},fetchModels:async d=>{var m,p,g;const f=await ot(`${o}&provider=${encodeURIComponent(d)}`);if(f.error)throw new Error(f.error);return u(((m=f.models_by_provider)==null?void 0:m[d])||((p=f.tts_models_by_provider)==null?void 0:p[d])||((g=f.music_models_by_provider)==null?void 0:g[d])||f.models||f.items)}}}const b$=["gateway_default","on","off"],lb={status:"loading"};function x$(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,s=n==null?void 0:n.streaming;return!s||typeof s!="object"||s.deltas!==!0?{status:"unsupported",reason:"not supported by this gateway (it does not advertise live replies)"}:{status:"supported",gatewayDefault:typeof s.default=="boolean"?s.default:null}}function k$(e){return b$.includes(e)?e:"gateway_default"}function S$(e,t){return e==="on"&&t.status!=="supported"?"gateway_default":e}function j$(e,t,n){if(e!=="on"||t.status!=="unsupported"||!n.length)return null;const s=n.find(o=>o.role==="user")||n[0];return{after:s.id?String(s.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 N$(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 C$(e,t){const n=N$(e.frame.data),s=n?`call:${n}`:`error:${e.error.message}`;return{after:t,message:{id:`stream-replies:malformed:${e.runId}:${s}`,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 E$(e,t){return e.some(n=>n.message.id===t.message.id)?[...e]:[...e,t]}function A$(e,t){const n=t.filter(d=>!!d);if(!n.length)return[...e];const s=[],o=new Set;for(const d of e){s.push(d);for(const f of n)!o.has(f)&&f.after!==null&&String(d.id)===f.after&&(s.push(f.message),o.add(f))}const l=n.filter(d=>!o.has(d)&&d.after===null),u=n.filter(d=>!o.has(d)&&d.after!==null);return[...l.map(d=>d.message),...s,...u.map(d=>d.message)]}function $$(e){return e.status==="supported"&&e.gatewayDefault!==null?`Gateway default (${e.gatewayDefault?"on":"off"})`:"Gateway default"}const Xt="@default",ln="abstractcode.agent.v1";function Ds(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Bn(e){return typeof e=="string"&&e.trim()?e.trim():void 0}const T$="gateway does not report a default agent workflow";function R$(e,t=ln){var p,g;const n=Ds(e);if(!n)return{status:"unavailable",reason:"the gateway's workflow list could not be loaded"};const s=Ds(n.default_agent_workflows);if(!s)return{status:"unavailable",reason:T$};const o=Ds(s[t]);if(!o){const _=Bn((g=Ds((p=Ds(n.default_agent_workflows_unavailable))==null?void 0:p[t]))==null?void 0:g.reason);return{status:"unavailable",reason:_?`no default workflow for ${t}: ${_}`:`gateway reports no default workflow for ${t}`}}const l=Bn(o.bundle_id),u=Bn(o.flow_id),d=Bn(o.registry_scope);if(!l||!u||!d)return{status:"unavailable",reason:`gateway's default workflow for ${t} is missing its bundle, flow or registry scope`};const f=Bn(o.bundle_version);return{status:"ok",workflow:{workflowId:Bn(o.workflow_id)??`${l}${f?`@${f}`:""}:${u}`,bundleId:l,...f?{bundleVersion:f}:{},flowId:u,registryScope:d,name:Bn(o.name)??u,...Bn(o.source)?{source:Bn(o.source)}:{}}}}function I$(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 L$(e,t,n=ln){if(e.status!=="ok")return null;const s=e.workflow,o=t.find(l=>(l.registryScope??"private")===s.registryScope&&l.bundleId===s.bundleId&&l.flowId===s.flowId&&(!s.bundleVersion||l.bundleVersion===s.bundleVersion));return o||{id:`${s.registryScope}:${s.workflowId}`,workflowId:s.workflowId,bundleId:s.bundleId,...s.bundleVersion?{bundleVersion:s.bundleVersion}:{},flowId:s.flowId,name:s.name,description:"",interfaces:[n],registryScope:s.registryScope}}function Vf(e,t=ln){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 M$(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 O$(e,t){return e===Xt?Cu:(t==null?void 0:t.workflowId)??e}function P$(e,t){return e===Cu||!t?Xt:`${t.registryScope}:${t.value}`}function D$(e){const t=n=>n===Xt||e.visible.some(s=>s.id===n)||!!e.runId&&e.workflows.some(s=>s.id===n);return e.selection&&t(e.selection)?e.selection:e.preferred&&t(e.preferred)?e.preferred:Xt}function pm(e){var n,s;const t=Ds((s=Ds((n=Ds(e))==null?void 0:n.input_data))==null?void 0:s.workflow_selection);return Bn(t==null?void 0:t.source)}function F$(e){var t;return pm(e.restoredInputs)==="gateway_default"?Xt:(t=e.restored)==null?void 0:t.id}function z$(e){return!Ds(e)||pm(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 B$(e){return e.selection===Xt?{flow_id:Xt,interface:e.interfaceId??ln,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 W$(e){const t=Ds(e);if(!t)return{text:"the gateway did not report which workflow it started",missing:!0};const n=Bn(t.name)??Bn(t.workflow_id)??Bn(t.flow_id)??"unnamed workflow",s=Bn(t.bundle_version);return{text:`running ${n}${s?` @${s}`:""}${t.source==="gateway_default"?" (gateway default)":""}`,missing:!1}}const Gf=25,U$=4,V$=e=>`runs?root_only=true&include_ledger_len=false&include_metrics=true&limit=${e}`;function G$(e){const t=(e==null?void 0:e.items)??(e==null?void 0:e.runs);return Array.isArray(t)?t.length:0}async function H$(e,t){let n=Math.max(1,t)*U$;for(;;){const s=await e(n);if((s==null?void 0:s.has_more)!==!0||G$(s)<n||wu(s).length>t)return s;n*=2}}function K$(e,t){return{sessions:e.slice(0,t),hasMore:e.length>t}}const Hf={gatewayDefault:{status:"loading"},executable:{status:"idle",data:null,error:""},workflows:[],policy:null,tools:[],sessions:[],capabilities:{},capabilitiesLoading:!0,sessionToolPolicy:null,capabilitiesError:"",toolCatalog:[],toolWarnings:[],streaming:lb,loading:!1,sessionsLoaded:!1,errors:[],hasMore:!1,archivedSessions:0};function J$(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 q$(e,t){const[n,s]=y.useState(Hf),o=y.useRef(Gf),l=y.useRef(0),u=y.useRef(),d=y.useRef(0),f=y.useRef(),m=y.useRef({identity:"",values:{}}),p=y.useCallback(S=>H$($=>ot(we(V$($)),{signal:S}),o.current),[]),g=S=>K$(wu(S,m.current.values),o.current),_=y.useCallback(async(S,$,R)=>{const N=()=>d.current!==$||R.aborted,E=g(S).sessions.filter(j=>!j.prompt&&!(j.firstRunId in m.current.values));for(let j=0;j<E.length;j+=4){if(N()||(await Promise.all(E.slice(j,j+4).map(async I=>{try{const L=await ot(we(`runs/${encodeURIComponent(I.firstRunId)}/input_data`),{signal:R});N()||(m.current.values[I.firstRunId]=L)}catch(L){!R.aborted&&(L==null?void 0:L.status)===401&&t()}})),N()))return;s(I=>({...I,sessions:g(S).sessions}))}},[t]),v=y.useCallback(async()=>{var R;if(!e)return;const S=++d.current;(R=f.current)==null||R.abort();const $=new AbortController;f.current=$,s(N=>({...N,loading:!0}));try{const N=await p($.signal);if(d.current!==S)return;const E=g(N);s(j=>({...j,loading:!1,sessions:E.sessions,sessionsLoaded:!0,hasMore:E.hasMore,archivedSessions:Zy(N),errors:j.errors.filter(I=>!I.startsWith("Conversations: "))})),await _(N,S,$.signal)}catch(N){if($.signal.aborted||d.current!==S)return;(N==null?void 0:N.status)===401&&t(),s(E=>({...E,loading:!1,errors:[...E.errors.filter(j=>!j.startsWith("Conversations: ")),`Conversations: ${At(N)}`]}))}},[e,p,_,t]),C=y.useCallback(async()=>{var ie,F;const S=++l.current,$=++d.current;(ie=f.current)==null||ie.abort(),(F=u.current)==null||F.abort();const R=new AbortController;if(u.current=R,m.current.identity!==e&&(m.current={identity:e,values:{}}),!e){s(Hf);return}s(D=>({...D,loading:!0,capabilitiesLoading:!0,errors:[],executable:{...D.executable,status:"loading",error:""}}));const N=D=>ot(we(D),{signal:R.signal}),E=await Promise.allSettled([N("bundles?all_versions=true&include_drafts=false"),N("workspace/policy"),N("discovery/tools"),p(R.signal),N("discovery/capabilities"),N("workflow-catalog?scope=tenant"),N("config/capability-defaults"),N($v(ln))]);if(l.current!==S)return;const j=D=>E[D].status==="fulfilled"?E[D].value:void 0,I=[];E.forEach((D,M)=>{var J,B;D.status==="rejected"&&(((J=D.reason)==null?void 0:J.status)===401&&t(),!(M===5&&[403,404,501].includes((B=D.reason)==null?void 0:B.status))&&M!==7&&I.push(`${["Workflows","Workspace policy","Tools","Conversations","Capabilities","Shared workflows","Gateway defaults"][M]}: ${At(D.reason)}`))});let L=[];if(E[2].status==="fulfilled")try{L=f1(j(2))}catch(D){I.push(`Tools: ${At(D)}`)}const z=d.current===$,V=g(j(3));let Z;if(E[7].status==="rejected")Z={status:"error",data:null,error:`Workflows for this app: ${At(E[7].reason)}`};else try{Z={status:"ready",data:t0(j(7),ln),error:""}}catch(D){Z={status:"error",data:null,error:String((D==null?void 0:D.message)||D)}}s(D=>({executable:Z,workflows:JA(j(0),j(5)),policy:j(1)?QA(j(1)):null,tools:XA(j(2)),sessions:z&&j(3)?V.sessions:D.sessions,sessionsLoaded:D.sessionsLoaded||!!(z&&j(3)),capabilities:J$(j(4)),capabilitiesLoading:!1,sessionToolPolicy:_1(j(4)),toolCatalog:L,toolWarnings:h1(j(2)),capabilitiesError:E[4].status==="rejected"?`Could not read the gateway's capabilities: ${At(E[4].reason)}`:"",streaming:x$(j(4),E[4].status==="rejected"?At(E[4].reason):void 0),defaultModel:v$(j(6)),gatewayDefault:R$(j(0)),loading:!1,errors:I,hasMore:z&&j(3)?V.hasMore:D.hasMore,archivedSessions:z&&j(3)?Zy(j(3)):D.archivedSessions})),z&&j(3)&&await _(j(3),$,R.signal)},[e,t,p,_]);y.useEffect(()=>(o.current=Gf,s(Hf),C(),()=>{var S,$;l.current+=1,d.current+=1,(S=u.current)==null||S.abort(),($=f.current)==null||$.abort()}),[C]);const x=y.useCallback(()=>{o.current+=Gf,v()},[v]),k=y.useCallback(S=>{s($=>({...$,sessions:$.sessions.filter(R=>R.sessionId!==S),archivedSessions:$.archivedSessions+1})),v()},[v]);return{...n,refresh:C,loadMore:x,forgetSession:k}}async function Kf(e){if(e.inputSchema)return ew(e.inputSchema);if(!e.bundleId)return;const t=encodeURIComponent(e.bundleId),n=encodeURIComponent(e.flowId),s=e.registryScope==="tenant_catalog"&&e.bundleVersion?we(`workflow-catalog/${t}/versions/${encodeURIComponent(e.bundleVersion)}/flows/${n}/input_schema?scope=tenant`):we(`bundles/${t}/flows/${n}/input_schema${e.bundleVersion?`?bundle_version=${encodeURIComponent(e.bundleVersion)}`:""}`),o=await ot(s),l=ew(o);if(!l||o!=null&&o.native_loop_factory||(o==null?void 0:o.version)!==1||!Array.isArray(o==null?void 0:o.inputs)||!(o!=null&&o.input_data_schema)||!Array.isArray(l.required)||!l.required.length)return l;const u=e.bundleVersion||o.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},f=g=>{for(const[_,v]of Object.entries(d))if((g==null?void 0:g[_])!==v)throw new Error("The Gateway returned inputs for a different workflow version. Refresh workflows and retry.");if(e.registryScope==="tenant_catalog"&&(g==null?void 0:g.registry_scope)!=="tenant_catalog")throw new Error("The Gateway returned inputs from a different workflow registry. Refresh workflows and retry.")};f(o);const m=e.registryScope==="tenant_catalog"?we(`workflow-catalog/${t}/versions/${encodeURIComponent(u)}/flows/${n}?scope=tenant`):we(`bundles/${t}/flows/${n}?bundle_version=${encodeURIComponent(u)}`),p=await ot(m);return f(p),g$(l,p.flow)}const Jf=e=>we(`runs/${encodeURIComponent(e)}`);function Y$(e){return{getRun:(t,n)=>ot(Jf(t),{signal:n}),getHistory:(t,n)=>ot(`${Jf(t)}/history_bundle?include_subruns=true&include_session=true&ledger_mode=full`,{signal:n}),getLedger:(t,n,s)=>ot(`${Jf(t)}/ledger?after=${n}&limit=200`,{signal:s}),streamLedger:(t,n,s,o,l,u)=>Ur.stream_ledger(t,{after:n,on_step:s,signal:o,on_open:l,on_delta:u,on_delta_error:(d,f)=>e.onDeltaError({runId:t,error:d,frame:f})}),replayView:jE({fetch:(t,n)=>fetch(we(t),{...n,credentials:"same-origin"})}),submitCommand:(t,n)=>ot(we("commands"),{method:"POST",body:JSON.stringify(t),signal:n})}}function Os(e){return typeof e=="string"?e.trim():""}function Q$(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},s=(Array.isArray(t.skills)?t.skills:[]).flatMap(d=>{const f=d&&typeof d=="object"&&!Array.isArray(d)?d:null,m=Os(f==null?void 0:f.name);if(!f||!m)return[];const p=f.source&&typeof f.source=="object"&&!Array.isArray(f.source)?f.source:void 0;return[{name:m,description:Os(f.description),trustLevel:Os(f.trust_level)||"unverified",blocked:f.blocked===!0,requiresReview:f.requires_review===!0,reasons:Array.isArray(f.reasons)?f.reasons.map(Os).filter(Boolean):[],source:p?{source:Os(p.source),binding:Os(p.binding),ambiguous:p.ambiguous===!0}:void 0}]}),o=Array.isArray(t.warnings)?t.warnings.map(Os).filter(Boolean):[],l=Os(t.shelf),u=Os(t.shelf_source);return{skills:s.sort((d,f)=>d.name.localeCompare(f.name)),warnings:o,...l?{shelf:l}:{},...u?{shelfSource:u}:{}}}function X$({inventory:e}){return a.jsxs("div",{className:"code-skills-empty",role:"status",children:[a.jsx("p",{children:a.jsx("strong",{children:"This gateway offers no skills."})}),e.warnings.length?e.warnings.map((t,n)=>a.jsx("p",{children:e.shelf?t:`The gateway has no skill shelf: ${t}`},`${t}:${n}`)):a.jsx("p",{children:"The gateway gave no reason for the empty list."}),e.shelf?a.jsxs("p",{className:"code-field-help",children:["Skill shelf: ",a.jsx("code",{children:e.shelf}),e.shelfSource?` (source: ${e.shelfSource})`:""]}):a.jsx("p",{className:"code-field-help",children:"The gateway did not report a skill shelf location."})]})}function Z$(e){var s;const t=e.trustLevel.replace(/[_-]+/g," "),n=(s=e.source)!=null&&s.source?`Adopted from ${e.source.source}`:"Source has no adoption record";return`Trust: ${t}. ${n}${e.requiresReview?". Review required":""}.`}function eT({skill:e,checked:t,disabled:n,onChange:s,lockedReasonId:o}){const l=e.reasons.join(" ")||"Blocked by gateway policy.",u=e.blocked?`Blocked by the gateway: ${l}`:n?"Available when a gateway is connected and no run is in progress.":null;return a.jsx("div",{className:"code-field code-skill-row",children:a.jsx(Wr,{variant:"row",action:"skill",label:e.name,description:a.jsxs(a.Fragment,{children:[e.description?a.jsx("span",{className:"code-skill-row__desc",children:e.description}):null,a.jsx("span",{className:"code-skill-row__trust",children:Z$(e)})]}),checked:t,unavailableReason:u,describedBy:!e.blocked&&n?o:void 0,onChange:s})})}function tT({value:e,onChange:t,disabled:n,lockedReasonId:s}){const[o,l]=y.useState({skills:[],warnings:[]}),[u,d]=y.useState(""),[f,m]=y.useState(!0),[p,g]=y.useState(""),[_,v]=y.useState(0);y.useEffect(()=>{const S=new AbortController;return m(!0),g(""),ot(we("skills"),{signal:S.signal}).then($=>{S.signal.aborted||l(Q$($))}).catch($=>{S.signal.aborted||g(At($))}).finally(()=>{S.signal.aborted||m(!1)}),()=>S.abort()},[_]);const C=y.useMemo(()=>new Set(e.map(Os).filter(Boolean)),[e]),x=y.useMemo(()=>{const S=u.trim().toLocaleLowerCase();return S?o.skills.filter($=>`${$.name}
93
- ${$.description}
94
- ${$.trustLevel}`.toLocaleLowerCase().includes(S)):o.skills},[o.skills,u]),k=(S,$)=>{const R=$?[...C,S]:[...C].filter(N=>N!==S);t([...new Set(R)])};return a.jsxs("section",{className:"code-settings-section","aria-labelledby":"code-skills-heading",children:[a.jsx("h3",{id:"code-skills-heading",children:"Skills"}),a.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."}),a.jsxs("label",{className:"code-field",children:["Find a skill",a.jsx("input",{type:"search",value:u,onChange:S=>d(S.target.value),disabled:n||f,placeholder:"Search names, descriptions, or trust"})]}),f?a.jsx("p",{className:"code-muted",role:"status",children:"Loading skills from the gateway…"}):null,p?a.jsxs("div",{className:"code-inline-error",role:"alert",children:["Skill selection is unavailable: ",p," ",a.jsx("button",{className:"code-text-button",type:"button",onClick:()=>v(S=>S+1),disabled:n,children:"Retry"})]}):null,o.warnings.length&&o.skills.length?a.jsxs("details",{className:"code-disabled-tools",children:[a.jsxs("summary",{children:["Gateway reported ",o.warnings.length," skills warning",o.warnings.length===1?"":"s"]}),o.warnings.map((S,$)=>a.jsx("p",{children:S},`${S}:${$}`))]}):null,!f&&!p&&!o.skills.length?a.jsx(X$,{inventory:o}):null,!f&&!p&&o.skills.length&&!x.length?a.jsx("p",{className:"code-muted",children:"No skills match your search."}):null,x.map(S=>a.jsx(eT,{skill:S,checked:C.has(S.name),disabled:n,lockedReasonId:s,onChange:$=>k(S.name,$)},S.name))]})}const nT="code-settings-locked",or={provider:"",model:"",reasoning:"",maxIterations:"",maxTokens:"",system:"",workspace:null,toolLayer:{},skills:[],workflow:"@default",streamReplies:"gateway_default"};function sT({tab:e,value:t,onChange:n,toolCatalog:s,toolWarnings:o,toolsNotice:l,automationTools:u,disabled:d,defaultModel:f,workflowDefault:m,streaming:p=lb,lockedReasonId:g=nT,workspaceRootFixed:_,hideStreamReplies:v,lockedText:C,connected:x=!1,automationFolders:k=!1,workspaceRequest:S,sessionId:$,onOpenDefaultWorkspaces:R,workspaceRefreshKey:N}){const E=j=>n({...t,...j});return a.jsxs(a.Fragment,{children:[d?a.jsx("p",{className:"code-notice",id:g,children:C||"Settings are unavailable while disconnected or while a run is active. Reconnect, or finish or stop the run, then try again."}):null,e==="model"?a.jsxs(a.Fragment,{children:[a.jsx("section",{className:"code-settings-section","aria-label":"Model",children:a.jsx(_u,{defaultModeLabel:m?"Workflow default":"Gateway default",value:t,onChange:E,disabled:d,effectiveDefault:f,enableSpeculation:!0,inheritLabel:"Gateway default",fetchProviders:So.fetchProviders,fetchModels:So.fetchModels,fetchModelCapabilities:So.fetchModelCapabilities,...m?{defaultHint:f?`Workflow default: ${f.provider} · ${f.model}.`:void 0}:{fetchGatewayDefault:So.fetchGatewayDefault}})}),a.jsxs("section",{className:"code-settings-section",children:[a.jsx("h3",{children:"Behavior"}),a.jsxs("div",{className:"code-field-pair",children:[a.jsxs("label",{className:"code-field",children:["Iteration limit",a.jsx("input",{type:"number",min:1,step:1,placeholder:"Workflow default",value:t.maxIterations,disabled:d,onChange:j=>E({maxIterations:j.target.value})})]}),a.jsxs("label",{className:"code-field",children:["Context token limit",a.jsx("input",{type:"number",min:1,step:1,placeholder:"Gateway default",value:t.maxTokens,disabled:d,onChange:j=>E({maxTokens:j.target.value})})]})]}),a.jsxs("label",{className:"code-field",children:["Additional instructions",a.jsx("textarea",{rows:5,value:t.system,placeholder:"Project conventions or guidance for this conversation…",disabled:d,onChange:j=>E({system:j.target.value})})]}),a.jsx("p",{className:"code-field-help",children:"Reasoning and additional instructions depend on the selected workflow and model."}),v?null:a.jsx(rT,{value:t.streamReplies,onChange:j=>E({streamReplies:j}),disabled:d,streaming:p})]})]}):e==="workspace"?a.jsxs("section",{className:"code-settings-section",children:[_?a.jsxs("p",{className:"code-field-help","data-setting":"workspace-root-fixed",children:["Runs work in the automation workspace ",a.jsx("code",{title:_,children:_.split(/[\\/]/).filter(Boolean).pop()||_}),"."]}):null,a.jsx(J_,{connected:x,request:S,sessionId:$,onOpenDefaults:R,refreshKey:N,automation:k?{value:t.workspace,onChange:j=>E({workspace:j})}:void 0})]}):e==="tools"?a.jsxs("section",{className:"code-settings-section",children:[l?a.jsxs("p",{className:"code-notice",role:"status",children:[l.text,a.jsx("button",{type:"button","aria-label":"Dismiss notice",onClick:l.onDismiss,children:"Dismiss"})]}):null,a.jsx(R1,{catalog:s,layer:"app",value:t.toolLayer,onChange:j=>E({toolLayer:j}),onReset:()=>E({toolLayer:{}}),disabled:d,warnings:o,savedWhere:u?"Saved in this automation's definition":Zv,note:u?"Auto tools run without asking at every occurrence; Ask tools wait for you; Off tools are not offered. Gateway restrictions always apply.":"Auto tools run without asking, also when this app is closed; Ask tools wait for you; Off tools are not offered. Gateway restrictions always apply."})]}):a.jsx(tT,{value:t.skills,onChange:j=>E({skills:j}),disabled:d,lockedReasonId:g})]})}function rT({value:e,onChange:t,disabled:n,streaming:s}){const o=s.status!=="supported",l=s.status==="unsupported"?`Unavailable: ${s.reason}. Replies appear when they are complete.`:s.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 a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"code-field",children:["Stream replies",a.jsxs("select",{"aria-label":"Stream replies","aria-describedby":"code-stream-replies-help",value:e,disabled:n||o,onChange:u=>t(u.target.value),children:[a.jsx("option",{value:"gateway_default",children:$$(s)}),a.jsx("option",{value:"on",children:"On"}),a.jsx("option",{value:"off",children:"Off"})]})]}),a.jsx("p",{id:"code-stream-replies-help",className:"code-field-help","data-streaming":s.status,children:l})]})}const tw="Your Permissions setting became per-tool defaults on this device — review them";function qf(e){return`abstractcode.tools.migrated.v1:${e}`}function aT(e){const t=e&&typeof e=="object"?e:{},n=typeof t.permissions=="string"?t.permissions:"default",s=t.toolsCustomized===!0;return!s&&(n==="default"||!n)?null:{tools:t.tools&&typeof t.tools=="object"?t.tools:void 0,toolsCustomized:s,permissions:n}}function oT(e,t){if(!Oo(e))return!1;const n=e.riskRank??4;return t==="read"?e.gatewayDefault==="auto"||n<=1:t==="write"?n<=2||["write_file","edit_file"].includes(e.name):!1}function iT(e,t){var d,f,m;const n={},s=e.toolsCustomized===!0&&((d=e.tools)==null?void 0:d.mode)==="custom",o=new Set(Array.isArray((f=e.tools)==null?void 0:f.selected)?e.tools.selected.filter(p=>typeof p=="string"):[]),l=e.toolsCustomized===!0?((m=e.tools)==null?void 0:m.approval)||{}:{},u=String(e.permissions||"default");for(const p of t){if(!p.offered)continue;if(s&&!o.has(p.name)){n[p.name]="off";continue}const g=l[p.name];g==="approve"?n[p.name]="auto":g==="ask"?n[p.name]="ask":(u==="all"?Oo(p):oT(p,u))&&(n[p.name]="auto")}return Po(t,{app:n}).app}function lT(e,t){const n=rm(e,{app:t}),s={...t};for(const o of e)Oo(o)&&n[o.name].mode==="ask"&&(s[o.name]="auto");return Po(e,{app:s}).app}function cT(e,t){const n=rm(e,{app:t}),s=e.filter(o=>Oo(o)&&n[o.name].mode!=="off");return s.length>0&&s.some(o=>o.gatewayDefault!=="auto")&&s.every(o=>n[o.name].mode==="auto")}function uT(e,t){const n={};for(const[s,o]of Object.entries(t))o!=="auto"&&(n[s]=o);return Po(e,{app:n}).app}const nl=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Wc=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!==""):[];function cb(e,t){const n=nl(e),s=nl(n._runtime),o=Array.isArray(s.allowed_tools)?Wc(s.allowed_tools):Array.isArray(n.tools)?Wc(n.tools):null,l=nl(s.tool_policy),u={};for(const d of t)o&&!o.includes(d.name)&&(u[d.name]="off");for(const d of Wc(l.require_approval_tools))u[d]!=="off"&&(u[d]="ask");for(const d of Wc(l.auto_approve_tools))u[d]!=="off"&&(u[d]="auto");return Po(t,{app:u}).app}function dT(e,t,n,s={}){const o={...nl(e)};if(uu(n,{app:t}))return Xv(o,Yc(n,{app:t},s));const l={...nl(o._runtime)};return delete o.tools,delete l.allowed_tools,delete l.tool_policy,Object.keys(l).length?o._runtime=l:delete o._runtime,o}function ub(e){return`abstractcode.workspace.v2:${e}`}function fT(e){try{const{showAllWorkflows:t,tools:n,toolsCustomized:s,permissions:o,toolLayer:l,legacyTools:u,...d}=JSON.parse(e||"{}"),f=aT({tools:n,toolsCustomized:s,permissions:o})??(u&&typeof u=="object"?u:null),m=typeof d.workflow=="string"&&d.workflow.trim()?d.workflow.trim():or.workflow;return{...or,...d,workflow:m,speculation:Fh(d.speculation),streamReplies:k$(d.streamReplies),toolLayer:{},...f?{legacyTools:f}:{}}}catch{return or}}function db(e){try{return fT(localStorage.getItem(ub(e)))}catch{return or}}function hT(e,t){const{workflow:n,toolLayer:s,...o}=t,l=n&&n!=="@default"?{...o,workflow:n}:o;try{localStorage.setItem(ub(e),JSON.stringify(l))}catch{}}const Th=we("accounts/me/preferences");function Rh(e){var n;const t=pa((n=pa(e))==null?void 0:n.time_zone);if(!t||!Array.isArray(t.choices)||typeof t.gateway_default!="string"||typeof t.effective!="string")throw new Error("The gateway's account preferences answer has no time_zone block (choices, gateway_default, effective).");return{value:typeof t.value=="string"&&t.value?t.value:null,gateway_default:t.gateway_default,effective:t.effective,label:typeof t.label=="string"?t.label:"Time zone",help:typeof t.help=="string"?t.help:"",choices:t.choices.map(String)}}function pa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ih(e,t=ln){var o;const n=pa(e);if(!n||!Array.isArray(n.apps)||!pa((o=pa(n.preferences))==null?void 0:o.default_workflow))throw new Error("The gateway's account preferences answer has no apps or default_workflow.");const s=n.apps.map(pa).find(l=>(l==null?void 0:l.interface)===t);if(!s)throw new Error(`The gateway's account preferences have no row for ${t}.`);if(typeof s.gateway_default_label!="string"||!Array.isArray(s.choices))throw new Error(`The gateway's account preferences row for ${t} has no gateway_default_label or choices.`);return{interface:t,value:typeof s.value=="string"&&s.value.trim()?s.value:null,state:typeof s.state=="string"?s.state:"default",reason:typeof s.reason=="string"&&s.reason?s.reason:null,gatewayDefaultLabel:s.gateway_default_label,choices:s.choices.map(pa).filter(Boolean).map(l=>({value:String(l.value),label:String(l.label??l.name??l.value),workflowId:String(l.workflow_id??"")}))}}function mT(e){const t=String(e||"").trim();if(!t||t===Xt)return null;const n=t.startsWith("tenant_catalog:")?"catalog":t.startsWith("private:")?"private":"",s=n?t.slice(t.indexOf(":")+1):t,o=s.indexOf(":");if(o<=0)return null;const l=s.slice(0,o).split("@")[0],u=s.slice(o+1);return!l||!u?null:n==="catalog"?`catalog:${l}:${u}`:`${l}:${u}`}function pT(e,t){if(!e)return Xt;const n=e.startsWith("catalog:"),s=n?e.slice(8):e,o=s.indexOf(":");if(o<=0)return Xt;const l=s.slice(0,o),u=s.slice(o+1),d=t.find(f=>f.bundleId===l&&f.flowId===u&&(f.registryScope??"private")==="private"!==n);return d?d.id:Xt}function gT(e){return e instanceof Error?e.message:String(e)}function nw(e){const t=e;return typeof(t==null?void 0:t.status)=="number"?t.status:0}async function yT(e,t,n){let s,o;try{const l=await e(Th);s=Ih(l),o=Rh(l)}catch(l){return nw(l)===404?{status:"unsupported"}:{status:"error",message:gT(l)}}if(t&&t!==Xt){let l=!0;if(s.value===null){const u=mT(t);if(u)try{const d=await e(Th,{method:"PUT",body:JSON.stringify({default_workflow:{[ln]:u}})});s=Ih(d),o=Rh(d)}catch(d){l=nw(d)===400}}l&&n()}return{status:"ok",row:s,timeZone:o}}function wT(e,t){const[n,s]=y.useState({status:"loading"}),o=y.useRef(t);o.current=t,y.useEffect(()=>{let f=!0;if(s({status:"loading"}),!!e)return yT(ot,db(e).workflow,()=>{f&&o.current()}).then(m=>{f&&s(m)}),()=>{f=!1}},[e]);const l=y.useCallback(async f=>{const m=await ot(Th,{method:"PUT",body:JSON.stringify(f)}),p=Ih(m),g=Rh(m);return s({status:"ok",row:p,timeZone:g}),{row:p,timeZone:g}},[]),u=y.useCallback(async f=>(await l({default_workflow:{[ln]:f}})).row,[l]),d=y.useCallback(async f=>(await l({time_zone:f})).timeZone,[l]);return{state:n,save:u,saveTimeZone:d}}function vT(e){const{row:t}=e,[n,s]=y.useState(!1),[o,l]=y.useState(null),u=t.value??"",d=t.choices.some(f=>f.value===u);return a.jsxs("div",{className:"code-account-workflow","data-account-workflow":!0,children:[a.jsxs("label",{className:"code-field",children:["Default for new conversations",a.jsxs("select",{"aria-label":"Default for new conversations",value:u,disabled:e.disabled||n,"aria-busy":n||void 0,onChange:async f=>{const m=f.target.value||null;s(!0),l(null);try{await e.save(m),l({ok:!0,text:"Saved."})}catch(p){l({ok:!1,text:`Not saved. ${p instanceof Error?p.message:String(p)}`})}finally{s(!1)}},children:[a.jsx("option",{value:"",children:t.gatewayDefaultLabel}),u&&!d?a.jsx("option",{value:u,children:`${u} (no longer runs)`}):null,t.choices.map(f=>a.jsx("option",{value:f.value,title:f.workflowId||void 0,children:f.label},f.value))]})]}),t.state==="broken"&&t.reason?a.jsx("p",{className:"code-field-help code-workflow-resolved is-missing",role:"alert","data-account-workflow-reason":!0,children:t.reason}):a.jsx("p",{className:"code-field-help",children:"Kept by the gateway for your account: the Assistant and every browser use the same choice. This conversation's workflow is picked above."}),o?a.jsx("p",{className:`code-field-help${o.ok?"":" is-error"}`,role:"status","data-account-workflow-note":!0,children:o.text}):null]})}function sw(e){const[t,n]=y.useState(!1),[s,o]=y.useState(null);return a.jsx("div",{className:"code-account-time-zone","data-account-time-zone":!0,children:a.jsx(o1,{id:"code-account-time-zone",block:e.block,disabled:e.disabled||t,note:s,onChange:async l=>{n(!0),o(null);try{await e.save(l),o({ok:!0,text:"Saved."})}catch(u){o({ok:!1,text:`Not saved. ${u instanceof Error?u.message:String(u)}`})}finally{n(!1)}}})})}const _T=bu("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).";function bT(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function xT(e){var o;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 s=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{(o=s==null?void 0:s.focus)==null||o.call(s)}catch{}}}async function kT(e){var s;const t=String(e??""),n=globalThis.navigator;if(typeof((s=n==null?void 0:n.clipboard)==null?void 0:s.writeText)=="function")try{return await n.clipboard.writeText(t),!0}catch{}return xT(t)}async function gm(e){const t=String(e??"");return t?kT(t):!1}const ST=e=>we(`runs/${encodeURIComponent(e)}/workspace`),ol=(e,t)=>fetch(e,{...t,credentials:"same-origin"});async function fb(e){await ot(`${ST(e)}/open`,{method:"POST"})}function rw(e,t){return typeof e.size_bytes!="number"?null:dm({name:e.name,size:e.size_bytes},t)}function jT(e,t){return t?t.state==="refused"?`Not attached: ${t.error||"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 NT(e,t,n,s){const o=rw(t,n);if(o)return`Not attached: ${o}`;const l=new AbortController,u=await fetch(E_(e,t.path),{credentials:"same-origin",signal:l.signal});if(!u.ok)throw new Error(`Could not read ${t.name} (${u.status}): ${await u.text()}`);const d=rw({...t,size_bytes:f_(u)},n);if(d)return l.abort(),`Not attached: ${d}`;const f=await u.blob(),[m]=s([new File([f],t.name,{type:f.type})]);return jT(t.name,m)}function CT({runId:e,enabled:t,refreshKey:n,maxAttachmentBytes:s,onAttachFiles:o,heading:l="Conversation files"}){const[u,d]=y.useState(""),[f,m]=y.useState("");return e?a.jsxs(a.Fragment,{children:[u?a.jsx("p",{className:"code-field-help",role:"status",children:u}):null,t?a.jsx(um,{fetchGateway:ol,runId:e,title:l,refreshKey:n,className:"code-workspace-browser",copyText:gm,onOpenFolder:()=>fb(e),fileActions:p=>a.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:f===p.path,onClick:()=>{m(p.path),d(""),NT(e,p,s,o).then(d).catch(g=>d(At(g))).finally(()=>m(""))},children:a.jsx(de,{name:f===p.path?"loader":"paperclip",size:15})})},e):null]}):a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(de,{name:"folder",size:28}),a.jsx("p",{children:"This conversation's files appear here."}),a.jsx("small",{children:"Start a conversation; the files its workflow creates and edits are listed and previewed here."})]})}const ET=new Set(["abstract.progress","abstractcode.progress"]);function yo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ga(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function AT(e){if(!yo(e))return null;const t=yo(e.effect)?e.effect:null;if(!t||String(t.type||"")!=="emit_event")return null;const n=yo(t.payload)?t.payload:null,s=String((n==null?void 0:n.name)??(n==null?void 0:n.event_name)??"").trim();if(!ET.has(s))return null;const o=yo(e.result)?e.result:null,l=yo(o==null?void 0:o.payload)?o==null?void 0:o.payload:null,u=yo(n==null?void 0:n.payload)?n==null?void 0:n.payload:null,d=l||u;if(!d||String(d.kind||"")!=="llm")return null;const f=String(d.phase||"").trim();return f!=="prefill"&&f!=="generate"&&f!=="complete"?null:d}function $T(e){let t=null;for(const n of e||[]){const s=AT(n);s&&(t=s)}return!t||t.phase==="complete"||t.final===!0?null:t}function jo(e){return Math.round(e).toLocaleString()}function hb(e){if(!e||e.phase!=="prefill")return null;const t=ga(e.prompt_tokens),n=ga(e.prefill_processed_tokens);if(t===null||t<=0||n===null||n<0)return null;const s=Math.min(n,t),o=Math.min(99,Math.round(s/t*100));return{processed:s,total:t,percent:o}}function mb(e){return`${jo(e.processed)} / ${jo(e.total)} tokens (${e.percent}%)`}function TT(e){if(!e)return"";if(e.phase==="prefill"){const t=hb(e);if(t)return`Prefill · ${mb(t)}`;const n=ga(e.prompt_tokens);if(n===null||n<=0)return"Prefill";const s=ga(e.cached_tokens),o=ga(e.fed_tokens),l=[];s!==null&&s>0&&l.push(`${jo(s)} cached`),o!==null&&o>0&&l.push(`${jo(o)} new`);const u=l.length?` (${l.join(", ")})`:"";return`Prefill · ${jo(n)} tokens${u}`}if(e.phase==="generate"){const t=ga(e.generated_tokens)??0,n=Math.round(t)===1?"token":"tokens",s=ga(e.tokens_per_second),o=s!==null&&s>0?` · ${Math.round(s)} tok/s`:"";return`Generating · ${jo(t)} ${n}${o}`}return""}function RT(e){return TT($T(e))}const pb=new Set(["abstract.progress","abstractcode.progress"]),IT=new Set(["abstract.status","abstractcode.status"]);function Ge(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ym(e){const t=Ge(e);return!!(t&&t.$slim)}function Ot(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 rn(e,t=120){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function Yi(e,t=120){var o,l;if(e==null)return"";if(typeof e=="string")return rn(e,t);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return rn(e.length===0?"[]":`${e.length} ${e.length===1?"item":"items"}`,t);const n=Ge(e);if(!n)return"";if(ym(n)){const u=String(((o=n.$slim)==null?void 0:o.field)||""),d=Ot((l=n.$slim)==null?void 0:l.bytes);return`${u||"payload"} stored${d?` · ${Wn(d)} bytes`:""}`}const s=[];for(const[u,d]of Object.entries(n)){const f=typeof d=="string"?rn(d,60):typeof d=="number"||typeof d=="boolean"?String(d):Array.isArray(d)?`${d.length} items`:d==null?"":"{…}";if(f&&(s.push(`${u.replace(/_/g," ")} ${f}`),s.join(" · ").length>=t))break}return rn(s.join(" · "),t)}function Iu(e){return`${e>=100?String(Math.round(e)):e.toFixed(e<1?2:1).replace(/\.0+$/,"")} s`}function gb(e,t){const n=Date.parse(String(e||"")),s=Date.parse(String(t||""));if(!Number.isFinite(n)||!Number.isFinite(s))return null;const o=(s-n)/1e3;return o>=0?o:null}function LT(e){const t=String(e||""),n=/T(\d{2}:\d{2}:\d{2})/.exec(t);return n?n[1]:""}function yb(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 un(e,t=" · "){return e.filter(n=>!!n).join(t)}const aw="visual_react_agent_";function MT(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 OT(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(aw)){const s=t.slice(aw.length),o=/^(.*)_(\d+)_(\d+)_(\d+)_([0-9a-f]{6,12})_(.+)$/.exec(s);if(o){let l=o[1];if(l.includes("__")){const u=l.split("__").filter(Boolean);for(let d=u.length-1;d>=0;d-=1){const f=MT(u[d]);if(f&&f.length>3){l=f;break}}}return{name:l,node:o[6]}}return{name:s,node:""}}return{name:t,node:""}}function PT(e){var n;if(!Array.isArray(e)||!e.length)return"";const t=new Map;for(const s of e){const o=String(((n=Ge(s))==null?void 0:n.name)||"").trim()||"tool";t.set(o,(t.get(o)||0)+1)}return[...t.entries()].map(([s,o])=>o>1?`${s} ×${o}`:s).join(", ")}function DT(e){var d;const t=Ge(e);if(!t)return null;const n=Ge(t.effect);if(!n||String(n.type||"")!=="emit_event")return null;const s=Ge(n.payload),o=String((s==null?void 0:s.name)??(s==null?void 0:s.event_name)??"").trim();if(!pb.has(o))return null;const l=Ge((d=Ge(t.result))==null?void 0:d.payload),u=Ge(s==null?void 0:s.payload);return l||u}function FT(e){if(!e.length)return"";const t=e[e.length-1];let n=null,s=null,o=null,l=null,u=null;for(const p of e)n=Ot(p.prompt_tokens)??n,s=Ot(p.cached_tokens)??s,o=Ot(p.generated_tokens)??o,l=Ot(p.tokens_per_second)??l,u=Ot(p.elapsed_s)??u;if(t.final===!0||String(t.phase||"")==="complete")return un([n!==null?`${Wn(n)} tokens in`:null,s!==null&&s>0?`${Wn(s)} cached`:null,o!==null?`${Wn(o)} out`:null,u!==null?Iu(u):null,l!==null&&l>0?`${Math.round(l)} tok/s`:null]);const f=n!==null?`prefill ${Wn(n)} tokens${s!==null&&s>0?` (${Wn(s)} cached)`:""}`:"prefill";if(String(t.phase||"")==="prefill"){const p=hb(t);return p?`prefill ${mb(p)}`:f}const m=un([`generating ${Wn(o??0)} ${Math.round(o??0)===1?"token":"tokens"}`,l!==null&&l>0?`${Math.round(l)} tok/s`:null]);return`${f} → ${m}`}function zT(e){if(!e.length)return"";const t=e[e.length-1],n=Ot(t.step)??Ot(t.index),s=Ot(t.total)??Ot(t.steps),o=Ot(t.percent)??Ot(t.progress),l=Ot(t.frame),u=Ot(t.elapsed_s);return un([typeof t.label=="string"?rn(t.label,60):null,typeof t.phase=="string"&&!t.label?rn(t.phase,40):null,n!==null?`step ${Wn(n)}${s!==null?`/${Wn(s)}`:""}`:null,l!==null?`frame ${Wn(l)}`:null,o!==null?`${Math.round(o<=1?o*100:o)}%`:null,u!==null?Iu(u):null])}function Lh(e){return e.length?String(e[e.length-1].kind||"")==="llm"?FT(e):zT(e):""}function BT(e,t,n){var S;const s=String(e.provider||"").trim(),o=yb(e.model||(t==null?void 0:t.model)),l=un(["llm",s,o])||"llm call";if(!t){const $=Ge(e.params)||{};return{title:l,detail:un([Ot($.temperature)!==null?`temperature ${$.temperature}`:null,$.thinking?`thinking ${$.thinking}`:null,(S=Ge($.speculation))!=null&&S.mode?`speculation ${Ge($.speculation).mode}`:null])}}const u=Ge(t.usage)||{},d=Ge(t.metadata)||{},f=Ge(d.prompt_cache)||{},m=Ge(d.performance)||{},p=Ot(u.prompt_tokens)??Ot(u.input_tokens),g=Ot(u.completion_tokens)??Ot(u.output_tokens),_=Ot(f.cached_tokens),v=String(f.outcome||"").trim(),C=gb(n.started_at,n.ended_at),x=Ot(m.generation_tokens_per_second),k=Array.isArray(t.tool_calls)?t.tool_calls.length:0;return{title:l,detail:un([p!==null?`${Wn(p)} tokens in`:null,_!==null&&_>0?`${Wn(_)} cached`:v?`${v} cache`:null,g!==null?`${Wn(g)} out`:null,C!==null?Iu(C):null,x!==null&&x>0?`${Math.round(x)} tok/s`:null,k?`${k} tool ${k===1?"call":"calls"}`:null])}}function WT(e,t){if(t.length<=60)return rn(t,60);if(e==="url")try{const n=new URL(t),s=n.pathname.split("/").filter(Boolean).pop()||"";return rn(`${n.host}${s?` · …/${s}`:""}`,72)}catch{}if(e==="file path"||e==="path"){const n=t.split(/[\\/]/).pop()||t;return rn(`${n} · ${t.slice(0,24)}…`,60)}return rn(t,60)}function UT(e,t){const n=Array.isArray(e.tool_calls)?e.tool_calls:[],s=PT(n),o=Ge(n[0]),l=o?p_(o.arguments):{label:"",value:""},u=Array.isArray(t==null?void 0:t.results)?t.results:[],d=u.filter(m=>{var p;return((p=Ge(m))==null?void 0:p.success)===!0}).length,f=u.length-d;return{title:un(["tools",s||"tool call"]),detail:un([l.value?`${l.label} ${WT(l.label,l.value)}`:null,u.length?`${d} ok`:null,f>0?`${f} failed`:null])}}function VT(e,t){var m,p;const{name:n,node:s}=OT(e.workflow_id),o=Ge(e.vars),l=o&&!ym(o)?o:null,u=Ge(l==null?void 0:l.context),d=typeof(u==null?void 0:u.task)=="string"?u.task:typeof(l==null?void 0:l.request)=="string"?l.request:"",f=String(((p=Ge((m=Ge(t==null?void 0:t.wait))==null?void 0:m.details))==null?void 0:p.sub_run_id)||"").slice(0,8);return l&&typeof l.state=="string"&&!u?{title:"subflow · status",detail:un([rn(l.state,80),f&&`run ${f}`])}:d?{title:"subflow · agent loop",detail:un([n,rn(d,90),f&&`run ${f}`])}:{title:un(["subflow",n||"workflow"]),detail:un([s,l?Yi(l,80):null,f&&`run ${f}`])}}function GT(e,t){const n=e.until,s=gb(t.started_at,n),o=LT(n);return{title:s!==null?`wait · delay ${Iu(s)}`:`wait · until ${o}`,detail:un([s!==null&&o?`until ${o}`:null,e.resume_to_node?`resumes at ${e.resume_to_node}`:null])}}function Mh(e){var d;const t=Ge(e)||{},n=Ge(t.effect),s=String((n==null?void 0:n.type)||"").trim(),o=Ge(n==null?void 0:n.payload)||{},l=Ge(t.result);if(s==="emit_event"){const f=String(o.name??o.event_name??"").trim();if(pb.has(f))return{kind:"progress",title:"progress",detail:"",isProgress:!0,isStatus:!1,isResume:!1,hidden:!0};if(IT.has(f))return{kind:"event",title:"status",detail:Yi(o.payload,80),isProgress:!1,isStatus:!0,isResume:!1,hidden:!0};const m=String(o.scope||"").trim();return{kind:"event",title:`event · ${f||"unnamed"}${m?` (${m})`:""}`,detail:Yi(o.payload??(l==null?void 0:l.payload),110),isProgress:!1,isStatus:!1,isResume:!1,hidden:!1}}if(s==="resume")return{kind:"step",title:"resume",detail:String(o.wait_reason||""),isProgress:!1,isStatus:!1,isResume:!0,hidden:!0};const u={isProgress:!1,isStatus:!1,isResume:!1,hidden:!1};if(s==="llm_call")return{kind:"llm",...BT(o,l,t),...u};if(s==="tool_calls")return{kind:"tools",...UT(o,l),...u};if(s==="start_subworkflow")return{kind:"subflow",...VT(o,l),...u};if(s==="wait_until")return{kind:"wait",...GT(o,t),...u};if(s==="wait_event")return{kind:"wait",title:"wait · event",detail:un([typeof o.prompt=="string"?rn(o.prompt,90):null,!o.prompt&&o.wait_key?rn(String(o.wait_key),70):null]),...u};if(s==="ask_user")return{kind:"ask",title:"ask · your input",detail:rn(String(o.prompt||((d=Ge(l==null?void 0:l.wait))==null?void 0:d.prompt)||"").split(`
95
- `)[0],110),...u};if(s==="answer_user")return{kind:"message",title:"message",detail:rn(String(o.message||""),110),...u};if(!s){if((l==null?void 0:l.completed)===!0){const f=Ge(l.output)||{},m=Ge(f.stop_reason)||{},p=Ot(f.iterations),g=un([String(m.code||f.outcome||"").replace(/_/g," ")||null,p!==null?`${Wn(p)} ${p===1?"iteration":"iterations"}`:null]),_=[f.answer,f.response,f.result].find(v=>typeof v=="string"&&v.trim());return{kind:"run",title:"run finished",detail:g||(typeof _=="string"?rn(_,110):Yi(f,110)),...u}}return{kind:"step",title:String(t.node_id||"workflow step"),detail:"",...u}}return{kind:"step",title:s.replace(/_/g," "),detail:Yi(o,110),...u}}function wb(e,t,n){var l,u;const s=Ge(e)||{},o=String(s.status||"").trim();if(s.error)return{status:"failed",statusLabel:"failed"};if(o==="failed")return{status:"failed",statusLabel:"failed"};if(o==="completed")return{status:"completed",statusLabel:"completed"};if(o==="waiting"){if(n)return{status:"completed",statusLabel:"completed"};const d=Ge((l=Ge(s.result))==null?void 0:l.wait);return String(((u=Ge(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 o==="started"?{status:"started",statusLabel:"running"}:{status:o||"started",statusLabel:o||"running"}}function HT(e){var o;const t=Ge(e.record)||{},n=String(((o=Ge(t.effect))==null?void 0:o.type)||"(none)"),s=String(t.idempotency_key||t.step_id||e.cursor);return`${e.runId}|${n}|${s}|${t.attempt??1}`}function KT(e){var f;const t=e.map(m=>Ge(m.record)||{}),n=t[t.length-1]||{},s={};for(const m of t){const p=Ge((f=Ge(m.effect))==null?void 0:f.payload);if(p)for(const[g,_]of Object.entries(p))ym(_)&&g in s||(s[g]=_)}let o=null,l=null,u=null,d=null;for(const m of t)m.result!==null&&m.result!==void 0&&(o=m.result),m.error!==null&&m.error!==void 0&&(l=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:s}:n.effect,result:o,error:l,started_at:u,ended_at:d}}function JT(e){var n,s;const t=[];for(const o of e){const l=Ge((s=Ge((n=Ge(o.record))==null?void 0:n.result))==null?void 0:s.wait),u=String((l==null?void 0:l.wait_key)||"").trim();u&&t.push(u)}return t}function qT(e,t){return`${e}|${String(t.step_id||t.node_id||"")}`}function YT(e,t){const n=new Map;for(const l of t){const u=DT(l.record);if(!u)continue;const d=qT(l.runId,u),f=n.get(d)||{entries:[],payloads:[]};f.entries.push(l),f.payloads.push(u),n.set(d,f)}if(!n.size)return e.map(l=>({...l}));const s=new Set,o=e.map(l=>{const u=l.stepIds.map(v=>`${l.runId}|${v}`).filter(v=>n.has(v));if(!u.length)return{...l};const d=[],f=[];for(const v of u)s.add(v),d.push(...n.get(v).payloads),f.push(...n.get(v).entries);const m=Lh(d),p=d[d.length-1],g=p.final===!0||String(p.phase||"")==="complete",_=!(g&&l.status==="completed"&&l.detail);return{...l,progress:_?m:"",progressFinal:g,progressEvents:f.map(v=>Ge(v.record)||{})}});for(const[l,u]of n.entries()){if(s.has(l))continue;const d=u.payloads,f=d[d.length-1],m=String(f.kind||""),p=u.entries[0];o.push({key:`progress:${l}`,runId:p.runId,cursor:u.entries[u.entries.length-1].cursor,kind:"progress",title:un(m==="llm"?["llm",String(f.provider||""),yb(f.model)]:["progress",m]),detail:"",status:f.final===!0||String(f.phase||"")==="complete"?"completed":"started",statusLabel:f.final===!0||String(f.phase||"")==="complete"?"completed":"running",nodeId:String(f.node_id||""),stepIds:[String(f.step_id||"")],progress:Lh(d),progressFinal:f.final===!0||String(f.phase||"")==="complete",entries:u.entries,progressEvents:u.entries.map(g=>Ge(g.record)||{}),merged:Ge(u.entries[u.entries.length-1].record)||{}})}return o}function vb(e,t){var g,_,v,C;const n=String(t||((g=e==null?void 0:e[0])==null?void 0:g.runId)||""),s=new Map,o=[],l=[],u=new Map,d=new Map,f=[];for(const x of e||[]){const k=Mh(x.record);if(k.isProgress){f.push(x);continue}if(k.isStatus)continue;if(k.isResume){const $=String(((C=(v=Ge((_=Ge(x.record))==null?void 0:_.effect))==null?void 0:v.payload)==null?void 0:C.wait_key)||"").trim();$&&l.push($);continue}const S=HT(x);d.set(x,d.size),u.set(x.runId,d.size-1),s.has(S)||(s.set(S,[]),o.push(S)),s.get(S).push(x)}const m=new Set(l),p=o.map(x=>{const k=s.get(x),S=KT(k),$=Mh(S),R=k[k.length-1],E=(u.get(R.runId)??-1)>(d.get(R)??1/0)||JT(k).some(I=>m.has(I)),j=wb(S,$.kind,E);return{key:x,runId:k[0].runId,cursor:k[k.length-1].cursor,kind:$.kind,title:$.kind==="run"&&n&&k[0].runId!==n?"subflow finished":$.title,detail:$.detail,status:j.status,statusLabel:j.statusLabel,nodeId:String(S.node_id||""),stepIds:[...new Set(k.map(I=>{var L;return String(((L=Ge(I.record))==null?void 0:L.step_id)||"")}).filter(Boolean))],progress:"",progressFinal:!1,entries:k,progressEvents:[],merged:S}});return YT(p,f)}const QT=new Set(["completed","failed","cancelled","denied","partly_denied"]);function XT(e){return e==="completed"||e==="denied"||e==="partly_denied"?"completed":e==="waiting"||e==="failed"||e==="cancelled"?e:"started"}function _b(e){const t=new Map;for(const l of e.messages||[])for(const u of l.step_ids||[]){const d=`${l.run_id}:${u}`;t.set(d,[...t.get(d)||[],l])}const n=new Map,s=new Map;for(const l of e.activities||[])if(l.kind==="llm")s.set(l.run_id,l.id);else if(l.kind==="tool"){const u=s.get(l.run_id);u&&!n.has(u)&&n.set(u,(l.tool_calls||[]).length),s.delete(l.run_id)}const o=Ge(e.interaction);return{sessionId:String(e.session_id||""),messageOf:(l,u)=>{for(const d of l.step_ids||[])for(const f of t.get(`${l.run_id}:${d}`)||[])if(u.includes(String(f.source||f.kind)))return String(f.text||"");return""},promptOf:l=>o&&l&&String(o.wait_key||"")===l?String(o.prompt||""):"",callsAfter:n}}function ZT(e,t){var p,g,_,v,C,x;const n=e,s=t||_b({root_run_id:n.run_id,activities:[n]}),o=String(n.effect_type||""),l=XT(String(n.status||"")),u=QT.has(String(n.status||"")),d=Array.isArray(n.tool_calls)?n.tool_calls:[];let f={},m=null;if(o==="llm_call"){f={provider:n.provider||"",model:n.model||""};const k=s.callsAfter.get(n.id)||0;u&&(m={usage:n.usage||{},model:n.model||"",...k?{tool_calls:Array.from({length:k},()=>({}))}:{}})}else if(o==="tool_calls")f={tool_calls:d.map(k=>({name:k.name,arguments:k.arguments,call_id:k.id}))},u&&(m={results:d.map(k=>({name:k.name,call_id:k.id,success:k.status==="completed",output:k.output,error:k.error}))});else if(o==="start_subworkflow")f={workflow_id:n.name||""},n.wait&&n.child_run_id&&(m={wait:{details:{sub_run_id:n.child_run_id}}});else if(o==="wait_until")(p=n.wait)!=null&&p.until&&(f={until:n.wait.until});else if(o==="wait_event"){const k=String(((g=n.wait)==null?void 0:g.wait_key)||""),S=s.promptOf(k)||s.messageOf(n,["question"]);f={...S?{prompt:S}:{},wait_key:k}}else o==="ask_user"?f={prompt:s.messageOf(n,["question","wait"])||s.promptOf(String(((_=n.wait)==null?void 0:_.wait_key)||""))}:o==="answer_user"?f={message:s.messageOf(n,["answer_user"])}:o==="emit_event"&&n.kind==="tool_policy"?f={name:"abstract.tool_policy_decision",scope:"run",payload:{decision:n.decision,source:n.source,session_id:s.sessionId,node_id:n.node_id,tool_calls:d.map(k=>({call_id:k.id,name:k.name,...k.matched?{matched:k.matched}:{}})),...n.policy?{policy:n.policy}:{}}}:o==="emit_event"&&(f={name:n.name||""});if(l==="waiting"&&n.wait){const k=n.wait.kind==="tool_approval";m={...m||{},wait:{...(m==null?void 0:m.wait)||{},wait_key:n.wait.wait_key,reason:n.wait.kind==="timer"?"until":n.wait.kind,details:{...((v=m==null?void 0:m.wait)==null?void 0:v.details)||{},...k?{mode:"approval_required"}:{}}}}}return{run_id:n.run_id,step_id:((C=n.step_ids)==null?void 0:C[0])||"",node_id:n.node_id||"",status:l,started_at:n.started_at||null,ended_at:n.ended_at||null,effect:o?{type:o,payload:f}:null,result:m,error:l==="failed"?((x=d.find(k=>k.error))==null?void 0:x.error)??"failed":null}}function ow(e){return(Array.isArray(e)?e:[]).map(t=>typeof t=="number"&&Number.isInteger(t)?t<0?`-${String(-t).padStart(11,"0")}`:String(t).padStart(12,"0"):t==null?"None":String(t))}function eR(e,t){const n=ow(e),s=ow(t);for(let o=0;o<Math.min(n.length,s.length);o+=1)if(n[o]!==s[o])return n[o]<s[o]?-1:1;return n.length-s.length}function tR(e,t){var l;if(!e)return[];const n=String(e.root_run_id||""),s=_b(e),o=[];for(const u of e.activities||[]){const d=ZT(u,s),f=Mh(d);f.kind==="wait"&&u.effect_type==="wait_until"&&!((l=u.wait)!=null&&l.until)&&(f.title="wait · timer",f.detail="");const m=wb(d,f.kind,!1),p=Ge(u.progress),g=Array.isArray(u.seqs)?u.seqs:[];o.push({order:u.order,row:{key:u.id,runId:u.run_id,cursor:g.length?Math.max(...g):0,kind:f.kind,title:f.title,detail:f.detail,status:m.status,statusLabel:m.statusLabel,nodeId:String(u.node_id||""),stepIds:[...new Set((u.step_ids||[]).filter(Boolean))],progress:p?Lh([p]):"",progressFinal:!!(p&&(p.final===!0||String(p.phase||"")==="complete")),entries:[{cursor:g.length?Math.max(...g):0,record:u,runId:u.run_id}],progressEvents:p?[p]:[],merged:d,...t&&u.kind==="tool"?{tools:t(u)}:{}}})}for(const u of e.runs||[]){if(String(u.status||"")!=="completed")continue;const d=String(u.run_id||""),f=(e.messages||[]).find(C=>C.id===`${d}:final`),m=(e.activities||[]).filter(C=>C.run_id===d),p=m[m.length-1]||(e.activities||[]).find(C=>C.child_run_id===d),g=(f==null?void 0:f.order)||[String((p==null?void 0:p.ended_at)||(p==null?void 0:p.started_at)||""),d,Number(u.last_seq||0)],_=f?String(f.text||""):"",v={run_id:d,status:"completed",effect:null,result:{completed:!0,output:_?{answer:_}:{}}};o.push({order:g,row:{key:`${d}:finished`,runId:d,cursor:Number(u.last_seq||0),kind:"run",title:d===n?"run finished":"subflow finished",detail:_?rn(_,110):"",status:"completed",statusLabel:"completed",nodeId:"",stepIds:f!=null&&f.step_ids?[...f.step_ids]:[],progress:"",progressFinal:!1,entries:[{cursor:Number(u.last_seq||0),record:f||u,runId:d}],progressEvents:[],merged:v}})}return o.map((u,d)=>({...u,index:d})).sort((u,d)=>eR(u.order,d.order)||u.index-d.index).map(u=>u.row)}function nR(e){return((e==null?void 0:e.activities)||[]).filter(t=>Ge(t.progress)).map(t=>{var n;return{run_id:t.run_id,step_id:((n=t.step_ids)==null?void 0:n[0])||"",status:"completed",effect:{type:"emit_event",payload:{name:"abstract.progress",payload:t.progress}},result:null}})}const sR=["running","waiting","failed","completed"],rR={running:"Running",failed:"Failed",completed:"Done"},aR=new Set(["waiting for you","approval needed"]);function oR(e,t){var o;if(e!=="waiting")return rR[e]||e;const n=t.filter(l=>l.status==="waiting");if(n.some(l=>aR.has(l.statusLabel)))return"Waiting for you";const s=((o=n[n.length-1])==null?void 0:o.statusLabel)||"waiting";return s.charAt(0).toUpperCase()+s.slice(1)}function iR(e){for(const t of sR)if(e.some(n=>n.status===t))return t;return e.length?e[e.length-1].status:"completed"}function lR(e){const t=[];let n=null,s=0;for(const o of e){if(o.kind==="llm"||!n){const l=o.kind==="llm";l&&(s+=1),n={key:`${l?"step":"start"}:${o.key}`,title:l?`Step ${s}`:"Start",detail:l?o.title:"",status:"completed",statusLabel:"Done",rows:[],toolRows:0},t.push(n)}n.rows.push(o),o.kind==="tools"&&(n.toolRows+=1)}for(const o of t)o.status=iR(o.rows),o.statusLabel=oR(o.status,o.rows);return t}function cR(e){return e.length?e[e.length-1].key:""}function uR({policy:e,runId:t,enabled:n,isAdmin:s,refreshKey:o,onAttach:l,onAttachFiles:u,includeArtifacts:d=!0}){const[f,m]=y.useState("session");return a.jsxs(a.Fragment,{children:[s?a.jsxs("div",{className:"code-files-mode",role:"group","aria-label":"Files source",children:[a.jsx("button",{"aria-pressed":f==="session",onClick:()=>m("session"),children:"This conversation"}),a.jsx("button",{"aria-pressed":f==="shared",onClick:()=>m("shared"),children:"Gateway files (admin)"})]}):null,s?a.jsx("div",{hidden:f!=="shared",children:a.jsx(vR,{policy:e,enabled:n&&f==="shared",runId:t,onAttach:l})}):null,a.jsx("div",{hidden:s&&f!=="session",children:a.jsx(CT,{runId:t,enabled:n&&(!s||f==="session"),refreshKey:o,maxAttachmentBytes:e==null?void 0:e.maxAttachmentBytes,onAttachFiles:u})}),d?a.jsxs("section",{className:"code-rail-section","aria-labelledby":"code-artifacts-title",children:[a.jsx("h3",{id:"code-artifacts-title",className:"code-rail-section-title",children:"Generated outputs & attachments"}),a.jsx(kR,{runId:t,enabled:n,refreshKey:o})]}):null]})}function bb(e,t,n){return n?tR(n,s=>O_(s)):vb(e,t)}function dR({records:e,runId:t,view:n}){const s=y.useMemo(()=>bb(e,t,n),[e,t,n]);return s.length?a.jsx(xb,{rows:s}):a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(de,{name:"activity",size:28}),a.jsx("p",{children:"Follow the work as it happens."}),a.jsx("small",{children:"Model steps, tool calls and approvals appear here, one group per step."})]})}function fR(e,t,n){const s=bb(e,t,n),o=s.filter(d=>d.status==="waiting").length,l=s.filter(d=>d.status==="running").length,u=[o?`${o} waiting`:"",l?`${l} running`:""].filter(Boolean);return{count:o+l,hint:u.join(" · ")}}function xb({rows:e}){const t=y.useMemo(()=>lR(e),[e]),n=cR(t),[s,o]=y.useState({});return a.jsx("div",{className:"code-activity-groups",children:t.map(l=>{const u=s[l.key]??l.key===n;return a.jsxs("details",{className:`code-activity-group is-${l.status}`,"data-group":l.title,open:u,onToggle:d=>{const f=d.currentTarget.open;f!==u&&o(m=>({...m,[l.key]:f}))},children:[a.jsxs("summary",{children:[a.jsx(de,{name:"chevronRight",size:14,className:"code-activity-group-chevron"}),a.jsx("strong",{children:l.title}),l.detail?a.jsx("span",{className:"code-activity-group-detail",title:l.detail,children:l.detail}):a.jsx("span",{className:"code-activity-group-detail"}),a.jsx("span",{className:`code-step-dot is-${l.status}`,"aria-hidden":"true"}),a.jsx("small",{children:l.statusLabel})]}),u?a.jsx(hR,{group:l}):null]},l.key)})})}function hR({group:e}){const t=y.useMemo(()=>e.rows.flatMap(o=>o.entries.map(l=>({cursor:l.cursor,record:l.record,runId:l.runId}))),[e]),n=y.useMemo(()=>{const o=e.rows.filter(l=>Array.isArray(l.tools));return o.length?o.flatMap(l=>l.tools):el(t).tools},[e,t]),s=e.rows.filter(o=>o.kind!=="tools");return a.jsxs("div",{className:"code-activity-group-body",children:[s.map(o=>a.jsx(pR,{row:o},o.key)),n.length?a.jsx(im,{tools:n}):null]})}const mR={llm:"sparkle",tools:"terminal",subflow:"agent",event:"info",wait:"history",ask:"chat",message:"send",run:"playCircle",progress:"loader",step:"list"};function pR({row:e}){const t=e.merged,n=t.effect||{};return a.jsxs("details",{className:`code-activity-row code-activity-row--${e.kind}`,children:[a.jsxs("summary",{children:[a.jsx("span",{className:"code-activity-icon","aria-hidden":"true",children:a.jsx(de,{name:mR[e.kind],size:14})}),a.jsxs("span",{className:"code-activity-text",children:[a.jsx("span",{className:"code-activity-title",children:e.title}),e.detail?a.jsx("span",{className:"code-activity-sub",children:e.detail}):null,e.progress?a.jsx("span",{className:"code-activity-progress",children:e.progress}):null]}),a.jsx("span",{className:`code-step-dot is-${e.status}`}),a.jsx("small",{children:e.statusLabel})]}),a.jsxs("div",{className:"code-activity-detail",children:[a.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`:""]}),a.jsx(Co,{value:{input:n.payload,result:t.result,error:t.error,records:e.entries.map(s=>s.record),...e.progressEvents.length?{progress:e.progressEvents}:{}},collapseAfterDepth:2})]})]})}async function gR(e,t,n=2e3){var l;const s=[];let o=0;for(;s.length<n;){if(t!=null&&t.aborted)throw new DOMException("aborted","AbortError");const u=await Ur.get_ledger(e,{after:o,limit:500}),d=Array.isArray(u.items)?u.items:[];for(const f of d){const m=Number(f==null?void 0:f.cursor)||o+s.length+1;s.push({cursor:m,record:(f==null?void 0:f.record)??f,runId:String(((l=f==null?void 0:f.record)==null?void 0:l.run_id)||e)})}if(!d.length||!u.next_after||u.next_after<=o)break;o=u.next_after}return s}function yR({occurrences:e,nowMs:t,loadRecords:n=gR,onOpenRun:s}){var f;const o=y.useMemo(()=>[...e].sort((m,p)=>p.index-m.index),[e]),l=((f=o[0])==null?void 0:f.run_id)||"",[u,d]=y.useState({});return o.length?a.jsx("div",{className:"code-activity-groups","data-scope":"automation",children:o.map(m=>{const p=u[m.run_id]??m.run_id===l,g=m.finished_at||m.fired_at;return a.jsxs("details",{className:`code-activity-group is-${m.status}`,"data-group":`Run #${m.index}`,open:p,onToggle:_=>{const v=_.currentTarget.open;v!==p&&d(C=>({...C,[m.run_id]:v}))},children:[a.jsxs("summary",{children:[a.jsx(de,{name:"chevronRight",size:14,className:"code-activity-group-chevron"}),a.jsxs("strong",{children:["Run #",m.index]}),a.jsx("span",{className:"code-activity-group-detail",children:g?a.jsx("time",{title:Mo(g),children:$o(g,t)}):null}),a.jsx("span",{className:`code-step-dot is-${m.status}`,"aria-hidden":"true"}),a.jsx("small",{children:m.status})]}),p?a.jsx(wR,{occurrence:m,loadRecords:n,onOpenRun:s}):null]},m.run_id)})}):a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(de,{name:"activity",size:28}),a.jsx("p",{children:"No runs yet."}),a.jsx("small",{children:"Each run of this automation appears here as one group."})]})}function wR({occurrence:e,loadRecords:t,onOpenRun:n}){var u;const[s,o]=y.useState({status:"loading"});y.useEffect(()=>{const d=new AbortController;return o({status:"loading"}),t(e.run_id,d.signal).then(f=>!d.signal.aborted&&o({status:"ready",records:f})).catch(f=>!d.signal.aborted&&o({status:"error",message:`Run activity unavailable: ${At(f)}`})),()=>d.abort()},[e.run_id,e.status,t]);const l=y.useMemo(()=>s.status==="ready"?vb(s.records,e.run_id):[],[s,e.run_id]);return a.jsxs("div",{className:"code-activity-group-body",children:[(u=e.failure)!=null&&u.message?a.jsx("p",{className:"code-error-text",role:"alert",children:e.failure.message}):null,s.status==="loading"?a.jsx("p",{className:"code-muted",role:"status",children:"Loading run activity…"}):null,s.status==="error"?a.jsx("p",{className:"code-error-text",role:"alert",children:s.message}):null,s.status==="ready"?l.length?a.jsx(xb,{rows:l}):a.jsx("p",{className:"code-muted",children:"This run recorded no steps."}):null,n?a.jsxs("button",{type:"button",className:"code-subtle-button",onClick:()=>n(e.run_id),children:[a.jsx(de,{name:"chat",size:13})," ",a.jsx("span",{children:"Open as conversation"})]}):null]})}function vR({policy:e,enabled:t,runId:n,onAttach:s}){const[o,l]=y.useState(""),[u,d]=y.useState(""),[f,m]=y.useState([]),[p,g]=y.useState(!1),[_,v]=y.useState(""),[C,x]=y.useState(""),[k,S]=y.useState(0),[$,R]=y.useState("");return y.useEffect(()=>{const N=new AbortController;if(m([]),v(""),x(""),!t||!e)return;g(!0);const E=window.setTimeout(()=>{const j=new URLSearchParams({limit:"100"});o.trim()?j.set("query",o.trim()):u&&j.set("path",u),ot(we(`files/${o.trim()?"search":"list"}?${j}`),{signal:N.signal}).then(I=>{if(I.error)throw new Error(String(I.error));m(Array.isArray(I.items)?I.items:[]),(I.truncated||I.has_more)&&x("Showing the first 100 results. Search to narrow the list.")}).catch(I=>{N.signal.aborted||v(At(I))}).finally(()=>{N.signal.aborted||g(!1)})},o?220:0);return()=>{window.clearTimeout(E),N.abort()}},[t,e,o,u,k,n]),a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"code-pane-intro",children:[a.jsx(de,{name:"terminal",size:17}),a.jsxs("div",{children:[a.jsx("strong",{children:"Gateway files (admin)"}),a.jsx("span",{children:u||"The gateway's files"})]}),a.jsx("button",{className:"code-icon-button","aria-label":"Refresh files",onClick:()=>S(N=>N+1),disabled:!t,children:a.jsx(de,{name:"refresh",size:14})})]}),a.jsx("input",{className:"code-search","aria-label":"Search workspace files",placeholder:"Search files…",value:o,onChange:N=>l(N.target.value),disabled:!t}),u?a.jsx("button",{className:"code-back",onClick:()=>{d(u.split("/").slice(0,-1).join("/")),l("")},children:"← Parent folder"}):null,t?null:a.jsx("p",{className:"code-pane-empty",children:"Connect to browse your workspace."}),p?a.jsx("p",{className:"code-muted",role:"status",children:"Loading files…"}):null,_?a.jsxs("div",{className:"code-inline-error",role:"alert",children:[_,a.jsx("button",{onClick:()=>S(N=>N+1),children:"Retry"})]}):null,C?a.jsx("p",{className:"code-field-help",role:"status",children:C}):null,a.jsx("ul",{className:"code-file-list",children:f.map(N=>{const E=N.kind==="folder"||N.is_dir||N.type==="directory"||N.type==="dir";return a.jsx("li",{children:a.jsxs("button",{title:E?`Show ${N.path}`:`Attach ${N.path} to the conversation`,disabled:!!$,onClick:async()=>{if(E){d(N.path),l("");return}R(N.path),v("");try{await s(N.path),x(`${N.name||N.path} attached.`)}catch(j){v(At(j))}finally{R("")}},children:[a.jsx(de,{name:E?"folder":"paperclip",size:14}),a.jsx("span",{children:N.name||N.path}),$===N.path?a.jsx(de,{name:"loader",size:13}):a.jsx(de,{name:E?"chevronRight":"plus",size:13,className:"code-file-action"})]})},N.path)})}),!p&&!_&&t&&!f.length?a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(de,{name:"terminal",size:28}),a.jsx("p",{children:o?"No matching files.":"No shared files yet."}),a.jsx("small",{children:o?"Try a shorter name or another folder.":"Browse files exposed by your gateway or attach files from your device."})]}):null]})}function _R(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 bR(e){var s;const t=String(e.artifact_id||e.id||""),n=String(e.content_type||e.mime_type||"");return{id:t,name:String(e.filename||((s=e.metadata)==null?void 0:s.filename)||e.name||_R(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 xR(e){return iu(e)?"text":e==="image"||e==="pdf"||e==="audio"?"url":"none"}function kR({runId:e,enabled:t,refreshKey:n}){const[s,o]=y.useState([]),[l,u]=y.useState(""),[d,f]=y.useState(0),[m,p]=y.useState(null),[g,_]=y.useState({status:"loading"}),v=Date.now();y.useEffect(()=>{if(o([]),u(""),p(null),!e||!t)return;const x=new AbortController;return ot(we(`runs/${encodeURIComponent(e)}/artifacts?limit=200`),{signal:x.signal}).then(k=>o((Array.isArray(k.items)?k.items:Array.isArray(k.artifacts)?k.artifacts:[]).map(bR))).catch(k=>{x.signal.aborted||u(At(k))}),()=>x.abort()},[e,t,d,n]),y.useEffect(()=>{if(!m)return;let x=!0,k="";return _({status:"loading"}),Ur.get_run_artifact_blob(e,m.id).then(async({blob:S,content_type:$})=>{const R=xR(al(m.name,$));if(R==="text"){const N=await S.slice(0,du).text();x&&_({status:"ready",text:N,partial:S.size>du,total:S.size,contentType:$})}else R==="url"?(k=URL.createObjectURL(S.type?S:new Blob([S],{type:$})),x&&_({status:"ready",url:k,partial:!1,contentType:$})):x&&_({status:"ready",partial:!1,contentType:$})}).catch(S=>x&&_({status:"error",message:`Preview failed: ${At(S)}`})),()=>{x=!1,k&&URL.revokeObjectURL(k)}},[e,m]);const C=x=>void gA(e,x.id,x.name).catch(k=>u(At(k)));return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"code-rail-toolbar",children:a.jsx("button",{className:"code-icon-button","aria-label":"Refresh outputs",title:"Refresh",onClick:()=>f(x=>x+1),children:a.jsx(de,{name:"refresh",size:14})})}),l?a.jsx("p",{role:"alert",className:"code-error-text",children:l}):null,m?a.jsx(om,{name:m.name,sizeBytes:m.size,modified:m.created,nowMs:v,contentType:g.status==="ready"?g.contentType:m.contentType,status:g.status,...g.status==="error"?{error:g.message}:{},...g.status==="ready"?{text:g.text,url:g.url,...g.partial?{partialNote:h_(g.total)}:{}}:{},onDownload:()=>C(m),onClose:()=>p(null)}):s.length?a.jsx("ul",{className:"code-file-rows",children:s.map(x=>a.jsxs("li",{className:"code-file-row",children:[a.jsxs("button",{className:"code-file-row-name",title:`Preview ${x.name} · ${x.id}`,onClick:()=>p(x),children:[a.jsx(de,{name:"file",size:14}),a.jsx("span",{children:x.name})]}),a.jsxs("span",{className:"code-file-row-meta",children:[x.size!==void 0?a.jsx("span",{children:ml(x.size)}):null,x.created?a.jsx("time",{title:Mo(x.created),children:$o(x.created,v)}):null]}),a.jsx("button",{className:"code-icon-button","aria-label":`Download ${x.name}`,title:"Download",onClick:()=>C(x),children:a.jsx(de,{name:"download",size:14})})]},x.id))}):l?null:a.jsx("p",{className:"code-muted",children:"Generated files and attachments appear here."})]})}const SR=[{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"}],jR="abstractcode.rail.width.v1";function NR(e){return a.jsx(aN,{className:"code-rail",ariaLabel:"Workspace panels",idBase:"code-rail",storageKey:jR,active:e.panel,onActiveChange:t=>e.onPanel(t),panels:[...SR.map(t=>({id:t.id,label:t.label,icon:t.icon,defaultWidth:420,minWidth:320,maxWidth:900,content:e.content[t.id],...t.id==="activity"?{badge:e.activityBadge,hint:e.activityHint}:{}})),{...e.docs,minWidth:320,maxWidth:900}]})}const _a=e=>e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},Lr=e=>typeof e=="string"?e:typeof e=="number"?String(e):"",CR=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!==""):[];function Fi(e,t=[]){const n=_a(e),s=_a(n._runtime),o=_a(n._limits),l=Lr(n.provider)||Lr(s.provider),u=Lr(n.model)||Lr(s.model);return{...or,provider:l&&u?l:"",model:l&&u?u:"",reasoning:Lr(s.thinking),...s.speculation!==void 0?{speculation:s.speculation}:{},maxIterations:Lr(o.max_iterations),maxTokens:Lr(o.max_tokens),system:Lr(s.system_prompt_extra),workspace:n.workspace&&typeof n.workspace=="object"&&Array.isArray(n.workspace.folders)?n.workspace:null,toolLayer:cb(n,t),skills:CR(n.skills),workflow:or.workflow,streamReplies:"gateway_default"}}function Ms(e,t,n){n==null||n===""||Array.isArray(n)&&!n.length?delete e[t]:e[t]=n}function iw(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function ER(e,t,n=[]){let s=_a(e);const o=_a(s._runtime),l=_a(s._limits),u=!!(t.provider&&t.model);Ms(s,"provider",u?t.provider:""),Ms(s,"model",u?t.model:""),Ms(o,"provider",u?t.provider:""),Ms(o,"model",u?t.model:""),Ms(o,"thinking",t.reasoning),Ms(o,"speculation",t.speculation),Ms(o,"system_prompt_extra",t.system.trim()),Ms(l,"max_iterations",iw(t.maxIterations)),Ms(l,"max_tokens",iw(t.maxTokens)),Object.keys(o).length?s._runtime=o:delete s._runtime,Object.keys(l).length?s._limits=l:delete s._limits,delete s.workspace_access_mode,t.workspace===null?(s.workspace&&typeof s.workspace=="object"&&delete s.workspace_allowed_paths,delete s.workspace):(s.workspace={posture:t.workspace.posture,default_mode:t.workspace.default_mode,folders:t.workspace.folders.map(m=>({path:m.path,mode:m.mode}))},delete s.workspace_allowed_paths),Ms(s,"skills",t.skills);const d=cb(e,n),f=Po(n,{app:t.toolLayer}).app;return Ro(d)!==Ro(f)&&(s=dT(s,t.toolLayer,n)),s}function AR(e,t,n=[]){const s=_a(e.target.input_data),o=ER(s,t,n);return Ro(s)===Ro(o)?null:{target:{bundle_ref:e.target.bundle_ref,flow_id:e.target.flow_id,input_data:o}}}function Ro(e){if(Array.isArray(e))return`[${e.map(Ro).join(",")}]`;if(e&&typeof e=="object"){const t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ro(t[n])}`).join(",")}}`}return JSON.stringify(e)}const $R=700;function TR(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 kb(e){if(dl(e)){if(e.code==="revision_conflict")return"Not saved: the automation changed elsewhere. The latest revision is shown; make the change again.";const t=Lo(e);return`Not saved: ${t.title}${t.detail?` ${t.detail}`:""}`}return`Not saved: ${String((e==null?void 0:e.message)||e)}`}function RR(e,t,n=[]){const s=y.useRef(n);s.current=n;const o=(e==null?void 0:e.definition)??null,l=(e==null?void 0:e.summary.automation_id)??"",u=(o==null?void 0:o.revision)??0,[d,f]=y.useState(()=>Fi(o==null?void 0:o.target.input_data,s.current)),[m,p]=y.useState({status:"idle"}),g=y.useRef(null),_=y.useRef(null),v=y.useRef(o);v.current=o;const C=y.useRef(l);C.current=l;const x=y.useRef(t);x.current=t;const k=y.useRef({id:l,def:o}),S=async()=>{var j;_.current&&window.clearTimeout(_.current),_.current=null;const $=g.current;if(g.current=null,!$)return;const R=$.automationId===C.current?v.current:k.current.id===$.automationId?k.current.def:null;if(!R)return;const N=AR(R,$.prefs,s.current);if(!N)return;const E=()=>$.automationId===C.current;E()&&p({status:"saving"});try{await x.current($.automationId,N,R.revision),E()&&p({status:"saved",revision:R.revision+1})}catch(I){if(!E())return;p({status:"error",message:kb(I)}),f(Fi((j=v.current)==null?void 0:j.target.input_data,s.current))}};return y.useEffect(()=>{g.current&&g.current.automationId!==l&&S(),k.current={id:l,def:o},p({status:"idle"}),f(Fi(o==null?void 0:o.target.input_data,s.current))},[l]),y.useEffect(()=>{k.current={id:l,def:o},g.current||f(Fi(o==null?void 0:o.target.input_data,s.current))},[u]),y.useEffect(()=>{g.current||f(Fi(o==null?void 0:o.target.input_data,s.current))},[n]),y.useEffect(()=>()=>{_.current&&window.clearTimeout(_.current)},[]),!e||!o?null:{automationId:l,revision:u,draft:d,save:m,setSave:p,onChange:$=>{f($),g.current={prefs:$,automationId:l},_.current&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>void S(),$R)}}}function IR(e){return a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:"code-settings-binding",children:[a.jsx("span",{children:"Automation"})," ",a.jsx("strong",{title:e.summary.title,children:e.summary.title}),a.jsxs("span",{className:"code-settings-revision","data-testid":"automation-revision",children:["Revision ",e.settings.revision]})]}),a.jsx("p",{className:`code-settings-save is-${e.settings.save.status}`,role:"status","aria-live":"polite",children:TR(e.settings.save)||"Changes are saved as a new revision and apply from the next run."})]})}function LR(e){const t=e.definition.revision,[n,s]=y.useState([]),o=e.settings.setSave;return a.jsx("div",{className:"code-automation-definition","data-revision":t,children:a.jsx(Pv,{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,previewSchedule:e.previewSchedule,onSubmit:l=>{const u=cv(e.summary,l,e.definition);if(u===null){s(["Nothing changed."]);return}if("errors"in u){s(u.errors);return}s([]),o({status:"saving"}),(async()=>{const f=u;return l.target&&f.target&&e.prepareTarget?{...f,target:await e.prepareTarget(f.target)}:f})().then(f=>e.onRevise(f,t)).then(()=>o({status:"saved",revision:t+1})).catch(f=>{dl(f)?o({status:"error",message:kb(f)}):(o({status:"idle"}),s([String((f==null?void 0:f.message)||f)]))})}},`${e.summary.automation_id}:${t}`)})}const lw="—";function wo(e){return typeof e=="string"&&e?e:void 0}function MR(e){return e.endsWith("+00:00")||e.endsWith("Z")}function Yf(e){if(!e||typeof e!="object")return e;const t=e,n={...e},s=wo(t.next_run_at)??wo(t.next_fire_at);let o=wo(t.next_run_local),l=wo(t.time_zone)??"";return!o&&!l&&s&&MR(s)&&(o=s,l="UTC"),s?n.next_run_at=s:delete n.next_run_at,o?n.next_run_local=o:delete n.next_run_local,n.time_zone=l,n.schedule_rule_text=wo(t.schedule_rule_text)??lw,n.schedule_text=wo(t.schedule_text)??lw,n}function OR(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(Yf)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:Yf(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:Yf(n.summary)}:n}}}const PR=3e4,Uc=50;function DR(){return KS({fetch:(e,t)=>fetch(e,{...t,credentials:"same-origin"}),baseUrl:"",headers:$u})}function FR(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 zR(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 BR(e,t){return e===Xt?{flow_id:"@default",interface:ln}:!(t!=null&&t.bundleId)||!t.flowId?null:{bundle_ref:t.bundleVersion?`${t.bundleId}@${t.bundleVersion}`:t.bundleId,flow_id:t.flowId}}function WR(e){return e.filter(t=>t.status!=="archived")}function UR(e){const t=e==null?void 0:e.archived_automations;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function VR(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 GR(e,t,n,s){return{command_id:e,run_id:t,type:"resume",payload:{wait_key:n,payload:s},client_id:"abstractcode-web"}}function Sb(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 us(e){return dl(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function Qf(e,t){const n=new Map;for(const s of e)n.set(s.run_id,s);for(const s of t)n.set(s.run_id,s);return Array.from(n.values()).sort((s,o)=>o.index-s.index)}const HR={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 KR(e){return async(t,n,s)=>{await ot(we("commands"),{method:"POST",body:JSON.stringify(GR(e(),t,n,s))})}}class JR{constructor(t,n,s=[1500,4e3]){zt(this,"state",{...HR});zt(this,"listeners",new Set);zt(this,"listSeq",0);zt(this,"detailSeq",0);zt(this,"sourcesLoaded",!1);zt(this,"client");zt(this,"previewSchedule",t=>this.client.previewSchedule(t));this.answerWaitVia=n,this.followupsMs=s,this.client=OR(t)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}set(t){this.state={...this.state,...t};for(const n of this.listeners)n()}async listAll(t){return(await this.listPages(t)).items}async listPages(t){const n=[];let s,o=0;for(let l=0;l<200;l+=1){const u=await this.client.listAutomations({...t?{status:t}:{},...s?{cursor:s}:{},limit:Uc});if(s||(o=UR(u)),n.push(...u.items),!u.next_cursor)return{items:n,archivedCount:o};s=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:us(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:s}=await this.listPages();if(this.loadEmailStatus(),t!==this.listSeq)return;const o=this.state.detail,l=o?n.find(u=>u.automation_id===o.automationId):void 0;this.set({items:n,archivedCount:s,loaded:!0,loading:!1,listError:null,...o&&l?{detail:{...o,summary:l}}:{}}),this.state.archived!==null&&this.loadArchived(),o&&await this.reloadDetail(o.automationId)}catch(n){if(t!==this.listSeq)return;this.set({loading:!1,loaded:!0,listError:us(n)})}}async select(t){var o;const n=t.trim(),s=++this.detailSeq;if(!n){this.set({selectedId:"",detail:null});return}this.set({selectedId:n,notice:"",error:null,...((o=this.state.detail)==null?void 0:o.automationId)!==n?{detail:null}:{}});try{const[l,u]=await Promise.all([this.client.getAutomation(n),this.client.listOccurrences(n,{limit:Uc})]);if(s!==this.detailSeq)return;const d=this.state.items.find(f=>f.automation_id===n);if(this.set({detail:{automationId:n,summary:d??l.summary,definition:l.definition,occurrences:Qf([],u.items),nextCursor:u.next_cursor}}),!this.sourcesLoaded){const f=await this.client.listTriggerSources();this.sourcesLoaded=!0,this.set({triggerSources:f.items})}}catch(l){if(s!==this.detailSeq)return;this.set({error:us(l)})}}async reloadDetail(t){const[n,s]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Uc})]),o=this.state.detail;if(!o||o.automationId!==t)return;const l=this.state.items.find(u=>u.automation_id===t);this.set({detail:{...o,summary:l??n.summary,definition:n.definition,occurrences:Qf(o.occurrences,s.items),nextCursor:o.occurrences.length>s.items.length?o.nextCursor:s.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:Uc}),s=this.state.detail;if(!s||s.automationId!==t.automationId)return;this.set({detail:{...s,occurrences:Qf(s.occurrences,n.items),nextCursor:n.next_cursor}})}catch(n){this.set({error:us(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 us(n)}finally{this.set({busy:!1})}}command(t,n,s){return this.busyCall(()=>this.client.sendAutomationCommand(t,{type:n,...s?{command_id:s}:{}}))}async toggleActive(t,n){this.set({rowError:null});try{return await this.command(t.automation_id,iv(t),n)}catch(s){const o=us(s);throw this.set({rowError:{automationId:t.automation_id,error:o}}),o}}async unarchive(t,n){this.set({rowError:null});try{return await this.command(t,It.unarchive,n)}catch(s){const o=us(s);throw this.set({rowError:{automationId:t,error:o}}),o}}revise(t,n,s,o){return this.busyCall(()=>this.client.reviseAutomation(t,{changes:n,...s!==null?{expected_revision:s}:{},...o?{command_id:o}:{}}))}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 s of this.followupsMs)setTimeout(()=>void this.refresh(),s);return n}catch(n){throw us(n)}finally{this.set({busy:!1})}}async discuss(t,n,s,o){this.set({busy:!0});try{const l=await this.client.discuss(t,{occurrence_index:n,prompt:s,...o?{request_id:o}:{}});return this.set({notice:Sb(n,l)}),l}catch(l){throw us(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(s){throw us(s)}}answerWait(t,n,s){return this.busyCall(async()=>{var l;const o=(((l=this.state.detail)==null?void 0:l.occurrences)||[]).flatMap(u=>u.waits).find(u=>u.run_id===t&&u.wait_key===n);if(!o)throw new Error(`No loaded wait ${n} on run ${t}; reload the automation.`);await this.answerWaitVia(t,n,VR(o.kind,s))})}rowControls(t){return Ao(t,[],this.state.busy)}reportError(t){this.set({error:us(t)})}clearNotice(){this.set({notice:"",error:null})}}const cw={[It.pause]:"Automation paused.",[It.resume]:"Automation active.",[It.run_now]:"Run requested.",[It.stop_current]:"Stop requested.",[It.archive]:"Automation archived."},qR=[{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 uw(e){const t=e&&typeof e=="object"&&"code"in e?e:null;if(t){const n=Lo(t);return{tone:"error",text:n.title,detail:n.detail}}return{tone:"error",text:e instanceof Error?e.message:String(e)}}function YR(e){const t=e.summary,n=Ao(t,e.occurrences,e.busy),s=e.nowMs??Date.now(),o=Dv(t,s),[l,u]=y.useState(!1),[d,f]=y.useState(null),m=y.useRef(null);y.useEffect(()=>{u(!1),f(null)},[t.automation_id]),y.useEffect(()=>{var x;l&&((x=m.current)==null||x.focus())},[l]);const p=(x,k,S)=>{f({tone:"busy",text:x}),k().then(()=>f({tone:"ok",text:S}),$=>f(uw($)))},g=(x,k)=>p(k,()=>e.onCommand(x),cw[x]??"Done."),_=x=>{x==="run_now"?g(It.run_now,"Starting a run…"):x==="stop_current"?g(It.stop_current,"Stopping…"):x==="revise"?e.onEdit():x==="archive"&&u(!0)},v=t.workspace_root||"",C=e.triggerSources.length?Mv(t,e.triggerSources):null;return a.jsxs("header",{className:"code-auto-header","data-automation-id":t.automation_id,"aria-busy":e.busy||(d==null?void 0:d.tone)==="busy",children:[a.jsx("h2",{className:"code-auto-header__title",tabIndex:-1,children:t.title}),a.jsxs("div",{className:"code-auto-header__state",children:[a.jsx(ob,{variant:"inline",summary:t,busy:e.busy,onToggle:()=>p(t.status==="active"?"Pausing…":"Activating…",e.onToggleActive,cw[t.status==="active"?It.pause:It.resume])}),rb(t)?a.jsx(ab,{}):null,a.jsx("span",{className:"code-auto-header__timing","data-field":"timing",children:o.line})]}),a.jsx(tb,{summary:t,nowMs:s,className:"code-auto-header__notif"}),C?a.jsxs("p",{className:"code-auto-header__warn",role:"note","data-field":"trigger-problem",children:[a.jsx(de,{name:"warning",size:13})," ",a.jsx("span",{children:C})]}):null,v?a.jsxs("div",{className:"code-auto-header__workspace","data-field":"workspace",children:[a.jsx("span",{className:"code-auto-header__label",children:"Workspace"}),a.jsx("span",{className:"code-auto-header__folder",title:v,children:FA(v)}),a.jsx("button",{type:"button",className:"code-icon-button","data-action":"open-folder","aria-label":"Open folder",title:"Open folder",onClick:e.onOpenFolder,children:a.jsx(de,{name:"folder",size:15})}),a.jsx("button",{type:"button",className:"code-icon-button","data-action":"copy-path","aria-label":"Copy path",title:"Copy path",onClick:()=>void e.onCopyPath(v).then(x=>f(x?{tone:"ok",text:"Path copied."}:{tone:"error",text:"The browser refused the clipboard."}),x=>f(uw(x))),children:a.jsx(de,{name:"copy",size:15})})]}):null,e.workspaces?a.jsxs("div",{className:"code-auto-header__workspaces-row","data-section":"workspaces",children:[e.workspaces,e.onEditWorkspaces?a.jsx("button",{type:"button",className:"code-icon-button","data-action":"edit-workspaces","aria-label":"Change workspaces",title:"Change workspaces",onClick:e.onEditWorkspaces,children:a.jsx(de,{name:"edit",size:15})}):null]}):null,l?a.jsxs("div",{className:"code-auto-header__confirm",role:"group","aria-label":"Confirm archive",children:[a.jsxs("p",{children:["Archive “",t.title,"”? It will not run again; its history stays readable."]}),a.jsxs("div",{className:"code-auto-header__actions",children:[a.jsxs("button",{ref:m,type:"button",className:"code-subtle-button code-danger-button","data-action":"archive-confirm",disabled:!n.archive.enabled,onClick:()=>{u(!1),g(It.archive,"Archiving…")},children:[a.jsx(de,{name:"archive",size:14})," ",a.jsx("span",{children:"Archive"})]}),a.jsx("button",{type:"button",className:"code-subtle-button","data-action":"archive-cancel",onClick:()=>u(!1),children:a.jsx("span",{children:"Keep it"})})]})]}):a.jsx("div",{className:"code-auto-header__actions",role:"toolbar","aria-label":"Automation controls",children:qR.map(x=>{const k=n[x.id],S=rl(x.id,t);return a.jsxs("button",{type:"button",className:`code-subtle-button${x.id==="archive"?" code-danger-button":""}`,"data-action":x.action,disabled:!k.enabled,title:k.enabled?S:`${k.reason??"Not available now."}
96
- ${S}`,onClick:()=>_(x.id),children:[a.jsx(de,{name:x.icon,size:14})," ",a.jsx("span",{children:x.label})]},x.id)})}),d?a.jsxs("p",{className:`code-auto-header__result is-${d.tone}`,role:d.tone==="error"?"alert":"status","data-field":"result",children:[a.jsx(de,{name:d.tone==="busy"?"loader":d.tone==="ok"?"check":"error",size:13}),a.jsxs("span",{children:[d.text,d.detail?` ${d.detail}`:""]})]}):null]})}const jb="abstractcode.automation.panels",zi={occurrences:!0,folder:!0};function QR(e){try{const t=e==null?void 0:e.getItem(jb);if(!t)return{...zi};const n=JSON.parse(t);if(!n||typeof n!="object")return{...zi};const s=n;return{occurrences:typeof s.occurrences=="boolean"?s.occurrences:zi.occurrences,folder:typeof s.folder=="boolean"?s.folder:zi.folder}}catch{return{...zi}}}function XR(e,t){try{t==null||t.setItem(jb,JSON.stringify(e))}catch{}}function ZR(e,t){return{...e,[t]:!e[t]}}function dw(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function eI(){const[e,t]=y.useState(()=>QR(dw())),n=y.useCallback(s=>{t(o=>{const l=ZR(o,s);return XR(l,dw()),l})},[]);return[e,n]}const wm=e=>({toggle:`code-detail-${e}-toggle`,region:`code-detail-${e}`});function Nb(e){const t=wm(e.panel);return a.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:[a.jsx(de,{name:"chevronDown",size:13}),a.jsx("span",{className:"code-detail-toggle__label",children:e.label}),typeof e.count=="number"?a.jsx("span",{className:"code-detail-toggle__count",children:e.count}):null]})}const tI=".af-auto__timeline",nI=".af-auto__more";function sI(e,t,n){const s=(e==null?void 0:e.querySelector(tI))??null;if(!s||!s.parentNode)return t.parentNode&&t.remove(),!1;s.id!==n&&(s.id=n);const o=(e==null?void 0:e.querySelector(nI))??null,l=o&&o.parentNode===s.parentNode?o:s;return(t.parentNode!==l.parentNode||t.nextSibling!==l)&&l.parentNode.insertBefore(t,l),!0}function rI(e,t){const n=y.useMemo(()=>{if(typeof document>"u")return null;const l=document.createElement("div");return l.className="code-detail-head code-detail-head--occurrences",l},[]),[s,o]=y.useState(!1);return y.useLayoutEffect(()=>{const l=e.current;if(!n||!l||!t){n==null||n.remove(),o(!1);return}const u=wm("occurrences").region,d=()=>o(sI(l,n,u));d();const f=new MutationObserver(d);return f.observe(l,{childList:!0,subtree:!0}),()=>{f.disconnect(),n.remove()}},[e,n,t]),s?n:null}function aI(e){let t=5381;for(let s=0;s<e.length;s++)t=t*33^e.charCodeAt(s);return(t>>>0).toString(16).padStart(8,"0").repeat(8).slice(0,32)}async function oI(e){var t;try{const n=globalThis,s=(t=n==null?void 0:n.crypto)==null?void 0:t.subtle;if(!s||typeof s.digest!="function")throw new Error("subtle crypto unavailable");const o=new TextEncoder().encode(e),l=await s.digest("SHA-256",o),u=new Uint8Array(l);let d="";for(const f of u)d+=f.toString(16).padStart(2,"0");return d}catch{return aI(e)}}const fw=/^[a-zA-Z0-9_-]+$/;async function iI(e){const t=String(e||"").trim();if(!t)throw new Error("session_memory_owner_run_id: session_id is required");if(fw.test(t)){const s=`session_memory_${t}`;if(fw.test(s))return s}return`session_memory_sha_${(await oI(t)).slice(0,32)}`}function Cb(){return ot(we("voice/defaults"))}function lI(e,t){const n=new URLSearchParams({compact:"true"});return e&&n.set("provider",e),t&&n.set("model",t),ot(we(`voice/voices?${n.toString()}`))}function cI(e){const t={description:e.description};return e.name&&(t.name=e.name),e.language&&(t.language=e.language),ot(we("voice/design"),{method:"POST",body:JSON.stringify(t)})}function uI(e,t){const n=new FormData;return n.set("file",e,e.name||"recording.wav"),t.name&&n.set("name",t.name),t.language&&n.set("language",t.language),t.reference_text&&n.set("reference_text",t.reference_text),ot(we("voice/clones"),{method:"POST",body:n})}const dI={design:cI,clone:uI};function fI(e){return{...dI,list:()=>ot(we(Zx.clones)),rename:(t,n)=>ot(we(oh(t)),{method:"PATCH",body:JSON.stringify(n)}),remove:t=>ot(we(oh(t)),{method:"DELETE"}),...e?{share:t=>ot(we(ek(t)),{method:"POST"})}:{}}}const Lu={capture_mode:"hold",auto_send:!0};function hI({value:e,onChange:t,defaults:n,connected:s,isAdmin:o=!1,levelSource:l}){return a.jsx(r1,{value:e,onChange:t,fetchCatalog:lI,fetchDefaults:Cb,defaults:n.value??void 0,overrideOwner:"this app",nested:!0,voiceLibrary:fI(o),rows:{capture:!0},captureDefaults:Lu,levelSource:l??null,unavailableReason:s?null:"Connect to a gateway to configure voice."})}async function mI(e,t){return e||iI(t)}const hw=18e4;function Eb({runId:e,sessionId:t,capability:n,scope:s,preferences:o,onTranscript:l,onError:u}){var g,_;const d=y.useRef(!0),f=y.useRef(s);f.current=s,y.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=()=>{if(!d.current||f.current!==s)throw new Error("Voice session changed.")},p=$S({...qN({...Lu,...o}),tts_stream:((g=n.tts)==null?void 0:g.available)===!0&&e?async function*(v,C){m(),yield*kS({path:we(`runs/${encodeURIComponent(e)}/voice/tts/stream`),headers:$u(),signal:C,body:{text:v,request_id:va(),...QN(o)}})}:void 0,transcribe:((_=n.stt)==null?void 0:_.available)===!0&&(e||t)&&l?async(v,C)=>{var j;m();const x=Number(((j=n.stt)==null?void 0:j.max_upload_bytes)||0);if(x>0&&v.size>x)throw new Error("Recording exceeds the gateway's upload limit. Try a shorter recording.");const k=C.includes("mp4")?"m4a":C.includes("ogg")?"ogg":C.includes("wav")?"wav":"webm",S=new File([v],`recording.${k}`,{type:C||"audio/webm"}),$=await Ur.attachments_upload(t,S);m();let R;const N=await mI(e,t);m();const E=await Promise.race([Ur.audio_transcribe(N,{audio_artifact:$,request_id:va(),...XN(o)}),new Promise((I,L)=>{R=setTimeout(()=>L(new Error(`the gateway did not answer within ${hw/1e3} s`)),hw)})]).finally(()=>clearTimeout(R));return m(),{text:String(E.text||""),provider:E.provider??null,model:E.model??null}}:void 0,on_transcript:v=>{d.current&&f.current===s&&(l==null||l(v))},on_error:v=>{d.current&&f.current===s&&u(v)}});return y.useEffect(()=>{var v;return p.stop_tts(),(v=p.cancel_voice_ptt_recording)==null||v.call(p),()=>{var C;p.stop_tts(),(C=p.cancel_voice_ptt_recording)==null||C.call(p)}},[s,p.stop_tts,p.cancel_voice_ptt_recording]),p}function mw(e,t){const n=e.trimEnd();return n?`${n}
97
- ${t}`:t}function pI({voice:e,capability:t,preferences:n,route:s=""}){var o,l,u;return!((o=t.tts)!=null&&o.available)&&!((l=t.stt)!=null&&l.available)?null:a.jsxs(a.Fragment,{children:[(u=t.stt)!=null&&u.available?a.jsx(l1,{voice:e,mode:Eo(n.capture_mode??Lu.capture_mode),routeText:s,unavailableReason:bT()?null:_T,className:"code-voice-mic"}):null,e.tts_playback.status!=="idle"?a.jsx("button",{className:"code-icon-button","aria-label":"Stop spoken reply",onClick:e.stop_tts,children:a.jsx(de,{name:"x",size:14})}):null]})}const gI=ct.title;function pw(e){return`${gI}: ${e}`}function yI(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function wI(e){var n,s;const t=(s=(n=e==null?void 0:e.target)==null?void 0:n.input_data)==null?void 0:s.workspace;return yI(t)?t:null}function vI(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(s=>({path:s.path,mode:s.mode}))},n)}const _I=3e4,gw=new WeakMap;function bI(e,t,n=Date.now()){let s=gw.get(e);s||gw.set(e,s=new Map);const o=JSON.stringify(t),l=s.get(o);if(l&&n-l.at<_I)return l.answer;const u=bh(e)(t).then(d=>d.summary);return u.catch(()=>s==null?void 0:s.delete(o)),s.set(o,{at:n,answer:u}),u}function xI(e){const[t,n]=y.useState(null),s=JSON.stringify(e.value);return y.useEffect(()=>{if(!e.connected){n(null);return}let o=!0;return bI(e.request,e.value).then(l=>o&&n(pw(l))).catch(l=>o&&n(pw(tm(l)))),()=>{o=!1}},[e.request,e.connected,s,e.refreshKey]),t?a.jsx("span",{className:"code-auto-header__workspaces","data-field":"workspaces",title:t,children:t}):null}function kI(e,t,n={following:!1,epoch:0}){const s=y.useMemo(()=>new JR(DR(),KR(va)),[e]),o=y.useSyncExternalStore(d=>s.subscribe(d),()=>s.state),[l,u]=y.useState(()=>typeof document>"u"||document.visibilityState!=="hidden");return y.useEffect(()=>{const d=()=>u(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",d),()=>document.removeEventListener("visibilitychange",d)},[]),y.useEffect(()=>{if(!e||!t||!l||n.following)return;s.refresh();const d=window.setInterval(()=>void s.refresh(),PR);return()=>window.clearInterval(d)},[s,e,t,l,n.following]),y.useEffect(()=>{if(!e||!t||!n.following)return;const d=window.setTimeout(()=>void s.refresh(),n.epoch?500:0);return()=>window.clearTimeout(d)},[s,e,t,n.following,n.epoch]),{ctl:s,state:o}}function SI(e,t){const n=[];return e&&n.push(`${e} waiting for you`),t&&n.push(`${t} new`),n.join(" · ")}function Oh({error:e}){if(!e)return null;const t=Lo(e);return a.jsxs("p",{className:"code-inline-error",role:"alert","data-code":e.code,children:[a.jsx("strong",{children:t.title})," ",t.detail]})}function jI(e){const t=e.open??!0,n=fm("automations"),s=e.state,o=WR(s.items),l=s.archived??[],u=e.attention,d=u?u.needsYou+u.newResults:s.items.reduce((m,p)=>m+p.attention.pending_waits+p.attention.unseen_count,0),f=u?SI(u.needsYou,u.newResults):`${d} waiting`;return a.jsxs("section",{className:"code-panel code-automations","aria-label":"Automations","data-open":t?"true":"false",children:[a.jsx(Y_,{panel:"automations",open:t,onToggle:()=>{var m;return(m=e.onToggle)==null?void 0:m.call(e)},label:a.jsxs(a.Fragment,{children:["Automations",d?a.jsx("span",{className:"code-auto-badge","data-field":"attention-total",title:f,"aria-label":f,children:d}):null]}),actions:a.jsxs("span",{className:"code-auto-actions",children:[a.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:a.jsx(de,{name:"plus",size:13})}),a.jsx("button",{className:"code-icon-button","aria-label":"Refresh automations",disabled:!e.available.available||s.loading,onClick:e.onRefresh,children:a.jsx(de,{name:"refresh",size:13})})]})}),a.jsxs("div",{className:"code-auto-rows",id:n.region,role:"region","aria-labelledby":n.toggle,hidden:!t,children:[!e.discovering&&!e.available.available?a.jsx("p",{className:"code-history-empty",role:"note","data-unavailable":"true",children:e.available.reason}):null,a.jsx(Oh,{error:s.listError}),!s.loaded&&(e.discovering||e.available.available&&s.loading)?a.jsx(To,{children:"Loading automations…"}):null,e.available.available&&s.loaded&&!s.listError&&!s.items.length?a.jsx("p",{className:"code-history-empty",children:"No automations yet. + lets you choose a workflow and schedule."}):null,o.map(m=>{var p;return a.jsxs(yt.Fragment,{children:[a.jsx(o$,{summary:m,selected:e.selectedId===m.automation_id,busy:s.busy,nowMs:e.nowMs??Date.now(),onSelect:()=>e.onSelect(m.automation_id),onToggleActive:()=>{var g;return(g=e.onToggleActive)==null?void 0:g.call(e,m)}}),((p=s.rowError)==null?void 0:p.automationId)===m.automation_id?a.jsx(Oh,{error:s.rowError.error}):null]},m.automation_id)}),a.jsxs(X_,{list:"automations",count:s.archivedCount,open:e.archivedOpen===!0,onToggle:()=>{var m;return(m=e.onToggleArchived)==null?void 0:m.call(e)},children:[s.archived===null?a.jsx("li",{children:a.jsx(To,{children:"Loading archived automations…"})}):null,l.map(m=>{var p;return a.jsx(Z_,{id:m.automation_id,title:m.title,busy:s.busy,error:((p=s.rowError)==null?void 0:p.automationId)===m.automation_id?Lo(s.rowError.error).title:void 0,onOpen:()=>e.onSelect(m.automation_id),onUnarchive:()=>{var g;return(g=e.onUnarchive)==null?void 0:g.call(e,m)}},m.automation_id)})]})]})]})}function NI(e,t){const n=e.state.detail;if(!n)return null;const s=n.automationId;return{summary:n.summary,...n.definition?{definition:n.definition}:{},occurrences:n.occurrences,triggerSources:e.state.triggerSources,busy:e.state.busy,previewSchedule:e.previewSchedule,...e.state.error?{error:e.state.error}:{},onRevise:(o,l,u)=>e.revise(s,o,l,u==null?void 0:u.command_id),onCommand:(o,l,u)=>e.command(s,o,u==null?void 0:u.command_id),onDiscuss:async(o,l,u)=>{const d=await e.discuss(s,o,l,u==null?void 0:u.request_id);return t.openConversation(d.session_id,d.run_id,Sb(o,d)),d},onSeen:o=>e.seen(s,o),onLoadMore:()=>void e.loadMore(),onOpenRun:o=>t.openRun(o),onOpenWorkspace:o=>t.openWorkspace(o),onAnswerWait:(o,l,u)=>e.answerWait(o,l,u),emailStatus:e.state.emailStatus,...t.openMyEmail?{onOpenMyEmail:()=>{var o;return(o=t.openMyEmail)==null?void 0:o.call(t)}}:{}}}function CI(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 yw(e,t,n){if(t===e)return"Automation folder";const s=n.find(o=>o.run_id===t);return s?`Run #${s.index} folder`:"Run folder"}function EI(e){const t=e.panels.folder,n=wm("folder");return a.jsxs("div",{className:"code-auto-folder-section","data-open":t?"true":"false","data-folder":e.own?"automation":"run",children:[a.jsx("div",{className:"code-detail-head",children:a.jsx(Nb,{panel:"folder",label:e.title,open:t,onToggle:e.onToggle})}),a.jsx("div",{className:"code-detail-region",id:n.region,hidden:!t,children:e.children})]})}function AI(e){const t=e.ctl.state,n=t.detail,[s,o]=y.useState({automationId:"",runId:""}),l=(n==null?void 0:n.automationId)??"",[u,d]=y.useState(""),f=Eb({scope:l,runId:e.enabled?l:"",sessionId:l,capability:e.voiceCapability||{},preferences:e.voicePreferences||{},onError:d});y.useEffect(()=>d(""),[l]);const m=s.automationId===l&&s.runId?s.runId:l,p=NI(e.ctl,{...e.host,openWorkspace:x=>o({automationId:l,runId:x})}),[g,_]=eI(),v=y.useRef(null),C=rI(v,!!(n&&n.occurrences.length));return a.jsxs("main",{className:"code-conversation code-automation-main",id:"code-conversation",tabIndex:-1,"aria-label":"Automation",children:[a.jsxs("div",{className:"code-auto-main-head",children:[a.jsxs("button",{className:"code-subtle-button",onClick:e.onClose,children:[a.jsx(de,{name:"chat",size:14})," ",a.jsx("span",{children:"Back to the conversation"})]}),f.tts_playback.status!=="idle"?a.jsx("button",{type:"button",className:"code-subtle-button",onClick:f.stop_tts,children:"Stop spoken reply"}):null,t.notice?a.jsx("p",{className:"code-field-help",role:"status",children:t.notice}):null]}),n?a.jsxs("div",{className:"code-auto-main-body",ref:v,"data-occurrences":g.occurrences?"open":"closed",children:[u?a.jsx("p",{className:"code-inline-error",role:"alert",children:u}):null,a.jsx(YR,{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?a.jsx(xI,{request:Tu,connected:e.enabled,value:wI(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:()=>{o({automationId:l,runId:""}),g.folder||_("folder"),window.requestAnimationFrame(()=>{var x,k;return(k=(x=v.current)==null?void 0:x.querySelector(".code-auto-folder-section"))==null?void 0:k.scrollIntoView({block:"nearest"})})},onCopyPath:gm}),p?a.jsx(uA,{...p,hideHeader:!0,prepareTarget:e.prepareTarget,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,fetchGateway:ol,messageProps:{...f.tts_supported?{onSpeakToggle:x=>{f.toggle_tts(String(x.id||x.content),x.content)}}:{},getSpeakState:x=>f.tts_playback.key===String(x.id||x.content)?f.tts_playback.status:"idle"}}):null,C?il.createPortal(a.jsx(Nb,{panel:"occurrences",label:"Occurrences",count:n.summary.occurrence_count,open:g.occurrences,onToggle:()=>_("occurrences")}),C):null,e.enabled?a.jsx(EI,{panels:g,onToggle:()=>_("folder"),title:yw(n.automationId,m,n.occurrences),own:m===n.automationId,children:a.jsx(um,{className:"code-auto-folder",fetchGateway:ol,runId:m,title:yw(n.automationId,m,n.occurrences),refreshKey:CI(n.summary),onClose:m!==n.automationId?()=>o({automationId:l,runId:""}):void 0})}):null]}):t.error?a.jsx(Oh,{error:t.error}):a.jsx(To,{children:"Loading automation…"})]})}function $I(e){const[t,n]=y.useState(),[s,o]=y.useState(null);y.useEffect(()=>{e.open||o(null)},[e.open]);const[l,u]=y.useState(!1),d=y.useRef(!1),[f,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]),a.jsx(B0,{open:e.open,onClose:e.onClose,target:f||e.target,availableTools:e.availableTools,initialTools:f?null:e.initialTools,workflowPicker:e.workflowPickerOptions&&(f||e.target)?a.jsx(Lv,{target:f||e.target,options:e.workflowPickerOptions,onChange:m}):a.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:a.jsx(J_,{connected:e.connected!==!1,automation:{value:s,onChange:o},idPrefix:"code-new-automation-workspace"}),emailStatus:e.ctl.state.emailStatus,onOpenMyEmail:e.onOpenMyEmail,previewSchedule:e.ctl.previewSchedule,onOpenPreferences:e.onOpenPreferences,busy:e.ctl.state.busy||l,error:t,onSubmit:async p=>{var g,_;if(!d.current){d.current=!0,u(!0);try{const v=await((_=e.buildInput)==null?void 0:_.call(e,String(((g=p.target.input_data)==null?void 0:g.prompt)||""),f)),C=v&&e.availableTools!==void 0?Wh(v,ju(p.target.input_data)):v,x=vI(C||p.target.input_data,s),k=await e.ctl.create({...p,target:{...p.target,input_data:x}});return e.onCreated(k.automation_id),e.onClose(),k}catch(v){throw n(us(v)),v}finally{d.current=!1,u(!1)}}}})}const TI=()=>({cursor:0,waits:{},raised:{},seen:{},resolved:[],automationEpoch:0}),Nn=(e,t)=>typeof e[t]=="string"&&e[t]?e[t]:"",Xf=(e,t)=>typeof e[t]=="number"?e[t]:0,Zf=(e,t,n="")=>`${e}\0${t}\0${n}`;function RI(e,t){const n=Number(t.sequence||0);if(n>0&&n<=e.cursor)return e;const s={cursor:Math.max(e.cursor,n),waits:{...e.waits},raised:{...e.raised},seen:{...e.seen},resolved:e.resolved,automationEpoch:e.automationEpoch},o=t.data||{};switch(t.type){case"attention.raised":{const l=Nn(o,"run_id"),u=Nn(o,"wait_key");if(l&&u){const d=Nn(o,"step_id");if(Nn(o,"record_key")&&e.resolved.includes(Nn(o,"record_key"))||d&&e.resolved.includes(`step:${Zf(l,u,d)}`))break;s.waits[Zf(l,u,d)]=Nn(o,"session_id")}else if(Nn(o,"automation_id")&&Xf(o,"seq")>0){const d=Nn(o,"automation_id"),f=Xf(o,"seq"),m=s.raised[d]||[];f>(s.seen[d]||0)&&!m.includes(f)&&(s.raised[d]=[...m,f]),s.automationEpoch+=1}break}case"attention.seen":{const l=Nn(o,"record_key");l&&(s.resolved=[...s.resolved,l].slice(-500));const u=Nn(o,"run_id"),d=Nn(o,"wait_key");if(u&&d){const m=Nn(o,"step_id");m&&(s.resolved=[...s.resolved,`step:${Zf(u,d,m)}`].slice(-500));const p=`${u}\0${d}\0`;for(const g of Object.keys(s.waits))g.startsWith(p)&&(!m||g===p||g===p+m)&&delete s.waits[g]}const f=Nn(o,"automation_id");if(f){const m=Math.max(s.seen[f]||0,Xf(o,"seq"));s.seen[f]=m,s.raised[f]=(s.raised[f]||[]).filter(p=>p>m),s.automationEpoch+=1}break}case"run.started":case"run.finished":{if(t.type==="run.finished"&&Nn(o,"run_id")){const l=Nn(o,"run_id");for(const u of Object.keys(s.waits))u.startsWith(`${l}\0`)&&delete s.waits[u]}o.origin&&typeof o.origin=="object"&&o.origin.kind==="trigger"&&(s.automationEpoch+=1);break}case"trigger.event":case"wake.scheduled":case"wake.cancelled":s.automationEpoch+=1;break}return s}const II=e=>Object.keys(e.waits).length,LI=e=>Object.entries(e.raised).reduce((t,[n,s])=>t+s.filter(o=>o>(e.seen[n]||0)).length,0);class MI{constructor(t){zt(this,"fold",TI());zt(this,"state","stopped");zt(this,"listeners",new Set);zt(this,"abort",null);zt(this,"wakeUp",null);zt(this,"generation",0);this.opts=t}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}emit(){for(const t of this.listeners)t()}set(t){this.state!==t&&(this.state=t,this.emit())}apply(t){let n=this.fold;for(const s of t)n=RI(n,s);n!==this.fold&&(this.fold=n,this.emit())}nudge(){var t,n;(t=this.wakeUp)==null||t.call(this),this.opts.live()||(n=this.abort)==null||n.abort()}start(){this.state==="stopped"&&(this.set("connecting"),this.generation+=1,this.loop(this.generation))}stop(){var t,n;this.set("stopped"),(t=this.abort)==null||t.abort(),(n=this.wakeUp)==null||n.call(this)}get fetcher(){return this.opts.fetch||((t,n)=>fetch(t,{...n,credentials:"same-origin"}))}sleep(t){return new Promise(n=>{const s=setTimeout(()=>{this.wakeUp=null,n()},t);this.wakeUp=()=>{clearTimeout(s),this.wakeUp=null,n()}})}async catchUp(){for(let t=0;t<100;t+=1){const n=await this.fetcher(we(`me/events?after=${this.fold.cursor}&limit=1000`),{headers:{Accept:"application/json"}});if(!n.ok)throw Object.assign(new Error(`me/events: HTTP ${n.status}`),{status:n.status});const s=await n.json();if(this.apply(Array.isArray(s==null?void 0:s.events)?s.events:[]),!(s!=null&&s.more))return}}async tail(){const t=new AbortController;this.abort=t;const n={Accept:"text/event-stream"};this.fold.cursor>0&&(n["Last-Event-ID"]=String(this.fold.cursor));try{const s=await this.fetcher(we("me/events/stream?heartbeat_s=15"),{headers:n,signal:t.signal});if(!s.ok)throw Object.assign(new Error(`me/events/stream: HTTP ${s.status}`),{status:s.status});if(!s.body)return;const o=s.body.getReader(),l=new TextDecoder("utf-8"),u=new G_;for(;;){const{value:d,done:f}=await o.read();if(f)return;const m=[];if(u.push(l.decode(d,{stream:!0}),p=>{try{const g=JSON.parse(p.data??"");g&&typeof g=="object"&&(typeof g.sequence!="number"&&p.id&&/^\d+$/.test(p.id)&&(g.sequence=Number(p.id)),m.push(g))}catch{}}),this.apply(m),this.state==="stopped"||!this.opts.live())return}}catch(s){if((s==null?void 0:s.name)==="AbortError")return;throw s}finally{this.abort===t&&(this.abort=null)}}async loop(t){let n=1e3;const s=this.opts.maxBackoffMs??3e4;for(;this.state!=="stopped"&&t===this.generation;){try{await this.catchUp(),this.set("following"),n=1e3,this.opts.live()?await this.tail():await this.sleep(this.opts.catchUpMs??6e4);continue}catch(o){const l=Number((o==null?void 0:o.status)||0);if(l===404)return this.set("unsupported");if(l===401||l===403)return this.set("stopped")}if(this.state==="stopped"||t!==this.generation)return;await this.sleep(n),n=Math.min(s,n*2)}}}function OI(e,t){const n=()=>typeof document>"u"||document.visibilityState!=="hidden",s=y.useMemo(()=>new MI({live:n}),[e]),o=y.useSyncExternalStore(d=>s.subscribe(d),()=>s.fold),[l,u]=y.useState(s.state);return y.useEffect(()=>s.subscribe(()=>u(s.state)),[s]),y.useEffect(()=>{if(!e||!t)return;s.start();const d=()=>s.nudge();return document.addEventListener("visibilitychange",d),()=>{document.removeEventListener("visibilitychange",d),s.stop()}},[s,e,t]),{fold:o,state:l}}function PI(e){if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;const t=[...e.currentTarget.querySelectorAll('button[role="tab"]')].filter(o=>!o.disabled),n=t.indexOf(e.target);if(n<0||!t.length)return;e.preventDefault();const s=e.key==="Home"?0:e.key==="End"?t.length-1:(n+(e.key==="ArrowRight"?1:-1)+t.length)%t.length;t[s].focus(),t[s].click()}function DI(e){var f,m;const t=Object.keys(((f=e.schema)==null?void 0:f.properties)||{}),n=((m=e.schema)==null?void 0:m.required)||[],s=[e.promptProperty||"prompt","context","messages","attachments"],o=["provider","model","tools","skills","max_iterations","use_context","use_session_history"],l=ib(e.schema).map(p=>[p.provider,p.model,p.reasoning].filter(g=>!!g)),u=new Set(t.filter(p=>n.includes(p)&&!s.includes(p)));for(const p of l)p.some(g=>u.has(g))&&p.forEach(g=>u.add(g));const d=new Set(t.filter(p=>!u.has(p)&&!s.includes(p)&&!o.includes(p)));for(const p of l)p.some(g=>d.has(g))&&p.forEach(g=>d.add(g));return a.jsxs(a.Fragment,{children:[a.jsxs("section",{className:"code-settings-section","aria-label":"Automatic agent configuration",children:[a.jsx("h3",{children:u.size?"Workflow inputs":"Ready to chat"}),a.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?a.jsx(Ph,{...e,omit:t.filter(p=>!u.has(p)),rawObject:!1}):null,d.size?a.jsxs("details",{className:"code-advanced-inputs",children:[a.jsxs("summary",{children:["Advanced workflow inputs"," ",a.jsx("span",{className:"code-muted",children:"Optional"})]}),a.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."}),a.jsx(Ph,{...e,omit:t.filter(p=>!d.has(p)),rawObject:!1})]}):null]})}function FI(e,t,n){var o;if(!n.length)return t;const s=(o=e==null?void 0:e.properties)==null?void 0:o.attachments;if(!s||s.type&&s.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 zI(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 Ph({schema:e,values:t,onChange:n,disabled:s=!1,omit:o=[],rawObject:l=!1,onEditorError:u,defaultModel:d}){const[f,m]=yt.useState("fields"),p=Object.entries((e==null?void 0:e.properties)||{}).filter(([x])=>!o.includes(x)),g=ib(e),_=new Set(g.flatMap(x=>[x.provider,x.model,x.reasoning].filter(Boolean))),v=x=>{m(x),u==null||u("")},C=p.length?a.jsx("div",{className:"code-input-fields",children:p.map(([x,k])=>{const S={...k,type:y$(k)},$=g.find(I=>I.provider===x);if($)return a.jsxs("section",{className:"code-settings-section",children:[a.jsx("h3",{children:$.title}),a.jsx(_u,{value:{provider:String(t[$.provider]||""),model:String(t[$.model]||""),...$.reasoning?{reasoning:String(t[$.reasoning]||"")}:{}},onChange:I=>n({...t,[$.provider]:I.provider,[$.model]:I.model,...$.reasoning?{[$.reasoning]:I.reasoning||""}:{}}),..._$($.provider,S["x-abstract-type"]),fetchModelCapabilities:$.reasoning?So.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:s})]},x);if(_.has(x))return null;const R=`workflow-input-${x}`,N=String(S.title||x).replace(/_/g," "),E=Array.isArray(e==null?void 0:e.required)&&e.required.includes(x),j=I=>{const L={...t};I===void 0?delete L[x]:L[x]=I,n(L)};return a.jsxs("div",{className:"code-field",children:[a.jsxs("label",{htmlFor:R,children:[N,E?a.jsx("span",{"aria-label":"required",children:" *"}):null]}),S.enum?a.jsxs("select",{id:R,value:t[x]===void 0?"":JSON.stringify(t[x]),disabled:s,onChange:I=>j(I.target.value?JSON.parse(I.target.value):void 0),children:[a.jsxs("option",{value:"",children:["Choose ",N]}),S.enum.map(I=>a.jsx("option",{value:JSON.stringify(I),children:String(I)},JSON.stringify(I)))]}):S.type==="boolean"?a.jsxs("select",{id:R,value:t[x]===void 0?"":String(t[x]),disabled:s,onChange:I=>j(I.target.value?I.target.value==="true":void 0),children:[a.jsx("option",{value:"",children:"Workflow default"}),a.jsx("option",{value:"true",children:"Yes"}),a.jsx("option",{value:"false",children:"No"})]}):S.type==="number"||S.type==="integer"?a.jsx("input",{id:R,type:"number",value:typeof t[x]=="number"?String(t[x]):"",min:S.minimum,max:S.maximum,step:S.type==="integer"?1:"any",disabled:s,onChange:I=>j(I.target.value===""?void 0:Number(I.target.value))}):S.type==="object"||S.type==="array"?a.jsx(WI,{id:R,value:t[x],disabled:s,onChange:j},x):a.jsx("textarea",{id:R,rows:2,value:String(t[x]??""),disabled:s,onChange:I=>j(I.target.value)}),S.description?a.jsx("p",{className:"code-field-help",id:`${R}-help`,children:S.description}):null]},x)})}):a.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 l?a.jsxs("div",{children:[a.jsxs("div",{className:"code-settings-tabs",role:"tablist","aria-label":"Workflow input editor",onKeyDown:PI,children:[a.jsx("button",{type:"button",role:"tab",tabIndex:f==="fields"?0:-1,"aria-selected":f==="fields",onClick:()=>v("fields"),children:"Fields"}),a.jsx("button",{type:"button",role:"tab",tabIndex:f==="json"?0:-1,"aria-selected":f==="json",onClick:()=>v("json"),children:"JSON payload"})]}),f==="json"?a.jsxs(a.Fragment,{children:[a.jsx(BI,{value:t,disabled:s,onChange:n,onError:x=>u==null?void 0:u(x)}),a.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 BI({value:e,onChange:t,onError:n,disabled:s}){const[o,l]=yt.useState(JSON.stringify(e,null,2)),[u,d]=yt.useState(""),f=yt.useRef(e);return yt.useEffect(()=>{e!==f.current&&(f.current=e,l(JSON.stringify(e,null,2)),d(""),n(""))},[e,n]),a.jsxs("div",{className:"code-field",children:[a.jsx("label",{htmlFor:"workflow-input-payload",children:"Complete input object"}),a.jsx("textarea",{id:"workflow-input-payload",className:"code-mono",rows:12,value:o,disabled:s,"aria-invalid":!!u,onChange:m=>{l(m.target.value);const p=zI(m.target.value);if(!p.ok){d(p.error),n(p.error);return}f.current=p.value,d(""),n(""),t(p.value)}}),u?a.jsx("span",{role:"alert",className:"code-error-text",children:u}):null]})}function WI({id:e,value:t,onChange:n,disabled:s}){const[o,l]=yt.useState(t===void 0?"":JSON.stringify(t,null,2)),[u,d]=yt.useState(""),f=yt.useRef(t);return yt.useEffect(()=>{t!==f.current&&(f.current=t,l(t===void 0?"":JSON.stringify(t,null,2)),d(""))},[t]),a.jsxs(a.Fragment,{children:[a.jsx("textarea",{id:e,className:"code-mono",rows:4,value:o,disabled:s,"aria-invalid":!!u,onChange:m=>{l(m.target.value);try{const p=m.target.value.trim()?JSON.parse(m.target.value):void 0;f.current=p,n(p),d("")}catch{f.current=m.target.value,n(m.target.value),d("Enter valid JSON.")}}}),u?a.jsx("span",{role:"alert",className:"code-error-text",children:u}):null]})}function UI({active:e,paused:t,snapshot:n,onRevokeApproval:s,onCommand:o,onActivity:l,onInteraction:u,permissionsAll:d}){const f=y.useMemo(()=>PE(n),[n]),m=y.useMemo(()=>f.tone==="working"?RT(n.view?nR(n.view):n.records.map(k=>k.record)):"",[f.tone,n.records,n.view]),p=m||f.detail,[g,_]=y.useState(Date.now);y.useEffect(()=>{if(!e)return;const k=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(k)},[e]);const v=Date.parse(f.startedAt||""),C=Number.isFinite(v)?Math.max(0,Math.floor((g-v)/1e3)):null,x=C===null?"":C<60?`${C}s`:`${Math.floor(C/60)}m ${C%60}s`;return a.jsxs("div",{className:`code-run-strip code-run-strip--${f.tone}`,children:[a.jsxs("div",{className:"code-run-strip__activity",role:"status","aria-live":"polite",children:[a.jsx("span",{className:"code-run-strip__icon","aria-hidden":"true",children:a.jsx(de,{name:f.tone==="working"?"loader":f.tone==="success"?"check":f.tone==="error"?"error":f.tone==="waiting"?"history":"info",size:15})}),u&&f.tone==="waiting"?a.jsxs("button",{className:"code-run-strip__attention",onClick:u,title:"Go to the pending request",children:[a.jsx("strong",{children:f.label}),a.jsx(de,{name:"chevronRight",size:12})]}):a.jsx("strong",{children:f.label}),a.jsx("span",{className:`code-run-strip__detail${m?" code-run-strip__detail--live":""}`,title:p,children:p})]}),a.jsxs("span",{className:"code-run-strip__metrics","aria-label":"Run activity metrics",children:[e&&x?a.jsx("span",{children:x}):null,f.toolCalls?a.jsxs("span",{children:[f.toolCalls," ",f.toolCalls===1?"tool":"tools"]}):null,f.totalTokens!==void 0?a.jsxs("span",{children:[f.totalTokens.toLocaleString()," tokens"]}):null]}),e?a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:()=>o(t?"resume":"pause"),children:[t?"Resume":"Pause"," "]}),a.jsx("button",{onClick:()=>o("conclude"),children:"Conclude"})]}):null,a.jsxs("button",{onClick:l,children:["View activity ",a.jsx(de,{name:"chevronRight",size:12})]}),d?a.jsxs("div",{className:"code-run-strip__consent",children:[a.jsx(de,{name:"check",size:13}),a.jsx("span",{children:"Auto: every enabled tool · this browser"}),a.jsx("button",{onClick:s,children:"Revoke"})]}):null]})}function eh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Vc(e){return typeof e=="string"?e.trim():""}function VI(e){const t=eh(e),n=eh(t==null?void 0:t.gateway),s=eh(n==null?void 0:n.principal);return JSON.stringify([Vc((t==null?void 0:t.gateway_url)??(t==null?void 0:t.gatewayUrl)),Vc((s==null?void 0:s.tenant_id)??(s==null?void 0:s.tenantId)),Vc((s==null?void 0:s.runtime_id)??(s==null?void 0:s.runtimeId)),Vc((s==null?void 0:s.user_id)??(s==null?void 0:s.userId))||"session"])}function ww(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 GI(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 HI(e,t,n){return e.flatMap(s=>s.id===t.id?[]:s.sessionId!==t.sessionId||s.authEpoch!==t.authEpoch||s.sourceRunId!==t.sourceRunId?[s]:[{...s,sourceRunId:n}])}function th(){return new DOMException("The conversation changed before the run was attached.","AbortError")}const KI=Xk("abstractcode","0.13.0"),nh=e=>["completed","failed","cancelled","canceled"].includes(e);function vw(){const e=new URLSearchParams(window.location.hash.replace(/^#/,""));return{sessionId:e.get("session")||va(),runId:e.get("run")||""}}function Bi(e,t=""){const n=new URLSearchParams({session:e});t&&n.set("run",t),window.history.replaceState(null,"",`#${n}`)}function JI(){var jl,Nl,Cl,Ua,El,Al,$l,ri,Tl,Rl,Il,Ll,Ml,Ol,Pl,Va,gr,Dl,ai,oi,ii;const e=Lk({appName:"AbstractCode",variant:"blocking"}),t=e.connected?VI(e.status):"",n=y.useCallback(()=>{e.refresh()},[e.refresh]),s=q$(t,n),[o,l]=lS("abstractcode",{defaults:{theme:"observer-night"}}),[u,d]=y.useState(!1),[f,m]=y.useState(0),p=y.useCallback(()=>m(O=>O+1),[]),[g,_]=d1(t?`abstractcode.voice:${t}`:null);y.useEffect(()=>{St()},[t]);const[v,C]=y.useState(or),x=y.useRef(v);x.current=v;const k=y.useMemo(()=>t?O1(t):null,[t]),[S,$]=y.useState({}),[R,N]=y.useState(!1);y.useEffect(()=>{$(k?k.readApp(ln):{});let O=!1;try{O=!!t&&localStorage.getItem(qf(t))==="pending"}catch{}N(O)},[k,t]);const E=y.useCallback(O=>{$(O),k==null||k.writeApp(ln,Object.keys(O).length?O:null)},[k]),j=()=>{N(!1);try{localStorage.setItem(qf(t),"dismissed")}catch{}},I=S$(v.streamReplies,s.streaming),[L,z]=y.useState(or.workflow),V=y.useMemo(()=>M$(s.executable.data),[s.executable.data]),Z=y.useCallback(()=>C(O=>({...O,workflow:Xt})),[]),ie=wT(t,Z),F=ie.state.status==="ok",D=ie.state.status==="ok"?pT(ie.state.row.value,V):v.workflow,M=y.useRef(D);M.current=D;const J=y.useMemo(()=>L$(s.gatewayDefault,s.workflows),[s.gatewayDefault,s.workflows]),B=L===Xt?J:s.workflows.find(O=>O.id===L)||V.find(O=>O.id===L)||null,[Y,te]=y.useState(null),W=hm(B),[T,K]=y.useState(vw),[ne,ue]=y.useState(""),[oe,ve]=y.useState(""),[Ne,q]=y.useState(""),[be,xe]=y.useState(!1),Pe=y.useRef(!1),[Qe,He]=y.useState([]),qe=y.useRef(null),[ge,$e]=y.useState(),st=y.useRef(ge);st.current=ge;const[tt,Lt]=y.useState(!1),[ce,fe]=y.useState(""),[H,le]=y.useState(0),[he,Q]=y.useState({}),[_e,ae]=y.useState(""),[Se,Oe]=y.useState(null),[Fe,Ze]=y.useState(""),[Le,Ke]=y.useState(null),De=Hc(Gc.md);y.useEffect(()=>{De&&Ke(null)},[De]);const pt=Le!==null,St=O=>{De&&Ke(null)},jt=O=>{Zt(!1),Ke(O)},Pt=O=>{O?jt("workflow"):Le==="workflow"&&Ke(null)},Ss=Hc(Gc.md),Fo=Hc(Gc.lg),Qn=xA(Fo,Ss),Fs=y.useRef(Qn),[zs,Zt]=y.useState(!1),[ja,zo]=OA(),[ir,Na]=BA(),Bo=zR(s.capabilities),js=OI(t,e.connected),Ca=js.state==="following",{ctl:Jt,state:Bt}=kI(t,e.connected&&Bo.available,{following:Ca,epoch:js.fold.automationEpoch});y.useEffect(()=>{ir.automations&&Bt.loaded&&Bt.archivedCount>0&&Bt.archived===null&&Jt.loadArchived()},[ir.automations,Bt.loaded,Bt.archivedCount,Bt.archived,Jt]);const[Wt,ds]=y.useState(!1),[lr,Vr]=y.useState(!1),Wo=y.useRef(""),[Uo,Mu]=y.useState(""),Ns=y.useRef(null),[Cs,fs]=y.useState([]),[Vo,Xn]=y.useState(!1),[Go,Ea]=y.useState([]);y.useEffect(()=>{const O=v.legacyTools;if(!(!O||!k||s.loading||!s.toolCatalog.length)){if(!Object.keys(k.readApp(ln)).length){const se=iT(O,s.toolCatalog);if(Object.keys(se).length){E(se),N(!0);try{localStorage.setItem(qf(t),"pending")}catch{}q(`${tw} in Tools.`)}}C(({legacyTools:se,...je})=>je)}},[v.legacyTools,k,s.loading,s.toolCatalog,t,E]);const Aa=y.useRef(null),Ou=y.useMemo(()=>{var Ie,Ve;const O=((Ie=Aa.current)==null?void 0:Ie.runId)===T.runId?Aa.current.input:null;if(T.runId&&!Se&&!O)return{enabledTools:[],autoApproveTools:[]};const se=Se?Se.input_data:O,je=(Ve=se==null?void 0:se._runtime)==null?void 0:Ve.allowed_tools;return p1(Yc(s.toolCatalog,{app:S},{ceiling:Array.isArray(je)?je:null}))},[s.toolCatalog,S,Se,T.runId]),Ho=`${t}:${T.sessionId}:${T.runId}`,Nt=y.useRef(Ho);Nt.current=Ho;const yl=y.useRef(null),[$a,wl]=y.useState({scope:"",notes:[]}),Ta=y.useMemo(()=>Y$({onDeltaError:O=>{const se=Nt.current,je=C$(O,yl.current);wl(Ie=>({scope:se,notes:E$(Ie.scope===se?Ie.notes:[],je)}))}}),[]),{controller:Zn,snapshot:Ye}=sA({transport:Ta,runId:T.runId,enabled:e.connected,onAuthError:n,clientId:"abstractcode-web",authScopeKey:t,toolApprovalPolicy:Ou}),Es=s.sessionToolPolicy;y.useEffect(()=>{if(!(!e.connected||s.capabilitiesLoading)){if(s.capabilitiesError){Zn.setSessionToolPolicyClient(null,{reason:s.capabilitiesError});return}Zn.setSessionToolPolicyClient((Es==null?void 0:Es.supported)===!0&&T.sessionId?x1((O,se)=>ot(O,{method:se.method,...se.body===void 0?{}:{body:JSON.stringify(se.body)}}),T.sessionId,Es,{client:"abstractcode-web"}):null)}},[Zn,e.connected,s.capabilitiesLoading,s.capabilitiesError,Es,T.sessionId]);const Ut=!!T.runId&&!nh(Ye.status)&&Ye.status!=="idle",Ko=((jl=Ye.run)==null?void 0:jl.paused)===!0||Ye.status==="paused",Vt=Ut||be,Ra=Ye.loading&&Go.length?Go:Ye.messages,Ia=Ra[Ra.length-1];yl.current=Ia!=null&&Ia.id?String(Ia.id):null;const Bs=A$(Ra,[j$(v.streamReplies,s.streaming,Ra),...$a.scope===Ho?$a.notes:[]]),cr=((Cl=(Nl=s.capabilities)==null?void 0:Nl.assistant)==null?void 0:Cl.voice)||{},Gr=c1(e.connected?Cb:null,t),dn=Eb({scope:`${t}:${T.sessionId}:${T.runId}:${Wt}`,runId:t?T.runId:"",sessionId:T.sessionId,capability:cr,preferences:g,onTranscript:O=>{(g.auto_send??Lu.auto_send)===!1?ue(se=>mw(se,O)):za(O)},onError:ve}),es=[...Bs].reverse().find(O=>O.role==="assistant"),ur=es?String(es.id||es.content):"",Jo=y.useRef({scope:"",id:""});y.useEffect(()=>{const O=`${t}:${T.sessionId}`,se=Jo.current;if(se.scope!==O){Jo.current={scope:O,id:ur};return}!ur||ur===se.id||Vt||(Jo.current={scope:O,id:ur},g.read_aloud===!0&&dn.tts_supported&&(es!=null&&es.content)&&dn.toggle_tts(ur,es.content))},[t,T.sessionId,ur,Vt,g.read_aloud,dn.tts_supported]);const La=YE(Ye),$n=y.useMemo(()=>fA(La,Zn,{records:Ye.records,currentRun:Ye.run,onPermissionsAll:async()=>{E(lT(s.toolCatalog,S))},approveAllScope:"in this browser",sessionPolicy:{toolsetOf:O=>{var se;return(se=s.tools.find(je=>je.name===O))==null?void 0:se.toolset},ask:Object.entries(S).filter(([,O])=>O==="ask").map(([O])=>O)}}),[La,Ye.records,Ye.run,Ye.sessionPolicyMode,Ye.sessionPolicy,Ye.sessionPolicyClamped,Zn,s.tools,s.toolCatalog,S,E]),Vn=W?"prompt":w$(ge),dr=W||!!(Vn&&!((Ua=ge==null?void 0:ge.required)!=null&&Ua.some(O=>O!==Vn))),fr=String(((El=Se==null?void 0:Se.workspace)==null?void 0:El.workspace_root)||(($l=(Al=Ye.run)==null?void 0:Al.vars)==null?void 0:$l.workspace_root)||""),Ws=y.useMemo(()=>{var O;return YA(s.workflows,{inputData:Se,runWorkflowId:(O=Ye.run)==null?void 0:O.workflow_id})},[s.workflows,Se,(ri=Ye.run)==null?void 0:ri.workflow_id]),at=T.runId&&Se&&!s.loading&&Ye.run&&!Ws&&pm(Se)!=="gateway_default"?"This conversation's exact workflow version is unavailable. Restore it in the gateway, or start a new conversation with an available workflow.":"",fn=s.sessions.find(O=>O.sessionId===T.sessionId),Hr=(fn==null?void 0:fn.prompt)||((Tl=Bs.find(O=>O.role==="user"))==null?void 0:Tl.content)||"New conversation",Ma=FR((Rl=e.status)==null?void 0:Rl.gateway_url),Oa=Ma?()=>{window.open(Ma,"_blank","noopener,noreferrer")}:void 0,Pa={...Oa?{openMyEmail:Oa}:{},openConversation:(O,se,je)=>{Wo.current=je||"",ms(O,se)},openRun:O=>{ot(we(`runs/${encodeURIComponent(O)}`)).then(se=>{if(!(se!=null&&se.session_id))throw new Error(`The gateway reported no session for run ${O}.`);ms(se.session_id,O)}).catch(se=>Jt.reportError(se))}},qo=O=>{(!Wt||Bt.selectedId!==O)&&(ds(!0),Jt.select(O)),Zt(!1),Ke("workflow")},Yo=O=>{qo(O),Ke("workspace")},Kr=async O=>{const se=O.flow_id==="@default"?J:s.workflows.find(Gt=>`${Gt.bundleId}@${Gt.bundleVersion}`===("bundle_ref"in O?O.bundle_ref:"")&&Gt.flowId===O.flow_id);if(!se)throw new Error("The selected workflow is no longer available. Refresh the workflow list.");const je=await Kf(se);if(!je)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const Ie={...sr(je),...O.input_data},Ve=Uf(je,Ie);if(Ve.length)throw new Error(`${Ve.join(" ")} Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...O,input_data:Ie}},hs=((Il=Bt.detail)==null?void 0:Il.summary.title)||"Automation",ts=y.useRef(""),Gn=y.useRef(t),Dt=y.useRef(0);Gn.current!==t&&(Dt.current+=1,Gn.current=t);const Us=y.useRef(!1),Ct=y.useRef(T);Ct.current=T;const xn=BE({upload:O=>Ur.attachments_upload(Ct.current.sessionId,O),maxBytes:(Ll=s.policy)==null?void 0:Ll.maxAttachmentBytes}),Qo=[...Qe,...xn.attached],Jr=[...Qe.map((O,se)=>({id:`ref:${se}:${O.$artifact}`,name:O.filename||O.path||"Attachment",...typeof O.size_bytes=="number"?{size:O.size_bytes}:{},state:"attached"})),...xn.items],Pu=O=>{if(!O.startsWith("ref:"))return xn.remove(O);const se=Number(O.split(":")[1]);He(je=>je.filter((Ie,Ve)=>Ve!==se))};function Da(O){return xn.add(O),O.map(se=>{var Ie;const je=dm(se,(Ie=s.policy)==null?void 0:Ie.maxAttachmentBytes);return{name:se.name,state:je?"refused":"queued",...je?{error:je}:{}}})}y.useEffect(()=>{if(Pe.current=!1,xe(!1),xn.clear(),ve(""),q(""),!t){He([]),ue(""),fs([]),Xn(!1),Ea([]),C(or);return}if(ts.current&&ts.current!==t){const se={sessionId:va(),runId:""};K(se),Bi(se.sessionId)}ts.current=t,Us.current=!0;const O=db(t);C(O),z(O.workflow)},[t]),y.useEffect(()=>{if(t){if(Us.current){Us.current=!1;return}hT(t,v)}},[v,t]),y.useEffect(()=>{if(s.loading||!s.workflows.length)return;const O=D$({selection:L,preferred:D,visible:V,workflows:s.workflows,runId:T.runId});O!==L&&z(O)},[s.loading,s.workflows,V,L,D,T.runId]);const qr=ie.state.status==="ok"?`${t}|${ie.state.row.value??""}|${V.length}`:"";y.useEffect(()=>{!qr||T.runId||!V.length||z(M.current)},[qr]),y.useEffect(()=>{let O=!0;if(Q({}),ae(""),$e(void 0),fe(""),!B){Lt(!1);return}return Lt(!0),Kf(B).then(se=>{O&&($e(se),Q(sr(se)))}).catch(se=>{O&&fe(At(se))}).finally(()=>{O&&Lt(!1)}),()=>{O=!1}},[B==null?void 0:B.id,H]),y.useEffect(()=>{if(Oe(null),Ze(""),!t||!T.runId)return;const O=new AbortController;return ot(we(`runs/${encodeURIComponent(T.runId)}/input_data`),{signal:O.signal}).then(se=>{Oe(se)}).catch(se=>{O.signal.aborted||Ze(At(se))}),()=>O.abort()},[T.runId,t]),y.useEffect(()=>{Se&&Se.flow_id===(B==null?void 0:B.flowId)&&ge&&Q({...sr(ge),...p$(ge,Se.input_data)})},[Se,ge,B==null?void 0:B.flowId]),y.useEffect(()=>{!T.runId&&e.connected&&(fn!=null&&fn.latestRunId)&&K(O=>({...O,runId:fn.latestRunId}))},[T.runId,e.connected,fn==null?void 0:fn.latestRunId]),y.useEffect(()=>{Bi(T.sessionId,T.runId),Pe.current=!1,xe(!1),xn.clear(),He([]),Q(sr(st.current)),Ea([]),q(Wo.current),Wo.current="",ve(""),fs([]),Xn(!1)},[T.sessionId]),y.useEffect(()=>{const O=()=>{const se=vw();Pe.current=!1,xe(!1),xn.clear(),fs([]),Xn(!1),ue(""),K(se)};return window.addEventListener("hashchange",O),()=>window.removeEventListener("hashchange",O)},[]),y.useEffect(()=>{!T.runId||!nh(Ye.status)||s.refresh()},[T.runId,Ye.status]),y.useEffect(()=>{if(!T.runId||!Se)return;const O=F$({restoredInputs:Se,restored:Ws});O&&z(O)},[T.runId,Se,Ws==null?void 0:Ws.id]);const Fa=T.runId?z$(Se):"",Yr=y.useCallback(()=>{const O={sessionId:va(),runId:""};K(O),z(M.current),Bi(O.sessionId),ue(""),fs([]),Xn(!1),Zt(!1),ds(!1)},[]),ms=y.useCallback((O,se)=>{Pe.current=!1,xe(!1),xn.clear(),K({sessionId:O,runId:se}),Bi(O,se),Zt(!1),fs([]),Xn(!1),ue(""),ds(!1)},[]);y.useEffect(()=>{const O=Fs.current;Fs.current=Qn,O!==Qn&&Zt(se=>kA(se,Qn))},[Qn]),bA(zs,Ss,()=>document.querySelector(".code-sidebar"),()=>document.querySelector(".code-mobile-close")),y.useEffect(()=>{const O=se=>{var Ie;if(SA({key:se.key,defaultPrevented:se.defaultPrevented,overlayOpen:pt||lr||jA(),sidebarOpen:zs})==="sidebar"){Zt(!1),(Ie=document.querySelector(".code-mobile-nav"))==null||Ie.focus();return}(se.metaKey||se.ctrlKey)&&(se.key.toLowerCase()==="k"&&(se.preventDefault(),St(),Zt(!0),window.setTimeout(()=>{var Ve;return(Ve=Ns.current)==null?void 0:Ve.focus()},0)),se.key.toLowerCase()==="n"&&se.shiftKey&&(se.preventDefault(),Yr()))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[Yr,zs,lr,pt]);function Vs(O,se,je=[],Ie=!1,Ve=B,Gt=ge){let bt=t$({workflow:Ve||void 0,inputSchema:Gt,schemaInputs:se,prompt:O,promptProperty:Vn,model:v,reasoning:v.reasoning||void 0,speculation:v.speculation,streamReplies:I,systemPromptExtra:v.system||void 0,attachments:je,limits:{maxIterations:v.maxIterations?Number(v.maxIterations):void 0,maxTokens:v.maxTokens?Number(v.maxTokens):void 0},workspace:fr?{root:fr}:void 0,skills:v.skills.length?v.skills:void 0});return uu(s.toolCatalog,{app:S})&&(bt=Xv(bt,Yc(s.toolCatalog,{app:S}))),Ie&&(delete bt.workspace_root,delete bt.workspace_access_mode,delete bt.workspace_allowed_paths,delete bt.workspace,bt._runtime&&typeof bt._runtime=="object"&&delete bt._runtime.tool_policy),bt}async function ps(O){if(Pe.current)throw new Error("A turn is already being submitted.");if(!e.connected)throw new Error("Connect to your gateway first.");if(L===Xt&&s.gatewayDefault.status==="unavailable")throw new Error(`Gateway default: ${s.gatewayDefault.reason}. Choose a workflow from the list.`);if(!B)throw new Error("Choose a workflow first.");if(!s.policy)throw new Error("Workspace policy is unavailable. Reconnect or refresh before starting.");if(T.runId&&(!Se||Fe))throw new Error(Fe||"Wait for the gateway to restore this conversation's workspace.");if(at)throw new Error(at);if(tt||ce)throw new Error(ce||"Wait for workflow inputs to load.");if(_e)throw Pt(!0),new Error(_e);if(xn.sendBlock)throw new Error(xn.sendBlock);if(Ut)throw new Error("The current run is still active.");if(!W&&O.trim()&&!Vn)throw Pt(!0),new Error("This workflow uses structured inputs. Configure its inputs, then select Run workflow.");const se={...sr(ge),...he,...Vn&&O.trim()?{[Vn]:O.trim()}:{}},je=W?se:FI(ge,se,Qo);for(const[gs,ss]of[["Iteration limit",v.maxIterations],["Context token limit",v.maxTokens]])if(ss&&(!Number.isInteger(Number(ss))||Number(ss)<=0))throw new Error(`${gs} must be a positive whole number.`);Pe.current=!0,xe(!0),ve(""),q("");const Ie=T.sessionId,Ve=T.runId,Gt=t,bt=Dt.current;let yr="";try{const gs=Vs(O,je,Qo),ss=Uf(ge,gs);if(ss.length)throw Pt(!0),new Error(ss.join(" "));const Vu=B$({selection:L,workflow:B,sessionId:Ie,input:gs}),Hn=await ot(we("runs/start"),{method:"POST",body:JSON.stringify(Vu)});if(!Hn.run_id)throw new Error("The gateway did not return a run identifier.");if(Ct.current.sessionId!==Ie||Ct.current.runId!==Ve||Gn.current!==Gt||Dt.current!==bt)throw th();return yr=String(Hn.run_id),Aa.current={runId:yr,input:gs},te({runId:yr,...W$(Hn.resolved_workflow)}),Ea([...Bs,...O.trim()?[{id:`pending:${Hn.run_id}`,role:"user",content:O.trim()}]:[]]),K({sessionId:Ie,runId:Hn.run_id}),Bi(Ie,Hn.run_id),ue(""),He([]),xn.clear(),Pt(!1),Hn.runner_warning&&q(String(Hn.runner_warning)),s.refresh(),yr}finally{Ct.current.sessionId===Ie&&(Ct.current.runId===Ve||Ct.current.runId===yr)&&Gn.current===Gt&&Dt.current===bt&&(Pe.current=!1,xe(!1))}}async function za(O){const se=mw(ne,O);if(be){ue(se);return}try{await Qr(se)}catch(je){ue(se),ve(At(je))}}async function vl(O){if($n)throw new Error("Answer the pending workflow request above, or queue the next turn.");const se=T.sessionId,je=T.runId,Ie=Dt.current,Ve=await Zn.sendCommand("inject_guidance",{guidance:O});if(Ct.current.sessionId!==se||Ct.current.runId!==je||Dt.current!==Ie)throw th();return{accepted:(Ve==null?void 0:Ve.accepted)!==!1,...typeof(Ve==null?void 0:Ve.seq)=="number"?{seq:Ve.seq}:{},...(Ve==null?void 0:Ve.duplicate)===!0?{duplicate:!0}:{}}}function _l(O){return fs(se=>[...se,{id:va(),text:O,sessionId:T.sessionId,sourceRunId:T.runId,authEpoch:Dt.current}]),Xn(!0),{accepted:!0}}const Xo=Ut&&!be?{modes:$n?["queue"]:["guide","queue"],parked:Ye.status==="waiting"&&!$n,onSteer:async(O,se)=>se==="queue"?_l(O):vl(O)}:void 0;async function Qr(O){if(!Ut)return ps(O);if(!($n?_l(O):await vl(O)).accepted)throw new Error("The gateway did not accept this message.");ue(""),q($n?"Queued for the next turn.":"Guidance queued. The workflow will read it at its next supported boundary.")}async function Ba(O){var Ie,Ve;const se=String(((Ie=Ye.run)==null?void 0:Ie.run_id)||"");if(!ww(O,{sessionId:T.sessionId,runId:T.runId,snapshotRunId:se,snapshotSessionId:String(((Ve=Ye.run)==null?void 0:Ve.session_id)||""),authEpoch:Dt.current}))throw th();const je=await ps(O.text);fs(Gt=>HI(Gt,O,je))}y.useEffect(()=>{var je,Ie;if(!Vo||!Cs.length||!e.connected||!Se||Fe||Pe.current)return;const O=GI(Ye.status);if(O==="wait")return;if(O==="pause"){Xn(!1);const Ve=["failed","error"].includes(Ye.status.toLowerCase());q(`Queue paused because the run ${Ve?"failed":"was cancelled"}. Review the result, then use Run next to continue explicitly.`);return}const se=Cs[0];ww(se,{sessionId:T.sessionId,runId:T.runId,snapshotRunId:String(((je=Ye.run)==null?void 0:je.run_id)||""),snapshotSessionId:String(((Ie=Ye.run)==null?void 0:Ie.session_id)||""),authEpoch:Dt.current})&&Ba(se).catch(Ve=>{Ve instanceof DOMException&&Ve.name==="AbortError"||(Xn(!1),ve(At(Ve)))})},[Vo,Cs,Ye.status,(Ml=Ye.run)==null?void 0:Ml.run_id,(Ol=Ye.run)==null?void 0:Ol.session_id,e.connected,Se,Fe,T.sessionId,T.runId]);async function bl(){const O=T.sessionId,se=T.runId,je=Dt.current;await Zn.cancel(),Ct.current.sessionId===O&&Ct.current.runId===se&&Dt.current===je&&q("")}const Tn=O=>{const se=Dt.current,je=T.sessionId,Ie=T.runId;ve(""),O().catch(Ve=>{Ve instanceof DOMException&&Ve.name==="AbortError"||Dt.current===se&&Ct.current.sessionId===je&&Ct.current.runId===Ie&&ve(At(Ve))})},Xr=s.sessions.filter(O=>`${O.prompt||""} ${O.sessionId}`.toLowerCase().includes(Uo.toLowerCase())),[kn,Wa]=y.useState(null),[Zr,hr]=y.useState(!1),[xl,en]=y.useState(""),Gs=(O,se)=>{en(""),Wa({sessionId:O,where:se})},Zo=()=>{Wa(null),en("")},ea=async()=>{if(!kn||Zr)return;const{sessionId:O}=kn;hr(!0),en("");try{await u$(O)}catch(se){en(`Not archived: ${At(se)}`),hr(!1);return}if(hr(!1),Wa(null),O===T.sessionId){const se=d$(Xr,O);se?ms(se.sessionId,se.latestRunId):Yr()}s.forgetSession(O)},kl=a.jsx(UA,{busy:Zr,error:xl,onConfirm:()=>void ea(),onCancel:Zo}),ei=O=>{const se=[];(v.provider||v.model)&&!O.provider&&!O.model&&se.push("provider","model"),Object.keys(S).length>0&&!Object.keys(O.toolLayer).length&&se.push("tools"),O.toolLayer!==S&&E(O.toolLayer),v.maxIterations&&!O.maxIterations&&se.push("max_iterations"),se.length&&Q(Ie=>{const Ve={...Ie},Gt=sr(ge);for(const bt of se)delete Ve[bt],Object.prototype.hasOwnProperty.call(Gt,bt)&&(Ve[bt]=Gt[bt]);return Ve}),C({...O,toolLayer:{}})},ns=(O,se={...v,toolLayer:S},je=ei,Ie)=>a.jsx(sT,{tab:O,lockedReasonId:`code-${O}-locked`,value:se,onChange:je,toolCatalog:s.toolCatalog,toolWarnings:s.toolWarnings,automationTools:!!Ie,toolsNotice:!Ie&&R?{text:tw,onDismiss:j}:null,connected:e.connected,automationFolders:!!Ie,defaultModel:!Ie&&he.provider&&he.model?{provider:String(he.provider),model:String(he.model)}:s.defaultModel,workflowDefault:!Ie&&!!(he.provider&&he.model),streaming:s.streaming,disabled:Ie?!e.connected:Vt||!e.connected,workspaceRootFixed:Ie==null?void 0:Ie.root,sessionId:Ie?void 0:T.sessionId,onOpenDefaultWorkspaces:()=>d(!0),workspaceRefreshKey:f,hideStreamReplies:!!Ie,lockedText:Ie?"Connect to a gateway to edit this automation.":void 0}),mr=a.jsx(hI,{value:g,onChange:O=>{dn.stop_tts(),_(O)},defaults:Gr,connected:e.connected,isAdmin:((gr=(Va=(Pl=e.status)==null?void 0:Pl.gateway)==null?void 0:Va.principal)==null?void 0:gr.admin)===!0,levelSource:dn}),wt=Bt.detail,As=RR(Wt&&(wt!=null&&wt.definition)?{summary:wt.summary,definition:wt.definition}:null,(O,se,je)=>Jt.revise(O,se,je),s.toolCatalog),pr=(O,se,je)=>{if(Wt){if(!(wt!=null&&wt.definition)||!As)return Bt.selectedId?a.jsx(To,{children:"Loading automation…"}):a.jsx("p",{className:"code-muted",children:"Select an automation in the sidebar."});const Ie={root:wt.definition.workspace_root||""};return a.jsxs("div",{className:"code-automation-settings",id:`code-settings-${O}`,"data-revision":As.revision,children:[a.jsx(IR,{summary:wt.summary,settings:As}),je(As.draft,As.onChange,Ie)]})}return a.jsxs("div",{className:"code-conversation-settings",id:`code-settings-${O}`,children:[a.jsxs("p",{className:"code-settings-binding",children:[a.jsx("span",{children:"Conversation"})," ",a.jsx("strong",{title:Hr,children:Hr})]}),se()]})},Du=pr("model",()=>ns("model"),(O,se,je)=>ns("model",O,se,je)),Fu=pr("workflow",()=>a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"code-workflow-select","aria-busy":tt||void 0,children:[a.jsx(de,{name:"agent",size:17}),a.jsx(Iv,{id:"code-workflow-picker",className:"code-workflow-picker",interfaceId:ln,ariaLabel:"Workflow",workflows:{...s.executable,reload:()=>void s.refresh()},value:O$(L,B),currentLabel:B&&L!==Xt&&!V.some(O=>O.id===B.id)?{name:B.name,detail:T.runId&&B.bundleVersion?`conversation version ${B.bundleVersion}`:B.bundleVersion?`@${B.bundleVersion}`:""}:null,unavailableReason:e.connected?Vt?"A run is in progress.":null:"Connect to a gateway first.",onChange:(O,se)=>{const je=P$(O,se);z(je),F||C(Ie=>({...Ie,workflow:je}))}}),L===Xt&&Vf(J)?a.jsx("span",{className:"code-workflow-resolved is-missing",role:"alert",title:Vf(J),children:Vf(J)}):null,Fa?a.jsx("span",{className:"code-workflow-resolved is-missing",role:"status",title:Fa,children:Fa}):null,Y&&Y.runId===T.runId&&Y.missing?a.jsx("span",{className:"code-workflow-resolved is-missing",role:"status",children:Y.text}):null]}),ie.state.status==="ok"?a.jsxs(a.Fragment,{children:[a.jsx(vT,{row:ie.state.row,save:ie.save,disabled:!e.connected}),a.jsx(sw,{block:ie.state.timeZone,save:ie.saveTimeZone,disabled:!e.connected})]}):null,a.jsxs("div",{className:"code-settings code-workflow-inputs",children:[a.jsx("h3",{className:"code-settings-heading",children:"Inputs"}),a.jsx("p",{className:"code-muted",children:(B==null?void 0:B.description)||"Configure the values this workflow needs to run."}),tt?a.jsx("p",{role:"status",children:"Loading input schema…"}):ce?null:W||Vn?a.jsx(DI,{schema:ge,promptProperty:Vn,defaultModel:s.defaultModel,values:he,onChange:Q,disabled:Vt,onEditorError:ae},B==null?void 0:B.id):a.jsx(Ph,{schema:ge,defaultModel:s.defaultModel,values:he,onChange:Q,disabled:Vt,rawObject:!0,onEditorError:ae},B==null?void 0:B.id),ce?a.jsx("p",{role:"alert",className:"code-error-text",children:ce}):null,dr?a.jsxs("button",{className:"code-primary-button",onClick:()=>Pt(!1),children:["Back to chat ",a.jsx(de,{name:"chat",size:16})]}):a.jsxs("button",{className:"code-primary-button",disabled:Vt||tt||!!ce||!!_e||!e.connected,onClick:()=>Tn(()=>ps(ne||String(he[Vn||"prompt"]||""))),children:["Run workflow ",a.jsx(de,{name:"playCircle",size:16})]})]})]}),()=>wt!=null&&wt.definition&&As?a.jsxs(a.Fragment,{children:[a.jsx(LR,{summary:wt.summary,definition:wt.definition,settings:As,busy:Bt.busy,disabled:!e.connected,emailStatus:Bt.emailStatus,onOpenMyEmail:Pa.openMyEmail,onRevise:(O,se)=>Jt.revise(wt.automationId,O,se),previewSchedule:Jt.previewSchedule,prepareTarget:Kr,workflowPickerOptions:{interfaceId:ln,workflows:{...s.executable,reload:()=>void s.refresh()}}}),ie.state.status==="ok"?a.jsx(sw,{block:ie.state.timeZone,save:ie.saveTimeZone,disabled:!e.connected}):null]}):null),ti=pr("workspace",()=>a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:"code-current-workspace",children:["Current workspace ",a.jsx("code",{title:fr||"Gateway workspace",children:fr.split("/").filter(Boolean).pop()||"Gateway workspace"})]}),ns("workspace")]}),(O,se,je)=>ns("workspace",O,se,je)),zu=pr("tools",()=>ns("tools"),(O,se,je)=>ns("tools",O,se,je)),Bu=pr("skills",()=>ns("skills"),(O,se,je)=>ns("skills",O,se,je)),Wu=pr("voice",()=>mr,()=>mr),ni=Wt?`automation:${Bt.selectedId}`:`conversation:${T.sessionId}`,Sl=y.useRef({});y.useEffect(()=>{!Le||Le==="activity"||Le==="files"||Sl.current[Le]===ni||(Sl.current[Le]=ni,window.requestAnimationFrame(()=>{const O=document.querySelector(`#code-rail-panel-${Le} .af-rail__body`);O&&(O.scrollTop=0)}))},[ni,Le]);const si=Wt?{count:0,hint:""}:fR(Ye.records,T.runId,Ye.view),Uu=a.jsx(NR,{panel:Le,onPanel:Ke,docs:_A(e.connected),activityBadge:si.count,activityHint:si.hint,content:{activity:Wt?a.jsx(yR,{occurrences:(wt==null?void 0:wt.occurrences)||[],nowMs:Date.now(),onOpenRun:Pa.openRun}):a.jsx(dR,{records:Ye.records,runId:T.runId,view:Ye.view}),files:Wt?e.connected&&Bt.selectedId?a.jsx(um,{fetchGateway:ol,runId:Bt.selectedId,title:"Automation files",refreshKey:wt==null?void 0:wt.summary.updated_at,copyText:gm,onOpenFolder:()=>fb(Bt.selectedId)}):a.jsx("p",{className:"code-muted",children:"Connect to a gateway and select an automation to browse its files."}):a.jsx(a.Fragment,{children:a.jsx(uR,{policy:s.policy,runId:T.runId,enabled:e.connected,isAdmin:((oi=(ai=(Dl=e.status)==null?void 0:Dl.gateway)==null?void 0:ai.principal)==null?void 0:oi.admin)===!0,refreshKey:Ye.status,onAttachFiles:Da,onAttach:async O=>{const se=T.sessionId,je=T.runId,Ie=Dt.current,Ve=await Ur.attachments_ingest(se,O);Ct.current.sessionId===se&&Ct.current.runId===je&&Dt.current===Ie&&He(Gt=>[...Gt,Ve])}})}),model:Du,workflow:Fu,workspace:ti,tools:zu,skills:Bu,voice:Wu}},`rail:${t}`);return a.jsxs("div",{className:`code-app${zs?" code-app--nav-open":""}`,children:[a.jsx("a",{className:"code-skip-link",href:"#code-conversation",children:"Skip to conversation"}),a.jsxs(EA,{isDrawer:Ss,open:zs,children:[a.jsxs("div",{className:"code-brand",children:[a.jsxs("span",{className:"code-brand-mark","aria-hidden":"true",children:["a",a.jsx("span",{children:"c"})]}),a.jsxs("div",{children:[a.jsx("strong",{children:"AbstractCode"}),a.jsx("span",{children:"YOUR WORK, IN CONTEXT"})]}),a.jsx("button",{className:"code-mobile-close code-icon-button","aria-label":"Close navigation",onClick:()=>Zt(!1),children:a.jsx(de,{name:"x",size:18})})]}),a.jsxs("div",{className:"code-session-search",children:[a.jsx(de,{name:"history",size:14}),a.jsx("input",{ref:Ns,"aria-label":"Search conversations",placeholder:"Search conversations",value:Uo,onChange:O=>Mu(O.target.value)}),a.jsx("kbd",{children:"⌘K"})]}),a.jsxs(PA,{panels:ja,children:[a.jsx(jI,{state:Bt,attention:Ca?{needsYou:II(js.fold),newResults:LI(js.fold)}:null,available:Bo,discovering:s.capabilitiesLoading,createDisabled:tt||!!ce||!B,selectedId:Wt?Bt.selectedId:"",onSelect:O=>{ds(!0),Zt(!1),Jt.select(O)},onNew:()=>Vr(!0),onRefresh:()=>void Jt.refresh(),archivedOpen:ir.automations,onToggleArchived:()=>Na("automations"),onUnarchive:O=>void Jt.unarchive(O.automation_id).catch(()=>{}),onToggleActive:O=>void Jt.toggleActive(O).catch(()=>{}),open:ja.automations,onToggle:()=>zo("automations")}),a.jsxs(DA,{open:ja.conversations,onToggle:()=>zo("conversations"),actions:a.jsxs("span",{className:"code-auto-actions",children:[a.jsx("button",{className:"code-icon-button code-new-chat","aria-label":"New conversation",title:"New conversation (⇧⌘N)","aria-keyshortcuts":"Shift+Meta+N",onClick:Yr,children:a.jsx(de,{name:"plus",size:13})}),a.jsx("button",{className:"code-icon-button","aria-label":"Refresh conversations",disabled:!e.connected||s.loading,onClick:()=>void s.refresh(),children:a.jsx(de,{name:"refresh",size:13})})]}),children:[fn?null:a.jsx("button",{type:"button",className:"code-session code-card is-selected",onClick:()=>Zt(!1),children:a.jsxs("span",{children:[a.jsx("strong",{className:"code-card-title",children:"New conversation"}),a.jsx("small",{className:"code-card-meta",children:"Ready when you are"})]})}),Xr.map(O=>a.jsx(r$,{item:O,selected:O.sessionId===T.sessionId,onClick:()=>ms(O.sessionId,O.latestRunId),onAskArchive:e.connected?()=>Gs(O.sessionId,"card"):void 0,confirm:(kn==null?void 0:kn.where)==="card"&&kn.sessionId===O.sessionId?kl:void 0},O.sessionId)),s.sessionsLoaded&&!Xr.length?a.jsx("p",{className:"code-history-empty",children:Uo?"No conversations match your search.":"Your conversations will live here. Pick up where you left off, on any device."}):null,s.loading&&!s.sessionsLoaded?a.jsx(To,{children:"Loading conversations…"}):null,s.hasMore?a.jsx("button",{className:"code-load-more",onClick:s.loadMore,children:"Load more conversations"}):null,a.jsx(X_,{list:"conversations",count:s.archivedSessions,open:ir.conversations,onToggle:()=>Na("conversations"),children:a.jsx(f$,{enabled:e.connected&&ir.conversations,revision:s.archivedSessions,onOpen:O=>{Zt(!1),ms(O.sessionId,O.latestRunId)},onUnarchived:()=>void s.refresh()})})]})]})]}),zs?a.jsx("button",{className:"code-nav-scrim","aria-label":"Close conversation navigation",onClick:()=>Zt(!1)}):null,a.jsxs("div",{className:"code-main-shell",children:[a.jsxs("header",{className:"code-topbar",children:[a.jsx("button",{className:"code-mobile-nav code-icon-button","aria-label":"Open conversation navigation",onClick:()=>{St(),Zt(!0)},children:a.jsx(de,{name:"list",size:19})}),a.jsxs("div",{className:"code-breadcrumb",children:[a.jsx("span",{children:Wt?"Automations":"Conversations"}),a.jsx("span",{"aria-hidden":"true",children:"/"}),a.jsx("strong",{title:Wt?hs:Hr,children:Wt?hs:Hr})]}),!Wt&&fn&&e.connected?a.jsx(Bh,{className:"code-conversation-menu",label:"Conversation actions",title:"More actions",items:[{id:"archive",label:"Archive",danger:!0,onSelect:()=>Gs(fn.sessionId,"header")}]}):null,a.jsx(wS,{docs:{open:Le==="docs",onToggle:()=>{Ke(O=>O==="docs"?null:"docs"),Zt(!1)},label:"Docs assistant"},appearance:{value:o,onChange:l},about:{identity:KI,fetch:ol},identity:"menu",connection:e})]}),a.jsxs("div",{className:"code-content",children:[Wt?a.jsx(AI,{prepareTarget:Kr,workflowPickerOptions:{interfaceId:ln,workflows:{...s.executable,reload:()=>void s.refresh()}},ctl:Jt,availableTools:s.tools.filter(O=>O.enabled).map(O=>O.name),host:Pa,voiceCapability:cr,voicePreferences:g,enabled:e.connected,onClose:()=>ds(!1),onEdit:qo,onEditWorkspaces:Yo}):a.jsxs("main",{className:"code-conversation",id:"code-conversation",tabIndex:-1,children:[oe||Ye.error||Fe?a.jsxs("div",{className:"code-alert",role:"alert",children:[a.jsx(de,{name:"warning",size:16}),a.jsx("span",{children:oe||Ye.error||Fe}),Ye.error||Fe?a.jsx("button",{onClick:()=>{Fe?window.location.reload():Tn(()=>Zn.load(T.runId))},children:"Reconnect"}):a.jsx("button",{"aria-label":"Dismiss error",onClick:()=>ve(""),children:a.jsx(de,{name:"x",size:14})})]}):null,(kn==null?void 0:kn.where)==="header"&&kn.sessionId===T.sessionId?a.jsx("div",{className:"code-archive-confirm-bar",children:kl}):null,s.errors.length?a.jsx("div",{className:"code-discovery-errors",role:"status",children:a.jsxs("details",{children:[a.jsx("summary",{children:"Some gateway information could not be loaded"}),s.errors.map(O=>a.jsx("p",{children:O},O)),a.jsx("button",{onClick:()=>void s.refresh(),children:"Retry discovery"})]})}):null,at?a.jsxs("div",{className:"code-alert",role:"alert",children:[a.jsx("span",{children:at}),a.jsx("button",{onClick:Yr,children:"New conversation"})]}):null,ce?a.jsxs("div",{className:"code-alert",role:"alert",children:[a.jsxs("span",{children:["Workflow inputs: ",ce]}),a.jsx("button",{onClick:()=>le(O=>O+1),children:"Retry"})]}):null,Ne?a.jsxs("div",{className:"code-notice",role:"status",children:[Ne,a.jsx("button",{"aria-label":"Dismiss notice",onClick:()=>q(""),children:a.jsx(de,{name:"x",size:13})})]}):null,Ut||nh(Ye.status)?a.jsx(UI,{active:Ut,paused:Ko,snapshot:Ye,permissionsAll:cT(s.toolCatalog,S),onInteraction:$n&&!Ko?()=>{var je;const O=document.querySelector(".code-conversation .pc-chat-thread"),se=O==null?void 0:O.querySelector(".pc-workflow-interaction");!O||!se||(O.scrollTop+=se.getBoundingClientRect().top-O.getBoundingClientRect().top,(je=se.querySelector("h3"))==null||je.focus({preventScroll:!0}))}:void 0,onRevokeApproval:()=>{Zn.revokeToolApproval(),E(uT(s.toolCatalog,S))},onCommand:O=>Tn(()=>Zn.sendCommand(O,{})),onActivity:()=>{jt("activity")}}):null,a.jsx(qE,{streamReplies:I,messages:($n==null?void 0:$n.kind)==="tool-approval"?Bs.filter(O=>{var se,je;return!(((se=O.toolActivity)==null?void 0:se.status)==="waiting"&&O.toolActivity.runId===((je=Ye.interaction)==null?void 0:je.runId))}):Bs,messageProps:{...dn.tts_supported?{onSpeakToggle:O=>{dn.toggle_tts(O.id||O.content,O.content)}}:{},getSpeakState:O=>dn.tts_playback.key===(O.id||O.content)?dn.tts_playback.status:"idle"},draft:ne,onDraftChange:ue,onSend:Qr,busy:Vt,busyLabel:be?"Starting…":Ko?"Paused":"Working…",steer:Xo,toolbar:Bs.length?{exportTranscript:{filename:"conversation.md"}}:void 0,onCancel:bl,stopState:Ye.stop??null,disabled:!e.connected,interaction:$n,onAttach:()=>{var O;return(O=qe.current)==null?void 0:O.click()},onFiles:O=>{Da(O)},attachmentItems:Jr,onRemoveAttachment:Pu,onRetryAttachment:xn.retry,placeholder:Ut?$n?"Answer the request above, or queue the next task…":"Guide the current workflow, or queue the next task…":"Describe what you want to build, fix, or explore…",emptyState:Ut?null:a.jsx(qI,{workflow:B,loading:s.loading||tt,onSuggestion:ue,onInputs:()=>Pt(!0),isAgent:dr,onRun:()=>Tn(()=>ps(ne)),connected:e.connected}),composerExtras:a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"code-composer-workspace",title:fr||"Workspace is managed by the gateway",children:[a.jsx(de,{name:"terminal",size:14}),a.jsx("span",{children:fr.split("/").filter(Boolean).pop()||"Gateway workspace"})]}),e.connected?a.jsx(pI,{voice:dn,capability:cr,preferences:g,route:vS(g,Gr.value)},`${t}:${T.sessionId}:${T.runId}`):null]}),footer:a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:["Enter to send ",a.jsx("span",{"aria-hidden":"true",children:"·"})," Shift + Enter for a new line"]}),a.jsxs("span",{children:["Managed workspace",a.jsx("span",{className:"code-small-dot"})]})]})}),Cs.length?a.jsxs("div",{className:"code-queue",children:[a.jsxs("div",{children:[a.jsxs("strong",{children:[Cs.length," queued"," ",Cs.length===1?"turn":"turns"]}),a.jsx(Wr,{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:Vo,onChange:Xn})]}),Cs.map(O=>a.jsxs("div",{children:[a.jsx("span",{children:O.text}),Ut?null:a.jsx("button",{onClick:()=>Tn(()=>Ba(O)),children:"Run next"}),a.jsx("button",{"aria-label":"Remove queued turn",onClick:()=>fs(se=>se.filter(je=>je.id!==O.id)),children:a.jsx(de,{name:"x",size:13})})]},O.id))]}):null]}),Uu]}),a.jsxs("footer",{className:"code-statusbar",children:[a.jsxs("span",{children:[a.jsx("span",{className:`code-status-dot ${e.connected?"is-online":""}`}),e.connected?"Connected":e.phase==="loading"?"Connecting":"Disconnected"]}),a.jsx("span",{children:(B==null?void 0:B.name)||"No workflow selected"}),a.jsx("div",{}),a.jsx("span",{children:T.runId?`Run ${T.runId.slice(0,8)}`:"Ready to start"}),a.jsx("span",{children:o.theme.replace(/-/g," ")})]})]}),a.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:xn.announcement}),a.jsx("input",{ref:qe,hidden:!0,type:"file",multiple:!0,onChange:O=>{Da(Array.from(O.target.files||[])),O.target.value=""}}),a.jsx($I,{connected:e.connected,workflowPickerOptions:{interfaceId:ln,workflows:{...s.executable,reload:()=>void s.refresh()}},open:lr,onClose:()=>Vr(!1),onOpenPreferences:()=>{Vr(!1),jt("workflow")},target:BR(L,B),availableTools:s.tools.filter(O=>O.enabled).map(O=>O.name),initialTools:ju(uu(s.toolCatalog,{app:S})?{...he,tools:Yc(s.toolCatalog,{app:S}).tools}:he),buildInput:async(O,se)=>{if(!se)return Vs(O,{...sr(ge),...he},[],!0);const je=se.flow_id==="@default"?J:s.workflows.find(bt=>`${bt.bundleId}@${bt.bundleVersion}`===("bundle_ref"in se?se.bundle_ref:"")&&bt.flowId===se.flow_id);if(!je)throw new Error("The selected workflow is no longer available. Refresh the workflow list.");const Ie=await Kf(je);if(!Ie)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const Ve=Vs(O,sr(Ie),[],!0,je,Ie),Gt=Uf(Ie,Ve);if(Gt.length)throw new Error(Gt.join(" "));return Ve},workflowLabel:L===Xt?I$(s.gatewayDefault):(B==null?void 0:B.name)||"the selected workflow",initialPrompt:ne||((ii=[...Bs].reverse().find(O=>O.role==="user"))==null?void 0:ii.content)||"",ctl:Jt,onOpenMyEmail:Oa,onCreated:()=>{ds(!0),Zt(!1)}}),a.jsx(Ik,{...e.modalProps}),a.jsx($A,{open:u,onClose:()=>d(!1),connected:e.connected,onChanged:p})]})}function qI({workflow:e,loading:t,onSuggestion:n,onInputs:s,isAgent:o,onRun:l,connected:u}){return a.jsxs("div",{className:"code-welcome",children:[a.jsxs("div",{className:"code-welcome-symbol","aria-hidden":"true",children:[a.jsx("span",{children:"›"}),a.jsx("span",{children:"_"})]}),a.jsx("p",{className:"code-eyebrow",children:"A LITTLE CONTEXT. A LOT OF POSSIBILITY."}),a.jsx("h1",{children:"What are we building?"}),a.jsxs("p",{className:"code-welcome-description",children:["A focused space to think, code, and get things done.",a.jsx("br",{}),"Your workflows. Your tools. One conversation."]}),e&&!o?a.jsxs("div",{className:"code-workflow-welcome",children:[a.jsx(de,{name:"playCircle",size:21}),a.jsxs("div",{children:[a.jsx("strong",{children:e.name}),a.jsx("p",{children:e.description||"Run this workflow with its registered inputs."})]}),a.jsx("button",{onClick:s,children:"Configure inputs"}),a.jsx("button",{onClick:l,disabled:t||!u,children:"Run workflow"})]}):a.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=>a.jsxs("button",{onClick:()=>n(d.prompt),disabled:t,children:[a.jsx(de,{name:d.icon,size:18}),a.jsxs("span",{children:[a.jsx("strong",{children:d.title}),a.jsx("small",{children:d.detail})]}),a.jsx(de,{name:"chevronRight",size:13})]},d.title))}),a.jsx("p",{className:"code-welcome-hint",children:t?"Discovering your workflows…":e?a.jsxs(a.Fragment,{children:["Using ",a.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 YI extends yt.Component{constructor(){super(...arguments);zt(this,"state",{error:""})}static getDerivedStateFromError(n){return{error:n.message}}render(){return this.state.error?a.jsxs("div",{className:"code-crash",role:"alert",children:[a.jsx("h1",{children:"Something interrupted this view."}),a.jsx("p",{children:this.state.error}),a.jsx("p",{children:"Your runs are stored by the gateway."}),a.jsx("button",{onClick:()=>window.location.reload(),children:"Reload AbstractCode"})]}):this.props.children}}Vx();CA();"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("sw.js").catch(()=>{})});Dx.createRoot(document.getElementById("root")).render(a.jsx(yt.StrictMode,{children:a.jsx(YI,{children:a.jsx(JI,{})})}));