@abstractframework/code 0.13.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,97 +0,0 @@
1
- var Rx=Object.defineProperty;var Ix=(e,t,n)=>t in e?Rx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bt=(e,t,n)=>Ix(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 jw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var mf={exports:{}},Ri={},pf={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 Ng;function Mx(){if(Ng)return nt;Ng=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 _(R){return R===null||typeof R!="object"?null:(R=g&&R[g]||R["@@iterator"],typeof R=="function"?R:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,x={};function k(R,K,se){this.props=R,this.context=K,this.refs=x,this.updater=se||v}k.prototype.isReactComponent={},k.prototype.setState=function(R,K){if(typeof R!="object"&&typeof R!="function"&&R!=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,R,K,"setState")},k.prototype.forceUpdate=function(R){this.updater.enqueueForceUpdate(this,R,"forceUpdate")};function j(){}j.prototype=k.prototype;function A(R,K,se){this.props=R,this.context=K,this.refs=x,this.updater=se||v}var T=A.prototype=new j;T.constructor=A,C(T,k.prototype),T.isPureReactComponent=!0;var N=Array.isArray,E=Object.prototype.hasOwnProperty,S={current:null},I={key:!0,ref:!0,__self:!0,__source:!0};function M(R,K,se){var ce,ae={},we=null,Se=null;if(K!=null)for(ce in K.ref!==void 0&&(Se=K.ref),K.key!==void 0&&(we=""+K.key),K)E.call(K,ce)&&!I.hasOwnProperty(ce)&&(ae[ce]=K[ce]);var Q=arguments.length-2;if(Q===1)ae.children=se;else if(1<Q){for(var xe=Array(Q),ve=0;ve<Q;ve++)xe[ve]=arguments[ve+2];ae.children=xe}if(R&&R.defaultProps)for(ce in Q=R.defaultProps,Q)ae[ce]===void 0&&(ae[ce]=Q[ce]);return{$$typeof:e,type:R,key:we,ref:Se,props:ae,_owner:S.current}}function B(R,K){return{$$typeof:e,type:R.type,key:K,ref:R.ref,props:R.props,_owner:R._owner}}function G(R){return typeof R=="object"&&R!==null&&R.$$typeof===e}function Z(R){var K={"=":"=0",":":"=2"};return"$"+R.replace(/[=:]/g,function(se){return K[se]})}var oe=/\/+/g;function z(R,K){return typeof R=="object"&&R!==null&&R.key!=null?Z(""+R.key):K.toString(36)}function F(R,K,se,ce,ae){var we=typeof R;(we==="undefined"||we==="boolean")&&(R=null);var Se=!1;if(R===null)Se=!0;else switch(we){case"string":case"number":Se=!0;break;case"object":switch(R.$$typeof){case e:case t:Se=!0}}if(Se)return Se=R,ae=ae(Se),R=ce===""?"."+z(Se,0):ce,N(ae)?(se="",R!=null&&(se=R.replace(oe,"$&/")+"/"),F(ae,K,se,"",function(ve){return ve})):ae!=null&&(G(ae)&&(ae=B(ae,se+(!ae.key||Se&&Se.key===ae.key?"":(""+ae.key).replace(oe,"$&/")+"/")+R)),K.push(ae)),1;if(Se=0,ce=ce===""?".":ce+":",N(R))for(var Q=0;Q<R.length;Q++){we=R[Q];var xe=ce+z(we,Q);Se+=F(we,K,se,xe,ae)}else if(xe=_(R),typeof xe=="function")for(R=xe.call(R),Q=0;!(we=R.next()).done;)we=we.value,xe=ce+z(we,Q++),Se+=F(we,K,se,xe,ae);else if(we==="object")throw K=String(R),Error("Objects are not valid as a React child (found: "+(K==="[object Object]"?"object with keys {"+Object.keys(R).join(", ")+"}":K)+"). If you meant to render a collection of children, use an array instead.");return Se}function L(R,K,se){if(R==null)return R;var ce=[],ae=0;return F(R,ce,"","",function(we){return K.call(se,we,ae++)}),ce}function q(R){if(R._status===-1){var K=R._result;K=K(),K.then(function(se){(R._status===0||R._status===-1)&&(R._status=1,R._result=se)},function(se){(R._status===0||R._status===-1)&&(R._status=2,R._result=se)}),R._status===-1&&(R._status=0,R._result=K)}if(R._status===1)return R._result.default;throw R._result}var V={current:null},Y={transition:null},J={ReactCurrentDispatcher:V,ReactCurrentBatchConfig:Y,ReactCurrentOwner:S};function W(){throw Error("act(...) is not supported in production builds of React.")}return nt.Children={map:L,forEach:function(R,K,se){L(R,function(){K.apply(this,arguments)},se)},count:function(R){var K=0;return L(R,function(){K++}),K},toArray:function(R){return L(R,function(K){return K})||[]},only:function(R){if(!G(R))throw Error("React.Children.only expected to receive a single React element child.");return R}},nt.Component=k,nt.Fragment=n,nt.Profiler=o,nt.PureComponent=A,nt.StrictMode=s,nt.Suspense=f,nt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=J,nt.act=W,nt.cloneElement=function(R,K,se){if(R==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+R+".");var ce=C({},R.props),ae=R.key,we=R.ref,Se=R._owner;if(K!=null){if(K.ref!==void 0&&(we=K.ref,Se=S.current),K.key!==void 0&&(ae=""+K.key),R.type&&R.type.defaultProps)var Q=R.type.defaultProps;for(xe in K)E.call(K,xe)&&!I.hasOwnProperty(xe)&&(ce[xe]=K[xe]===void 0&&Q!==void 0?Q[xe]:K[xe])}var xe=arguments.length-2;if(xe===1)ce.children=se;else if(1<xe){Q=Array(xe);for(var ve=0;ve<xe;ve++)Q[ve]=arguments[ve+2];ce.children=Q}return{$$typeof:e,type:R.type,key:ae,ref:we,props:ce,_owner:Se}},nt.createContext=function(R){return R={$$typeof:u,_currentValue:R,_currentValue2:R,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},R.Provider={$$typeof:l,_context:R},R.Consumer=R},nt.createElement=M,nt.createFactory=function(R){var K=M.bind(null,R);return K.type=R,K},nt.createRef=function(){return{current:null}},nt.forwardRef=function(R){return{$$typeof:d,render:R}},nt.isValidElement=G,nt.lazy=function(R){return{$$typeof:p,_payload:{_status:-1,_result:R},_init:q}},nt.memo=function(R,K){return{$$typeof:m,type:R,compare:K===void 0?null:K}},nt.startTransition=function(R){var K=Y.transition;Y.transition={};try{R()}finally{Y.transition=K}},nt.unstable_act=W,nt.useCallback=function(R,K){return V.current.useCallback(R,K)},nt.useContext=function(R){return V.current.useContext(R)},nt.useDebugValue=function(){},nt.useDeferredValue=function(R){return V.current.useDeferredValue(R)},nt.useEffect=function(R,K){return V.current.useEffect(R,K)},nt.useId=function(){return V.current.useId()},nt.useImperativeHandle=function(R,K,se){return V.current.useImperativeHandle(R,K,se)},nt.useInsertionEffect=function(R,K){return V.current.useInsertionEffect(R,K)},nt.useLayoutEffect=function(R,K){return V.current.useLayoutEffect(R,K)},nt.useMemo=function(R,K){return V.current.useMemo(R,K)},nt.useReducer=function(R,K,se){return V.current.useReducer(R,K,se)},nt.useRef=function(R){return V.current.useRef(R)},nt.useState=function(R){return V.current.useState(R)},nt.useSyncExternalStore=function(R,K,se){return V.current.useSyncExternalStore(R,K,se)},nt.useTransition=function(){return V.current.useTransition()},nt.version="18.3.1",nt}var Cg;function Uh(){return Cg||(Cg=1,pf.exports=Mx()),pf.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 Eg;function Lx(){if(Eg)return Ri;Eg=1;var e=Uh(),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 Ri.Fragment=n,Ri.jsx=u,Ri.jsxs=u,Ri}var Ag;function Ox(){return Ag||(Ag=1,mf.exports=Lx()),mf.exports}var a=Ox(),y=Uh();const wt=jw(y);var Mc={},gf={exports:{}},Dn={},yf={exports:{}},wf={};/**
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 $g;function Px(){return $g||($g=1,(function(e){function t(Y,J){var W=Y.length;Y.push(J);e:for(;0<W;){var R=W-1>>>1,K=Y[R];if(0<o(K,J))Y[R]=J,Y[W]=K,W=R;else break e}}function n(Y){return Y.length===0?null:Y[0]}function s(Y){if(Y.length===0)return null;var J=Y[0],W=Y.pop();if(W!==J){Y[0]=W;e:for(var R=0,K=Y.length,se=K>>>1;R<se;){var ce=2*(R+1)-1,ae=Y[ce],we=ce+1,Se=Y[we];if(0>o(ae,W))we<K&&0>o(Se,ae)?(Y[R]=Se,Y[we]=W,R=we):(Y[R]=ae,Y[ce]=W,R=ce);else if(we<K&&0>o(Se,W))Y[R]=Se,Y[we]=W,R=we;else break e}}return J}function o(Y,J){var W=Y.sortIndex-J.sortIndex;return W!==0?W:Y.id-J.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,j=typeof clearTimeout=="function"?clearTimeout:null,A=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(Y){for(var J=n(m);J!==null;){if(J.callback===null)s(m);else if(J.startTime<=Y)s(m),J.sortIndex=J.expirationTime,t(f,J);else break;J=n(m)}}function N(Y){if(x=!1,T(Y),!C)if(n(f)!==null)C=!0,q(E);else{var J=n(m);J!==null&&V(N,J.startTime-Y)}}function E(Y,J){C=!1,x&&(x=!1,j(M),M=-1),v=!0;var W=_;try{for(T(J),g=n(f);g!==null&&(!(g.expirationTime>J)||Y&&!Z());){var R=g.callback;if(typeof R=="function"){g.callback=null,_=g.priorityLevel;var K=R(g.expirationTime<=J);J=e.unstable_now(),typeof K=="function"?g.callback=K:g===n(f)&&s(f),T(J)}else s(f);g=n(f)}if(g!==null)var se=!0;else{var ce=n(m);ce!==null&&V(N,ce.startTime-J),se=!1}return se}finally{g=null,_=W,v=!1}}var S=!1,I=null,M=-1,B=5,G=-1;function Z(){return!(e.unstable_now()-G<B)}function oe(){if(I!==null){var Y=e.unstable_now();G=Y;var J=!0;try{J=I(!0,Y)}finally{J?z():(S=!1,I=null)}}else S=!1}var z;if(typeof A=="function")z=function(){A(oe)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,L=F.port2;F.port1.onmessage=oe,z=function(){L.postMessage(null)}}else z=function(){k(oe,0)};function q(Y){I=Y,S||(S=!0,z())}function V(Y,J){M=k(function(){Y(e.unstable_now())},J)}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,q(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"):B=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 J=3;break;default:J=_}var W=_;_=J;try{return Y()}finally{_=W}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(Y,J){switch(Y){case 1:case 2:case 3:case 4:case 5:break;default:Y=3}var W=_;_=Y;try{return J()}finally{_=W}},e.unstable_scheduleCallback=function(Y,J,W){var R=e.unstable_now();switch(typeof W=="object"&&W!==null?(W=W.delay,W=typeof W=="number"&&0<W?R+W:R):W=R,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:J,priorityLevel:Y,startTime:W,expirationTime:K,sortIndex:-1},W>R?(Y.sortIndex=W,t(m,Y),n(f)===null&&Y===n(m)&&(x?(j(M),M=-1):x=!0,V(N,W-R))):(Y.sortIndex=K,t(f,Y),C||v||(C=!0,q(E))),Y},e.unstable_shouldYield=Z,e.unstable_wrapCallback=function(Y){var J=_;return function(){var W=_;_=J;try{return Y.apply(this,arguments)}finally{_=W}}}})(wf)),wf}var Tg;function Dx(){return Tg||(Tg=1,yf.exports=Px()),yf.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 Rg;function Fx(){if(Rg)return Dn;Rg=1;var e=Uh(),t=Dx();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,$){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=$}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 j=/[\-:]([a-z])/g;function A(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(j,A);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(j,A);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(j,A);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 T(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"),S=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),M=Symbol.for("react.strict_mode"),B=Symbol.for("react.profiler"),G=Symbol.for("react.provider"),Z=Symbol.for("react.context"),oe=Symbol.for("react.forward_ref"),z=Symbol.for("react.suspense"),F=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),V=Symbol.for("react.offscreen"),Y=Symbol.iterator;function J(r){return r===null||typeof r!="object"?null:(r=Y&&r[Y]||r["@@iterator"],typeof r=="function"?r:null)}var W=Object.assign,R;function K(r){if(R===void 0)try{throw Error()}catch(c){var i=c.stack.trim().match(/\n( *(at )?)/);R=i&&i[1]||""}return`
34
- `+R+r}var se=!1;function ce(r,i){if(!r||se)return"";se=!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
- `),$=w.length-1,D=b.length-1;1<=$&&0<=D&&w[$]!==b[D];)D--;for(;1<=$&&0<=D;$--,D--)if(w[$]!==b[D]){if($!==1||D!==1)do if($--,D--,0>D||w[$]!==b[D]){var U=`
37
- `+w[$].replace(" at new "," at ");return r.displayName&&U.includes("<anonymous>")&&(U=U.replace("<anonymous>",r.displayName)),U}while(1<=$&&0<=D);break}}}finally{se=!1,Error.prepareStackTrace=c}return(r=r?r.displayName||r.name:"")?K(r):""}function ae(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=ce(r.type,!1),r;case 11:return r=ce(r.type.render,!1),r;case 1:return r=ce(r.type,!0),r;default:return""}}function we(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 S:return"Portal";case B:return"Profiler";case M:return"StrictMode";case z:return"Suspense";case F:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case Z:return(r.displayName||"Context")+".Consumer";case G:return(r._context.displayName||"Context")+".Provider";case oe:var i=r.render;return r=r.displayName,r||(r=i.displayName||i.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case L:return i=r.displayName||null,i!==null?i:we(r.type)||"Memo";case q:i=r._payload,r=r._init;try{return we(r(i))}catch{}}return null}function Se(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 we(i);case 8:return i===M?"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 xe(r){var i=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(i==="checkbox"||i==="radio")}function ve(r){var i=xe(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($){h=""+$,b.call(this,$)}}),Object.defineProperty(r,i,{enumerable:c.enumerable}),{getValue:function(){return h},setValue:function($){h=""+$},stopTracking:function(){r._valueTracker=null,delete r[i]}}}}function Fe(r){r._valueTracker||(r._valueTracker=ve(r))}function Xe(r){if(!r)return!1;var i=r._valueTracker;if(!i)return!0;var c=i.getValue(),h="";return r&&(h=xe(r)?r.checked?"true":"false":r.value),r=h,r!==c?(i.setValue(r),!0):!1}function Ve(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 Je(r,i){var c=i.checked;return W({},i,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:c??r._wrapperState.initialChecked})}function me(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 Me(r,i){i=i.checked,i!=null&&T(r,"checked",i,!1)}function st(r,i){Me(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")?$t(r,i.type,c):i.hasOwnProperty("defaultValue")&&$t(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 $t(r,i,c){(i!=="number"||Ve(r.ownerDocument)!==r)&&(c==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+c&&(r.defaultValue=""+c))}var le=Array.isArray;function de(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 je(r,i){if(i.dangerouslySetInnerHTML!=null)throw Error(n(91));return W({},i,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function _e(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(le(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 ge(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 te(r){var i=r.textContent;i===r._wrapperState.initialValue&&i!==""&&i!==null&&(r.value=i)}function be(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 P(r,i){return r==null||r==="http://www.w3.org/1999/xhtml"?be(i):r==="http://www.w3.org/2000/svg"&&i==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var ie,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(ie=ie||document.createElement("div"),ie.innerHTML="<svg>"+i.valueOf().toString()+"</svg>",i=ie.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;i.firstChild;)r.appendChild(i.firstChild)}});function Ae(r,i){if(i){var c=r.firstChild;if(c&&c===r.lastChild&&c.nodeType===3){c.nodeValue=i;return}}r.textContent=i}var Ye={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},$e=["Webkit","ms","Moz","O"];Object.keys(Ye).forEach(function(r){$e.forEach(function(i){i=i+r.charAt(0).toUpperCase()+r.substring(1),Ye[i]=Ye[r]})});function Ge(r,i,c){return i==null||typeof i=="boolean"||i===""?"":c||typeof i!="number"||i===0||Ye.hasOwnProperty(r)&&Ye[r]?(""+i).trim():i+"px"}function Ee(r,i){r=r.style;for(var c in i)if(i.hasOwnProperty(c)){var h=c.indexOf("--")===0,w=Ge(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 js(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Bo=null,Yn=null,zs=null;function Bs(r){if(r=yi(r)){if(typeof Bo!="function")throw Error(n(280));var i=r.stateNode;i&&(i=ql(i),Bo(r.stateNode,r.type,i))}}function Zt(r){Yn?zs?zs.push(r):zs=[r]:Yn=r}function ja(){if(Yn){var r=Yn,i=zs;if(zs=Yn=null,Bs(r),i)for(r=0;r<i.length;r++)Bs(i[r])}}function Wo(r,i){return r(i)}function lr(){}var Na=!1;function Uo(r,i,c){if(Na)return r(i,c);Na=!0;try{return Wo(r,i,c)}finally{Na=!1,(Yn!==null||zs!==null)&&(lr(),ja())}}function Ns(r,i){var c=r.stateNode;if(c===null)return null;var h=ql(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 Wt(r,i,c,h,w,b,$,D,U){var re=Array.prototype.slice.call(arguments,3);try{i.apply(c,re)}catch(he){this.onError(he)}}var Ut=!1,us=null,cr=!1,Gr=null,Vo={onError:function(r){Ut=!0,us=r}};function Go(r,i,c,h,w,b,$,D,U){Ut=!1,us=null,Wt.apply(Vo,arguments)}function Fu(r,i,c,h,w,b,$,D,U){if(Go.apply(this,arguments),Ut){if(Ut){var re=us;Ut=!1,us=null}else throw Error(n(198));cr||(cr=!0,Gr=re)}}function Cs(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 Es(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 ds(r){if(Cs(r)!==r)throw Error(n(188))}function Ho(r){var i=r.alternate;if(!i){if(i=Cs(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 ds(w),r;if(b===h)return ds(w),i;b=b.sibling}throw Error(n(188))}if(c.return!==h.return)c=w,h=b;else{for(var $=!1,D=w.child;D;){if(D===c){$=!0,c=w,h=b;break}if(D===h){$=!0,h=w,c=b;break}D=D.sibling}if(!$){for(D=b.child;D;){if(D===c){$=!0,c=b,h=w;break}if(D===h){$=!0,h=b,c=w;break}D=D.sibling}if(!$)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 Qn(r){return r=Ho(r),r!==null?Ko(r):null}function Ko(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var i=Ko(r);if(i!==null)return i;r=r.sibling}return null}var Ea=t.unstable_scheduleCallback,Aa=t.unstable_cancelCallback,zu=t.unstable_shouldYield,Jo=t.unstable_requestPaint,Nt=t.unstable_now,bl=t.unstable_getCurrentPriorityLevel,$a=t.unstable_ImmediatePriority,xl=t.unstable_UserBlockingPriority,Ta=t.unstable_NormalPriority,Xn=t.unstable_LowPriority,Qe=t.unstable_IdlePriority,As=null,Vt=null;function qo(r){if(Vt&&typeof Vt.onCommitFiberRoot=="function")try{Vt.onCommitFiberRoot(As,r,void 0,(r.current.flags&128)===128)}catch{}}var Gt=Math.clz32?Math.clz32:Ws,Ra=Math.log,Ia=Math.LN2;function Ws(r){return r>>>=0,r===0?32:31-(Ra(r)/Ia|0)|0}var fs=64,Hr=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 Zn(r,i){var c=r.pendingLanes;if(c===0)return 0;var h=0,w=r.suspendedLanes,b=r.pingedLanes,$=c&268435455;if($!==0){var D=$&~w;D!==0?h=dn(D):(b&=$,b!==0&&(h=dn(b)))}else $=c&~w,$!==0?h=dn($):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-Gt(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 Yo(r,i){for(var c=r.suspendedLanes,h=r.pingedLanes,w=r.expirationTimes,b=r.pendingLanes;0<b;){var $=31-Gt(b),D=1<<$,U=w[$];U===-1?((D&c)===0||(D&h)!==0)&&(w[$]=ur(D,i)):U<=i&&(r.expiredLanes|=D),b&=~D}}function Ma(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function Tn(){var r=fs;return fs<<=1,(fs&4194240)===0&&(fs=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-Gt(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-Gt(c),b=1<<w;i[w]=0,h[w]=-1,r[w]=-1,c&=~b}}function Us(r,i){var c=r.entangledLanes|=i;for(r=r.entanglements;c;){var h=31-Gt(c),w=1<<h;w&i|r[h]&i&&(r[h]|=i),c&=~w}}var ot=0;function fn(r){return r&=-r,1<r?4<r?(r&268435455)!==0?16:536870912:4:1}var Kr,La,Oa,Pa,Qo,Xo=!1,Jr=[],hs=null,es=null,Gn=null,Dt=new Map,Vs=new Map,Ct=[],kn="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 Zo(r,i){switch(r){case"focusin":case"focusout":hs=null;break;case"dragenter":case"dragleave":es=null;break;case"mouseover":case"mouseout":Gn=null;break;case"pointerover":case"pointerout":Dt.delete(i.pointerId);break;case"gotpointercapture":case"lostpointercapture":Vs.delete(i.pointerId)}}function qr(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=yi(i),i!==null&&La(i)),r):(r.eventSystemFlags|=h,i=r.targetContainers,w!==null&&i.indexOf(w)===-1&&i.push(w),r)}function Bu(r,i,c,h,w){switch(i){case"focusin":return hs=qr(hs,r,i,c,h,w),!0;case"dragenter":return es=qr(es,r,i,c,h,w),!0;case"mouseover":return Gn=qr(Gn,r,i,c,h,w),!0;case"pointerover":var b=w.pointerId;return Dt.set(b,qr(Dt.get(b)||null,r,i,c,h,w)),!0;case"gotpointercapture":return b=w.pointerId,Vs.set(b,qr(Vs.get(b)||null,r,i,c,h,w)),!0}return!1}function Da(r){var i=na(r.target);if(i!==null){var c=Cs(i);if(c!==null){if(i=c.tag,i===13){if(i=Es(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 Yr(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=yi(c),i!==null&&La(i),r.blockedOn=c,!1;i.shift()}return!0}function Fa(r,i,c){Yr(r)&&c.delete(i)}function Qr(){Xo=!1,hs!==null&&Yr(hs)&&(hs=null),es!==null&&Yr(es)&&(es=null),Gn!==null&&Yr(Gn)&&(Gn=null),Dt.forEach(Fa),Vs.forEach(Fa)}function ms(r,i){r.blockedOn===i&&(r.blockedOn=null,Xo||(Xo=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Qr)))}function Gs(r){function i(w){return ms(w,r)}if(0<Jr.length){ms(Jr[0],r);for(var c=1;c<Jr.length;c++){var h=Jr[c];h.blockedOn===r&&(h.blockedOn=null)}}for(hs!==null&&ms(hs,r),es!==null&&ms(es,r),Gn!==null&&ms(Gn,r),Dt.forEach(i),Vs.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 kl(r,i,c,h){var w=ot,b=ps.transition;ps.transition=null;try{ot=1,ei(r,i,c,h)}finally{ot=w,ps.transition=b}}function Sl(r,i,c,h){var w=ot,b=ps.transition;ps.transition=null;try{ot=4,ei(r,i,c,h)}finally{ot=w,ps.transition=b}}function ei(r,i,c,h){if(za){var w=Ba(r,i,c,h);if(w===null)sd(r,i,h,Xr,c),Zo(r,h);else if(Bu(w,r,i,c,h))h.stopPropagation();else if(Zo(r,h),i&4&&-1<kn.indexOf(r)){for(;w!==null;){var b=yi(w);if(b!==null&&Kr(b),b=Ba(r,i,c,h),b===null&&sd(r,i,h,Xr,c),b===w)break;w=b}w!==null&&h.stopPropagation()}else sd(r,i,h,null,c)}}var Xr=null;function Ba(r,i,c,h){if(Xr=null,r=js(h),r=na(r),r!==null)if(i=Cs(r),i===null)r=null;else if(c=i.tag,c===13){if(r=Es(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 Xr=r,null}function jl(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(bl()){case $a:return 1;case xl:return 4;case Ta:case Xn:return 16;case Qe:return 536870912;default:return 16}default:return 16}}var Rn=null,Zr=null,Sn=null;function Wa(){if(Sn)return Sn;var r,i=Zr,c=i.length,h,w="value"in Rn?Rn.value:Rn.textContent,b=w.length;for(r=0;r<c&&i[r]===w[r];r++);var $=c-r;for(h=1;h<=$&&i[c-h]===w[b-h];h++);return Sn=w.slice(r,1<h?1-h:void 0)}function ea(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 Nl(){return!1}function en(r){function i(c,h,w,b,$){this._reactName=c,this._targetInst=w,this.type=h,this.nativeEvent=b,this.target=$,this.currentTarget=null;for(var D in r)r.hasOwnProperty(D)&&(c=r[D],this[D]=c?c(b):b[D]);return this.isDefaultPrevented=(b.defaultPrevented!=null?b.defaultPrevented:b.returnValue===!1)?hr:Nl,this.isPropagationStopped=Nl,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 Hs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},ti=en(Hs),ta=W({},Hs,{view:0,detail:0}),Cl=en(ta),ni,ts,mr,vt=W({},ta,{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"?(ni=r.screenX-mr.screenX,ts=r.screenY-mr.screenY):ts=ni=0,mr=r),ni)},movementY:function(r){return"movementY"in r?r.movementY:ts}}),$s=en(vt),pr=W({},vt,{dataTransfer:0}),Wu=en(pr),Uu=W({},ta,{relatedTarget:0}),si=en(Uu),Vu=W({},Hs,{animationName:0,elapsedTime:0,pseudoElement:0}),Gu=en(Vu),Hu=W({},Hs,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),ri=en(Hu),El=W({},Hs,{data:0}),ai=en(El),Ku={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Al={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"},$l={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Tl(r){var i=this.nativeEvent;return i.getModifierState?i.getModifierState(r):(r=$l[r])?!!i[r]:!1}function Ua(){return Tl}var Rl=W({},ta,{key:function(r){if(r.key){var i=Ku[r.key]||r.key;if(i!=="Unidentified")return i}return r.type==="keypress"?(r=ea(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?Al[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"?ea(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?ea(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),Il=en(Rl),Ml=W({},vt,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),oi=en(Ml),Ll=W({},ta,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Ua}),Ol=en(Ll),Pl=W({},Hs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Dl=en(Pl),Fl=W({},vt,{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}),zl=en(Fl),Bl=[9,13,27,32],Va=d&&"CompositionEvent"in window,gr=null;d&&"documentMode"in document&&(gr=document.documentMode);var Wl=d&&"TextEvent"in window&&!gr,ii=d&&(!Va||gr&&8<gr&&11>=gr),li=" ",ci=!1;function ui(r,i){switch(r){case"keyup":return Bl.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function O(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var ne=!1;function Ne(r,i){switch(r){case"compositionend":return O(i);case"keypress":return i.which!==32?null:(ci=!0,li);case"textInput":return r=i.data,r===li&&ci?null:r;default:return null}}function Pe(r,i){if(ne)return r==="compositionend"||!Va&&ui(r,i)?(r=Wa(),Sn=Zr=Rn=null,ne=!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 ii&&i.locale!=="ko"?null:i.data;default:return null}}var He={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 Ft(r){var i=r&&r.nodeName&&r.nodeName.toLowerCase();return i==="input"?!!He[r.type]:i==="textarea"}function bt(r,i,c,h){Zt(h),i=Hl(i,"onChange"),0<i.length&&(c=new ti("onChange","change",null,c,h),r.push({event:c,listeners:i}))}var gs=null,ys=null;function yr(r){Wm(r,0)}function Ga(r){var i=Ya(r);if(Xe(i))return r}function Ts(r,i){if(r==="change")return i}var jm=!1;if(d){var Ju;if(d){var qu="oninput"in document;if(!qu){var Nm=document.createElement("div");Nm.setAttribute("oninput","return;"),qu=typeof Nm.oninput=="function"}Ju=qu}else Ju=!1;jm=Ju&&(!document.documentMode||9<document.documentMode)}function Cm(){gs&&(gs.detachEvent("onpropertychange",Em),ys=gs=null)}function Em(r){if(r.propertyName==="value"&&Ga(ys)){var i=[];bt(i,ys,r,js(r)),Uo(yr,i)}}function Mb(r,i,c){r==="focusin"?(Cm(),gs=i,ys=c,gs.attachEvent("onpropertychange",Em)):r==="focusout"&&Cm()}function Lb(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return Ga(ys)}function Ob(r,i){if(r==="click")return Ga(i)}function Pb(r,i){if(r==="input"||r==="change")return Ga(i)}function Db(r,i){return r===i&&(r!==0||1/r===1/i)||r!==r&&i!==i}var ws=typeof Object.is=="function"?Object.is:Db;function di(r,i){if(ws(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)||!ws(r[w],i[w]))return!1}return!0}function Am(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function $m(r,i){var c=Am(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=Am(c)}}function Tm(r,i){return r&&i?r===i?!0:r&&r.nodeType===3?!1:i&&i.nodeType===3?Tm(r,i.parentNode):"contains"in r?r.contains(i):r.compareDocumentPosition?!!(r.compareDocumentPosition(i)&16):!1:!1}function Rm(){for(var r=window,i=Ve();i instanceof r.HTMLIFrameElement;){try{var c=typeof i.contentWindow.location.href=="string"}catch{c=!1}if(c)r=i.contentWindow;else break;i=Ve(r.document)}return i}function Yu(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 Fb(r){var i=Rm(),c=r.focusedElem,h=r.selectionRange;if(i!==c&&c&&c.ownerDocument&&Tm(c.ownerDocument.documentElement,c)){if(h!==null&&Yu(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=$m(c,b);var $=$m(c,h);w&&$&&(r.rangeCount!==1||r.anchorNode!==w.node||r.anchorOffset!==w.offset||r.focusNode!==$.node||r.focusOffset!==$.offset)&&(i=i.createRange(),i.setStart(w.node,w.offset),r.removeAllRanges(),b>h?(r.addRange(i),r.extend($.node,$.offset)):(i.setEnd($.node,$.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 zb=d&&"documentMode"in document&&11>=document.documentMode,Ha=null,Qu=null,fi=null,Xu=!1;function Im(r,i,c){var h=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Xu||Ha==null||Ha!==Ve(h)||(h=Ha,"selectionStart"in h&&Yu(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}),fi&&di(fi,h)||(fi=h,h=Hl(Qu,"onSelect"),0<h.length&&(i=new ti("onSelect","select",null,i,c),r.push({event:i,listeners:h}),i.target=Ha)))}function Ul(r,i){var c={};return c[r.toLowerCase()]=i.toLowerCase(),c["Webkit"+r]="webkit"+i,c["Moz"+r]="moz"+i,c}var Ka={animationend:Ul("Animation","AnimationEnd"),animationiteration:Ul("Animation","AnimationIteration"),animationstart:Ul("Animation","AnimationStart"),transitionend:Ul("Transition","TransitionEnd")},Zu={},Mm={};d&&(Mm=document.createElement("div").style,"AnimationEvent"in window||(delete Ka.animationend.animation,delete Ka.animationiteration.animation,delete Ka.animationstart.animation),"TransitionEvent"in window||delete Ka.transitionend.transition);function Vl(r){if(Zu[r])return Zu[r];if(!Ka[r])return r;var i=Ka[r],c;for(c in i)if(i.hasOwnProperty(c)&&c in Mm)return Zu[r]=i[c];return r}var Lm=Vl("animationend"),Om=Vl("animationiteration"),Pm=Vl("animationstart"),Dm=Vl("transitionend"),Fm=new Map,zm="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){Fm.set(r,i),l(i,[r])}for(var ed=0;ed<zm.length;ed++){var td=zm[ed],Bb=td.toLowerCase(),Wb=td[0].toUpperCase()+td.slice(1);wr(Bb,"on"+Wb)}wr(Lm,"onAnimationEnd"),wr(Om,"onAnimationIteration"),wr(Pm,"onAnimationStart"),wr("dblclick","onDoubleClick"),wr("focusin","onFocus"),wr("focusout","onBlur"),wr(Dm,"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 hi="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(" "),Ub=new Set("cancel close invalid load scroll toggle".split(" ").concat(hi));function Bm(r,i,c){var h=r.type||"unknown-event";r.currentTarget=c,Fu(h,i,void 0,r),r.currentTarget=null}function Wm(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 $=h.length-1;0<=$;$--){var D=h[$],U=D.instance,re=D.currentTarget;if(D=D.listener,U!==b&&w.isPropagationStopped())break e;Bm(w,D,re),b=U}else for($=0;$<h.length;$++){if(D=h[$],U=D.instance,re=D.currentTarget,D=D.listener,U!==b&&w.isPropagationStopped())break e;Bm(w,D,re),b=U}}}if(cr)throw r=Gr,cr=!1,Gr=null,r}function xt(r,i){var c=i[cd];c===void 0&&(c=i[cd]=new Set);var h=r+"__bubble";c.has(h)||(Um(i,r,2,!1),c.add(h))}function nd(r,i,c){var h=0;i&&(h|=4),Um(c,r,h,i)}var Gl="_reactListening"+Math.random().toString(36).slice(2);function mi(r){if(!r[Gl]){r[Gl]=!0,s.forEach(function(c){c!=="selectionchange"&&(Ub.has(c)||nd(c,!1,r),nd(c,!0,r))});var i=r.nodeType===9?r:r.ownerDocument;i===null||i[Gl]||(i[Gl]=!0,nd("selectionchange",!1,i))}}function Um(r,i,c,h){switch(jl(i)){case 1:var w=kl;break;case 4:w=Sl;break;default:w=ei}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 sd(r,i,c,h,w){var b=h;if((i&1)===0&&(i&2)===0&&h!==null)e:for(;;){if(h===null)return;var $=h.tag;if($===3||$===4){var D=h.stateNode.containerInfo;if(D===w||D.nodeType===8&&D.parentNode===w)break;if($===4)for($=h.return;$!==null;){var U=$.tag;if((U===3||U===4)&&(U=$.stateNode.containerInfo,U===w||U.nodeType===8&&U.parentNode===w))return;$=$.return}for(;D!==null;){if($=na(D),$===null)return;if(U=$.tag,U===5||U===6){h=b=$;continue e}D=D.parentNode}}h=h.return}Uo(function(){var re=b,he=js(c),ye=[];e:{var fe=Fm.get(r);if(fe!==void 0){var Ce=ti,Ie=r;switch(r){case"keypress":if(ea(c)===0)break e;case"keydown":case"keyup":Ce=Il;break;case"focusin":Ie="focus",Ce=si;break;case"focusout":Ie="blur",Ce=si;break;case"beforeblur":case"afterblur":Ce=si;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=$s;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Ce=Wu;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Ce=Ol;break;case Lm:case Om:case Pm:Ce=Gu;break;case Dm:Ce=Dl;break;case"scroll":Ce=Cl;break;case"wheel":Ce=zl;break;case"copy":case"cut":case"paste":Ce=ri;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Ce=oi}var Le=(i&4)!==0,zt=!Le&&r==="scroll",X=Le?fe!==null?fe+"Capture":null:fe;Le=[];for(var H=re,ee;H!==null;){ee=H;var ke=ee.stateNode;if(ee.tag===5&&ke!==null&&(ee=ke,X!==null&&(ke=Ns(H,X),ke!=null&&Le.push(pi(H,ke,ee)))),zt)break;H=H.return}0<Le.length&&(fe=new Ce(fe,Ie,null,c,he),ye.push({event:fe,listeners:Le}))}}if((i&7)===0){e:{if(fe=r==="mouseover"||r==="pointerover",Ce=r==="mouseout"||r==="pointerout",fe&&c!==Pt&&(Ie=c.relatedTarget||c.fromElement)&&(na(Ie)||Ie[Ks]))break e;if((Ce||fe)&&(fe=he.window===he?he:(fe=he.ownerDocument)?fe.defaultView||fe.parentWindow:window,Ce?(Ie=c.relatedTarget||c.toElement,Ce=re,Ie=Ie?na(Ie):null,Ie!==null&&(zt=Cs(Ie),Ie!==zt||Ie.tag!==5&&Ie.tag!==6)&&(Ie=null)):(Ce=null,Ie=re),Ce!==Ie)){if(Le=$s,ke="onMouseLeave",X="onMouseEnter",H="mouse",(r==="pointerout"||r==="pointerover")&&(Le=oi,ke="onPointerLeave",X="onPointerEnter",H="pointer"),zt=Ce==null?fe:Ya(Ce),ee=Ie==null?fe:Ya(Ie),fe=new Le(ke,H+"leave",Ce,c,he),fe.target=zt,fe.relatedTarget=ee,ke=null,na(he)===re&&(Le=new Le(X,H+"enter",Ie,c,he),Le.target=ee,Le.relatedTarget=zt,ke=Le),zt=ke,Ce&&Ie)t:{for(Le=Ce,X=Ie,H=0,ee=Le;ee;ee=Ja(ee))H++;for(ee=0,ke=X;ke;ke=Ja(ke))ee++;for(;0<H-ee;)Le=Ja(Le),H--;for(;0<ee-H;)X=Ja(X),ee--;for(;H--;){if(Le===X||X!==null&&Le===X.alternate)break t;Le=Ja(Le),X=Ja(X)}Le=null}else Le=null;Ce!==null&&Vm(ye,fe,Ce,Le,!1),Ie!==null&&zt!==null&&Vm(ye,zt,Ie,Le,!0)}}e:{if(fe=re?Ya(re):window,Ce=fe.nodeName&&fe.nodeName.toLowerCase(),Ce==="select"||Ce==="input"&&fe.type==="file")var De=Ts;else if(Ft(fe))if(jm)De=Pb;else{De=Lb;var Be=Mb}else(Ce=fe.nodeName)&&Ce.toLowerCase()==="input"&&(fe.type==="checkbox"||fe.type==="radio")&&(De=Ob);if(De&&(De=De(r,re))){bt(ye,De,c,he);break e}Be&&Be(r,fe,re),r==="focusout"&&(Be=fe._wrapperState)&&Be.controlled&&fe.type==="number"&&$t(fe,"number",fe.value)}switch(Be=re?Ya(re):window,r){case"focusin":(Ft(Be)||Be.contentEditable==="true")&&(Ha=Be,Qu=re,fi=null);break;case"focusout":fi=Qu=Ha=null;break;case"mousedown":Xu=!0;break;case"contextmenu":case"mouseup":case"dragend":Xu=!1,Im(ye,c,he);break;case"selectionchange":if(zb)break;case"keydown":case"keyup":Im(ye,c,he)}var We;if(Va)e:{switch(r){case"compositionstart":var qe="onCompositionStart";break e;case"compositionend":qe="onCompositionEnd";break e;case"compositionupdate":qe="onCompositionUpdate";break e}qe=void 0}else ne?ui(r,c)&&(qe="onCompositionEnd"):r==="keydown"&&c.keyCode===229&&(qe="onCompositionStart");qe&&(ii&&c.locale!=="ko"&&(ne||qe!=="onCompositionStart"?qe==="onCompositionEnd"&&ne&&(We=Wa()):(Rn=he,Zr="value"in Rn?Rn.value:Rn.textContent,ne=!0)),Be=Hl(re,qe),0<Be.length&&(qe=new ai(qe,r,null,c,he),ye.push({event:qe,listeners:Be}),We?qe.data=We:(We=O(c),We!==null&&(qe.data=We)))),(We=Wl?Ne(r,c):Pe(r,c))&&(re=Hl(re,"onBeforeInput"),0<re.length&&(he=new ai("onBeforeInput","beforeinput",null,c,he),ye.push({event:he,listeners:re}),he.data=We))}Wm(ye,i)})}function pi(r,i,c){return{instance:r,listener:i,currentTarget:c}}function Hl(r,i){for(var c=i+"Capture",h=[];r!==null;){var w=r,b=w.stateNode;w.tag===5&&b!==null&&(w=b,b=Ns(r,c),b!=null&&h.unshift(pi(r,b,w)),b=Ns(r,i),b!=null&&h.push(pi(r,b,w))),r=r.return}return h}function Ja(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function Vm(r,i,c,h,w){for(var b=i._reactName,$=[];c!==null&&c!==h;){var D=c,U=D.alternate,re=D.stateNode;if(U!==null&&U===h)break;D.tag===5&&re!==null&&(D=re,w?(U=Ns(c,b),U!=null&&$.unshift(pi(c,U,D))):w||(U=Ns(c,b),U!=null&&$.push(pi(c,U,D)))),c=c.return}$.length!==0&&r.push({event:i,listeners:$})}var Vb=/\r\n?/g,Gb=/\u0000|\uFFFD/g;function Gm(r){return(typeof r=="string"?r:""+r).replace(Vb,`
38
- `).replace(Gb,"")}function Kl(r,i,c){if(i=Gm(i),Gm(r)!==i&&c)throw Error(n(425))}function Jl(){}var rd=null,ad=null;function od(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 id=typeof setTimeout=="function"?setTimeout:void 0,Hb=typeof clearTimeout=="function"?clearTimeout:void 0,Hm=typeof Promise=="function"?Promise:void 0,Kb=typeof queueMicrotask=="function"?queueMicrotask:typeof Hm<"u"?function(r){return Hm.resolve(null).then(r).catch(Jb)}:id;function Jb(r){setTimeout(function(){throw r})}function ld(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),Gs(i);return}h--}else c!=="$"&&c!=="$?"&&c!=="$!"||h++;c=w}while(c);Gs(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 Km(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 qa=Math.random().toString(36).slice(2),Rs="__reactFiber$"+qa,gi="__reactProps$"+qa,Ks="__reactContainer$"+qa,cd="__reactEvents$"+qa,qb="__reactListeners$"+qa,Yb="__reactHandles$"+qa;function na(r){var i=r[Rs];if(i)return i;for(var c=r.parentNode;c;){if(i=c[Ks]||c[Rs]){if(c=i.alternate,i.child!==null||c!==null&&c.child!==null)for(r=Km(r);r!==null;){if(c=r[Rs])return c;r=Km(r)}return i}r=c,c=r.parentNode}return null}function yi(r){return r=r[Rs]||r[Ks],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function Ya(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(n(33))}function ql(r){return r[gi]||null}var ud=[],Qa=-1;function _r(r){return{current:r}}function kt(r){0>Qa||(r.current=ud[Qa],ud[Qa]=null,Qa--)}function _t(r,i){Qa++,ud[Qa]=r.current,r.current=i}var br={},hn=_r(br),In=_r(!1),sa=br;function Xa(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 Mn(r){return r=r.childContextTypes,r!=null}function Yl(){kt(In),kt(hn)}function Jm(r,i,c){if(hn.current!==br)throw Error(n(168));_t(hn,i),_t(In,c)}function qm(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,Se(r)||"Unknown",w));return W({},c,h)}function Ql(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||br,sa=hn.current,_t(hn,r),_t(In,In.current),!0}function Ym(r,i,c){var h=r.stateNode;if(!h)throw Error(n(169));c?(r=qm(r,i,sa),h.__reactInternalMemoizedMergedChildContext=r,kt(In),kt(hn),_t(hn,r)):kt(In),_t(In,c)}var Js=null,Xl=!1,dd=!1;function Qm(r){Js===null?Js=[r]:Js.push(r)}function Qb(r){Xl=!0,Qm(r)}function xr(){if(!dd&&Js!==null){dd=!0;var r=0,i=ot;try{var c=Js;for(ot=1;r<c.length;r++){var h=c[r];do h=h(!0);while(h!==null)}Js=null,Xl=!1}catch(w){throw Js!==null&&(Js=Js.slice(r+1)),Ea($a,xr),w}finally{ot=i,dd=!1}}return null}var Za=[],eo=0,Zl=null,ec=0,ns=[],ss=0,ra=null,qs=1,Ys="";function aa(r,i){Za[eo++]=ec,Za[eo++]=Zl,Zl=r,ec=i}function Xm(r,i,c){ns[ss++]=qs,ns[ss++]=Ys,ns[ss++]=ra,ra=r;var h=qs;r=Ys;var w=32-Gt(h)-1;h&=~(1<<w),c+=1;var b=32-Gt(i)+w;if(30<b){var $=w-w%5;b=(h&(1<<$)-1).toString(32),h>>=$,w-=$,qs=1<<32-Gt(i)+w|c<<w|h,Ys=b+r}else qs=1<<b|c<<w|h,Ys=r}function fd(r){r.return!==null&&(aa(r,1),Xm(r,1,0))}function hd(r){for(;r===Zl;)Zl=Za[--eo],Za[eo]=null,ec=Za[--eo],Za[eo]=null;for(;r===ra;)ra=ns[--ss],ns[ss]=null,Ys=ns[--ss],ns[ss]=null,qs=ns[--ss],ns[ss]=null}var Hn=null,Kn=null,Et=!1,vs=null;function Zm(r,i){var c=is(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 ep(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,Hn=r,Kn=vr(i.firstChild),!0):!1;case 6:return i=r.pendingProps===""||i.nodeType!==3?null:i,i!==null?(r.stateNode=i,Hn=r,Kn=null,!0):!1;case 13:return i=i.nodeType!==8?null:i,i!==null?(c=ra!==null?{id:qs,overflow:Ys}:null,r.memoizedState={dehydrated:i,treeContext:c,retryLane:1073741824},c=is(18,null,null,0),c.stateNode=i,c.return=r,r.child=c,Hn=r,Kn=null,!0):!1;default:return!1}}function md(r){return(r.mode&1)!==0&&(r.flags&128)===0}function pd(r){if(Et){var i=Kn;if(i){var c=i;if(!ep(r,i)){if(md(r))throw Error(n(418));i=vr(c.nextSibling);var h=Hn;i&&ep(r,i)?Zm(h,c):(r.flags=r.flags&-4097|2,Et=!1,Hn=r)}}else{if(md(r))throw Error(n(418));r.flags=r.flags&-4097|2,Et=!1,Hn=r}}}function tp(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;Hn=r}function tc(r){if(r!==Hn)return!1;if(!Et)return tp(r),Et=!0,!1;var i;if((i=r.tag!==3)&&!(i=r.tag!==5)&&(i=r.type,i=i!=="head"&&i!=="body"&&!od(r.type,r.memoizedProps)),i&&(i=Kn)){if(md(r))throw np(),Error(n(418));for(;i;)Zm(r,i),i=vr(i.nextSibling)}if(tp(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){Kn=vr(r.nextSibling);break e}i--}else c!=="$"&&c!=="$!"&&c!=="$?"||i++}r=r.nextSibling}Kn=null}}else Kn=Hn?vr(r.stateNode.nextSibling):null;return!0}function np(){for(var r=Kn;r;)r=vr(r.nextSibling)}function to(){Kn=Hn=null,Et=!1}function gd(r){vs===null?vs=[r]:vs.push(r)}var Xb=N.ReactCurrentBatchConfig;function wi(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($){var D=w.refs;$===null?delete D[b]:D[b]=$},i._stringRef=b,i)}if(typeof r!="string")throw Error(n(284));if(!c._owner)throw Error(n(290,r))}return r}function nc(r,i){throw r=Object.prototype.toString.call(i),Error(n(31,r==="[object Object]"?"object with keys {"+Object.keys(i).join(", ")+"}":r))}function sp(r){var i=r._init;return i(r._payload)}function rp(r){function i(X,H){if(r){var ee=X.deletions;ee===null?(X.deletions=[H],X.flags|=16):ee.push(H)}}function c(X,H){if(!r)return null;for(;H!==null;)i(X,H),H=H.sibling;return null}function h(X,H){for(X=new Map;H!==null;)H.key!==null?X.set(H.key,H):X.set(H.index,H),H=H.sibling;return X}function w(X,H){return X=$r(X,H),X.index=0,X.sibling=null,X}function b(X,H,ee){return X.index=ee,r?(ee=X.alternate,ee!==null?(ee=ee.index,ee<H?(X.flags|=2,H):ee):(X.flags|=2,H)):(X.flags|=1048576,H)}function $(X){return r&&X.alternate===null&&(X.flags|=2),X}function D(X,H,ee,ke){return H===null||H.tag!==6?(H=lf(ee,X.mode,ke),H.return=X,H):(H=w(H,ee),H.return=X,H)}function U(X,H,ee,ke){var De=ee.type;return De===I?he(X,H,ee.props.children,ke,ee.key):H!==null&&(H.elementType===De||typeof De=="object"&&De!==null&&De.$$typeof===q&&sp(De)===H.type)?(ke=w(H,ee.props),ke.ref=wi(X,H,ee),ke.return=X,ke):(ke=Nc(ee.type,ee.key,ee.props,null,X.mode,ke),ke.ref=wi(X,H,ee),ke.return=X,ke)}function re(X,H,ee,ke){return H===null||H.tag!==4||H.stateNode.containerInfo!==ee.containerInfo||H.stateNode.implementation!==ee.implementation?(H=cf(ee,X.mode,ke),H.return=X,H):(H=w(H,ee.children||[]),H.return=X,H)}function he(X,H,ee,ke,De){return H===null||H.tag!==7?(H=ha(ee,X.mode,ke,De),H.return=X,H):(H=w(H,ee),H.return=X,H)}function ye(X,H,ee){if(typeof H=="string"&&H!==""||typeof H=="number")return H=lf(""+H,X.mode,ee),H.return=X,H;if(typeof H=="object"&&H!==null){switch(H.$$typeof){case E:return ee=Nc(H.type,H.key,H.props,null,X.mode,ee),ee.ref=wi(X,null,H),ee.return=X,ee;case S:return H=cf(H,X.mode,ee),H.return=X,H;case q:var ke=H._init;return ye(X,ke(H._payload),ee)}if(le(H)||J(H))return H=ha(H,X.mode,ee,null),H.return=X,H;nc(X,H)}return null}function fe(X,H,ee,ke){var De=H!==null?H.key:null;if(typeof ee=="string"&&ee!==""||typeof ee=="number")return De!==null?null:D(X,H,""+ee,ke);if(typeof ee=="object"&&ee!==null){switch(ee.$$typeof){case E:return ee.key===De?U(X,H,ee,ke):null;case S:return ee.key===De?re(X,H,ee,ke):null;case q:return De=ee._init,fe(X,H,De(ee._payload),ke)}if(le(ee)||J(ee))return De!==null?null:he(X,H,ee,ke,null);nc(X,ee)}return null}function Ce(X,H,ee,ke,De){if(typeof ke=="string"&&ke!==""||typeof ke=="number")return X=X.get(ee)||null,D(H,X,""+ke,De);if(typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case E:return X=X.get(ke.key===null?ee:ke.key)||null,U(H,X,ke,De);case S:return X=X.get(ke.key===null?ee:ke.key)||null,re(H,X,ke,De);case q:var Be=ke._init;return Ce(X,H,ee,Be(ke._payload),De)}if(le(ke)||J(ke))return X=X.get(ee)||null,he(H,X,ke,De,null);nc(H,ke)}return null}function Ie(X,H,ee,ke){for(var De=null,Be=null,We=H,qe=H=0,sn=null;We!==null&&qe<ee.length;qe++){We.index>qe?(sn=We,We=null):sn=We.sibling;var lt=fe(X,We,ee[qe],ke);if(lt===null){We===null&&(We=sn);break}r&&We&&lt.alternate===null&&i(X,We),H=b(lt,H,qe),Be===null?De=lt:Be.sibling=lt,Be=lt,We=sn}if(qe===ee.length)return c(X,We),Et&&aa(X,qe),De;if(We===null){for(;qe<ee.length;qe++)We=ye(X,ee[qe],ke),We!==null&&(H=b(We,H,qe),Be===null?De=We:Be.sibling=We,Be=We);return Et&&aa(X,qe),De}for(We=h(X,We);qe<ee.length;qe++)sn=Ce(We,X,qe,ee[qe],ke),sn!==null&&(r&&sn.alternate!==null&&We.delete(sn.key===null?qe:sn.key),H=b(sn,H,qe),Be===null?De=sn:Be.sibling=sn,Be=sn);return r&&We.forEach(function(Tr){return i(X,Tr)}),Et&&aa(X,qe),De}function Le(X,H,ee,ke){var De=J(ee);if(typeof De!="function")throw Error(n(150));if(ee=De.call(ee),ee==null)throw Error(n(151));for(var Be=De=null,We=H,qe=H=0,sn=null,lt=ee.next();We!==null&&!lt.done;qe++,lt=ee.next()){We.index>qe?(sn=We,We=null):sn=We.sibling;var Tr=fe(X,We,lt.value,ke);if(Tr===null){We===null&&(We=sn);break}r&&We&&Tr.alternate===null&&i(X,We),H=b(Tr,H,qe),Be===null?De=Tr:Be.sibling=Tr,Be=Tr,We=sn}if(lt.done)return c(X,We),Et&&aa(X,qe),De;if(We===null){for(;!lt.done;qe++,lt=ee.next())lt=ye(X,lt.value,ke),lt!==null&&(H=b(lt,H,qe),Be===null?De=lt:Be.sibling=lt,Be=lt);return Et&&aa(X,qe),De}for(We=h(X,We);!lt.done;qe++,lt=ee.next())lt=Ce(We,X,qe,lt.value,ke),lt!==null&&(r&&lt.alternate!==null&&We.delete(lt.key===null?qe:lt.key),H=b(lt,H,qe),Be===null?De=lt:Be.sibling=lt,Be=lt);return r&&We.forEach(function(Tx){return i(X,Tx)}),Et&&aa(X,qe),De}function zt(X,H,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 De=ee.key,Be=H;Be!==null;){if(Be.key===De){if(De=ee.type,De===I){if(Be.tag===7){c(X,Be.sibling),H=w(Be,ee.props.children),H.return=X,X=H;break e}}else if(Be.elementType===De||typeof De=="object"&&De!==null&&De.$$typeof===q&&sp(De)===Be.type){c(X,Be.sibling),H=w(Be,ee.props),H.ref=wi(X,Be,ee),H.return=X,X=H;break e}c(X,Be);break}else i(X,Be);Be=Be.sibling}ee.type===I?(H=ha(ee.props.children,X.mode,ke,ee.key),H.return=X,X=H):(ke=Nc(ee.type,ee.key,ee.props,null,X.mode,ke),ke.ref=wi(X,H,ee),ke.return=X,X=ke)}return $(X);case S:e:{for(Be=ee.key;H!==null;){if(H.key===Be)if(H.tag===4&&H.stateNode.containerInfo===ee.containerInfo&&H.stateNode.implementation===ee.implementation){c(X,H.sibling),H=w(H,ee.children||[]),H.return=X,X=H;break e}else{c(X,H);break}else i(X,H);H=H.sibling}H=cf(ee,X.mode,ke),H.return=X,X=H}return $(X);case q:return Be=ee._init,zt(X,H,Be(ee._payload),ke)}if(le(ee))return Ie(X,H,ee,ke);if(J(ee))return Le(X,H,ee,ke);nc(X,ee)}return typeof ee=="string"&&ee!==""||typeof ee=="number"?(ee=""+ee,H!==null&&H.tag===6?(c(X,H.sibling),H=w(H,ee),H.return=X,X=H):(c(X,H),H=lf(ee,X.mode,ke),H.return=X,X=H),$(X)):c(X,H)}return zt}var no=rp(!0),ap=rp(!1),sc=_r(null),rc=null,so=null,yd=null;function wd(){yd=so=rc=null}function vd(r){var i=sc.current;kt(sc),r._currentValue=i}function _d(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 ro(r,i){rc=r,yd=so=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&i)!==0&&(Ln=!0),r.firstContext=null)}function rs(r){var i=r._currentValue;if(yd!==r)if(r={context:r,memoizedValue:i,next:null},so===null){if(rc===null)throw Error(n(308));so=r,rc.dependencies={lanes:0,firstContext:r}}else so=so.next=r;return i}var oa=null;function bd(r){oa===null?oa=[r]:oa.push(r)}function op(r,i,c,h){var w=i.interleaved;return w===null?(c.next=c,bd(i)):(c.next=w.next,w.next=c),i.interleaved=c,Qs(r,h)}function Qs(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 xd(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ip(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 Xs(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,Qs(r,c)}return w=h.interleaved,w===null?(i.next=i,bd(h)):(i.next=w.next,w.next=i),h.interleaved=i,Qs(r,c)}function ac(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,Us(r,c)}}function lp(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 $={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};b===null?w=b=$:b=b.next=$,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 oc(r,i,c,h){var w=r.updateQueue;kr=!1;var b=w.firstBaseUpdate,$=w.lastBaseUpdate,D=w.shared.pending;if(D!==null){w.shared.pending=null;var U=D,re=U.next;U.next=null,$===null?b=re:$.next=re,$=U;var he=r.alternate;he!==null&&(he=he.updateQueue,D=he.lastBaseUpdate,D!==$&&(D===null?he.firstBaseUpdate=re:D.next=re,he.lastBaseUpdate=U))}if(b!==null){var ye=w.baseState;$=0,he=re=U=null,D=b;do{var fe=D.lane,Ce=D.eventTime;if((h&fe)===fe){he!==null&&(he=he.next={eventTime:Ce,lane:0,tag:D.tag,payload:D.payload,callback:D.callback,next:null});e:{var Ie=r,Le=D;switch(fe=i,Ce=c,Le.tag){case 1:if(Ie=Le.payload,typeof Ie=="function"){ye=Ie.call(Ce,ye,fe);break e}ye=Ie;break e;case 3:Ie.flags=Ie.flags&-65537|128;case 0:if(Ie=Le.payload,fe=typeof Ie=="function"?Ie.call(Ce,ye,fe):Ie,fe==null)break e;ye=W({},ye,fe);break e;case 2:kr=!0}}D.callback!==null&&D.lane!==0&&(r.flags|=64,fe=w.effects,fe===null?w.effects=[D]:fe.push(D))}else Ce={eventTime:Ce,lane:fe,tag:D.tag,payload:D.payload,callback:D.callback,next:null},he===null?(re=he=Ce,U=ye):he=he.next=Ce,$|=fe;if(D=D.next,D===null){if(D=w.shared.pending,D===null)break;fe=D,D=fe.next,fe.next=null,w.lastBaseUpdate=fe,w.shared.pending=null}}while(!0);if(he===null&&(U=ye),w.baseState=U,w.firstBaseUpdate=re,w.lastBaseUpdate=he,i=w.shared.interleaved,i!==null){w=i;do $|=w.lane,w=w.next;while(w!==i)}else b===null&&(w.shared.lanes=0);ca|=$,r.lanes=$,r.memoizedState=ye}}function cp(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 vi={},Is=_r(vi),_i=_r(vi),bi=_r(vi);function ia(r){if(r===vi)throw Error(n(174));return r}function kd(r,i){switch(_t(bi,i),_t(_i,r),_t(Is,vi),r=i.nodeType,r){case 9:case 11:i=(i=i.documentElement)?i.namespaceURI:P(null,"");break;default:r=r===8?i.parentNode:i,i=r.namespaceURI||null,r=r.tagName,i=P(i,r)}kt(Is),_t(Is,i)}function ao(){kt(Is),kt(_i),kt(bi)}function up(r){ia(bi.current);var i=ia(Is.current),c=P(i,r.type);i!==c&&(_t(_i,r),_t(Is,c))}function Sd(r){_i.current===r&&(kt(Is),kt(_i))}var Tt=_r(0);function ic(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 jd=[];function Nd(){for(var r=0;r<jd.length;r++)jd[r]._workInProgressVersionPrimary=null;jd.length=0}var lc=N.ReactCurrentDispatcher,Cd=N.ReactCurrentBatchConfig,la=0,Rt=null,qt=null,tn=null,cc=!1,xi=!1,ki=0,Zb=0;function mn(){throw Error(n(321))}function Ed(r,i){if(i===null)return!1;for(var c=0;c<i.length&&c<r.length;c++)if(!ws(r[c],i[c]))return!1;return!0}function Ad(r,i,c,h,w,b){if(la=b,Rt=i,i.memoizedState=null,i.updateQueue=null,i.lanes=0,lc.current=r===null||r.memoizedState===null?sx:rx,r=c(h,w),xi){b=0;do{if(xi=!1,ki=0,25<=b)throw Error(n(301));b+=1,tn=qt=null,i.updateQueue=null,lc.current=ax,r=c(h,w)}while(xi)}if(lc.current=fc,i=qt!==null&&qt.next!==null,la=0,tn=qt=Rt=null,cc=!1,i)throw Error(n(300));return r}function $d(){var r=ki!==0;return ki=0,r}function Ms(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return tn===null?Rt.memoizedState=tn=r:tn=tn.next=r,tn}function as(){if(qt===null){var r=Rt.alternate;r=r!==null?r.memoizedState:null}else r=qt.next;var i=tn===null?Rt.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?Rt.memoizedState=tn=r:tn=tn.next=r}return tn}function Si(r,i){return typeof i=="function"?i(r):i}function Td(r){var i=as(),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 $=w.next;w.next=b.next,b.next=$}h.baseQueue=w=b,c.pending=null}if(w!==null){b=w.next,h=h.baseState;var D=$=null,U=null,re=b;do{var he=re.lane;if((la&he)===he)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:he,action:re.action,hasEagerState:re.hasEagerState,eagerState:re.eagerState,next:null};U===null?(D=U=ye,$=h):U=U.next=ye,Rt.lanes|=he,ca|=he}re=re.next}while(re!==null&&re!==b);U===null?$=h:U.next=D,ws(h,i.memoizedState)||(Ln=!0),i.memoizedState=h,i.baseState=$,i.baseQueue=U,c.lastRenderedState=h}if(r=c.interleaved,r!==null){w=r;do b=w.lane,Rt.lanes|=b,ca|=b,w=w.next;while(w!==r)}else w===null&&(c.lanes=0);return[i.memoizedState,c.dispatch]}function Rd(r){var i=as(),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 $=w=w.next;do b=r(b,$.action),$=$.next;while($!==w);ws(b,i.memoizedState)||(Ln=!0),i.memoizedState=b,i.baseQueue===null&&(i.baseState=b),c.lastRenderedState=b}return[b,h]}function dp(){}function fp(r,i){var c=Rt,h=as(),w=i(),b=!ws(h.memoizedState,w);if(b&&(h.memoizedState=w,Ln=!0),h=h.queue,Id(pp.bind(null,c,h,r),[r]),h.getSnapshot!==i||b||tn!==null&&tn.memoizedState.tag&1){if(c.flags|=2048,ji(9,mp.bind(null,c,h,w,i),void 0,null),nn===null)throw Error(n(349));(la&30)!==0||hp(c,i,w)}return w}function hp(r,i,c){r.flags|=16384,r={getSnapshot:i,value:c},i=Rt.updateQueue,i===null?(i={lastEffect:null,stores:null},Rt.updateQueue=i,i.stores=[r]):(c=i.stores,c===null?i.stores=[r]:c.push(r))}function mp(r,i,c,h){i.value=c,i.getSnapshot=h,gp(i)&&yp(r)}function pp(r,i,c){return c(function(){gp(i)&&yp(r)})}function gp(r){var i=r.getSnapshot;r=r.value;try{var c=i();return!ws(r,c)}catch{return!0}}function yp(r){var i=Qs(r,1);i!==null&&ks(i,r,1,-1)}function wp(r){var i=Ms();return typeof r=="function"&&(r=r()),i.memoizedState=i.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Si,lastRenderedState:r},i.queue=r,r=r.dispatch=nx.bind(null,Rt,r),[i.memoizedState,r]}function ji(r,i,c,h){return r={tag:r,create:i,destroy:c,deps:h,next:null},i=Rt.updateQueue,i===null?(i={lastEffect:null,stores:null},Rt.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 vp(){return as().memoizedState}function uc(r,i,c,h){var w=Ms();Rt.flags|=r,w.memoizedState=ji(1|i,c,void 0,h===void 0?null:h)}function dc(r,i,c,h){var w=as();h=h===void 0?null:h;var b=void 0;if(qt!==null){var $=qt.memoizedState;if(b=$.destroy,h!==null&&Ed(h,$.deps)){w.memoizedState=ji(i,c,b,h);return}}Rt.flags|=r,w.memoizedState=ji(1|i,c,b,h)}function _p(r,i){return uc(8390656,8,r,i)}function Id(r,i){return dc(2048,8,r,i)}function bp(r,i){return dc(4,2,r,i)}function xp(r,i){return dc(4,4,r,i)}function kp(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 Sp(r,i,c){return c=c!=null?c.concat([r]):null,dc(4,4,kp.bind(null,i,r),c)}function Md(){}function jp(r,i){var c=as();i=i===void 0?null:i;var h=c.memoizedState;return h!==null&&i!==null&&Ed(i,h[1])?h[0]:(c.memoizedState=[r,i],r)}function Np(r,i){var c=as();i=i===void 0?null:i;var h=c.memoizedState;return h!==null&&i!==null&&Ed(i,h[1])?h[0]:(r=r(),c.memoizedState=[r,i],r)}function Cp(r,i,c){return(la&21)===0?(r.baseState&&(r.baseState=!1,Ln=!0),r.memoizedState=c):(ws(c,i)||(c=Tn(),Rt.lanes|=c,ca|=c,r.baseState=!0),i)}function ex(r,i){var c=ot;ot=c!==0&&4>c?c:4,r(!0);var h=Cd.transition;Cd.transition={};try{r(!1),i()}finally{ot=c,Cd.transition=h}}function Ep(){return as().memoizedState}function tx(r,i,c){var h=Er(r);if(c={lane:h,action:c,hasEagerState:!1,eagerState:null,next:null},Ap(r))$p(i,c);else if(c=op(r,i,c,h),c!==null){var w=Nn();ks(c,r,h,w),Tp(c,i,h)}}function nx(r,i,c){var h=Er(r),w={lane:h,action:c,hasEagerState:!1,eagerState:null,next:null};if(Ap(r))$p(i,w);else{var b=r.alternate;if(r.lanes===0&&(b===null||b.lanes===0)&&(b=i.lastRenderedReducer,b!==null))try{var $=i.lastRenderedState,D=b($,c);if(w.hasEagerState=!0,w.eagerState=D,ws(D,$)){var U=i.interleaved;U===null?(w.next=w,bd(i)):(w.next=U.next,U.next=w),i.interleaved=w;return}}catch{}finally{}c=op(r,i,w,h),c!==null&&(w=Nn(),ks(c,r,h,w),Tp(c,i,h))}}function Ap(r){var i=r.alternate;return r===Rt||i!==null&&i===Rt}function $p(r,i){xi=cc=!0;var c=r.pending;c===null?i.next=i:(i.next=c.next,c.next=i),r.pending=i}function Tp(r,i,c){if((c&4194240)!==0){var h=i.lanes;h&=r.pendingLanes,c|=h,i.lanes=c,Us(r,c)}}var fc={readContext:rs,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},sx={readContext:rs,useCallback:function(r,i){return Ms().memoizedState=[r,i===void 0?null:i],r},useContext:rs,useEffect:_p,useImperativeHandle:function(r,i,c){return c=c!=null?c.concat([r]):null,uc(4194308,4,kp.bind(null,i,r),c)},useLayoutEffect:function(r,i){return uc(4194308,4,r,i)},useInsertionEffect:function(r,i){return uc(4,2,r,i)},useMemo:function(r,i){var c=Ms();return i=i===void 0?null:i,r=r(),c.memoizedState=[r,i],r},useReducer:function(r,i,c){var h=Ms();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=tx.bind(null,Rt,r),[h.memoizedState,r]},useRef:function(r){var i=Ms();return r={current:r},i.memoizedState=r},useState:wp,useDebugValue:Md,useDeferredValue:function(r){return Ms().memoizedState=r},useTransition:function(){var r=wp(!1),i=r[0];return r=ex.bind(null,r[1]),Ms().memoizedState=r,[i,r]},useMutableSource:function(){},useSyncExternalStore:function(r,i,c){var h=Rt,w=Ms();if(Et){if(c===void 0)throw Error(n(407));c=c()}else{if(c=i(),nn===null)throw Error(n(349));(la&30)!==0||hp(h,i,c)}w.memoizedState=c;var b={value:c,getSnapshot:i};return w.queue=b,_p(pp.bind(null,h,b,r),[r]),h.flags|=2048,ji(9,mp.bind(null,h,b,c,i),void 0,null),c},useId:function(){var r=Ms(),i=nn.identifierPrefix;if(Et){var c=Ys,h=qs;c=(h&~(1<<32-Gt(h)-1)).toString(32)+c,i=":"+i+"R"+c,c=ki++,0<c&&(i+="H"+c.toString(32)),i+=":"}else c=Zb++,i=":"+i+"r"+c.toString(32)+":";return r.memoizedState=i},unstable_isNewReconciler:!1},rx={readContext:rs,useCallback:jp,useContext:rs,useEffect:Id,useImperativeHandle:Sp,useInsertionEffect:bp,useLayoutEffect:xp,useMemo:Np,useReducer:Td,useRef:vp,useState:function(){return Td(Si)},useDebugValue:Md,useDeferredValue:function(r){var i=as();return Cp(i,qt.memoizedState,r)},useTransition:function(){var r=Td(Si)[0],i=as().memoizedState;return[r,i]},useMutableSource:dp,useSyncExternalStore:fp,useId:Ep,unstable_isNewReconciler:!1},ax={readContext:rs,useCallback:jp,useContext:rs,useEffect:Id,useImperativeHandle:Sp,useInsertionEffect:bp,useLayoutEffect:xp,useMemo:Np,useReducer:Rd,useRef:vp,useState:function(){return Rd(Si)},useDebugValue:Md,useDeferredValue:function(r){var i=as();return qt===null?i.memoizedState=r:Cp(i,qt.memoizedState,r)},useTransition:function(){var r=Rd(Si)[0],i=as().memoizedState;return[r,i]},useMutableSource:dp,useSyncExternalStore:fp,useId:Ep,unstable_isNewReconciler:!1};function _s(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 Ld(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 hc={isMounted:function(r){return(r=r._reactInternals)?Cs(r)===r:!1},enqueueSetState:function(r,i,c){r=r._reactInternals;var h=Nn(),w=Er(r),b=Xs(h,w);b.payload=i,c!=null&&(b.callback=c),i=Sr(r,b,w),i!==null&&(ks(i,r,w,h),ac(i,r,w))},enqueueReplaceState:function(r,i,c){r=r._reactInternals;var h=Nn(),w=Er(r),b=Xs(h,w);b.tag=1,b.payload=i,c!=null&&(b.callback=c),i=Sr(r,b,w),i!==null&&(ks(i,r,w,h),ac(i,r,w))},enqueueForceUpdate:function(r,i){r=r._reactInternals;var c=Nn(),h=Er(r),w=Xs(c,h);w.tag=2,i!=null&&(w.callback=i),i=Sr(r,w,h),i!==null&&(ks(i,r,h,c),ac(i,r,h))}};function Rp(r,i,c,h,w,b,$){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(h,b,$):i.prototype&&i.prototype.isPureReactComponent?!di(c,h)||!di(w,b):!0}function Ip(r,i,c){var h=!1,w=br,b=i.contextType;return typeof b=="object"&&b!==null?b=rs(b):(w=Mn(i)?sa:hn.current,h=i.contextTypes,b=(h=h!=null)?Xa(r,w):br),i=new i(c,b),r.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,i.updater=hc,r.stateNode=i,i._reactInternals=r,h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=w,r.__reactInternalMemoizedMaskedChildContext=b),i}function Mp(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&&hc.enqueueReplaceState(i,i.state,null)}function Od(r,i,c,h){var w=r.stateNode;w.props=c,w.state=r.memoizedState,w.refs={},xd(r);var b=i.contextType;typeof b=="object"&&b!==null?w.context=rs(b):(b=Mn(i)?sa:hn.current,w.context=Xa(r,b)),w.state=r.memoizedState,b=i.getDerivedStateFromProps,typeof b=="function"&&(Ld(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&&hc.enqueueReplaceState(w,w.state,null),oc(r,c,w,h),w.state=r.memoizedState),typeof w.componentDidMount=="function"&&(r.flags|=4194308)}function oo(r,i){try{var c="",h=i;do c+=ae(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 Pd(r,i,c){return{value:r,source:null,stack:c??null,digest:i??null}}function Dd(r,i){try{console.error(i.value)}catch(c){setTimeout(function(){throw c})}}var ox=typeof WeakMap=="function"?WeakMap:Map;function Lp(r,i,c){c=Xs(-1,c),c.tag=3,c.payload={element:null};var h=i.value;return c.callback=function(){_c||(_c=!0,Zd=h),Dd(r,i)},c}function Op(r,i,c){c=Xs(-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(){Dd(r,i)}}var b=r.stateNode;return b!==null&&typeof b.componentDidCatch=="function"&&(c.callback=function(){Dd(r,i),typeof h!="function"&&(Nr===null?Nr=new Set([this]):Nr.add(this));var $=i.stack;this.componentDidCatch(i.value,{componentStack:$!==null?$:""})}),c}function Pp(r,i,c){var h=r.pingCache;if(h===null){h=r.pingCache=new ox;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=_x.bind(null,r,i,c),i.then(r,r))}function Dp(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 Fp(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=Xs(-1,1),i.tag=2,Sr(c,i,1))),c.lanes|=1),r):(r.flags|=65536,r.lanes=w,r)}var ix=N.ReactCurrentOwner,Ln=!1;function jn(r,i,c,h){i.child=r===null?ap(i,null,c,h):no(i,r.child,c,h)}function zp(r,i,c,h,w){c=c.render;var b=i.ref;return ro(i,w),h=Ad(r,i,c,h,b,w),c=$d(),r!==null&&!Ln?(i.updateQueue=r.updateQueue,i.flags&=-2053,r.lanes&=~w,Zs(r,i,w)):(Et&&c&&fd(i),i.flags|=1,jn(r,i,h,w),i.child)}function Bp(r,i,c,h,w){if(r===null){var b=c.type;return typeof b=="function"&&!of(b)&&b.defaultProps===void 0&&c.compare===null&&c.defaultProps===void 0?(i.tag=15,i.type=b,Wp(r,i,b,h,w)):(r=Nc(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 $=b.memoizedProps;if(c=c.compare,c=c!==null?c:di,c($,h)&&r.ref===i.ref)return Zs(r,i,w)}return i.flags|=1,r=$r(b,h),r.ref=i.ref,r.return=i,i.child=r}function Wp(r,i,c,h,w){if(r!==null){var b=r.memoizedProps;if(di(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,Zs(r,i,w)}return Fd(r,i,c,h,w)}function Up(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},_t(lo,Jn),Jn|=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,_t(lo,Jn),Jn|=r,null;i.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=b!==null?b.baseLanes:c,_t(lo,Jn),Jn|=h}else b!==null?(h=b.baseLanes|c,i.memoizedState=null):h=c,_t(lo,Jn),Jn|=h;return jn(r,i,w,c),i.child}function Vp(r,i){var c=i.ref;(r===null&&c!==null||r!==null&&r.ref!==c)&&(i.flags|=512,i.flags|=2097152)}function Fd(r,i,c,h,w){var b=Mn(c)?sa:hn.current;return b=Xa(i,b),ro(i,w),c=Ad(r,i,c,h,b,w),h=$d(),r!==null&&!Ln?(i.updateQueue=r.updateQueue,i.flags&=-2053,r.lanes&=~w,Zs(r,i,w)):(Et&&h&&fd(i),i.flags|=1,jn(r,i,c,w),i.child)}function Gp(r,i,c,h,w){if(Mn(c)){var b=!0;Ql(i)}else b=!1;if(ro(i,w),i.stateNode===null)pc(r,i),Ip(i,c,h),Od(i,c,h,w),h=!0;else if(r===null){var $=i.stateNode,D=i.memoizedProps;$.props=D;var U=$.context,re=c.contextType;typeof re=="object"&&re!==null?re=rs(re):(re=Mn(c)?sa:hn.current,re=Xa(i,re));var he=c.getDerivedStateFromProps,ye=typeof he=="function"||typeof $.getSnapshotBeforeUpdate=="function";ye||typeof $.UNSAFE_componentWillReceiveProps!="function"&&typeof $.componentWillReceiveProps!="function"||(D!==h||U!==re)&&Mp(i,$,h,re),kr=!1;var fe=i.memoizedState;$.state=fe,oc(i,h,$,w),U=i.memoizedState,D!==h||fe!==U||In.current||kr?(typeof he=="function"&&(Ld(i,c,he,h),U=i.memoizedState),(D=kr||Rp(i,c,D,h,fe,U,re))?(ye||typeof $.UNSAFE_componentWillMount!="function"&&typeof $.componentWillMount!="function"||(typeof $.componentWillMount=="function"&&$.componentWillMount(),typeof $.UNSAFE_componentWillMount=="function"&&$.UNSAFE_componentWillMount()),typeof $.componentDidMount=="function"&&(i.flags|=4194308)):(typeof $.componentDidMount=="function"&&(i.flags|=4194308),i.memoizedProps=h,i.memoizedState=U),$.props=h,$.state=U,$.context=re,h=D):(typeof $.componentDidMount=="function"&&(i.flags|=4194308),h=!1)}else{$=i.stateNode,ip(r,i),D=i.memoizedProps,re=i.type===i.elementType?D:_s(i.type,D),$.props=re,ye=i.pendingProps,fe=$.context,U=c.contextType,typeof U=="object"&&U!==null?U=rs(U):(U=Mn(c)?sa:hn.current,U=Xa(i,U));var Ce=c.getDerivedStateFromProps;(he=typeof Ce=="function"||typeof $.getSnapshotBeforeUpdate=="function")||typeof $.UNSAFE_componentWillReceiveProps!="function"&&typeof $.componentWillReceiveProps!="function"||(D!==ye||fe!==U)&&Mp(i,$,h,U),kr=!1,fe=i.memoizedState,$.state=fe,oc(i,h,$,w);var Ie=i.memoizedState;D!==ye||fe!==Ie||In.current||kr?(typeof Ce=="function"&&(Ld(i,c,Ce,h),Ie=i.memoizedState),(re=kr||Rp(i,c,re,h,fe,Ie,U)||!1)?(he||typeof $.UNSAFE_componentWillUpdate!="function"&&typeof $.componentWillUpdate!="function"||(typeof $.componentWillUpdate=="function"&&$.componentWillUpdate(h,Ie,U),typeof $.UNSAFE_componentWillUpdate=="function"&&$.UNSAFE_componentWillUpdate(h,Ie,U)),typeof $.componentDidUpdate=="function"&&(i.flags|=4),typeof $.getSnapshotBeforeUpdate=="function"&&(i.flags|=1024)):(typeof $.componentDidUpdate!="function"||D===r.memoizedProps&&fe===r.memoizedState||(i.flags|=4),typeof $.getSnapshotBeforeUpdate!="function"||D===r.memoizedProps&&fe===r.memoizedState||(i.flags|=1024),i.memoizedProps=h,i.memoizedState=Ie),$.props=h,$.state=Ie,$.context=U,h=re):(typeof $.componentDidUpdate!="function"||D===r.memoizedProps&&fe===r.memoizedState||(i.flags|=4),typeof $.getSnapshotBeforeUpdate!="function"||D===r.memoizedProps&&fe===r.memoizedState||(i.flags|=1024),h=!1)}return zd(r,i,c,h,b,w)}function zd(r,i,c,h,w,b){Vp(r,i);var $=(i.flags&128)!==0;if(!h&&!$)return w&&Ym(i,c,!1),Zs(r,i,b);h=i.stateNode,ix.current=i;var D=$&&typeof c.getDerivedStateFromError!="function"?null:h.render();return i.flags|=1,r!==null&&$?(i.child=no(i,r.child,null,b),i.child=no(i,null,D,b)):jn(r,i,D,b),i.memoizedState=h.state,w&&Ym(i,c,!0),i.child}function Hp(r){var i=r.stateNode;i.pendingContext?Jm(r,i.pendingContext,i.pendingContext!==i.context):i.context&&Jm(r,i.context,!1),kd(r,i.containerInfo)}function Kp(r,i,c,h,w){return to(),gd(w),i.flags|=256,jn(r,i,c,h),i.child}var Bd={dehydrated:null,treeContext:null,retryLane:0};function Wd(r){return{baseLanes:r,cachePool:null,transitions:null}}function Jp(r,i,c){var h=i.pendingProps,w=Tt.current,b=!1,$=(i.flags&128)!==0,D;if((D=$)||(D=r!==null&&r.memoizedState===null?!1:(w&2)!==0),D?(b=!0,i.flags&=-129):(r===null||r.memoizedState!==null)&&(w|=1),_t(Tt,w&1),r===null)return pd(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):($=h.children,r=h.fallback,b?(h=i.mode,b=i.child,$={mode:"hidden",children:$},(h&1)===0&&b!==null?(b.childLanes=0,b.pendingProps=$):b=Cc($,h,0,null),r=ha(r,h,c,null),b.return=i,r.return=i,b.sibling=r,i.child=b,i.child.memoizedState=Wd(c),i.memoizedState=Bd,r):Ud(i,$));if(w=r.memoizedState,w!==null&&(D=w.dehydrated,D!==null))return lx(r,i,$,h,D,w,c);if(b){b=h.fallback,$=i.mode,w=r.child,D=w.sibling;var U={mode:"hidden",children:h.children};return($&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),D!==null?b=$r(D,b):(b=ha(b,$,c,null),b.flags|=2),b.return=i,h.return=i,h.sibling=b,i.child=h,h=b,b=i.child,$=r.child.memoizedState,$=$===null?Wd(c):{baseLanes:$.baseLanes|c,cachePool:null,transitions:$.transitions},b.memoizedState=$,b.childLanes=r.childLanes&~c,i.memoizedState=Bd,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 Ud(r,i){return i=Cc({mode:"visible",children:i},r.mode,0,null),i.return=r,r.child=i}function mc(r,i,c,h){return h!==null&&gd(h),no(i,r.child,null,c),r=Ud(i,i.pendingProps.children),r.flags|=2,i.memoizedState=null,r}function lx(r,i,c,h,w,b,$){if(c)return i.flags&256?(i.flags&=-257,h=Pd(Error(n(422))),mc(r,i,$,h)):i.memoizedState!==null?(i.child=r.child,i.flags|=128,null):(b=h.fallback,w=i.mode,h=Cc({mode:"visible",children:h.children},w,0,null),b=ha(b,w,$,null),b.flags|=2,h.return=i,b.return=i,h.sibling=b,i.child=h,(i.mode&1)!==0&&no(i,r.child,null,$),i.child.memoizedState=Wd($),i.memoizedState=Bd,b);if((i.mode&1)===0)return mc(r,i,$,null);if(w.data==="$!"){if(h=w.nextSibling&&w.nextSibling.dataset,h)var D=h.dgst;return h=D,b=Error(n(419)),h=Pd(b,h,void 0),mc(r,i,$,h)}if(D=($&r.childLanes)!==0,Ln||D){if(h=nn,h!==null){switch($&-$){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|$))!==0?0:w,w!==0&&w!==b.retryLane&&(b.retryLane=w,Qs(r,w),ks(h,r,w,-1))}return af(),h=Pd(Error(n(421))),mc(r,i,$,h)}return w.data==="$?"?(i.flags|=128,i.child=r.child,i=bx.bind(null,r),w._reactRetry=i,null):(r=b.treeContext,Kn=vr(w.nextSibling),Hn=i,Et=!0,vs=null,r!==null&&(ns[ss++]=qs,ns[ss++]=Ys,ns[ss++]=ra,qs=r.id,Ys=r.overflow,ra=i),i=Ud(i,h.children),i.flags|=4096,i)}function qp(r,i,c){r.lanes|=i;var h=r.alternate;h!==null&&(h.lanes|=i),_d(r.return,i,c)}function Vd(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 Yp(r,i,c){var h=i.pendingProps,w=h.revealOrder,b=h.tail;if(jn(r,i,h.children,c),h=Tt.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&&qp(r,c,i);else if(r.tag===19)qp(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(_t(Tt,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&&ic(r)===null&&(w=c),c=c.sibling;c=w,c===null?(w=i.child,i.child=null):(w=c.sibling,c.sibling=null),Vd(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&&ic(r)===null){i.child=w;break}r=w.sibling,w.sibling=c,c=w,w=r}Vd(i,!0,c,null,b);break;case"together":Vd(i,!1,null,null,void 0);break;default:i.memoizedState=null}return i.child}function pc(r,i){(i.mode&1)===0&&r!==null&&(r.alternate=null,i.alternate=null,i.flags|=2)}function Zs(r,i,c){if(r!==null&&(i.dependencies=r.dependencies),ca|=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 cx(r,i,c){switch(i.tag){case 3:Hp(i),to();break;case 5:up(i);break;case 1:Mn(i.type)&&Ql(i);break;case 4:kd(i,i.stateNode.containerInfo);break;case 10:var h=i.type._context,w=i.memoizedProps.value;_t(sc,h._currentValue),h._currentValue=w;break;case 13:if(h=i.memoizedState,h!==null)return h.dehydrated!==null?(_t(Tt,Tt.current&1),i.flags|=128,null):(c&i.child.childLanes)!==0?Jp(r,i,c):(_t(Tt,Tt.current&1),r=Zs(r,i,c),r!==null?r.sibling:null);_t(Tt,Tt.current&1);break;case 19:if(h=(c&i.childLanes)!==0,(r.flags&128)!==0){if(h)return Yp(r,i,c);i.flags|=128}if(w=i.memoizedState,w!==null&&(w.rendering=null,w.tail=null,w.lastEffect=null),_t(Tt,Tt.current),h)break;return null;case 22:case 23:return i.lanes=0,Up(r,i,c)}return Zs(r,i,c)}var Qp,Gd,Xp,Zp;Qp=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}},Gd=function(){},Xp=function(r,i,c,h){var w=r.memoizedProps;if(w!==h){r=i.stateNode,ia(Is.current);var b=null;switch(c){case"input":w=Je(r,w),h=Je(r,h),b=[];break;case"select":w=W({},w,{value:void 0}),h=W({},h,{value:void 0}),b=[];break;case"textarea":w=je(r,w),h=je(r,h),b=[];break;default:typeof w.onClick!="function"&&typeof h.onClick=="function"&&(r.onclick=Jl)}St(c,h);var $;c=null;for(re in w)if(!h.hasOwnProperty(re)&&w.hasOwnProperty(re)&&w[re]!=null)if(re==="style"){var D=w[re];for($ in D)D.hasOwnProperty($)&&(c||(c={}),c[$]="")}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(D=w!=null?w[re]:void 0,h.hasOwnProperty(re)&&U!==D&&(U!=null||D!=null))if(re==="style")if(D){for($ in D)!D.hasOwnProperty($)||U&&U.hasOwnProperty($)||(c||(c={}),c[$]="");for($ in U)U.hasOwnProperty($)&&D[$]!==U[$]&&(c||(c={}),c[$]=U[$])}else c||(b||(b=[]),b.push(re,c)),c=U;else re==="dangerouslySetInnerHTML"?(U=U?U.__html:void 0,D=D?D.__html:void 0,U!=null&&D!==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||D===U||(b=[])):(b=b||[]).push(re,U))}c&&(b=b||[]).push("style",c);var re=b;(i.updateQueue=re)&&(i.flags|=4)}},Zp=function(r,i,c,h){c!==h&&(i.flags|=4)};function Ni(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 ux(r,i,c){var h=i.pendingProps;switch(hd(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 Mn(i.type)&&Yl(),pn(i),null;case 3:return h=i.stateNode,ao(),kt(In),kt(hn),Nd(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(r===null||r.child===null)&&(tc(i)?i.flags|=4:r===null||r.memoizedState.isDehydrated&&(i.flags&256)===0||(i.flags|=1024,vs!==null&&(nf(vs),vs=null))),Gd(r,i),pn(i),null;case 5:Sd(i);var w=ia(bi.current);if(c=i.type,r!==null&&i.stateNode!=null)Xp(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=ia(Is.current),tc(i)){h=i.stateNode,c=i.type;var b=i.memoizedProps;switch(h[Rs]=i,h[gi]=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<hi.length;w++)xt(hi[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":me(h,b),xt("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!b.multiple},xt("invalid",h);break;case"textarea":_e(h,b),xt("invalid",h)}St(c,b),w=null;for(var $ in b)if(b.hasOwnProperty($)){var D=b[$];$==="children"?typeof D=="string"?h.textContent!==D&&(b.suppressHydrationWarning!==!0&&Kl(h.textContent,D,r),w=["children",D]):typeof D=="number"&&h.textContent!==""+D&&(b.suppressHydrationWarning!==!0&&Kl(h.textContent,D,r),w=["children",""+D]):o.hasOwnProperty($)&&D!=null&&$==="onScroll"&&xt("scroll",h)}switch(c){case"input":Fe(h),tt(h,b,!0);break;case"textarea":Fe(h),te(h);break;case"select":case"option":break;default:typeof b.onClick=="function"&&(h.onclick=Jl)}h=w,i.updateQueue=h,h!==null&&(i.flags|=4)}else{$=w.nodeType===9?w:w.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=be(c)),r==="http://www.w3.org/1999/xhtml"?c==="script"?(r=$.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof h.is=="string"?r=$.createElement(c,{is:h.is}):(r=$.createElement(c),c==="select"&&($=r,h.multiple?$.multiple=!0:h.size&&($.size=h.size))):r=$.createElementNS(r,c),r[Rs]=i,r[gi]=h,Qp(r,i,!1,!1),i.stateNode=r;e:{switch($=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<hi.length;w++)xt(hi[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":me(r,h),w=Je(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":_e(r,h),w=je(r,h),xt("invalid",r);break;default:w=h}St(c,w),D=w;for(b in D)if(D.hasOwnProperty(b)){var U=D[b];b==="style"?Ee(r,U):b==="dangerouslySetInnerHTML"?(U=U?U.__html:void 0,U!=null&&Oe(r,U)):b==="children"?typeof U=="string"?(c!=="textarea"||U!=="")&&Ae(r,U):typeof U=="number"&&Ae(r,""+U):b!=="suppressContentEditableWarning"&&b!=="suppressHydrationWarning"&&b!=="autoFocus"&&(o.hasOwnProperty(b)?U!=null&&b==="onScroll"&&xt("scroll",r):U!=null&&T(r,b,U,$))}switch(c){case"input":Fe(r),tt(r,h,!1);break;case"textarea":Fe(r),te(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?de(r,!!h.multiple,b,!1):h.defaultValue!=null&&de(r,!!h.multiple,h.defaultValue,!0);break;default:typeof w.onClick=="function"&&(r.onclick=Jl)}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)Zp(r,i,r.memoizedProps,h);else{if(typeof h!="string"&&i.stateNode===null)throw Error(n(166));if(c=ia(bi.current),ia(Is.current),tc(i)){if(h=i.stateNode,c=i.memoizedProps,h[Rs]=i,(b=h.nodeValue!==c)&&(r=Hn,r!==null))switch(r.tag){case 3:Kl(h.nodeValue,c,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&Kl(h.nodeValue,c,(r.mode&1)!==0)}b&&(i.flags|=4)}else h=(c.nodeType===9?c:c.ownerDocument).createTextNode(h),h[Rs]=i,i.stateNode=h}return pn(i),null;case 13:if(kt(Tt),h=i.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(Et&&Kn!==null&&(i.mode&1)!==0&&(i.flags&128)===0)np(),to(),i.flags|=98560,b=!1;else if(b=tc(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[Rs]=i}else to(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;pn(i),b=!1}else vs!==null&&(nf(vs),vs=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||(Tt.current&1)!==0?Yt===0&&(Yt=3):af())),i.updateQueue!==null&&(i.flags|=4),pn(i),null);case 4:return ao(),Gd(r,i),r===null&&mi(i.stateNode.containerInfo),pn(i),null;case 10:return vd(i.type._context),pn(i),null;case 17:return Mn(i.type)&&Yl(),pn(i),null;case 19:if(kt(Tt),b=i.memoizedState,b===null)return pn(i),null;if(h=(i.flags&128)!==0,$=b.rendering,$===null)if(h)Ni(b,!1);else{if(Yt!==0||r!==null&&(r.flags&128)!==0)for(r=i.child;r!==null;){if($=ic(r),$!==null){for(i.flags|=128,Ni(b,!1),h=$.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,$=b.alternate,$===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=$.childLanes,b.lanes=$.lanes,b.child=$.child,b.subtreeFlags=0,b.deletions=null,b.memoizedProps=$.memoizedProps,b.memoizedState=$.memoizedState,b.updateQueue=$.updateQueue,b.type=$.type,r=$.dependencies,b.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),c=c.sibling;return _t(Tt,Tt.current&1|2),i.child}r=r.sibling}b.tail!==null&&Nt()>co&&(i.flags|=128,h=!0,Ni(b,!1),i.lanes=4194304)}else{if(!h)if(r=ic($),r!==null){if(i.flags|=128,h=!0,c=r.updateQueue,c!==null&&(i.updateQueue=c,i.flags|=4),Ni(b,!0),b.tail===null&&b.tailMode==="hidden"&&!$.alternate&&!Et)return pn(i),null}else 2*Nt()-b.renderingStartTime>co&&c!==1073741824&&(i.flags|=128,h=!0,Ni(b,!1),i.lanes=4194304);b.isBackwards?($.sibling=i.child,i.child=$):(c=b.last,c!==null?c.sibling=$:i.child=$,b.last=$)}return b.tail!==null?(i=b.tail,b.rendering=i,b.tail=i.sibling,b.renderingStartTime=Nt(),i.sibling=null,c=Tt.current,_t(Tt,h?c&1|2:c&1),i):(pn(i),null);case 22:case 23:return rf(),h=i.memoizedState!==null,r!==null&&r.memoizedState!==null!==h&&(i.flags|=8192),h&&(i.mode&1)!==0?(Jn&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 dx(r,i){switch(hd(i),i.tag){case 1:return Mn(i.type)&&Yl(),r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 3:return ao(),kt(In),kt(hn),Nd(),r=i.flags,(r&65536)!==0&&(r&128)===0?(i.flags=r&-65537|128,i):null;case 5:return Sd(i),null;case 13:if(kt(Tt),r=i.memoizedState,r!==null&&r.dehydrated!==null){if(i.alternate===null)throw Error(n(340));to()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 19:return kt(Tt),null;case 4:return ao(),null;case 10:return vd(i.type._context),null;case 22:case 23:return rf(),null;case 24:return null;default:return null}}var gc=!1,gn=!1,fx=typeof WeakSet=="function"?WeakSet:Set,Te=null;function io(r,i){var c=r.ref;if(c!==null)if(typeof c=="function")try{c(null)}catch(h){Lt(r,i,h)}else c.current=null}function Hd(r,i,c){try{c()}catch(h){Lt(r,i,h)}}var eg=!1;function hx(r,i){if(rd=za,r=Rm(),Yu(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 $=0,D=-1,U=-1,re=0,he=0,ye=r,fe=null;t:for(;;){for(var Ce;ye!==c||w!==0&&ye.nodeType!==3||(D=$+w),ye!==b||h!==0&&ye.nodeType!==3||(U=$+h),ye.nodeType===3&&($+=ye.nodeValue.length),(Ce=ye.firstChild)!==null;)fe=ye,ye=Ce;for(;;){if(ye===r)break t;if(fe===c&&++re===w&&(D=$),fe===b&&++he===h&&(U=$),(Ce=ye.nextSibling)!==null)break;ye=fe,fe=ye.parentNode}ye=Ce}c=D===-1||U===-1?null:{start:D,end:U}}else c=null}c=c||{start:0,end:0}}else c=null;for(ad={focusedElem:r,selectionRange:c},za=!1,Te=i;Te!==null;)if(i=Te,r=i.child,(i.subtreeFlags&1028)!==0&&r!==null)r.return=i,Te=r;else for(;Te!==null;){i=Te;try{var Ie=i.alternate;if((i.flags&1024)!==0)switch(i.tag){case 0:case 11:case 15:break;case 1:if(Ie!==null){var Le=Ie.memoizedProps,zt=Ie.memoizedState,X=i.stateNode,H=X.getSnapshotBeforeUpdate(i.elementType===i.type?Le:_s(i.type,Le),zt);X.__reactInternalSnapshotBeforeUpdate=H}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){Lt(i,i.return,ke)}if(r=i.sibling,r!==null){r.return=i.return,Te=r;break}Te=i.return}return Ie=eg,eg=!1,Ie}function Ci(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&&Hd(i,c,b)}w=w.next}while(w!==h)}}function yc(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 Kd(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 tg(r){var i=r.alternate;i!==null&&(r.alternate=null,tg(i)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(i=r.stateNode,i!==null&&(delete i[Rs],delete i[gi],delete i[cd],delete i[qb],delete i[Yb])),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 ng(r){return r.tag===5||r.tag===3||r.tag===4}function sg(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||ng(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 Jd(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=Jl));else if(h!==4&&(r=r.child,r!==null))for(Jd(r,i,c),r=r.sibling;r!==null;)Jd(r,i,c),r=r.sibling}function qd(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(qd(r,i,c),r=r.sibling;r!==null;)qd(r,i,c),r=r.sibling}var an=null,bs=!1;function jr(r,i,c){for(c=c.child;c!==null;)rg(r,i,c),c=c.sibling}function rg(r,i,c){if(Vt&&typeof Vt.onCommitFiberUnmount=="function")try{Vt.onCommitFiberUnmount(As,c)}catch{}switch(c.tag){case 5:gn||io(c,i);case 6:var h=an,w=bs;an=null,jr(r,i,c),an=h,bs=w,an!==null&&(bs?(r=an,c=c.stateNode,r.nodeType===8?r.parentNode.removeChild(c):r.removeChild(c)):an.removeChild(c.stateNode));break;case 18:an!==null&&(bs?(r=an,c=c.stateNode,r.nodeType===8?ld(r.parentNode,c):r.nodeType===1&&ld(r,c),Gs(r)):ld(an,c.stateNode));break;case 4:h=an,w=bs,an=c.stateNode.containerInfo,bs=!0,jr(r,i,c),an=h,bs=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,$=b.destroy;b=b.tag,$!==void 0&&((b&2)!==0||(b&4)!==0)&&Hd(c,i,$),w=w.next}while(w!==h)}jr(r,i,c);break;case 1:if(!gn&&(io(c,i),h=c.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=c.memoizedProps,h.state=c.memoizedState,h.componentWillUnmount()}catch(D){Lt(c,i,D)}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 ag(r){var i=r.updateQueue;if(i!==null){r.updateQueue=null;var c=r.stateNode;c===null&&(c=r.stateNode=new fx),i.forEach(function(h){var w=xx.bind(null,r,h);c.has(h)||(c.add(h),h.then(w,w))})}}function xs(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,$=i,D=$;e:for(;D!==null;){switch(D.tag){case 5:an=D.stateNode,bs=!1;break e;case 3:an=D.stateNode.containerInfo,bs=!0;break e;case 4:an=D.stateNode.containerInfo,bs=!0;break e}D=D.return}if(an===null)throw Error(n(160));rg(b,$,w),an=null,bs=!1;var U=w.alternate;U!==null&&(U.return=null),w.return=null}catch(re){Lt(w,i,re)}}if(i.subtreeFlags&12854)for(i=i.child;i!==null;)og(i,r),i=i.sibling}function og(r,i){var c=r.alternate,h=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(xs(i,r),Ls(r),h&4){try{Ci(3,r,r.return),yc(3,r)}catch(Le){Lt(r,r.return,Le)}try{Ci(5,r,r.return)}catch(Le){Lt(r,r.return,Le)}}break;case 1:xs(i,r),Ls(r),h&512&&c!==null&&io(c,c.return);break;case 5:if(xs(i,r),Ls(r),h&512&&c!==null&&io(c,c.return),r.flags&32){var w=r.stateNode;try{Ae(w,"")}catch(Le){Lt(r,r.return,Le)}}if(h&4&&(w=r.stateNode,w!=null)){var b=r.memoizedProps,$=c!==null?c.memoizedProps:b,D=r.type,U=r.updateQueue;if(r.updateQueue=null,U!==null)try{D==="input"&&b.type==="radio"&&b.name!=null&&Me(w,b),jt(D,$);var re=jt(D,b);for($=0;$<U.length;$+=2){var he=U[$],ye=U[$+1];he==="style"?Ee(w,ye):he==="dangerouslySetInnerHTML"?Oe(w,ye):he==="children"?Ae(w,ye):T(w,he,ye,re)}switch(D){case"input":st(w,b);break;case"textarea":ge(w,b);break;case"select":var fe=w._wrapperState.wasMultiple;w._wrapperState.wasMultiple=!!b.multiple;var Ce=b.value;Ce!=null?de(w,!!b.multiple,Ce,!1):fe!==!!b.multiple&&(b.defaultValue!=null?de(w,!!b.multiple,b.defaultValue,!0):de(w,!!b.multiple,b.multiple?[]:"",!1))}w[gi]=b}catch(Le){Lt(r,r.return,Le)}}break;case 6:if(xs(i,r),Ls(r),h&4){if(r.stateNode===null)throw Error(n(162));w=r.stateNode,b=r.memoizedProps;try{w.nodeValue=b}catch(Le){Lt(r,r.return,Le)}}break;case 3:if(xs(i,r),Ls(r),h&4&&c!==null&&c.memoizedState.isDehydrated)try{Gs(i.containerInfo)}catch(Le){Lt(r,r.return,Le)}break;case 4:xs(i,r),Ls(r);break;case 13:xs(i,r),Ls(r),w=r.child,w.flags&8192&&(b=w.memoizedState!==null,w.stateNode.isHidden=b,!b||w.alternate!==null&&w.alternate.memoizedState!==null||(Xd=Nt())),h&4&&ag(r);break;case 22:if(he=c!==null&&c.memoizedState!==null,r.mode&1?(gn=(re=gn)||he,xs(i,r),gn=re):xs(i,r),Ls(r),h&8192){if(re=r.memoizedState!==null,(r.stateNode.isHidden=re)&&!he&&(r.mode&1)!==0)for(Te=r,he=r.child;he!==null;){for(ye=Te=he;Te!==null;){switch(fe=Te,Ce=fe.child,fe.tag){case 0:case 11:case 14:case 15:Ci(4,fe,fe.return);break;case 1:io(fe,fe.return);var Ie=fe.stateNode;if(typeof Ie.componentWillUnmount=="function"){h=fe,c=fe.return;try{i=h,Ie.props=i.memoizedProps,Ie.state=i.memoizedState,Ie.componentWillUnmount()}catch(Le){Lt(h,c,Le)}}break;case 5:io(fe,fe.return);break;case 22:if(fe.memoizedState!==null){cg(ye);continue}}Ce!==null?(Ce.return=fe,Te=Ce):cg(ye)}he=he.sibling}e:for(he=null,ye=r;;){if(ye.tag===5){if(he===null){he=ye;try{w=ye.stateNode,re?(b=w.style,typeof b.setProperty=="function"?b.setProperty("display","none","important"):b.display="none"):(D=ye.stateNode,U=ye.memoizedProps.style,$=U!=null&&U.hasOwnProperty("display")?U.display:null,D.style.display=Ge("display",$))}catch(Le){Lt(r,r.return,Le)}}}else if(ye.tag===6){if(he===null)try{ye.stateNode.nodeValue=re?"":ye.memoizedProps}catch(Le){Lt(r,r.return,Le)}}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;he===ye&&(he=null),ye=ye.return}he===ye&&(he=null),ye.sibling.return=ye.return,ye=ye.sibling}}break;case 19:xs(i,r),Ls(r),h&4&&ag(r);break;case 21:break;default:xs(i,r),Ls(r)}}function Ls(r){var i=r.flags;if(i&2){try{e:{for(var c=r.return;c!==null;){if(ng(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&&(Ae(w,""),h.flags&=-33);var b=sg(r);qd(r,b,w);break;case 3:case 4:var $=h.stateNode.containerInfo,D=sg(r);Jd(r,D,$);break;default:throw Error(n(161))}}catch(U){Lt(r,r.return,U)}r.flags&=-3}i&4096&&(r.flags&=-4097)}function mx(r,i,c){Te=r,ig(r)}function ig(r,i,c){for(var h=(r.mode&1)!==0;Te!==null;){var w=Te,b=w.child;if(w.tag===22&&h){var $=w.memoizedState!==null||gc;if(!$){var D=w.alternate,U=D!==null&&D.memoizedState!==null||gn;D=gc;var re=gn;if(gc=$,(gn=U)&&!re)for(Te=w;Te!==null;)$=Te,U=$.child,$.tag===22&&$.memoizedState!==null?ug(w):U!==null?(U.return=$,Te=U):ug(w);for(;b!==null;)Te=b,ig(b),b=b.sibling;Te=w,gc=D,gn=re}lg(r)}else(w.subtreeFlags&8772)!==0&&b!==null?(b.return=w,Te=b):lg(r)}}function lg(r){for(;Te!==null;){var i=Te;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||yc(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:_s(i.type,c.memoizedProps);h.componentDidUpdate(w,c.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var b=i.updateQueue;b!==null&&cp(i,b,h);break;case 3:var $=i.updateQueue;if($!==null){if(c=null,i.child!==null)switch(i.child.tag){case 5:c=i.child.stateNode;break;case 1:c=i.child.stateNode}cp(i,$,c)}break;case 5:var D=i.stateNode;if(c===null&&i.flags&4){c=D;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 he=re.memoizedState;if(he!==null){var ye=he.dehydrated;ye!==null&&Gs(ye)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}gn||i.flags&512&&Kd(i)}catch(fe){Lt(i,i.return,fe)}}if(i===r){Te=null;break}if(c=i.sibling,c!==null){c.return=i.return,Te=c;break}Te=i.return}}function cg(r){for(;Te!==null;){var i=Te;if(i===r){Te=null;break}var c=i.sibling;if(c!==null){c.return=i.return,Te=c;break}Te=i.return}}function ug(r){for(;Te!==null;){var i=Te;try{switch(i.tag){case 0:case 11:case 15:var c=i.return;try{yc(4,i)}catch(U){Lt(i,c,U)}break;case 1:var h=i.stateNode;if(typeof h.componentDidMount=="function"){var w=i.return;try{h.componentDidMount()}catch(U){Lt(i,w,U)}}var b=i.return;try{Kd(i)}catch(U){Lt(i,b,U)}break;case 5:var $=i.return;try{Kd(i)}catch(U){Lt(i,$,U)}}}catch(U){Lt(i,i.return,U)}if(i===r){Te=null;break}var D=i.sibling;if(D!==null){D.return=i.return,Te=D;break}Te=i.return}}var px=Math.ceil,wc=N.ReactCurrentDispatcher,Yd=N.ReactCurrentOwner,os=N.ReactCurrentBatchConfig,it=0,nn=null,Ht=null,on=0,Jn=0,lo=_r(0),Yt=0,Ei=null,ca=0,vc=0,Qd=0,Ai=null,On=null,Xd=0,co=1/0,er=null,_c=!1,Zd=null,Nr=null,bc=!1,Cr=null,xc=0,$i=0,ef=null,kc=-1,Sc=0;function Nn(){return(it&6)!==0?Nt():kc!==-1?kc:kc=Nt()}function Er(r){return(r.mode&1)===0?1:(it&2)!==0&&on!==0?on&-on:Xb.transition!==null?(Sc===0&&(Sc=Tn()),Sc):(r=ot,r!==0||(r=window.event,r=r===void 0?16:jl(r.type)),r)}function ks(r,i,c,h){if(50<$i)throw $i=0,ef=null,Error(n(185));dr(r,c,h),((it&2)===0||r!==nn)&&(r===nn&&((it&2)===0&&(vc|=c),Yt===4&&Ar(r,on)),Pn(r,h),c===1&&it===0&&(i.mode&1)===0&&(co=Nt()+500,Xl&&xr()))}function Pn(r,i){var c=r.callbackNode;Yo(r,i);var h=Zn(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?Qb(fg.bind(null,r)):Qm(fg.bind(null,r)),Kb(function(){(it&6)===0&&xr()}),c=null;else{switch(fn(h)){case 1:c=$a;break;case 4:c=xl;break;case 16:c=Ta;break;case 536870912:c=Qe;break;default:c=Ta}c=_g(c,dg.bind(null,r))}r.callbackPriority=i,r.callbackNode=c}}function dg(r,i){if(kc=-1,Sc=0,(it&6)!==0)throw Error(n(327));var c=r.callbackNode;if(uo()&&r.callbackNode!==c)return null;var h=Zn(r,r===nn?on:0);if(h===0)return null;if((h&30)!==0||(h&r.expiredLanes)!==0||i)i=jc(r,h);else{i=h;var w=it;it|=2;var b=mg();(nn!==r||on!==i)&&(er=null,co=Nt()+500,da(r,i));do try{wx();break}catch(D){hg(r,D)}while(!0);wd(),wc.current=b,it=w,Ht!==null?i=0:(nn=null,on=0,i=Yt)}if(i!==0){if(i===2&&(w=Ma(r),w!==0&&(h=w,i=tf(r,w))),i===1)throw c=Ei,da(r,0),Ar(r,h),Pn(r,Nt()),c;if(i===6)Ar(r,h);else{if(w=r.current.alternate,(h&30)===0&&!gx(w)&&(i=jc(r,h),i===2&&(b=Ma(r),b!==0&&(h=b,i=tf(r,b))),i===1))throw c=Ei,da(r,0),Ar(r,h),Pn(r,Nt()),c;switch(r.finishedWork=w,r.finishedLanes=h,i){case 0:case 1:throw Error(n(345));case 2:fa(r,On,er);break;case 3:if(Ar(r,h),(h&130023424)===h&&(i=Xd+500-Nt(),10<i)){if(Zn(r,0)!==0)break;if(w=r.suspendedLanes,(w&h)!==h){Nn(),r.pingedLanes|=r.suspendedLanes&w;break}r.timeoutHandle=id(fa.bind(null,r,On,er),i);break}fa(r,On,er);break;case 4:if(Ar(r,h),(h&4194240)===h)break;for(i=r.eventTimes,w=-1;0<h;){var $=31-Gt(h);b=1<<$,$=i[$],$>w&&(w=$),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*px(h/1960))-h,10<h){r.timeoutHandle=id(fa.bind(null,r,On,er),h);break}fa(r,On,er);break;case 5:fa(r,On,er);break;default:throw Error(n(329))}}}return Pn(r,Nt()),r.callbackNode===c?dg.bind(null,r):null}function tf(r,i){var c=Ai;return r.current.memoizedState.isDehydrated&&(da(r,i).flags|=256),r=jc(r,i),r!==2&&(i=On,On=c,i!==null&&nf(i)),r}function nf(r){On===null?On=r:On.push.apply(On,r)}function gx(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(!ws(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&=~Qd,i&=~vc,r.suspendedLanes|=i,r.pingedLanes&=~i,r=r.expirationTimes;0<i;){var c=31-Gt(i),h=1<<c;r[c]=-1,i&=~h}}function fg(r){if((it&6)!==0)throw Error(n(327));uo();var i=Zn(r,0);if((i&1)===0)return Pn(r,Nt()),null;var c=jc(r,i);if(r.tag!==0&&c===2){var h=Ma(r);h!==0&&(i=h,c=tf(r,h))}if(c===1)throw c=Ei,da(r,0),Ar(r,i),Pn(r,Nt()),c;if(c===6)throw Error(n(345));return r.finishedWork=r.current.alternate,r.finishedLanes=i,fa(r,On,er),Pn(r,Nt()),null}function sf(r,i){var c=it;it|=1;try{return r(i)}finally{it=c,it===0&&(co=Nt()+500,Xl&&xr())}}function ua(r){Cr!==null&&Cr.tag===0&&(it&6)===0&&uo();var i=it;it|=1;var c=os.transition,h=ot;try{if(os.transition=null,ot=1,r)return r()}finally{ot=h,os.transition=c,it=i,(it&6)===0&&xr()}}function rf(){Jn=lo.current,kt(lo)}function da(r,i){r.finishedWork=null,r.finishedLanes=0;var c=r.timeoutHandle;if(c!==-1&&(r.timeoutHandle=-1,Hb(c)),Ht!==null)for(c=Ht.return;c!==null;){var h=c;switch(hd(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&Yl();break;case 3:ao(),kt(In),kt(hn),Nd();break;case 5:Sd(h);break;case 4:ao();break;case 13:kt(Tt);break;case 19:kt(Tt);break;case 10:vd(h.type._context);break;case 22:case 23:rf()}c=c.return}if(nn=r,Ht=r=$r(r.current,null),on=Jn=i,Yt=0,Ei=null,Qd=vc=ca=0,On=Ai=null,oa!==null){for(i=0;i<oa.length;i++)if(c=oa[i],h=c.interleaved,h!==null){c.interleaved=null;var w=h.next,b=c.pending;if(b!==null){var $=b.next;b.next=w,h.next=$}c.pending=h}oa=null}return r}function hg(r,i){do{var c=Ht;try{if(wd(),lc.current=fc,cc){for(var h=Rt.memoizedState;h!==null;){var w=h.queue;w!==null&&(w.pending=null),h=h.next}cc=!1}if(la=0,tn=qt=Rt=null,xi=!1,ki=0,Yd.current=null,c===null||c.return===null){Yt=1,Ei=i,Ht=null;break}e:{var b=r,$=c.return,D=c,U=i;if(i=on,D.flags|=32768,U!==null&&typeof U=="object"&&typeof U.then=="function"){var re=U,he=D,ye=he.tag;if((he.mode&1)===0&&(ye===0||ye===11||ye===15)){var fe=he.alternate;fe?(he.updateQueue=fe.updateQueue,he.memoizedState=fe.memoizedState,he.lanes=fe.lanes):(he.updateQueue=null,he.memoizedState=null)}var Ce=Dp($);if(Ce!==null){Ce.flags&=-257,Fp(Ce,$,D,b,i),Ce.mode&1&&Pp(b,re,i),i=Ce,U=re;var Ie=i.updateQueue;if(Ie===null){var Le=new Set;Le.add(U),i.updateQueue=Le}else Ie.add(U);break e}else{if((i&1)===0){Pp(b,re,i),af();break e}U=Error(n(426))}}else if(Et&&D.mode&1){var zt=Dp($);if(zt!==null){(zt.flags&65536)===0&&(zt.flags|=256),Fp(zt,$,D,b,i),gd(oo(U,D));break e}}b=U=oo(U,D),Yt!==4&&(Yt=2),Ai===null?Ai=[b]:Ai.push(b),b=$;do{switch(b.tag){case 3:b.flags|=65536,i&=-i,b.lanes|=i;var X=Lp(b,U,i);lp(b,X);break e;case 1:D=U;var H=b.type,ee=b.stateNode;if((b.flags&128)===0&&(typeof H.getDerivedStateFromError=="function"||ee!==null&&typeof ee.componentDidCatch=="function"&&(Nr===null||!Nr.has(ee)))){b.flags|=65536,i&=-i,b.lanes|=i;var ke=Op(b,D,i);lp(b,ke);break e}}b=b.return}while(b!==null)}gg(c)}catch(De){i=De,Ht===c&&c!==null&&(Ht=c=c.return);continue}break}while(!0)}function mg(){var r=wc.current;return wc.current=fc,r===null?fc:r}function af(){(Yt===0||Yt===3||Yt===2)&&(Yt=4),nn===null||(ca&268435455)===0&&(vc&268435455)===0||Ar(nn,on)}function jc(r,i){var c=it;it|=2;var h=mg();(nn!==r||on!==i)&&(er=null,da(r,i));do try{yx();break}catch(w){hg(r,w)}while(!0);if(wd(),it=c,wc.current=h,Ht!==null)throw Error(n(261));return nn=null,on=0,Yt}function yx(){for(;Ht!==null;)pg(Ht)}function wx(){for(;Ht!==null&&!zu();)pg(Ht)}function pg(r){var i=vg(r.alternate,r,Jn);r.memoizedProps=r.pendingProps,i===null?gg(r):Ht=i,Yd.current=null}function gg(r){var i=r;do{var c=i.alternate;if(r=i.return,(i.flags&32768)===0){if(c=ux(c,i,Jn),c!==null){Ht=c;return}}else{if(c=dx(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 fa(r,i,c){var h=ot,w=os.transition;try{os.transition=null,ot=1,vx(r,i,c,h)}finally{os.transition=w,ot=h}return null}function vx(r,i,c,h){do uo();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||bc||(bc=!0,_g(Ta,function(){return uo(),null})),b=(c.flags&15990)!==0,(c.subtreeFlags&15990)!==0||b){b=os.transition,os.transition=null;var $=ot;ot=1;var D=it;it|=4,Yd.current=null,hx(r,c),og(c,r),Fb(ad),za=!!rd,ad=rd=null,r.current=c,mx(c),Jo(),it=D,ot=$,os.transition=b}else r.current=c;if(bc&&(bc=!1,Cr=r,xc=w),b=r.pendingLanes,b===0&&(Nr=null),qo(c.stateNode),Pn(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(_c)throw _c=!1,r=Zd,Zd=null,r;return(xc&1)!==0&&r.tag!==0&&uo(),b=r.pendingLanes,(b&1)!==0?r===ef?$i++:($i=0,ef=r):$i=0,xr(),null}function uo(){if(Cr!==null){var r=fn(xc),i=os.transition,c=ot;try{if(os.transition=null,ot=16>r?16:r,Cr===null)var h=!1;else{if(r=Cr,Cr=null,xc=0,(it&6)!==0)throw Error(n(331));var w=it;for(it|=4,Te=r.current;Te!==null;){var b=Te,$=b.child;if((Te.flags&16)!==0){var D=b.deletions;if(D!==null){for(var U=0;U<D.length;U++){var re=D[U];for(Te=re;Te!==null;){var he=Te;switch(he.tag){case 0:case 11:case 15:Ci(8,he,b)}var ye=he.child;if(ye!==null)ye.return=he,Te=ye;else for(;Te!==null;){he=Te;var fe=he.sibling,Ce=he.return;if(tg(he),he===re){Te=null;break}if(fe!==null){fe.return=Ce,Te=fe;break}Te=Ce}}}var Ie=b.alternate;if(Ie!==null){var Le=Ie.child;if(Le!==null){Ie.child=null;do{var zt=Le.sibling;Le.sibling=null,Le=zt}while(Le!==null)}}Te=b}}if((b.subtreeFlags&2064)!==0&&$!==null)$.return=b,Te=$;else e:for(;Te!==null;){if(b=Te,(b.flags&2048)!==0)switch(b.tag){case 0:case 11:case 15:Ci(9,b,b.return)}var X=b.sibling;if(X!==null){X.return=b.return,Te=X;break e}Te=b.return}}var H=r.current;for(Te=H;Te!==null;){$=Te;var ee=$.child;if(($.subtreeFlags&2064)!==0&&ee!==null)ee.return=$,Te=ee;else e:for($=H;Te!==null;){if(D=Te,(D.flags&2048)!==0)try{switch(D.tag){case 0:case 11:case 15:yc(9,D)}}catch(De){Lt(D,D.return,De)}if(D===$){Te=null;break e}var ke=D.sibling;if(ke!==null){ke.return=D.return,Te=ke;break e}Te=D.return}}if(it=w,xr(),Vt&&typeof Vt.onPostCommitFiberRoot=="function")try{Vt.onPostCommitFiberRoot(As,r)}catch{}h=!0}return h}finally{ot=c,os.transition=i}}return!1}function yg(r,i,c){i=oo(c,i),i=Lp(r,i,1),r=Sr(r,i,1),i=Nn(),r!==null&&(dr(r,1,i),Pn(r,i))}function Lt(r,i,c){if(r.tag===3)yg(r,r,c);else for(;i!==null;){if(i.tag===3){yg(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=oo(c,r),r=Op(i,r,1),i=Sr(i,r,1),r=Nn(),i!==null&&(dr(i,1,r),Pn(i,r));break}}i=i.return}}function _x(r,i,c){var h=r.pingCache;h!==null&&h.delete(i),i=Nn(),r.pingedLanes|=r.suspendedLanes&c,nn===r&&(on&c)===c&&(Yt===4||Yt===3&&(on&130023424)===on&&500>Nt()-Xd?da(r,0):Qd|=c),Pn(r,i)}function wg(r,i){i===0&&((r.mode&1)===0?i=1:(i=Hr,Hr<<=1,(Hr&130023424)===0&&(Hr=4194304)));var c=Nn();r=Qs(r,i),r!==null&&(dr(r,i,c),Pn(r,c))}function bx(r){var i=r.memoizedState,c=0;i!==null&&(c=i.retryLane),wg(r,c)}function xx(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),wg(r,c)}var vg;vg=function(r,i,c){if(r!==null)if(r.memoizedProps!==i.pendingProps||In.current)Ln=!0;else{if((r.lanes&c)===0&&(i.flags&128)===0)return Ln=!1,cx(r,i,c);Ln=(r.flags&131072)!==0}else Ln=!1,Et&&(i.flags&1048576)!==0&&Xm(i,ec,i.index);switch(i.lanes=0,i.tag){case 2:var h=i.type;pc(r,i),r=i.pendingProps;var w=Xa(i,hn.current);ro(i,c),w=Ad(null,i,h,r,w,c);var b=$d();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,Mn(h)?(b=!0,Ql(i)):b=!1,i.memoizedState=w.state!==null&&w.state!==void 0?w.state:null,xd(i),w.updater=hc,i.stateNode=w,w._reactInternals=i,Od(i,h,r,c),i=zd(null,i,h,!0,b,c)):(i.tag=0,Et&&b&&fd(i),jn(null,i,w,c),i=i.child),i;case 16:h=i.elementType;e:{switch(pc(r,i),r=i.pendingProps,w=h._init,h=w(h._payload),i.type=h,w=i.tag=Sx(h),r=_s(h,r),w){case 0:i=Fd(null,i,h,r,c);break e;case 1:i=Gp(null,i,h,r,c);break e;case 11:i=zp(null,i,h,r,c);break e;case 14:i=Bp(null,i,h,_s(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:_s(h,w),Fd(r,i,h,w,c);case 1:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:_s(h,w),Gp(r,i,h,w,c);case 3:e:{if(Hp(i),r===null)throw Error(n(387));h=i.pendingProps,b=i.memoizedState,w=b.element,ip(r,i),oc(i,h,null,c);var $=i.memoizedState;if(h=$.element,b.isDehydrated)if(b={element:h,isDehydrated:!1,cache:$.cache,pendingSuspenseBoundaries:$.pendingSuspenseBoundaries,transitions:$.transitions},i.updateQueue.baseState=b,i.memoizedState=b,i.flags&256){w=oo(Error(n(423)),i),i=Kp(r,i,h,c,w);break e}else if(h!==w){w=oo(Error(n(424)),i),i=Kp(r,i,h,c,w);break e}else for(Kn=vr(i.stateNode.containerInfo.firstChild),Hn=i,Et=!0,vs=null,c=ap(i,null,h,c),i.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{if(to(),h===w){i=Zs(r,i,c);break e}jn(r,i,h,c)}i=i.child}return i;case 5:return up(i),r===null&&pd(i),h=i.type,w=i.pendingProps,b=r!==null?r.memoizedProps:null,$=w.children,od(h,w)?$=null:b!==null&&od(h,b)&&(i.flags|=32),Vp(r,i),jn(r,i,$,c),i.child;case 6:return r===null&&pd(i),null;case 13:return Jp(r,i,c);case 4:return kd(i,i.stateNode.containerInfo),h=i.pendingProps,r===null?i.child=no(i,null,h,c):jn(r,i,h,c),i.child;case 11:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:_s(h,w),zp(r,i,h,w,c);case 7:return jn(r,i,i.pendingProps,c),i.child;case 8:return jn(r,i,i.pendingProps.children,c),i.child;case 12:return jn(r,i,i.pendingProps.children,c),i.child;case 10:e:{if(h=i.type._context,w=i.pendingProps,b=i.memoizedProps,$=w.value,_t(sc,h._currentValue),h._currentValue=$,b!==null)if(ws(b.value,$)){if(b.children===w.children&&!In.current){i=Zs(r,i,c);break e}}else for(b=i.child,b!==null&&(b.return=i);b!==null;){var D=b.dependencies;if(D!==null){$=b.child;for(var U=D.firstContext;U!==null;){if(U.context===h){if(b.tag===1){U=Xs(-1,c&-c),U.tag=2;var re=b.updateQueue;if(re!==null){re=re.shared;var he=re.pending;he===null?U.next=U:(U.next=he.next,he.next=U),re.pending=U}}b.lanes|=c,U=b.alternate,U!==null&&(U.lanes|=c),_d(b.return,c,i),D.lanes|=c;break}U=U.next}}else if(b.tag===10)$=b.type===i.type?null:b.child;else if(b.tag===18){if($=b.return,$===null)throw Error(n(341));$.lanes|=c,D=$.alternate,D!==null&&(D.lanes|=c),_d($,c,i),$=b.sibling}else $=b.child;if($!==null)$.return=b;else for($=b;$!==null;){if($===i){$=null;break}if(b=$.sibling,b!==null){b.return=$.return,$=b;break}$=$.return}b=$}jn(r,i,w.children,c),i=i.child}return i;case 9:return w=i.type,h=i.pendingProps.children,ro(i,c),w=rs(w),h=h(w),i.flags|=1,jn(r,i,h,c),i.child;case 14:return h=i.type,w=_s(h,i.pendingProps),w=_s(h.type,w),Bp(r,i,h,w,c);case 15:return Wp(r,i,i.type,i.pendingProps,c);case 17:return h=i.type,w=i.pendingProps,w=i.elementType===h?w:_s(h,w),pc(r,i),i.tag=1,Mn(h)?(r=!0,Ql(i)):r=!1,ro(i,c),Ip(i,h,w),Od(i,h,w,c),zd(null,i,h,!0,r,c);case 19:return Yp(r,i,c);case 22:return Up(r,i,c)}throw Error(n(156,i.tag))};function _g(r,i){return Ea(r,i)}function kx(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 is(r,i,c,h){return new kx(r,i,c,h)}function of(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Sx(r){if(typeof r=="function")return of(r)?1:0;if(r!=null){if(r=r.$$typeof,r===oe)return 11;if(r===L)return 14}return 2}function $r(r,i){var c=r.alternate;return c===null?(c=is(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 Nc(r,i,c,h,w,b){var $=2;if(h=r,typeof r=="function")of(r)&&($=1);else if(typeof r=="string")$=5;else e:switch(r){case I:return ha(c.children,w,b,i);case M:$=8,w|=8;break;case B:return r=is(12,c,i,w|2),r.elementType=B,r.lanes=b,r;case z:return r=is(13,c,i,w),r.elementType=z,r.lanes=b,r;case F:return r=is(19,c,i,w),r.elementType=F,r.lanes=b,r;case V:return Cc(c,w,b,i);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case G:$=10;break e;case Z:$=9;break e;case oe:$=11;break e;case L:$=14;break e;case q:$=16,h=null;break e}throw Error(n(130,r==null?r:typeof r,""))}return i=is($,c,i,w),i.elementType=r,i.type=h,i.lanes=b,i}function ha(r,i,c,h){return r=is(7,r,h,i),r.lanes=c,r}function Cc(r,i,c,h){return r=is(22,r,h,i),r.elementType=V,r.lanes=c,r.stateNode={isHidden:!1},r}function lf(r,i,c){return r=is(6,r,null,i),r.lanes=c,r}function cf(r,i,c){return i=is(4,r.children!==null?r.children:[],r.key,i),i.lanes=c,i.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},i}function jx(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 uf(r,i,c,h,w,b,$,D,U){return r=new jx(r,i,c,D,U),i===1?(i=1,b===!0&&(i|=8)):i=0,b=is(3,null,null,i),r.current=b,b.stateNode=r,b.memoizedState={element:h,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null},xd(b),r}function Nx(r,i,c){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:S,key:h==null?null:""+h,children:r,containerInfo:i,implementation:c}}function bg(r){if(!r)return br;r=r._reactInternals;e:{if(Cs(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(Mn(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(Mn(c))return qm(r,c,i)}return i}function xg(r,i,c,h,w,b,$,D,U){return r=uf(c,h,!0,r,w,b,$,D,U),r.context=bg(null),c=r.current,h=Nn(),w=Er(c),b=Xs(h,w),b.callback=i??null,Sr(c,b,w),r.current.lanes=w,dr(r,w,h),Pn(r,h),r}function Ec(r,i,c,h){var w=i.current,b=Nn(),$=Er(w);return c=bg(c),i.context===null?i.context=c:i.pendingContext=c,i=Xs(b,$),i.payload={element:r},h=h===void 0?null:h,h!==null&&(i.callback=h),r=Sr(w,i,$),r!==null&&(ks(r,w,$,b),ac(r,w,$)),$}function Ac(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 kg(r,i){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var c=r.retryLane;r.retryLane=c!==0&&c<i?c:i}}function df(r,i){kg(r,i),(r=r.alternate)&&kg(r,i)}function Cx(){return null}var Sg=typeof reportError=="function"?reportError:function(r){console.error(r)};function ff(r){this._internalRoot=r}$c.prototype.render=ff.prototype.render=function(r){var i=this._internalRoot;if(i===null)throw Error(n(409));Ec(r,i,null,null)},$c.prototype.unmount=ff.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var i=r.containerInfo;ua(function(){Ec(null,r,null,null)}),i[Ks]=null}};function $c(r){this._internalRoot=r}$c.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 hf(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Tc(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function jg(){}function Ex(r,i,c,h,w){if(w){if(typeof h=="function"){var b=h;h=function(){var re=Ac($);b.call(re)}}var $=xg(i,h,r,0,null,!1,!1,"",jg);return r._reactRootContainer=$,r[Ks]=$.current,mi(r.nodeType===8?r.parentNode:r),ua(),$}for(;w=r.lastChild;)r.removeChild(w);if(typeof h=="function"){var D=h;h=function(){var re=Ac(U);D.call(re)}}var U=uf(r,0,!1,null,null,!1,!1,"",jg);return r._reactRootContainer=U,r[Ks]=U.current,mi(r.nodeType===8?r.parentNode:r),ua(function(){Ec(i,U,c,h)}),U}function Rc(r,i,c,h,w){var b=c._reactRootContainer;if(b){var $=b;if(typeof w=="function"){var D=w;w=function(){var U=Ac($);D.call(U)}}Ec(i,$,r,w)}else $=Ex(c,i,r,w,h);return Ac($)}Kr=function(r){switch(r.tag){case 3:var i=r.stateNode;if(i.current.memoizedState.isDehydrated){var c=dn(i.pendingLanes);c!==0&&(Us(i,c|1),Pn(i,Nt()),(it&6)===0&&(co=Nt()+500,xr()))}break;case 13:ua(function(){var h=Qs(r,1);if(h!==null){var w=Nn();ks(h,r,1,w)}}),df(r,1)}},La=function(r){if(r.tag===13){var i=Qs(r,134217728);if(i!==null){var c=Nn();ks(i,r,134217728,c)}df(r,134217728)}},Oa=function(r){if(r.tag===13){var i=Er(r),c=Qs(r,i);if(c!==null){var h=Nn();ks(c,r,i,h)}df(r,i)}},Pa=function(){return ot},Qo=function(r,i){var c=ot;try{return ot=r,i()}finally{ot=c}},Bo=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=ql(h);if(!w)throw Error(n(90));Xe(h),st(h,w)}}}break;case"textarea":ge(r,c);break;case"select":i=c.value,i!=null&&de(r,!!c.multiple,i,!1)}},Wo=sf,lr=ua;var Ax={usingClientEntryPoint:!1,Events:[yi,Ya,ql,Zt,ja,sf]},Ti={findFiberByHostInstance:na,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},$x={bundleType:Ti.bundleType,version:Ti.version,rendererPackageName:Ti.rendererPackageName,rendererConfig:Ti.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=Qn(r),r===null?null:r.stateNode},findFiberByHostInstance:Ti.findFiberByHostInstance||Cx,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 Ic=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ic.isDisabled&&Ic.supportsFiber)try{As=Ic.inject($x),Vt=Ic}catch{}}return Dn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Ax,Dn.createPortal=function(r,i){var c=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!hf(i))throw Error(n(200));return Nx(r,i,null,c)},Dn.createRoot=function(r,i){if(!hf(r))throw Error(n(299));var c=!1,h="",w=Sg;return i!=null&&(i.unstable_strictMode===!0&&(c=!0),i.identifierPrefix!==void 0&&(h=i.identifierPrefix),i.onRecoverableError!==void 0&&(w=i.onRecoverableError)),i=uf(r,1,!1,null,null,c,!1,h,w),r[Ks]=i.current,mi(r.nodeType===8?r.parentNode:r),new ff(i)},Dn.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=Qn(i),r=r===null?null:r.stateNode,r},Dn.flushSync=function(r){return ua(r)},Dn.hydrate=function(r,i,c){if(!Tc(i))throw Error(n(200));return Rc(null,r,i,!0,c)},Dn.hydrateRoot=function(r,i,c){if(!hf(r))throw Error(n(405));var h=c!=null&&c.hydratedSources||null,w=!1,b="",$=Sg;if(c!=null&&(c.unstable_strictMode===!0&&(w=!0),c.identifierPrefix!==void 0&&(b=c.identifierPrefix),c.onRecoverableError!==void 0&&($=c.onRecoverableError)),i=xg(i,null,r,1,c??null,w,!1,b,$),r[Ks]=i.current,mi(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 $c(i)},Dn.render=function(r,i,c){if(!Tc(i))throw Error(n(200));return Rc(null,r,i,!1,c)},Dn.unmountComponentAtNode=function(r){if(!Tc(r))throw Error(n(40));return r._reactRootContainer?(ua(function(){Rc(null,null,r,!1,function(){r._reactRootContainer=null,r[Ks]=null})}),!0):!1},Dn.unstable_batchedUpdates=sf,Dn.unstable_renderSubtreeIntoContainer=function(r,i,c,h){if(!Tc(c))throw Error(n(200));if(r==null||r._reactInternals===void 0)throw Error(n(38));return Rc(r,i,c,!1,h)},Dn.version="18.3.1-next-f1338f8080-20240426",Dn}var Ig;function Nw(){if(Ig)return gf.exports;Ig=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(),gf.exports=Fx(),gf.exports}var Mg;function zx(){if(Mg)return Mc;Mg=1;var e=Nw();return Mc.createRoot=e.createRoot,Mc.hydrateRoot=e.hydrateRoot,Mc}var Bx=zx();const Wx=jw(Bx),Cw=[{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"]}];Cw.map(e=>({id:e.id,label:e.label}));function Ux(e){return`theme-${String(e||"").trim()||"dark"}`}function Lg(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(Ux(e))}catch{}}const ih=[{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}],lh=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function Vx(e){const t=String(e).trim();return ih.find(n=>n.id===t)||ih[1]}function Gx(e){const t=String(e).trim();return lh.find(n=>n.id===t)||lh[1]}function Og(e){try{const t=document.documentElement,n=Vx(e.font_scale||"md"),s=Gx(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(s.density))}catch{}}const qc={md:"(max-width: 1023.98px)",lg:"(max-width: 1439.98px)"};function Hx(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function Yc(e){const[t,n]=y.useState(()=>Hx(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 Ii=null;function Kx(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 Jx(){if(Ii)return Ii;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}=Kx(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),Ii=()=>{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"),Ii=null},Ii}var ul=Nw();function fo(...e){return e.filter(Boolean).join(" ")}function xn({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:j,validateCustomValue:A,onChange:T,renderOption:N,renderValue:E}){const S=y.useRef(null),I=y.useRef(null),M=y.useRef(null),B=y.useRef(k),G=y.useId(),Z=C||`af-select-${G.replace(/[^a-zA-Z0-9_-]/g,"")}`,oe=`${Z}-listbox`,[z,F]=y.useState(!1),[L,q]=y.useState(""),[V,Y]=y.useState(0),[J,W]=y.useState("bottom"),[R,K]=y.useState({left:0,top:0,width:0});y.useEffect(()=>{B.current=k},[k]);const se=y.useMemo(()=>{if(!x)return t;const le=String(e??"").trim();return!le||t.some(de=>de.value===le)?t:[...t,{value:le,label:le}]},[x,t,e]),ce=y.useMemo(()=>{const le=String(e??"");return se.find(de=>de.value===le)||null},[se,e]),ae=y.useMemo(()=>(ce==null?void 0:ce.label)||String(e||"").trim()||"",[ce,e]),we=y.useMemo(()=>{const le=L.trim().toLowerCase();return le?se.filter(de=>de.label.toLowerCase().includes(le)||de.value.toLowerCase().includes(le)):se},[se,L]),Se=y.useMemo(()=>{if(!d)return null;const le=L.trim();if(!le||se.some(_e=>_e.value===le))return null;const je=(A==null?void 0:A(le,{options:se}))||"";return{value:le,label:j?j(le):`Use "${le}"`,disabled:!!je,reason:je}},[d,j,se,L,A]),Q=y.useMemo(()=>{const le=Se?[Se,...we]:we;if(le.length>0)return le;const de=String(e??"").trim();return o&&de?[{value:de,label:ae||de}]:le},[Se,we,o,ae,e]),xe=y.useCallback(()=>{const le=S.current;if(!le)return;const de=le.getBoundingClientRect(),je=Math.max(de.width,m),_e=Math.max(8,Math.min(de.left,window.innerWidth-je-8)),ge=window.innerHeight-de.bottom,te=de.top,be=ge>=220||ge>=te?"bottom":"top";W(be);const P=be==="bottom"?de.bottom+6:de.top-6;K({left:_e,top:P,width:je})},[m]),ve=y.useCallback(()=>{F(!1),q("")},[]);y.useEffect(()=>{var le;z&&((le=B.current)==null||le.call(B))},[z]),y.useEffect(()=>{if(!z)return;xe();const le=()=>xe();return window.addEventListener("resize",le),window.addEventListener("scroll",le,!0),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0)}},[z,xe]),y.useEffect(()=>{if(!z)return;const le=de=>{var _e,ge;const je=de.target;je&&((_e=S.current)!=null&&_e.contains(je)||(ge=I.current)!=null&&ge.contains(je)||ve())};return document.addEventListener("mousedown",le,!0),()=>document.removeEventListener("mousedown",le,!0)},[z,ve]),y.useEffect(()=>{if(!z)return;const le=Math.max(0,Q.findIndex(de=>de.value===e));Y(le===-1?0:le),l&&setTimeout(()=>{var de;return(de=M.current)==null?void 0:de.focus()},0)},[z,l,e,Q]);const Fe=le=>{var je;const de=Q.find(_e=>_e.value===le);de!=null&&de.disabled||(T(le),ve(),(je=S.current)==null||je.focus())},Xe=le=>{var de,je;if(le.key==="Escape")return le.preventDefault(),ve(),(de=S.current)==null||de.focus(),!0;if(le.key==="Tab")return ve(),(je=S.current)==null||je.focus(),!1;if(le.key==="ArrowDown")return le.preventDefault(),Y(_e=>Math.min(_e+1,Math.max(0,Q.length-1))),!0;if(le.key==="ArrowUp")return le.preventDefault(),Y(_e=>Math.max(_e-1,0)),!0;if(le.key==="Home")return le.preventDefault(),Y(0),!0;if(le.key==="End")return le.preventDefault(),Y(Math.max(0,Q.length-1)),!0;if(le.key==="Enter"){le.preventDefault();const _e=Q[V];return _e&&Fe(_e.value),!0}return!1},Ve=le=>{if(!s){if(z){if(Xe(le))return;if(le.key===" "&&!l){le.preventDefault();const de=Q[V];de&&Fe(de.value)}return}(le.key==="Enter"||le.key===" "||le.key==="ArrowDown"||le.key==="ArrowUp")&&(le.preventDefault(),F(!0))}},Je=!!String(e||"").trim(),me=Je?ae:n,Me=Se!=null&&Se.disabled?Se.reason||"Unavailable":"",st=z&&Q.length>0?`${Z}-opt-${V}`:void 0,tt=a.jsx("span",{className:fo("af-select-value",!Je&&"af-select-value--placeholder"),children:o&&!Je?"Loading…":me}),$t=E?E(ce,String(e||"")):tt;return a.jsxs("span",{className:fo("af-select",p==="pin"?"af-select--pin":"af-select--panel",g),children:[a.jsxs("button",{ref:S,id:Z,type:"button",className:fo("af-select-trigger",f&&Je&&"af-select-trigger--clearable",_),disabled:s,onMouseDown:le=>le.stopPropagation(),onClick:le=>{le.stopPropagation(),!s&&F(de=>!de)},onKeyDown:Ve,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":z,"aria-controls":z?oe:void 0,"aria-activedescendant":l?void 0:st,"aria-label":v,children:[$t,a.jsx("span",{className:fo("af-select-caret",z&&"af-select-caret--open"),children:"▾"})]}),f&&Je?a.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:s,onMouseDown:le=>{le.preventDefault(),le.stopPropagation()},onClick:le=>{var de;le.preventDefault(),le.stopPropagation(),T(""),ve(),(de=S.current)==null||de.focus()},title:"Clear",children:"×"}):null,z?ul.createPortal(a.jsxs("div",{ref:I,className:fo("af-select-popover",J==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${R.left}px`,top:`${R.top}px`,width:`${R.width}px`},onMouseDown:le=>le.stopPropagation(),onClick:le=>le.stopPropagation(),onWheel:le=>le.stopPropagation(),onKeyDown:Xe,tabIndex:-1,children:[l?a.jsxs("div",{className:"af-select-search",children:[a.jsx("input",{ref:M,className:"af-select-search-input",value:L,onChange:le=>q(le.target.value),placeholder:u,onKeyDown:Xe,role:"combobox","aria-expanded":!0,"aria-controls":oe,"aria-activedescendant":st,"aria-invalid":!!Me,"aria-describedby":Me?`${Z}-custom-error`:void 0}),Me?a.jsx("div",{id:`${Z}-custom-error`,className:"af-select-custom-error",role:"alert",children:Me}):null]}):null,a.jsx("div",{className:"af-select-options",role:"listbox",id:oe,"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((le,de)=>{var P;const je=le.value===e,_e=de===V,ge=String(le.group||"").trim(),te=de>0?String(((P=Q[de-1])==null?void 0:P.group)||"").trim():"",be=!!ge&&ge!==te;return a.jsxs(wt.Fragment,{children:[be?a.jsx("div",{className:"af-select-group",role:"presentation",children:ge}):null,a.jsx("div",{id:`${Z}-opt-${de}`,role:"option","aria-selected":je,className:fo("af-select-option",je&&"af-select-option--selected",_e&&"af-select-option--highlighted",le.disabled&&"af-select-option--disabled"),title:le.disabled?le.reason||"Unavailable":void 0,onMouseEnter:()=>Y(de),onMouseDown:ie=>{ie.preventDefault(),ie.stopPropagation()},onClick:()=>Fe(le.value),"aria-disabled":le.disabled?!0:void 0,children:N?N(le,{selected:je,highlighted:_e}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"af-select-option-label",children:[a.jsx("span",{children:le.label}),le.reason?a.jsx("small",{className:"af-select-option-reason",children:le.reason}):null]}),je?a.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},le.value)})})]}),document.body):null]})}function qx(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 Yx(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 ch="Provided by connected pin";function Qx(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=qx(e.providers),_=Yx(e.models),v=typeof e.markSaved=="object"?e.markSaved:null,C=(N,E,S,I)=>e.markSaved&&!S&&!I&&(!v||v[E]===N)?`${N} (saved)`:N,x=t||!!e.loadingProviders,k=t||!!e.loadingModels,j=[...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)}]:[]],A=[...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)}]:[]],T=(N,E)=>a.jsxs("div",{className:"af-pmp__pinned","data-pinned":N,children:[a.jsx("span",{className:"af-pmp__pinned-text",children:ch}),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?T("provider",m):a.jsx(xn,{value:m,options:j,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?T("model",p):a.jsx(xn,{value:p,options:A,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 Vh(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 Xx(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 Pg(e){const t=Vh(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function Zx(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 ek(e){const t=Xx(e.capabilities),n=Pg(e.value),s=(t==null?void 0:t.supported_depths.map(String))||[],o=Pg(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(xn,{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(Zx(f))}),d&&!e.hideNote?a.jsx("div",{role:"status",className:"af-pmp__hint",children:d}):null]})}const Wr="api/gateway",dl="api/connection/gateway";function pe(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?`${Wr}/${t}`:Wr}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 tk(e){const t=String(e||""),n=`/${Wr}/`;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 nk=(e,t)=>{const n=String(e||"");if(!n)throw new Error(`A voice route needs a ${t}.`);return encodeURIComponent(n)},sk={clones:"voice/clones"};function uh(e){return`voice/clones/${nk(e,"voice id")}`}function rk(e){return`${uh(e)}/deploy`}const Ew="discovery/providers",ak="discovery/models/capabilities",ok="config/capability-defaults",ik="discovery/capabilities";function lk(e){const t=String(e||"").trim();if(!t)throw new Error("gatewayProviderModelsRoute needs a provider.");return`${Ew}/${encodeURIComponent(t)}/models`}const Aw=/^(?!\.+$)[A-Za-z0-9_.:-]{1,256}$/;function ck(e){const t=String(e??"");if(!Aw.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 vn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,It=e=>typeof e=="string"?e.trim():"";function $w(e){var p,g;const t=vn(e);if((t==null?void 0:t.ok)===!1){const _=Array.isArray(t.errors)?t.errors.map(It).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(vn).find(v=>v&&It(v.key)===_&&It(v.source)!=="not_configured"),o=s("output.text"),l=s("input.text"),u=[o,l].find(_=>_&&It(_.provider)&&It(_.model));if(!u)return null;const d=It(o==null?void 0:o.reasoning)||It(l==null?void 0:l.reasoning),f=Vh(((p=vn(l==null?void 0:l.options))==null?void 0:p.speculation)??((g=vn(o==null?void 0:o.options))==null?void 0:g.speculation)),m=Array.isArray(t==null?void 0:t.warnings)?t.warnings.map(It).filter(Boolean):[];return{provider:It(u.provider),model:It(u.model),...d?{reasoning:d}:{},...f!==void 0?{speculation:f}:{},...It(u.source)?{source:It(u.source)}:{},...m.length?{warnings:m}:{}}}function uk(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 dk(e,t="Gateway default"){const n=uk(e);return n?`${t} · ${n}`:t}function fk(e){var s,o,l,u,d,f;const t=vn((s=vn(e))==null?void 0:s.capabilities)??vn(e),n=(f=vn((d=vn((u=vn((l=vn((o=vn(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(It).filter(Boolean))]:[]}function hk(e){if(typeof e=="string")return e.trim()?{name:e.trim()}:null;const t=vn(e),n=It(t==null?void 0:t.id)||It(t==null?void 0:t.provider)||It(t==null?void 0:t.name);if(!n)return null;const s=It(t==null?void 0:t.label)||It(t==null?void 0:t.display_name);return s&&s!==n?{name:n,display_name:s}:{name:n}}function mk(e){return{async fetchProviders(){const t=vn(await e(pe(`${Ew}?include_models=false`))),n=Array.isArray(t==null?void 0:t.items)?t.items.map(hk).filter(s=>!!s):[];if(!n.length&&It(t==null?void 0:t.error))throw new Error(It(t==null?void 0:t.error));return n},async fetchModels(t){const n=vn(await e(pe(`${lk(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():It((u=vn(l))==null?void 0:u.id)}).filter(Boolean))];if(!o.length&&It(n==null?void 0:n.error))throw new Error(It(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(pe(`${ak}?${s.toString()}`))},async fetchGatewayDefault(){return $w(await e(pe(ok)))},async fetchReasoningLadder(){return fk(await e(pe(ik)))}}}const pk="The gateway does not say which reasoning levels this model supports.",gk="Set anyway",yk="Reasoning and MTP choices appear when the gateway can describe the selected model.",wk="Reasoning choices appear when the gateway can describe the selected model.";function ju(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,j]=y.useState(""),[A,T]=y.useState([]),[N,E]=y.useState({}),[S,I]=y.useState(!1),[M,B]=y.useState(""),G=y.useRef(e);G.current=e;const[Z,oe]=y.useState({status:"idle",value:null,message:""}),z=e.fetchGatewayDefault;y.useEffect(()=>{if(!z||t)return;let de=!0;const je=_e=>oe(ge=>JSON.stringify(ge)===JSON.stringify(_e)?ge:_e);return oe(_e=>_e.status==="idle"?{..._e,status:"loading"}:_e),z().then(_e=>{var ge;de&&(_e?(ge=_e.warnings)!=null&&ge.length?je({status:"unusable",value:_e,message:_e.warnings.join(" ")}):je({status:"resolved",value:_e,message:""}):je({status:"none",value:null,message:""}))}).catch(_e=>{de&&je({status:"error",value:null,message:String((_e==null?void 0:_e.message)||_e)})}),()=>{de=!1}},[z,t]);const F=Z.status==="resolved"?Z.value:null,L=y.useRef({provider:String(n.provider||"").trim(),model:String(n.model||"").trim()});y.useEffect(()=>{if(!m||l.provider||t)return;let de=!0;return x(!0),(async()=>{try{const je=await G.current.fetchProviders();if(!de)return;v(Array.isArray(je)?je:[]),j("")}catch(je){if(!de)return;v([]),j(`#FALLBACK provider discovery failed: ${String((je==null?void 0:je.message)||je)}`)}finally{de&&x(!1)}})(),()=>{de=!1}},[m,l.provider,t]);const q=String(n.provider||"").trim();y.useEffect(()=>{if(!q||t||l.model){T([]),B(""),I(!1);return}let de=!0;return T([]),I(!0),B(""),(async()=>{try{const je=await G.current.fetchModels(q);if(!de)return;const _e=[],ge={};for(const te of Array.isArray(je)?je:[]){const be=typeof te=="string"?te:String((te==null?void 0:te.id)||"");be&&(_e.push(be),typeof te!="string"&&(te!=null&&te.label)&&te.label!==be&&(ge[be]=String(te.label)))}T(_e),E(ge)}catch(je){if(!de)return;T([]),B(`#FALLBACK model discovery failed: ${String((je==null?void 0:je.message)||je)}`)}finally{de&&I(!1)}})(),()=>{de=!1}},[q,t,l.model]);const V=String(n.model||"").trim(),Y=e.defaultModeLabel||"Gateway default",J=Z.status==="none"?`${Y} · none configured`:dk(F,Y),W=e.customModeLabel||"Custom",R=e.effectiveDefault||(Z.value?{provider:Z.value.provider,model:Z.value.model}:void 0),K=q||(R==null?void 0:R.provider)||"",se=V||(q?"":R==null?void 0:R.model)||"",[ce,ae]=y.useState({levels:[],error:"",loading:!1}),[we,Se]=y.useState(!1),Q=!!e.fetchModelCapabilities,[xe,ve]=y.useState();y.useEffect(()=>{let de=!0;if(ve(void 0),ae({levels:[],error:"",loading:Q&&!!se}),!(!Q||!se||t))return G.current.fetchModelCapabilities(se,K).then(je=>{var P;if(!de)return;if(je!=null&&je.error)throw new Error(String(je.error));ve(je);const _e=(je==null?void 0:je.capabilities)||je||{},ge=_e.reasoning_levels||_e.thinking_levels,te=Array.isArray(ge)?[...new Set(ge.filter(ie=>typeof ie=="string"&&!!ie.trim()))]:[];!te.length&&_e.thinking_support===!0&&((P=_e.thinking_control)!=null&&P.prompt_disable_token)&&te.push("off","auto");const be=typeof _e.thinking_support=="boolean"?_e.thinking_support:void 0;ae({levels:te,support:be,error:"",loading:!1})}).catch(je=>{de&&ae({levels:[],error:String((je==null?void 0:je.message)||je),loading:!1})}),()=>{de=!1}},[K,se,Q,t]),y.useEffect(()=>Se(!1),[K,se]);const Fe=e.inheritLabel||"Workflow / Gateway default",Xe=p&&(F!=null&&F.reasoning)?`${Fe} (${F.reasoning})`:Fe,Ve=!p||e.optionsInDefaultMode!==!1,Je=e.reasoningLadder?[...new Set(e.reasoningLadder.filter(de=>typeof de=="string"&&de.trim()))]:null,me=ce.loading?"loading":ce.levels.length||ce.support===!0?"supported":ce.support===!1?"unsupported":"unknown",Me=e.unknownReasoning==="allow-override"&&!!(Je!=null&&Je.length),st=String(n.reasoning||"").trim();let tt=[],$t=!1;if(!Je)tt=ce.levels.map(de=>({value:de,label:de}));else if(me==="supported"||me==="loading"){const de=ce.levels;tt=[...Je,...de.filter(_e=>!Je.includes(_e))].map(_e=>!de.length||de.includes(_e)?{value:_e,label:_e}:{value:_e,label:_e,disabled:!0,reason:"This model does not advertise it"})}else me==="unknown"&&Me&&($t=!we,tt=Je.map(de=>({value:de,label:de})));st&&!tt.some(de=>de.value===st)&&tt.push({value:st,label:`${st} (saved)`});const le=(Q||Me)&&(tt.length>0||me==="unknown"&&Me);return a.jsxs("div",{className:`af-pmp${o?" af-pmp--compact":""}${e.className?` ${e.className}`:""}`,"data-gateway-default":z?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:J,"data-default-choice":"",children:J}),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(Qx,{provider:q,model:V,providers:_,models:A,modelDisplayNames:N,markSaved:L.current,providerPinned:l.provider,modelPinned:l.model,disabled:t,loadingProviders:C,loadingModels:S,providerError:k||void 0,modelError:M||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:o,gatewayDefaultLabel:o?J:void 0,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:de=>e.onChange({...n,provider:de.provider,model:de.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."}),Ve&&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:ch})]}):Ve&&le?a.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":me,children:[a.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),a.jsx(xn,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:Xe,value:n.reasoning||"",options:[{value:"",label:Xe},...tt],disabled:t||ce.loading||$t,onChange:de=>e.onChange({...n,reasoning:de})}),me==="unknown"&&Me?a.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[pk," ",a.jsxs("label",{className:"af-pmp__override",children:[a.jsx("input",{type:"checkbox",checked:we,disabled:t,onChange:de=>{Se(de.target.checked),!de.target.checked&&n.reasoning&&e.onChange({...n,reasoning:""})}})," ",gk]})]}):null]}):null,Ve&&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:ch})]}):Ve&&e.enableSpeculation?a.jsx(ek,{value:n.speculation,inheritLabel:Fe,onChange:de=>e.onChange({...n,speculation:de}),capabilities:xe,disabled:t,loading:ce.loading,hideNote:!!ce.error}):null,Ve&&ce.error?a.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?yk:wk,a.jsxs("details",{className:"af-pmp__details",children:[a.jsx("summary",{children:"Technical details"}),a.jsx("span",{children:ce.error})]})]}):null]})}function Dg(...e){return e.filter(Boolean).join(" ")}function vk({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:j=!1,rememberLabel:A="Remember this browser",onRememberChange:T,loading:N=!1,submitting:E=!1,submitDisabled:S=!1,submitLabel:I="Sign in",submittingLabel:M="Signing in...",closeLabel:B="Close",signOutLabel:G="Sign out",showClose:Z=!1,showSignOut:oe=!1,error:z,message:F,className:L,onSubmit:q,onClose:V,onSignOut:Y}){const J=N||E,W=J||S||!String(m||"").trim()||!String(_||"").trim(),R=K=>{K.preventDefault(),!W&&q()};return a.jsxs("form",{className:Dg("af-gateway-signin",L),onSubmit:R,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:Dg("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:J})]}):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:J}),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:J}),a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>k==null?void 0:k(!C),disabled:J,children:C?"Hide":"Show"})]}),a.jsxs("label",{className:"af-gateway-signin__checkbox",children:[a.jsx("input",{type:"checkbox",checked:!!j,onChange:K=>T==null?void 0:T(K.target.checked),disabled:J}),A]})]}),z?a.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:z}):null,!z&&F?a.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:F}):null,a.jsxs("div",{className:"af-gateway-signin__actions",children:[Z?a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:V,disabled:J,children:B}):null,oe?a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(Y==null?void 0:Y()),disabled:J,children:G}):null,a.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:W,children:E?M:I})]})]})}function _k(e){return e==="light"?"Light":"Dark"}function bk(e){const t=e.themes&&e.themes.length?e.themes:Cw,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:_k(u.group)})),[t]);return a.jsx(xn,{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 xk(e){const t=e.scales&&e.scales.length?e.scales:ih,n=e.variant||"panel",s=y.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return a.jsx(xn,{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 kk(e){const t=e.densities&&e.densities.length?e.densities:lh,n=e.variant||"panel",s=y.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return a.jsx(xn,{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 Sk=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function jk(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 ue({name:e,size:t=16,className:n,title:s,...o}){const l=s?void 0:!0,u=Sk.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,jk(e)]})}function Nk(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function Ck(e){return Nk(e)?!e.checked:null}let Ek=0;function Ur(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-${++Ek}`:void 0),j=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",x?"af-switch--unavailable":"",g||""].filter(Boolean).join(" "),A=N=>{const E=Ck({checked:n,unavailableReason:C,busy:f});if(E===null){N.preventDefault();return}s==null||s(E)},T=a.jsxs("button",{type:"button",role:"switch",id:_,className:j,"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:A,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?T:a.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[T,a.jsx("span",{id:k,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:C})]})}function Ak(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 $k=150,Gh="data-af-tip";function Tk(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 Fg=0;function Tw(e){return e?String(e.getAttribute(Gh)||"").trim():""}function vf(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const s=n.closest(`[${Gh}]`);return!s||!t.contains(s)||!Tw(s)?null:s}function Rk(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:$k;Fg+=1;const l=n.createElement("div");l.className="af-tooltip",l.setAttribute("role","tooltip");const u=`af-tooltip-${Fg}`;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 L=d.getBoundingClientRect(),q=l.getBoundingClientRect(),V=Tk(L,{width:q.width,height:q.height},{width:s.innerWidth,height:s.innerHeight});l.style.top=`${V.top}px`,l.style.left=`${V.left}px`,l.setAttribute("data-side",V.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=""},j=L=>{v(),C(),d&&d!==L&&k();const q=Tw(L);if(!q||L.isConnected===!1)return;if(d=L,l.textContent=q,l.hidden=!1,String(L.getAttribute("aria-label")||"").trim()!==q){const Y=L.getAttribute("aria-describedby");_=Y&&Y!==u?Y:null,L.setAttribute("aria-describedby",_?`${_} ${u}`:u)}x()},A=L=>{C(),d!==L&&f!==L&&(v(),f=L,m=setTimeout(()=>{const q=f;m=null,f=null,q&&j(q)},o))},T=()=>{v(),d&&(C(),p=setTimeout(k,100))},N=L=>{try{if(typeof L.matches=="function")return L.matches(":focus-visible")}catch{}return g},E=L=>{if(L.pointerType==="touch")return;if(l.contains(L.target)){C();return}const V=vf(L.target,e);V&&A(V)},S=L=>{const V=L.relatedTarget||null;if(!(V&&(l.contains(V)||d&&d.contains(V)||f&&f.contains(V)))){if(f&&!d){v();return}d&&T()}},I=L=>{const q=L.relatedTarget||null;q&&(l.contains(q)||d&&d.contains(q))||T()},M=L=>{const q=vf(L.target,e);q&&N(q)&&A(q)},B=L=>{const q=vf(L.target,e);q&&(q===d||q===f)&&k()},G=()=>{g=!1,k()},Z=L=>{if(L.key==="Escape"||L.key==="Esc"){d?(L.preventDefault(),k()):v();return}!L.metaKey&&!L.ctrlKey&&!L.altKey&&(g=!0)},oe=()=>k(),z=e;z.addEventListener("pointerover",E),z.addEventListener("pointerout",S),z.addEventListener("focusin",M),z.addEventListener("focusout",B),l.addEventListener("pointerover",E),l.addEventListener("pointerout",I),n.addEventListener("pointerdown",G,!0),s.addEventListener("keydown",Z,!0),s.addEventListener("scroll",oe,!0),s.addEventListener("resize",oe);let F=!1;return()=>{F||(F=!0,k(),z.removeEventListener("pointerover",E),z.removeEventListener("pointerout",S),z.removeEventListener("focusin",M),z.removeEventListener("focusout",B),l.removeEventListener("pointerover",E),l.removeEventListener("pointerout",I),n.removeEventListener("pointerdown",G,!0),s.removeEventListener("keydown",Z,!0),s.removeEventListener("scroll",oe,!0),s.removeEventListener("resize",oe),l.parentNode&&l.parentNode.removeChild(l))}}const Lc=new WeakMap;function Ik(e){let t=Lc.get(e);t||(t={count:0,release:Rk(e)},Lc.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const s=Lc.get(e);s&&(s.count-=1,s.count<=0&&(s.release(),Lc.delete(e)))}}function Lo(){y.useEffect(()=>{if(!(typeof document>"u"))return Ik(document)},[])}function ru(e){Lo();const t=wt.Children.only(e.children),n=String(e.content||"").trim();return n?wt.cloneElement(t,{[Gh]:n}):t}function Mk(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}function Rw(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function Lk(e){const t=e||{},n=t.connectionPath||dl,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"),j=y.useRef(!1),A=y.useRef(0),T=y.useCallback(F=>{var q;A.current+=1,f(F),(q=o.current)==null||q.call(o,F);const L=Rw(F);if(L)p("connected"),x.current="connected",v.current=!1,k.current="none",C.current||_(!1);else if(F!==null){const V=x.current;p("disconnected"),x.current="disconnected",V!=="disconnected"&&(k.current=j.current?"signout":V==="connected"?"mid":"boot");const Y=l.current==="blocking"||k.current!=="mid"||u.current;!v.current&&Y&&_(!0)}F!==null&&(C.current=L)},[]),N=y.useCallback(async()=>{const F=A.current;try{const L=await dh(n);if(A.current!==F)return;T(L)}catch{if(A.current!==F)return;T(null)}},[n,T]),[E,S]=y.useState(!1),[I,M]=y.useState(null),B=y.useCallback(async()=>{S(!0),M(null),A.current+=1;let F=null;try{await Mw(n)}catch(L){F=String((L==null?void 0:L.message)||L||"Sign-out request failed")}j.current=!0;try{await N()}finally{j.current=!1}return M(F),S(!1),F===null&&x.current!=="connected"},[n,N]),G=y.useRef(!1);y.useEffect(()=>{G.current||(G.current=!0,N())},[N]);const Z=y.useCallback(()=>{_(!0)},[]),oe=y.useCallback(()=>{const F=x.current;s==="blocking"&&F==="disconnected"||(F==="disconnected"&&(v.current=!0),_(!1))},[s]),z=y.useMemo(()=>({isOpen:g,onClose:oe,blocking:s==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:d,onStatusChange:T}),[g,oe,s,m,t.appName,n,t.defaultGatewayUrl,d,T]);return{status:d,phase:m,connected:m==="connected",modalOpen:g,signingOut:E,signOutError:I,openModal:Z,refresh:N,signOut:B,modalProps:z}}const Ok="default";function Pr(e){return typeof e=="string"?e.trim():""}function zg(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0}function Pk(e){var m;if(!e||!Rw(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=zg(t.roles);u&&(s.roles=u);const d=zg(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!==Ok?`${n}/${t}`:t}function Hh(e){const t=Pr(e);if(!t)return"";try{return new URL(t).host||t}catch{return t}}async function dh(e=dl){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 Dk(e,t=dl){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 Mw(e=dl){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 _f(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 Fk(e){var d,f;if(!e)return{label:"Signed out",tone:"warn"};if(!e.has_session)return{label:"Signed out",tone:"warn"};const t=e.gateway||{},n=(d=t.principal)==null?void 0:d.user_id,s=(f=t.principal)==null?void 0:f.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=typeof e.gateway_status=="number"?e.gateway_status:null,l=Hh(e.gateway_url);if(o===0)return{label:`Gateway${l?` at ${l}`:""} did not answer — is it running?`,tone:"err"};if(o===502||o===503||o===504)return{label:`Gateway unavailable (HTTP ${o}) — try again shortly`,tone:"err"};if(o!==null&&o>=500)return{label:`Gateway error (HTTP ${o}) — try again shortly`,tone:"err"};if(o!==null&&o>=400&&o!==401&&o!==403)return{label:`Gateway answered HTTP ${o} — check the gateway URL`,tone:"err"};const u=t.error||t.detail;return typeof u=="string"&&u.trim()?{label:"Session rejected — sign in again",tone:"err"}:{label:"Sign in required",tone:"err"}}function zk(e){const t=e.connectionPath||dl,[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,j]=y.useState(!1),[A,T]=y.useState(!0),[N,E]=y.useState(""),[S,I]=y.useState(""),M=y.useMemo(()=>Fk(u),[u]),B=z=>{var F;d(z),(F=e.onStatusChange)==null||F.call(e,z)},G=y.useRef(!1);if(y.useEffect(()=>{var F;if(!e.isOpen)return;const z=!G.current;if(G.current=!0,z&&e.initialStatus!==void 0&&e.initialStatus!==null){const L=e.initialStatus;B(L),typeof L.gateway_url=="string"&&L.gateway_url.trim()&&g(_f(L.gateway_url));const q=(F=L.gateway)==null?void 0:F.principal;q!=null&&q.user_id&&v(q.user_id);return}s(!0),E(""),dh(t).then(L=>{var V;B(L),typeof L.gateway_url=="string"&&L.gateway_url.trim()&&g(_f(L.gateway_url));const q=(V=L.gateway)==null?void 0:V.principal;q!=null&&q.user_id&&v(q.user_id)}).catch(L=>E(`Failed to load connection status: ${String((L==null?void 0:L.message)||L)}`)).finally(()=>s(!1))},[e.isOpen]),y.useEffect(()=>{if(!e.isOpen)return;const z=F=>{F.key==="Escape"&&!F.defaultPrevented&&!e.blocking&&(F.preventDefault(),e.onClose())};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const Z=async()=>{l(!0),E(""),I("");try{const z=_f(p);g(z);const F=await Dk({gateway_url:z,gateway_user_id:_,gateway_token:C,persist:A},t);B(F),x(""),m(!0),e.onClose()}catch(z){E(String((z==null?void 0:z.message)||z))}finally{l(!1)}},oe=async()=>{l(!0),E(""),I("");try{await Mw(t),x("");const z=await dh(t).catch(()=>null);B(z),I("Signed out. This browser no longer holds a gateway session.")}catch(z){E(String((z==null?void 0:z.message)||z))}finally{l(!1)}};return a.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:z=>{!e.blocking&&z.target===z.currentTarget&&e.onClose()},children:a.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:a.jsx(vk,{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:M.label,statusTone:M.tone,showGatewayUrl:!0,gatewayUrl:p,onGatewayUrlChange:z=>g(z),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:j,remember:A,rememberLabel:"Keep this browser signed in",onRememberChange:T,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:oe,error:N,message:S,onSubmit:Z})})})}function Bk(){return globalThis.crypto}function Wk(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=Bk();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return Wk(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Nu(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 bf={neutral:"var(--text-secondary)",muted:"var(--text-muted)",accent:"var(--accent)",info:"var(--info)",success:"var(--success)",warning:"var(--warning)",error:"var(--error)"},Uk=/^var\(--[a-z0-9-]+\)$/i;function Vk(e,t){const n=e||"neutral";if(n==="custom"){const s=String(t||"").trim();return Uk.test(s)?s:bf.neutral}return bf[n]||bf.neutral}function Lw(e,t,n){return[e,`${e}--${t.tone||"neutral"}`,t.size==="sm"?`${e}--sm`:"",n||"",t.className||""].filter(Boolean).join(" ")}function Ow(e){return{"--af-chip-hue":Vk(e.tone,e.hue)}}function Gk(e){return a.jsxs("span",{className:Lw("af-chip",e,e.onRemove?"af-chip--removable":""),style:Ow(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 Hk(e){return a.jsx("button",{type:"button",className:Lw("af-chip",e,"af-chip--button"),style:Ow(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 Kk=["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 Jk(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 qk(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 xf(e){return Array.from(e.querySelectorAll(Kk)).filter(n=>!(typeof n.closest=="function"&&n.closest("[hidden], [inert], [aria-hidden='true']")||qk(n)||typeof n.getClientRects=="function"&&n.getClientRects().length===0))}const Bg=new WeakMap;function Yk(e,t){const n=t.document||e.ownerDocument,s=e.querySelector(".af-modal")||e,o=n.activeElement,l=Bg.get(n)||[];Bg.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?xf(x)[0]:void 0)||xf(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=xf(s),j=n.activeElement,A=!!j&&s.contains(j);if(k.length===0){x.preventDefault(),s.focus({preventScroll:!0});return}const T=Jk(k,j,x.shiftKey,A&&j!==s);T&&(x.preventDefault(),T.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 Qk(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 Yk(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?ul.createPortal(l,document.body):l}function Xk(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 Wg=0;function Zk(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")||(Wg+=1,t.setAttribute("id",`af-menu-${Wg}`)),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 T=Array.from(t.querySelectorAll(".af-menu__item")),N=T.filter(E=>!E.hidden&&!E.hasAttribute("disabled"));for(const E of T)E.setAttribute("role","menuitem"),E.setAttribute("tabindex","-1");return N};l();let u=!1;const d=()=>{if(!u)return;const T=e.getBoundingClientRect(),N=t.getBoundingClientRect(),E=Xk(T,{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=T=>{const N=l();if(!N.length)return;const E=(T%N.length+N.length)%N.length;N[E].focus({preventScroll:!0})},m=T=>{u||(u=!0,t.hidden=!1,e.setAttribute("aria-expanded","true"),d(),f(T),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=T=>{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),T&&e.focus({preventScroll:!0}),n.onClose&&n.onClose())};function g(T){const N=T.target;N&&(t.contains(N)||e.contains(N))||p(!1)}function _(){p(!1)}const v=T=>{T.preventDefault(),u?p(!0):m(0)},C=T=>{T.key==="ArrowDown"||(T.key==="Enter"||T.key===" ")&&!u?(T.preventDefault(),m(0)):T.key==="ArrowUp"&&(T.preventDefault(),m(-1))},x=T=>{if(!u||T.key!=="Escape"&&T.key!=="Esc")return;const N=T.target;N&&N!==e&&!t.contains(N)&&N!==s.body||(T.preventDefault(),p(!0))},k=T=>{if(!u)return;const E=l().indexOf(s.activeElement);T.key==="ArrowDown"?(T.preventDefault(),f(E+1)):T.key==="ArrowUp"?(T.preventDefault(),f(E<0?-1:E-1)):T.key==="Home"?(T.preventDefault(),f(0)):T.key==="End"?(T.preventDefault(),f(-1)):T.key==="Tab"&&p(!1)},j=T=>{const N=T.target,E=N&&typeof N.closest=="function"?N.closest(".af-menu__item"):null;if(!E||!t.contains(E))return;const S=s.activeElement,I=!S||S===s.body||t.contains(S);p(I)};e.addEventListener("click",v),e.addEventListener("keydown",C),t.addEventListener("keydown",k),t.addEventListener("click",j);let A=!1;return()=>{A||(A=!0,p(!1),e.removeEventListener("click",v),e.removeEventListener("keydown",C),t.removeEventListener("keydown",k),t.removeEventListener("click",j))}}function Kh(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 Zk(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 eS={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"},tS={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"}},nS={framework:eS,apps:tS},au=nS;function Pw(){return{...au.framework}}function sS(){return Object.keys(au.apps).sort()}function rS(e,t){const n=Object.prototype.hasOwnProperty.call(au.apps,e)?au.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${sS().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 aS(e,t){try{const n=await e(pe("about"),{method:"GET",headers:{Accept:"application/json"},signal:t});if(!n.ok)return kf(null,`HTTP ${n.status}`);const s=await n.json().catch(()=>null);return kf(s)}catch(n){return kf(null,String((n==null?void 0:n.message)||n||"request failed"))}}const oS={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function ko(e){return typeof e=="string"?e.trim():""}function kf(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=ko(n.abstractgateway),o=ko(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 iS(e){const t=Pw();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 lS(e){const t=e||{},n=ko(t.framework),s=ko(t.gateway);return[["AbstractFramework",n||ko(t.frameworkNote)||"not reported"],["AbstractGateway",s||ko(t.gatewayNote)||"not connected"]]}const cS='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Dw(e,t,n){if(e.key!=="Tab"||!t)return;const s=Array.from(t.querySelectorAll(cS));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 uS(e){const t=Pw();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:lS(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:iS(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 dS(e){Lo();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}Dw(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(uS,{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(ue,{name:"x",size:16})})})})}):null}const Qc={theme:"dark",font_scale:"md",header_density:"standard"};function fS(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Qc.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Qc.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Qc.header_density}}function hS(e){return`af_appearance_${e}_v1`}function mS(e,t){const n=hS(e),s=y.useMemo(()=>({...Qc,...(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=fS({...s,...JSON.parse(d)}))}catch{}try{Lg(u.theme),Og({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return y.useEffect(()=>{Lg(o.theme),Og({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function pS(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(bk,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),a.jsx("label",{className:"af-appearance__label",children:"Font size"}),a.jsx(xk,{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(kk,{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}function gS(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 yS(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function wS(e,t){return yS(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 vS(e,t){const n=Hh(t);return`Signed in as ${Iw(e)}${n?` · gateway ${n}`:""}`}const Sf="--af-topbar-h";function _S(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(Sf,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(Sf)===l&&o.style.removeProperty(Sf)}},[e,t])}function bS(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function xS(e){var N,E;const t=wS(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);Lo(),_S(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 S=x.current;if(!o||!S)return;const I=typeof AbortController<"u"?new AbortController:null;let M=!0;return m(oS),aS(S,I==null?void 0:I.signal).then(B=>{M&&m(B)}),()=>{M=!1,I==null||I.abort()}},[o]);const k=gS(n,s),j=e.identity&&n==="connected"?Pk(t.status):null,A=()=>void t.disconnect();let T=null;if(j&&e.identity){const S=Iw(j),I=vS(j,(N=t.status)==null?void 0:N.gateway_url),M=a.jsxs(a.Fragment,{children:[a.jsx(ue,{name:"user",size:14}),a.jsx("span",{className:"af-topbar__identity-label",children:S})]});if(e.identity==="badge")T=a.jsx("span",{className:"af-topbar__identity af-topbar__identity--badge","data-af-identity":"badge","data-af-tip":I,"aria-label":I,children:M});else{const B=bS(j.userId),G=Hh((E=t.status)==null?void 0:E.gateway_url);T=a.jsx(Kh,{label:`Account: ${I}`,tip:I,className:"af-topbar__account",buttonClassName:"af-topbar__identity af-topbar__identity--menu",buttonContent:M,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 ",S]}),G?a.jsxs("span",{className:"af-topbar__account-host",children:["Gateway ",G]}):null]}),items:[{id:"copy-user-id",label:"Copy user id",onSelect:B||(()=>{}),hidden:!B},{id:"disconnect",label:"Disconnect",onSelect:A,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(ue,{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(ue,{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(ue,{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 S;l(!0),(S=g.onOpen)==null||S.call(g)},children:a.jsx(ue,{name:"info",size:16})}):null,T,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(ue,{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"?A: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(dS,{open:o,onClose:()=>l(!1),identity:g.identity,versions:g.versions||(g.fetch?f:void 0),extra:g.extra}):null,_&&"value"in _?a.jsx(pS,{open:u,onClose:()=>d(!1),value:_.value,onChange:_.onChange,title:_.title,note:_.note}):null]})}function fh(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function Ug(e,t,n=!1){if(n)return"unknown";if(!e)return"";const s=e[t];return!s||!s.configured?"not set":fh(s)||"not set"}function kS(e,t){var n;return e.stt_provider?fh({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?fh(t.stt):""}function Fw(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function SS(e,t,n){return`Transcribing… ${Fw(e,t)}${n?` · ${n}`:""}`}const Cu=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function ou(e){var o;const t=Nu("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=Cu())!=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 zw(e){const t=Cu();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 jS(){const e=Cu();if(!(e!=null&&e.getUserMedia))throw new Error(Nu("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Bw(e){const t=Cu();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 Eu(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Ww(){const e=Eu();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function Uw(e,t,n=1){const s=Eu();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 Vw=.02;function Vg(){return Object.assign(new Error("The recording was stopped before it began."),{name:"AbortError"})}async function Gw(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 Vg();const n=await Bw(e.deviceId);if((u=e.signal)!=null&&u.aborted)throw n.getTracks().forEach(f=>f.stop()),Vg();let s=0;const o=Uw(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 Hw(e,t={}){var o,l,u,d;if((o=t.signal)!=null&&o.aborted)return;const n=Eu();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,j;(j=(k=t.signal)==null?void 0:k.removeEventListener)==null||j.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 NS(e={}){var s,o;const t=Eu();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 $o(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}async function*CS(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),j=new Uint8Array(k.length);for(let A=0;A<k.length;A+=1)j[A]=k.charCodeAt(A);yield j.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 Mi(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const Kw=350;function ES(){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 AS(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function $S(){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 jf(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 TS(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 RS(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 Jw(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const Oc=new WeakMap;function IS(e,t){const n=e;if(!(typeof n.setSinkId!="function"||Oc.get(e)===t)){Oc.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>Oc.delete(e))}catch{Oc.delete(e)}}}function MS(e){const t=y.useRef(e);t.current=e;const n=te=>{var be,P;return(P=(be=t.current).on_error)==null?void 0:P.call(be,te)},s=y.useMemo(()=>AS()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),o=y.useMemo(()=>ES()&&typeof e.transcribe=="function",[e.transcribe]),[l,u]=y.useState({key:"",status:"idle"}),d=y.useRef(l),f=y.useCallback(te=>{d.current=te,u(be=>be.key===te.key&&be.status===te.status?be:te)},[]),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),j=y.useRef(0),A=y.useRef(null),T=y.useRef([]),N=y.useRef(0),E=y.useRef(!0),S=y.useRef(!1),I=()=>{try{const te=globalThis,be=(te==null?void 0:te.AudioContext)||(te==null?void 0:te.webkitAudioContext);if(!be)return null;if(!g.current){const Oe=new be,Ae=Oe.createGain();Ae.gain.value=1,Ae.connect(Oe.destination),g.current=Oe,_.current=Ae}const P=g.current,ie=_.current;if(!P||!ie)return null;IS(P,t.current.output_device_id||""),ie.gain.value=ba(t.current.volume)*(t.current.muted?0:1);try{P.state==="suspended"&&P.resume()}catch{}return{ctx:P,gain:ie}}catch{return null}};y.useEffect(()=>{const te=_.current;te&&(te.gain.value=ba(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const M=y.useCallback(()=>{const te=v.current;if(v.current=null,!!te){try{te.onended=null}catch{}try{te.stop()}catch{}try{te.disconnect()}catch{}}},[]),B=y.useCallback(()=>{var te;M(),j.current+=1,(te=A.current)==null||te.abort(),A.current=null,T.current=[],N.current=0,E.current=!0,S.current=!1,p.current="",m.current="",C.current=null,x.current=0,k.current=0,f({key:"",status:"idle"})},[M,f]);y.useEffect(()=>()=>{var te,be;B();try{(te=_.current)==null||te.disconnect()}catch{}try{(be=g.current)==null||be.close()}catch{}g.current=null,_.current=null,C.current=null},[]);const G=async(te,be,P)=>{const ie=j.current,Oe=I();if(!Oe)throw new Error("TTS playback is not supported in this browser");const{ctx:Ae,gain:Ye}=Oe;try{Ae.state==="suspended"&&await Ae.resume()}catch{}if(ie!==j.current)return;M();const $e=Ae.createBufferSource();$e.buffer=be,$e.connect(Ye);const Ge=Number.isFinite(Number(be.duration))?Number(be.duration):0,Ee=Math.max(0,Math.min(Number(P||0),Ge>0?Math.max(0,Ge-.01):0));k.current=Ae.currentTime-Ee,x.current=Ee,v.current=$e,m.current=te,$e.onended=()=>{v.current===$e&&(v.current=null,x.current=0,k.current=0,m.current="",f({key:"",status:"idle"}))},$e.start(0,Ee),f({key:te,status:"playing"})},Z=(te,be)=>{if(be!==j.current)return;const P=I();if(!P)return;const ie=T.current,Oe=N.current;if(Oe>=ie.length){E.current&&(m.current="",x.current=0,k.current=0,f({key:"",status:"idle"}));return}const Ae=ie[Oe],{ctx:Ye,gain:$e}=P;M();const Ge=Ye.createBufferSource();Ge.buffer=Ae,Ge.connect($e);const Ee=Number.isFinite(Number(Ae.duration))?Number(Ae.duration):0,pt=Math.max(0,Math.min(Number(x.current||0),Ee>0?Math.max(0,Ee-.01):0));k.current=Ye.currentTime-pt,v.current=Ge,m.current=te,Ge.onended=()=>{be===j.current&&v.current===Ge&&(v.current=null,N.current=Oe+1,x.current=0,Z(te,be))};try{Ye.state==="suspended"&&Ye.resume()}catch{}Ge.start(0,pt),f({key:te,status:"playing"})},oe=async(te,be,P)=>{var $e;const ie=I();if(!ie){n==null||n("This browser cannot play spoken replies.");return}M();const Oe=++j.current;($e=A.current)==null||$e.abort();const Ae=new AbortController;A.current=Ae,T.current=[],N.current=0,E.current=!1,S.current=!1,C.current=null,x.current=0,k.current=0,m.current=te,p.current=te,f({key:te,status:"loading"}),n==null||n("");let Ye=null;try{for await(const Ge of P(be,Ae.signal)){if(Oe!==j.current)return;let Ee;try{Ee=await jf(ie.ctx,Ge),Ye||(Ye=TS(Ge))}catch{if(!Ye)continue;try{Ee=await jf(ie.ctx,RS(Ye,Ge))}catch{continue}}if(Oe!==j.current)return;T.current.push(Ee),!v.current&&!S.current&&(p.current="",Z(te,Oe))}if(Oe!==j.current)return;if(E.current=!0,T.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),B();return}!v.current&&!S.current&&Z(te,Oe)}catch(Ge){if(Oe!==j.current)return;n==null||n(Mi("Reading aloud failed",Ge)),B()}finally{A.current===Ae&&(A.current=null)}},z=y.useCallback(async(te,be)=>{var pt;const P=String(te||"").trim(),ie=String(be||"").trim();if(!P||!ie)return;const Oe=t.current.tts,Ae=t.current.tts_stream;if(typeof Oe!="function"&&typeof Ae!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Ye=I();if(!Ye){n==null||n("This browser cannot play spoken replies.");return}const $e=d.current,Ge=$e.key===P;if(Ge&&$e.status==="playing"){if(v.current){const St=Math.max(0,Ye.ctx.currentTime-Number(k.current||0));x.current=St}else x.current=0;S.current=!0,M(),f({key:P,status:"paused"});return}if(Ge&&$e.status==="paused"){if(T.current.length>0){n==null||n(""),S.current=!1,f({key:P,status:"playing"}),Z(P,j.current);return}const St=C.current;if(St){n==null||n(""),S.current=!1;try{await G(P,St,x.current)}catch(jt){n==null||n(Mi("Reading aloud failed",jt)),f({key:"",status:"idle"})}return}}if(Ge&&$e.status==="loading")return;if(typeof Ae=="function"){await oe(P,ie,Ae);return}M(),j.current+=1,(pt=A.current)==null||pt.abort(),A.current=null;const Ee=j.current;T.current=[],N.current=0,E.current=!0,S.current=!1,C.current=null,x.current=0,k.current=0,m.current=P,p.current=P,f({key:P,status:"loading"}),n==null||n("");try{const St=await Oe(ie);if(p.current!==P||j.current!==Ee)return;const jt=await jf(Ye.ctx,St);if(p.current!==P||j.current!==Ee)return;C.current=jt,x.current=0,await G(P,jt,0)}catch(St){if(j.current!==Ee)return;p.current===P&&(p.current="",m.current="",f({key:"",status:"idle"})),n==null||n(Mi("Reading aloud failed",St))}},[]),[F,L]=y.useState(!1),[q,V]=y.useState(!1),Y=y.useRef(!1),J=y.useRef(o);J.current=o;const W=y.useCallback(te=>{Y.current=te,L(be=>be===te?be:te)},[]),R=y.useRef(!1),K=y.useRef(null),se=y.useRef(null),ce=y.useRef([]),ae=y.useRef(""),we=y.useRef(0),Se=y.useRef(!1),Q=y.useRef(!1),[xe,ve]=y.useState(0),Fe=y.useRef(0),Xe=y.useRef(null),Ve=y.useRef(0),Je=y.useRef(new Set),me=y.useRef(null),Me=y.useCallback(te=>{const be=Math.round(Math.min(1,Math.max(0,Number(te)||0))*20)/20;if(be!==Ve.current){Ve.current=be;for(const P of Array.from(Je.current))P(be)}},[]),st=y.useCallback(te=>(Je.current.add(te),te(Ve.current),()=>{Je.current.delete(te)}),[]),tt=y.useRef(new Set),$t=y.useCallback(te=>(tt.current.add(te),()=>{tt.current.delete(te)}),[]);function le(){var P,ie;const te=me.current;me.current=null;try{te==null||te()}catch{}Me(0);try{(ie=(P=K.current)==null?void 0:P.getTracks)==null||ie.call(P).forEach(Oe=>{try{Oe.stop()}catch{}})}catch{}K.current=null;const be=Xe.current;Xe.current=null;try{be==null||be.close()}catch{}}const de=y.useCallback(()=>{we.current+=1,Se.current=!1;const te=se.current;if(te){te.onstop=null,te.ondataavailable=null,te.onerror=null;try{te.stop()}catch{}}se.current=null,le(),W(!1),R.current=!1,V(!1),ve(0),ce.current=[]},[W]);y.useEffect(()=>()=>de(),[de]);async function je(te,be){var Ae,Ye;if(n==null||n(""),R.current)return;const P=Fe.current?Date.now()-Fe.current:1/0;if(!te||!te.size||P<Kw){ve(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 ie=t.current.transcribe;if(typeof ie!="function"){n==null||n("Speech to text is not available on this gateway.");return}R.current=!0;const Oe=we.current;V(!0),ve(Date.now());try{const $e=await ie(te,be),Ge=typeof $e=="string"||!$e?{text:String($e||"")}:$e,Ee=String(Ge.text||"").trim();if(Oe!==we.current)return;if(Ee){(Ye=(Ae=t.current).on_transcript)==null||Ye.call(Ae,Ee,{...Ge,text:Ee});for(const pt of Array.from(tt.current))pt(Ee,{...Ge,text:Ee})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch($e){if(Oe===we.current){const Ge=String(($e==null?void 0:$e.message)||$e||"").trim().replace(/\.$/,"");n==null||n(Ge?`Transcription failed: ${Ge}.`:"Transcription failed.")}}finally{Oe===we.current&&(R.current=!1,V(!1),ve(0))}}const _e=y.useCallback(async()=>{if(n==null||n(""),!J.current){n==null||n(Nu("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(R.current||Se.current||Y.current||se.current)return;ce.current=[];const te=we.current;Se.current=!0,Q.current=!1;try{const be=await Bw(t.current.input_device_id||"");if(te!==we.current){be.getTracks().forEach($e=>$e.stop());return}if(Q.current){Q.current=!1,be.getTracks().forEach($e=>$e.stop()),ve(0);return}K.current=be;const P=Number(t.current.input_gain??1);try{me.current=Uw(be,Me,Number.isFinite(P)&&P>0?P:1)}catch{}const ie=$S();ae.current=ie;let Oe=be;const Ae=Number(t.current.input_gain??1);if(Number.isFinite(Ae)&&Ae>0&&Ae!==1&&Ww()){const $e=globalThis.AudioContext||globalThis.webkitAudioContext,Ge=new $e,Ee=Ge.createGain();Ee.gain.value=Ae;const pt=Ge.createMediaStreamDestination();Ge.createMediaStreamSource(be).connect(Ee),Ee.connect(pt),Xe.current=Ge,Oe=pt.stream}const Ye=ie?new MediaRecorder(Oe,{mimeType:ie}):new MediaRecorder(Oe);se.current=Ye,Ye.ondataavailable=$e=>{if(te===we.current)try{$e!=null&&$e.data&&ce.current.push($e.data)}catch{}},Ye.onerror=()=>{te===we.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Ye.onstop=()=>{if(te===we.current){W(!1),le(),se.current=null;try{const $e=new Blob(ce.current,{type:ae.current||""});je($e,ae.current)}catch($e){n==null||n(Mi("The recording could not be prepared",$e))}}},Ye.start(),Fe.current=Date.now(),ve(Fe.current),W(!0)}catch(be){if(te!==we.current)return;le(),se.current=null,W(!1),ve(0),n==null||n(ou(be))}finally{te===we.current&&(Se.current=!1)}},[]),ge=y.useCallback(()=>{const te=se.current;if(Se.current&&!te){Q.current=!0;return}if(!(!Y.current||!te)){W(!1);try{te.stop()}catch(be){n==null||n(Mi("The recording could not stop",be))}}},[]);return y.useEffect(()=>{if(!F||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&$o(t.current.capture_mode)==="toggle")return;const te=()=>ge();return window.addEventListener("pointerup",te),window.addEventListener("pointercancel",te),()=>{window.removeEventListener("pointerup",te),window.removeEventListener("pointercancel",te)}},[F]),{tts_supported:s,tts_playback:l,toggle_tts:z,stop_tts:B,voice_ptt_supported:o,voice_ptt_recording:F,voice_ptt_busy:q,start_voice_ptt_recording:_e,stop_voice_ptt_recording:ge,cancel_voice_ptt_recording:de,voice_ptt_since:xe,subscribe_level:st,voice_capture_mode:$o(e.capture_mode),add_transcript_listener:$t}}const Gg=["Your voices","Engine voices","Shared voices"];function qw(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 Au(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 LS(e){return Array.from(new Set(e.map(Au).filter(Boolean))).sort()}function OS(e,t){if(!t)return!0;const n=Au(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 Yw={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"},Qw=Yw,xa=e=>Qw[e]||e,Nf=e=>String((e==null?void 0:e.voice_id)||(e==null?void 0:e.id)||""),Pc=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):[],PS=200;function DS({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 je,_e,ge,te,be;const C=p||m,[x,k]=y.useState({state:"idle",error:""}),j=y.useRef(0),A=y.useRef(null),T=y.useRef(null),N=y.useRef(null),E=y.useRef(null),S=y.useRef(n);S.current=n;const[I,M]=y.useState({}),[B,G]=y.useState(""),[Z,oe]=y.useState(!1),[z,F]=y.useState(""),[L,q]=y.useState(0),V=y.useRef(e);V.current=e;const Y=y.useRef(!0),J=()=>{var P,ie;j.current+=1,E.current!==null&&clearTimeout(E.current),E.current=null,(P=A.current)==null||P.abort(),A.current=null,(ie=T.current)==null||ie.abort(),T.current=null};y.useEffect(()=>(Y.current=!0,()=>{Y.current=!1,J()}),[]);const W=P=>JSON.stringify([P.provider||"",P.model||"",P.voice||"",P.profile||""]),R=P=>`The sample did not play: ${String((P==null?void 0:P.message)||P).replace(/\.$/,"")}.`,K=(P,ie)=>{const Oe=new AbortController;T.current=Oe,k({state:"playing",error:""}),Hw(P,{deviceId:(_==null?void 0:_.deviceId)||"",volume:_==null?void 0:_.volume,signal:Oe.signal}).then(()=>Y.current&&j.current===ie&&k({state:"idle",error:""})).catch(Ae=>Y.current&&j.current===ie&&k({state:"idle",error:R(Ae)}))},se=P=>{if(!g)return;J();const ie=j.current,Oe=new AbortController;A.current=Oe,k({state:"loading",error:""}),g(P,void 0,{signal:Oe.signal}).then(Ae=>{!Y.current||j.current!==ie||(A.current=null,N.current={key:W(P),bytes:Ae},K(Ae,ie))}).catch(Ae=>{!Y.current||j.current!==ie||(A.current=null,k({state:"idle",error:R(Ae)}))})},ce=P=>{if(!g)return;J();const ie=j.current;if(N.current&&N.current.key===W(P)){K(N.current.bytes,ie);return}k({state:"loading",error:""}),E.current=setTimeout(()=>{E.current=null,Y.current&&j.current===ie&&se(P)},PS)},ae=()=>{if(x.state!=="idle"){J(),k({state:"idle",error:""});return}const P=V.current;if(N.current&&N.current.key===W(P)){J(),K(N.current.bytes,j.current);return}se(P)};y.useEffect(()=>{F("")},[e.provider]),y.useEffect(()=>{let P=!0;return oe(!0),M({}),G(""),S.current(e.provider,e.model).then(ie=>{P&&(M(ie),G(ie.error?String(ie.error):""))}).catch(ie=>{P&&G(String((ie==null?void 0:ie.message)||ie))}).finally(()=>{P&&oe(!1)}),()=>{P=!1}},[e.provider,e.model,L]);const we=Array.isArray(I.items)?I.items:[...Array.isArray(I.profiles)?I.profiles.map(P=>({...P,voice_kind:"profile"})):[],...Array.isArray(I.voices)?I.voices.map(P=>({...P,voice_kind:"voice"})):[]],Se=P=>JSON.stringify([P.provider||"",P.model||"",P.voice_kind==="profile"?"profile":"voice",P.id]),Q=P=>(!e.provider||!P.provider||P.provider===e.provider)&&(!e.model||!P.model||P.model===e.model),xe=P=>JSON.stringify([P.provider||"",P.voice_kind==="profile"?"profile":"voice",P.id]),ve=new Map;for(const P of we){if(!(P!=null&&P.id))continue;const ie=xe(P);ve.has(ie)||ve.set(ie,new Set),ve.get(ie).add(String(P.model||""))}const Fe=P=>{var ie;return(((ie=ve.get(xe(P)))==null?void 0:ie.size)||0)>1},Xe=P=>Fe(P)&&!e.model?JSON.stringify([P.provider||"","",P.voice_kind==="profile"?"profile":"voice",P.id]):Se(P),Ve=we.find(P=>P.id===(e.profile||e.voice)&&P.voice_kind==="profile"==!!e.profile&&Q(P))||(!e.profile&&e.voice?we.find(P=>P.id===e.voice&&P.voice_kind==="profile"&&Q(P)):void 0),Je=Ve?Xe(Ve):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",me=LS(we),Me=me.length>1;y.useEffect(()=>{!Me&&!Z&&F("")},[Me,Z]);const st=Me?z:"",tt=new Set,$t=we.filter(P=>(P==null?void 0:P.id)&&(!e.provider||!P.provider||P.provider===e.provider)&&(!Fe(P)||!e.model||P.model===e.model||!ve.get(xe(P)).has(e.model))&&(OS(P,st)||Xe(P)===Je)).filter(P=>{const ie=Xe(P);return tt.has(ie)?!1:(tt.add(ie),!0)}).map(P=>{const ie=Au(P);return{value:Xe(P),group:qw(P),label:`${P.label||P.name||P.id}${ie?` · ${xa(ie)}`:""}${!e.provider&&P.provider?` · ${P.provider}`:""}`}}).sort((P,ie)=>Gg.indexOf(P.group)-Gg.indexOf(ie.group)),le=String(((je=Ve==null?void 0:Ve.tags)==null?void 0:je.description)||"").trim();Je&&!$t.some(P=>P.value===Je)&&$t.unshift({value:Je,group:"",label:`${e.profile||e.voice} (saved)`});const de=P=>t({...e,...P});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(ju,{defaultHint:d,value:{provider:e.provider||"",model:e.model||""},onChange:P=>{J(),k({state:"idle",error:""}),t({...e,...P,voice:"",profile:""})},fetchProviders:async()=>{const P=await S.current();if(P.error&&!Pc(P.tts_providers||P.providers).length)throw new Error(P.error);return Pc(P.tts_providers||P.providers).map(ie=>({name:ie}))},fetchModels:async P=>{var $e,Ge;const ie=await S.current(P),Oe=Pc((($e=ie.tts_models_by_provider)==null?void 0:$e[P])||ie.tts_models||ie.models),Ae=Array.isArray((Ge=ie.tts_model_details_by_provider)==null?void 0:Ge[P])?ie.tts_model_details_by_provider[P]:[],Ye=new Map(Ae.filter(Ee=>Ee&&Ee.id).map(Ee=>[String(Ee.id),String(Ee.label||(Ee.role==="cloning"?`${Ee.id} (clones)`:Ee.id))]));return Oe.map(Ee=>({id:Ee,label:Ye.get(Ee)||Ee}))},providerLabel:"Speech provider",modelLabel:"Speech model"}),Me?a.jsxs("label",{children:["Voices that speak",a.jsx(xn,{ariaLabel:"Voice language",placeholder:"Any language",value:z,searchable:!1,options:[{value:"",label:"Any language"},...me.map(P=>({value:P,label:xa(P)}))],onChange:F})]}):null,a.jsxs("label",{children:["Voice / profile",a.jsxs("span",{className:"af-voice-settings__voice-row",children:[a.jsx(xn,{ariaLabel:"AI voice",placeholder:f||"Gateway / provider default",value:Je,disabled:Z,options:[{value:"",label:f||"Gateway / provider default"},...$t],onChange:P=>{let ie;if(!P)ie={voice:"",profile:""};else{const[Oe,Ae,Ye,$e]=JSON.parse(P);ie={provider:Oe||e.provider||"",model:Ae||(Oe&&Oe!==e.provider?"":e.model)||"",voice:Ye==="voice"?$e:"",profile:Ye==="profile"?$e:""}}de(ie),ce({...e,...ie})}}),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:ae,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,le?a.jsx("p",{className:"af-voice-settings__description",children:le}):null,Z?a.jsx("p",{role:"status",children:"Loading available voices…"}):null,B?a.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",B,". Your saved choice is preserved."]}):null,!Z&&!B&&e.provider&&we.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:P=>de({speed:P.target.value?Number(P.target.value):void 0}),children:[a.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(P=>a.jsxs("option",{value:P,children:[P,"×"]},P))]})]}),l&&((ge=(_e=I.controls)==null?void 0:_e.quality_preset)!=null&&ge.supported)?a.jsxs("label",{children:["Quality",a.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:P=>de({quality_preset:P.target.value}),children:[a.jsx("option",{value:"",children:"Gateway default"}),Pc(I.controls.quality_preset.values).map(P=>a.jsx("option",{value:P,children:P},P))]})]}):null,(be=(te=I.controls)==null?void 0:te.instructions)!=null&&be.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:P=>de({instructions:P.target.value})})]}):null]}):null,C&&(C.design||C.clone)?a.jsx(BS,{creation:C,defaultLanguage:st,recordFrom:v,onCreated:(P,ie)=>{const Oe=V.current;t({...Oe,provider:ie||Oe.provider||"",model:"",voice:P,profile:""}),q(Ae=>Ae+1)}}):null,p!=null&&p.list?a.jsx(US,{library:p,refreshKey:L,onChanged:()=>q(P=>P+1),onRemoved:P=>{const ie=V.current;ie.voice===P&&t({...ie,voice:""})}}):null,u?a.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const FS={value:"",label:"Detect from the recording"},zS=3e4;function BS({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),[j,A]=y.useState(""),[T,N]=y.useState(!1),[E,S]=y.useState(!1),[I,M]=y.useState(0),[B,G]=y.useState({text:"",tone:"info"}),Z=y.useRef(!1),oe=y.useRef(!0),z=y.useRef(null);y.useEffect(()=>(oe.current=!0,()=>{var J;oe.current=!1,(J=z.current)==null||J.abort()}),[]);const F=Object.keys(Qw).map(J=>({value:J,label:xa(J)})),L=l==="design"?g:v,q=()=>{if(z.current){z.current.abort();return}const J=new AbortController;z.current=J;const W=Date.now();S(!0),G({text:"Recording — read a few sentences, then press Stop.",tone:"info"}),Gw({deviceId:(s==null?void 0:s.deviceId)||"",gain:s==null?void 0:s.gain,ms:zS,signal:J.signal,onLevel:R=>oe.current&&M(R)}).then(({blob:R,peak:K})=>{if(oe.current){if(K<Vw){G({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}k(R),G({text:`Recording ready (${Math.max(1,Math.round((Date.now()-W)/1e3))} s).`,tone:"ok"})}}).catch(R=>{oe.current&&((R==null?void 0:R.name)==="AbortError"?G({text:"Recording cancelled.",tone:"info"}):G({text:ou(R),tone:"error"}))}).finally(()=>{z.current===J&&(z.current=null),oe.current&&(S(!1),M(0))})},V=async()=>{if(!(Z.current||z.current)){Z.current=!0,N(!0),G({text:l==="design"?"Creating the voice from your description…":"Cloning the voice from your recording…",tone:"info"});try{const J=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:j.trim()||void 0,...v?{language:v}:{},...o!=null&&o.provider?{provider:o.provider}:{},...o!=null&&o.provider&&o.model?{model:o.model}:{}});if(!oe.current)return;G({text:`Voice ready: ${J.name||J.voice_id}. It is selected above.`,tone:"ok"}),n(J.voice_id,J.engine||(l==="design"?"qwen3-tts":void 0))}catch(J){if(!oe.current)return;G({text:`The voice was not created: ${String((J==null?void 0:J.message)||J).replace(/\.$/,"")}.`,tone:"error"})}finally{Z.current=!1,oe.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:T||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:T||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:J=>f(J.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:J=>{const W=J.target.files&&J.target.files[0]||null;k(W),W&&G({text:"",tone:"info"})}})]}),a.jsxs("div",{className:"af-voice-create__record",children:[a.jsx("button",{type:"button","data-action":"record-sample",disabled:T,onClick:q,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:j,onChange:J=>A(J.target.value)})]})]}),a.jsxs("label",{children:["Name",a.jsx("input",{"aria-label":"Voice name",value:m,placeholder:"My voice",onChange:J=>p(J.target.value)})]}),a.jsxs("label",{children:["Language",a.jsx(xn,{ariaLabel:"Voice language for creation",value:L,searchable:!1,options:l==="design"?F:[FS,...F],onChange:l==="design"?_:C})]}),a.jsx("button",{type:"button","data-action":"create-voice",disabled:T||!Y,onClick:V,children:T?"Creating…":"Create voice"}),B.text?a.jsx("p",{className:`af-voice-note af-voice-note--${B.tone}`,role:"status","data-voice-note":"create",children:B.text}):null]})}const WS=e=>Array.isArray(e)?e:Array.isArray(e==null?void 0:e.voices)?e.voices:[],Hg=e=>String((e==null?void 0:e.message)||e||"").trim().replace(/\.$/,"");function US({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,j]=y.useState(0),A=y.useRef(e);A.current=e;const T=y.useRef(!1),N=y.useRef(!0);y.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]),y.useEffect(()=>{const I=A.current.list;if(!I)return;let M=!0;return d(B=>({loading:!0,error:B.error})),I().then(B=>{M&&(l(WS(B).filter(G=>{var Z;return Nf(G)&&!((Z=G==null?void 0:G.tags)!=null&&Z.builtin)})),d({loading:!1,error:""}))}).catch(B=>M&&d({loading:!1,error:`The voices could not be listed: ${Hg(B)}.`})),()=>{M=!1}},[t,k]);const E=(I,M,B,G)=>{T.current||(T.current=!0,v(I),x({text:"",tone:"info"}),M().then(()=>{N.current&&(x({text:B,tone:"ok"}),m(null),g(""),G==null||G(),j(Z=>Z+1),n==null||n())}).catch(Z=>N.current&&x({text:`${Hg(Z)||"The gateway refused"}.`,tone:"error"})).finally(()=>{T.current=!1,N.current&&v("")}))},S=I=>String(I.name||I.label||Nf(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 M=Nf(I),B=qw(I)==="Shared voices",G=Au(I),Z=String(I.engine||I.provider||""),oe=_===M;return a.jsxs("li",{className:"af-voice-library__item","data-voice-id":M,children:[(f==null?void 0:f.id)===M?a.jsxs("span",{className:"af-voice-library__edit",children:[a.jsx("input",{"aria-label":`New name for ${S(I)}`,value:f.name,onChange:z=>m({id:M,name:z.target.value})}),a.jsx("button",{type:"button","data-action":"save-voice-name",disabled:oe||!f.name.trim(),onClick:()=>E(M,()=>A.current.rename(M,{name:f.name.trim()}),`Renamed to ${f.name.trim()}.`),children:"Save"}),a.jsx("button",{type:"button","data-action":"cancel-voice-name",disabled:oe,onClick:()=>m(null),children:"Cancel"})]}):a.jsxs("span",{className:"af-voice-library__name",children:[S(I),a.jsx("span",{className:"af-voice-library__meta",children:[B?"Shared":"Yours",G?xa(G):"",Z].filter(Boolean).join(" · ")})]}),p===M?a.jsxs("span",{className:"af-voice-library__confirm",role:"group","aria-label":`Delete ${S(I)}?`,children:["Delete ",S(I),"?",a.jsx("button",{type:"button","data-action":"confirm-delete-voice",disabled:oe,onClick:()=>E(M,()=>A.current.remove(M),`${S(I)} was deleted.`,()=>s==null?void 0:s(M)),children:"Delete"}),a.jsx("button",{type:"button","data-action":"keep-voice",disabled:oe,onClick:()=>g(""),children:"Keep"})]}):(f==null?void 0:f.id)!==M?a.jsxs("span",{className:"af-voice-library__actions",children:[e.rename?a.jsx("button",{type:"button","data-action":"rename-voice",disabled:!!_,onClick:()=>m({id:M,name:S(I)}),children:"Rename"}):null,e.remove?a.jsx("button",{type:"button","data-action":"delete-voice",disabled:!!_,onClick:()=>g(M),children:"Delete"}):null,e.share&&!B?a.jsx("button",{type:"button","data-action":"share-voice",disabled:!!_,onClick:()=>E(M,()=>A.current.share(M),`${S(I)} is shared with everyone.`),children:"Share"}):null]}):null]},M)})}):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 Cf=pe("automations"),VS=pe("trigger-sources"),GS=pe("me/email"),HS=pe("me/email/accounts"),KS=pe("triggers/connections"),JS=pe("automations/schedule-preview");class Kg 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 qS(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 Ef(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 YS(){return Fr()}function QS(e){const t=e.newId??YS,n=o=>`${Cf}/${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 Kg(qS(m.status,g));if(!_||g===null||typeof g!="object")throw new Kg({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",`${Cf}${Ef({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>s("GET",n(o)),createAutomation:o=>s("POST",Cf,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${Ef({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${Ef({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>s("GET",VS),getMyEmail:()=>s("GET",GS),listTriggerConnections:()=>s("GET",KS),listMailboxes:()=>s("GET",HS),previewSchedule:o=>s("POST",JS,{trigger:o})}}function $u(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 Jh(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 XS(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 hh(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const ZS={active:"Active",pause:"Pause",resume:"Resume",run_now:"Run now",stop_current:"Stop current",revise:"Edit",archive:"Archive",unarchive:"Unarchive",discuss:"Discuss"},ej={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.`},tj="Next scheduled run: {time}.",nj="Growing context: later runs see this run in their history.",sj={run_now:{name:"playCircle"}},rj={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."},aj={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."},qh={labels:ZS,hints:ej,run_now_next_run_line:tj,run_now_growing_line:nj,icons:sj,email:rj,schedule:aj},el={manual:"By hand",schedule:"On a schedule",something:"When something arrives",main_mailbox:"your main mailbox"};function Tu(e){const t=String(e||"");return t.startsWith("feed")?"feed":t.startsWith("webhook")?"webhook":"other"}function oj(e,t){const n=Tu(t);return n==="feed"?`When ${e} has a new item`:n==="webhook"?`When ${e} is called`:`When ${e} sends something`}function Xw(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 Zw(e){if(!e)return!1;const t=String(e.source_id||"");return!(t==="schedule"||t==="manual"||!t)}function Yh(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"?el.main_mailbox:s}function Qh(e,t){const n=Xw(e);return n?(t??[]).find(s=>s.connection_id===n)??null:null}function ij(e,t,n){var u;if(!e||!Zw(e))return"";const s=String(e.source_id||"");if(s.startsWith("email"))return Yh((u=e.config)==null?void 0:u.account,n);const o=Qh(e,t);if(o!=null&&o.label)return o.label;const l=Tu(s);return l==="feed"?"A feed":l==="webhook"?"A webhook":"A connection"}function Xh(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():el.schedule}if(l==="manual")return el.manual;if(l.startsWith("email"))return`When mail arrives in ${Yh((d=e.config)==null?void 0:d.account,n)}`;if(Xw(e)){const f=Qh(e,t),m=Tu(l),p=(f==null?void 0:f.label)||(m==="feed"?"a feed":m==="webhook"?"a webhook":"a connection");return oj(p,l)}return el.something}const lj=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Af(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)} ${lj[Number(l)-1]??l}`;return{day:s,clock:o,label:d}}function cj(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 mh(e,t={}){if(!e)return"";const n=Date.parse(e);if(Number.isNaN(n))return"";const s=cj(t.timeZone),o=s??"UTC",l=s?"":" UTC",u=t.nowMs??Date.now(),d=Af(n,o),f=Af(u,o).day,m=Af(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 tr(e){return typeof e=="string"?e.trim():""}function Dc(e){return e?`: “${e}”`:""}function Fc(e,t,n){return`${e} ${e===1?t:n}`}function uj(e,t={}){var p,g,_;if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,s=tr(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=mh(tr(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=Yh((g=(p=t.trigger)==null?void 0:p.config)==null?void 0:g.account,t.mailboxes),m=`${Fc(C,"new message","new messages")}${Dc(tr((_=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:{},j=tr(u.connection_id)||tr(n.connectionid),A={source_id:l,config:{connection_id:j}},T=Qh(j?A:t.trigger,t.connections),N=Tu(l);f=(T==null?void 0:T.label)||ij(j?A:t.trigger??A,t.connections,t.mailboxes);const E=S=>{var I;return!!S&&typeof S=="object"&&((I=S.data)==null?void 0:I.test)===!0};v.length&&v.every(E)?m=C===1?"Test event":`${C} test events`:N==="webhook"?m=`${Fc(C,"call","calls")}${Dc(tr(x.subject))}`:N==="feed"?m=`${Fc(C,"new item","new items")}${Dc(tr(k.title)||tr(x.subject))}`:m=`${Fc(C,"new event","new events")}${Dc(tr(x.subject))}`}return{source:f,what:m,at:d,text:[f,m,d].filter(Boolean).join(" · ")}}const dj=/^([1-9][0-9]*)([smhd])$/,fj={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function fl(e){if(typeof e!="string")return null;const t=dj.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function hj(e){const t=fl(e);if(!t)return`every ${e}`;const[n,s]=fj[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${s}`}function iu(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 ev(e,t,n){return Xh(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function tv(e){return e==="growing"?"Growing — each run sees the previous runs":"Independent — each run starts fresh"}const mj={active:"Active",paused:"Paused",completed:"Completed",failed:"Failed",archived:"Archived"},et=qh.email,nv="email.received",sv=1,pj="1h",gj="60s",rv=60,Zh=100,ph=1e3,Jg=200,qg=200,Yg=50;function hl(e){return!!e&&e.source_id===nv&&e.source_version===sv}function em(e){return!!e&&e.effective_enabled===!0}function av(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 yj=/[\s<>,;:"()[\]]/;function gh(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!yj.test(t)}function wj(e){const t=e.trim().toLowerCase();return!!t&&!t.includes("@")&&t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")&&!/[\s<>,;:"()[\]/*]/.test(t)}const tm={usesModel:!0,every:null,maxBatch:null,fromIn:"",fromDomainIn:"",toIn:"",subjectContains:"",hasAttachment:"any"};function nm(e){return e?pj:gj}function ov(e){const t=fl(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}function $f(e,t,n,s,o){const l=av(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>Jg&&o.push(`${t}: at most ${Jg} entries.`),l}function iv(e){const t=[],n={uses_model:e.usesModel};e.every===null?n.every=nm(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&&(ov(n.every)??0)<rv&&t.push("The check interval is at least 60 seconds."),e.maxBatch===null?n.max_batch=Zh:!Number.isInteger(e.maxBatch)||e.maxBatch<1||e.maxBatch>ph?t.push(`At most this many emails per run: a whole number from 1 to ${ph}.`):n.max_batch=e.maxBatch;const s={},o=$f(e.fromIn,et.from_in,gh,"an email address",t);o&&(s.from_in=o);const l=$f(e.fromDomainIn,et.from_domain_in,wj,"a domain like example.com",t);l&&(s.from_domain_in=l);const u=$f(e.toIn,et.to_in,gh,"an email address",t);u&&(s.to_in=u);const d=e.subjectContains.trim();return d&&(d.length>qg||/[\r\n]/.test(d)?t.push(`${et.subject_contains}: one line of at most ${qg} 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 lv(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:nm(t.uses_model!==!1);s.push(`checked ${hj(l)}`);const u=typeof t.max_batch=="number"?t.max_batch:Zh;return s.push(`up to ${u} per run`),s.join(" · ")}const tl={mode:"self",addresses:""};function yh(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=av(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=>!gh(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>Yg&&t.push(`At most ${Yg-1} addresses.`),{recipients:["self",...n],errors:t}}function vj(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function _j(e){const t=(e??["self"]).filter(n=>n!=="self");return t.length?`Me and ${t.join(", ")}`:"Only me"}function cv(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function uv(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}function bj(e){return uv(e)?"In the console and by email":"In the console"}const Mt={pause:"automation.pause",resume:"automation.resume",run_now:"automation.run_now",stop_current:"automation.stop_current",archive:"automation.archive",unarchive:"automation.unarchive"},xj=new Set(["running","waiting","backoff"]);function kj(e,t=[]){return e.current_occurrence!=null}function Sj(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 jj(e,t){var n;return e.next_run_at&&e.next_run_local?`${vv(e.next_run_local,e.time_zone)} (${Nj(e.next_run_at,t)})`:e.status==="paused"?"none while paused":e.status==="active"&&e.trigger&&Zw(e.trigger)?Qg.event:e.status==="active"&&((n=e.trigger)==null?void 0:n.source_id)==="manual"?Qg.manual:"none scheduled"}const Qg={event:"when something new arrives",manual:"when someone presses Run now"};function Nj(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 To(e,t=[],n=!1){const s=new Set(e.capabilities),o=e.status,l=kj(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 dv(e){return e.status==="active"?Mt.pause:Mt.resume}function Cj(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 Ej(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=Cj(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:!xj.has(t.status)}})}function Aj(e){const t=e.attention.items;return t.length?t[t.length-1].cursor:null}function $j(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 Tj={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 Oo(e){return{title:Tj[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function ml(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 fv(e,t){var l,u,d;const n=e.trigger,s=n.source_id==="schedule"||hl(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:Rj(n)?Pj(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??ol),prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,tools:$u(t==null?void 0:t.target.input_data),notifyEmail:t?uv(t.notify):null,emailRecipients:t?vj((d=t.notify)==null?void 0:d.recipients):null}}function hv(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=fv(e,n);if(t.every!==u.every&&t.every!==null){const m=hl(e.trigger);if(!fl(t.every))s.push("Interval must be a whole number of minutes, hours or days.");else if(m&&(ov(t.every)??0)<rv)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=rm(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(gv(d)||s.push(pv),(t.context!==e.context_mode||d!==u.growingMaxTokens)&&(o.context=yv(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:Jh(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=yh(t.notifyEmail?t.emailRecipients??tl:u.emailRecipients??tl),p=yh(u.emailRecipients??tl).recipients;m.errors.length?s.push(...m.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(m.recipients)!==JSON.stringify(p))&&(o.notify=cv(t.notifyEmail,m.recipients))}if(s.length)return{errors:s};if(n&&t.target&&hh(t.target)!==hh(n.target)){const m=((f=o.target)==null?void 0:f.input_data)||n.target.input_data;o.target={...t.target,input_data:XS(m)}}return Object.keys(o).length?o:null}const ol=5e4,mv="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.",pv="Max growing context must be a positive whole number of tokens.";function gv(e){return Number.isSafeInteger(e)&&e>0}function yv(e,t){return{mode:e,...t!==ol?{growing:{max_tokens:t}}:{}}}const dt=qh.schedule,lu=["mon","tue","wed","thu","fri","sat","sun"],wv=["daily","weekly","monthly"],sm=2;function Rj(e){return e.source_id==="schedule"&&e.source_version===sm}function Ij(e,t=sm){const n=e==null?void 0:e.schedule_rule_text;return typeof n=="string"&&n?n:el.schedule}const Mj=/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/;function vv(e,t){if(!e)return"";const n=Mj.exec(e);return n?`${n[1]} ${n[2]}${t?` ${t}`:""}`:e}function Lj(e,t="account"){return(t==="account"?dt.time_zone_line:dt.time_zone_line_automation).replace("{time_zone}",e)}const Oj=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function _v(e){return wv.includes(e.kind)}function rm(e){const t=[];if(Oj.test(e.at)||t.push(dt.error_at),e.kind==="weekly"){const n=lu.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 Pj(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)?lu.filter(s=>t.days.includes(s)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}const Dj=[{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 bv(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 Fj(e){const t=e.trim().split(`
56
- `)[0].trim();return t.length>120?`${t.slice(0,119)}…`:t}const zj=/^\d{4}-\d{2}-\d{2}T([01][0-9]|2[0-3]):[0-5][0-9]$/;function Xg(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=bv(e.until);s?n.until=s:t.push("Stop at must be a date and time (UTC).")}return n}function Bj(e){const t=[],n=e.when;if(n.kind==="once"){const d=(n.at||"").trim().slice(0,16);return zj.test(d)?{config:{kind:"once",at:d},errors:t}:{config:null,errors:[dt.error_once]}}if(_v(n)){const d=rm(n),f=Xg(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=bv(e.startAt),l||t.push("First run must be a date and time (UTC)."));const u=Xg(e,t);return t.length||!o?{config:null,errors:t}:{config:{kind:"every",every:o,...l?{start_at:l}:{},...u},errors:t}}function xv(e){const t=Bj(e);return t.config?{trigger:{source_id:"schedule",source_version:sm,config:t.config},errors:[]}:{trigger:null,errors:t.errors}}function Wj(e){return e.kind==="every"||e.kind==="once"||_v(e)}function Uj(e){if(e.trigger==="email"){const t=iv(e.email??tm);return t.errors.length?"":lv(t.config)}return""}function Vj(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()||Fj(s);o.length>120&&n.push("Title is at most 120 characters.");const l=e.trigger==="email",u=l?iv(e.email??tm):null,d=l?null:xv(e);n.push(...u?u.errors:d.errors);const f=e.notifyEmail&&e.emailRecipients&&e.emailRecipients.mode==="list"?yh(e.emailRecipients):null;f&&n.push(...f.errors);const m=e.growingMaxTokens??ol;if(e.context==="growing"&&!gv(m)&&n.push(pv),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:nv,source_version:sv,config:u.config}:d.trigger,context:yv(e.context,e.context==="growing"?m:ol),policy:{tool_approval:e.toolApproval??"auto"}};return e.notifyEmail===!0&&(g.notify=cv(!0,f==null?void 0:f.recipients)),{ok:!0,body:g}}const Gj="Tools run without asking (you approve them now by creating this automation)";function Hj(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 Kj(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 kv={ask_user:"Question for you",tool_approval:"Approval needed",event:"Waiting for an event"};class Sv{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||Jj(n.error))&&this.open.delete(t)}}function Jj(e){return ml(e)&&e.status>0&&e.code!=="invalid_response"}function jv(){return Fr()}class qj{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 Zg(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 Yj="08:00",Qj=["mon"],Nv={at:Yj,days:[...Qj],day:1};function Cv(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 am(e,t){return{...e,at:t.at,...t.kind==="weekly"?{days:[...t.days]}:{},...t.kind==="monthly"?{day:t.day}:{}}}function ey(e){return am(Nv,e)}const Xj=[...Array.from({length:31},(e,t)=>String(t+1)),"last"];function Ev(e){const t=e.value,n=s=>{if(t.kind!=="weekly")return;const o=t.days.includes(s);e.onChange({...t,days:lu.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}),lu.map(s=>a.jsx(Hk,{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:Xj.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 Zj(e){return a.jsxs("p",{className:"af-schedule__tz","data-time-zone":e.timeZone,children:[a.jsx(ru,{content:dt.time_zone_hint,children:a.jsx("span",{tabIndex:0,className:"af-schedule__tz-text",children:Lj(e.timeZone,e.whose??"account")})}),e.onOpenPreferences&&(e.whose??"account")==="account"?a.jsxs(a.Fragment,{children:[" · ",a.jsx(ru,{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 e0(e){const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message?t.message:String(e)}function Av(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:e0(p)})})},n);return()=>clearTimeout(m)},[s,n]),o}function $v(e){const t=e.state;return t.phase==="ok"?a.jsxs(a.Fragment,{children:[e.showZone===!1?null:a.jsx(Zj,{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 ty(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 t0(e){const t=e.disabled===!0,n=y.useMemo(()=>ty([...e.options||[],...e.value||[]]),[e.options,e.value]),s=y.useMemo(()=>ty(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 Tv(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(t0,{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 Ru="@default",Rv="No workflows available for this app — ask your admin.",Iv={shared:"Shared",mine:"Mine"};class Rr extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function Mv(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 n0(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function s0(e,t={}){return e===null?n0(t):Mv(e,t)}function qn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Kt(e){return typeof e=="string"?e.trim():""}const zc="update the gateway";function r0(e,t){var d,f;const n=qn(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const s=qn(n[t]);if(!s)return{status:"unavailable",reason:Kt((f=qn((d=qn(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 a0(e,t){return Lv(e,t)}function Lv(e,t,n={}){var d,f;const s=qn(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): ${zc}.`);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=qn(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 _=qn(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): ${zc}.`);if(typeof p.shipped!="boolean")throw new Rr(`The gateway did not say whether ${g} ships with it (shipped missing): ${zc}.`);const C=Kt(p.bundle_version),x=Array.isArray(p.entrypoints)?p.entrypoints:[];for(const k of x){const j=qn(k),A=Kt(j==null?void 0:j.flow_id);if(!j||!A)continue;const T=Array.isArray(j.interfaces)?j.interfaces.map(Kt).filter(Boolean):[],N=u0((d=qn(p.automation_defaults))==null?void 0:d[A]),E=j.triggerable===!0||!!N;if(t===null){if(!T.length&&!E)continue}else if(!T.includes(t))throw new Rr(`The gateway offered ${g}:${A}, which does not declare ${t}: ${zc}.`);l.push({value:Kt(j.workflow_id)||`${g}${C?`@${C}`:""}:${A}`,bundleId:g,bundleVersion:C,flowId:A,name:Kt(j.name)||Kt((f=qn(p.metadata))==null?void 0:f.name)||g,description:Kt(j.description)||Kt(p.description),registryScope:Kt(p.registry_scope)||"private",group:v==="user"?"mine":"shared",shipped:p.shipped,interfaces:T,...t===null?{showInterfaces:!0}:{},...N?{automationTrigger:N}:{},...E?{triggerable:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:u?r0(s,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function o0(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:Iv[n],entries:e.filter(s=>s.group===n).sort(t)})).filter(n=>n.entries.length>0)}const i0={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function l0(e){return i0[e]??e}function c0(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?!e.interfaces.length&&e.automationTrigger?[Xh(e.automationTrigger),n].filter(Boolean).join(" · "):[[...new Set(e.interfaces.map(l0))].join(", "),n].filter(Boolean).join(" · "):n}function u0(e){var l;const t=qn((l=qn(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=qn(t.config)??{},o=Kt(t.connection_id);return{source_id:n,source_version:t.source_version,config:s,...o?{connection_id:o}:{}}}function d0(e){return e.value}function f0(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function h0(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 m0(e,t=!0){const n=(e==null?void 0:e.entries)??[],s=[];t&&s.push({key:"default",value:Ru,name:"Gateway default",detail:f0((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of o0(n))for(const l of o.entries)s.push({key:l.value,value:l.value,name:l.name,detail:c0(l,n),title:d0(l),group:o.id,entry:l});return s}async function p0(e,t,n){var l;const s=await fetch(ut(e,pe(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 g0(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 y0(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=s0(t,{allVersions:s});return(d.current?d.current(C,{signal:v.signal}):p0(l,C,v.signal)).then(k=>{v.signal.aborted||g({status:"ready",data:Lv(k,t,{defaultInterface:n}),error:""})}).catch(k=>{v.signal.aborted||g({status:"error",data:null,error:g0(k)})}),()=>v.abort()},[t,n,s,o,l,u,f]);const _=y.useCallback(()=>m(v=>v+1),[]);return{...p,reload:_}}function w0(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 Ov(...e){return e.filter(Boolean).join(" ")}function Pv(e){const t=y0({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(()=>m0(n.data,s).map(M=>{const B=M.entry&&C?C(M.entry):null;return B?{...M,detail:B}:M}),[n.data,s,C]),k=x.find(M=>M.value===e.value),j=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===Ru?"Gateway default":"Choose a flow",detail:""},A=String(e.unavailableReason||"").trim(),T=!A&&n.status==="ready",N=y.useCallback(()=>{d(!1),m(-1)},[]),E=y.useCallback(()=>{if(!T)return;v(w0(g.current)),d(!0);const M=x.findIndex(B=>B.value===e.value);m(M>=0?M:0)},[T,x,e.value]),S=y.useCallback(M=>{var B;N(),M.value!==e.value&&e.onChange(M.value,M.entry),(B=g.current)==null||B.focus()},[N,e]);y.useEffect(()=>{if(!u)return;const M=G=>{p.current&&!p.current.contains(G.target)&&N()},B=()=>N();return document.addEventListener("mousedown",M),document.addEventListener("touchstart",M),window.addEventListener("resize",B),()=>{document.removeEventListener("mousedown",M),document.removeEventListener("touchstart",M),window.removeEventListener("resize",B)}},[u,N]),y.useEffect(()=>{var B;if(!u||f<0)return;const M=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(B=M==null?void 0:M.scrollIntoView)==null||B.call(M,{block:"nearest"})},[u,f,o]);const I=M=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(M.key)&&(M.preventDefault(),E());return}if(M.key==="Escape"){M.preventDefault(),N();return}if(M.key==="Tab"){N();return}if(M.key==="Enter"||M.key===" "){M.preventDefault(),f>=0&&x[f]&&S(x[f]);return}const B=h0(M.key,f,x.length);B!==null&&(M.preventDefault(),m(B))};return a.jsxs("div",{ref:p,className:Ov("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":T?void 0:!0,title:A||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:j.name}),j.detail?a.jsx("span",{className:"af-workflow-picker__detail",children:j.detail}):null]}),a.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?a.jsx(v0,{id:l,idBase:o,rows:x,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:_,onHighlight:m,onChoose:S}):null,n.status==="error"?a.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&x.every(M=>!M.entry)&&!s?a.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:Rv}):null]})}function v0(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:Ov("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:Iv[l]}),u.map(d=>t(d.row,d.index))]},l)),o.length===0?a.jsx("p",{className:"af-workflow-picker__empty",children:Rv}):null]})}function Dv(e){const t=hh(e.target);return a.jsxs("div",{className:"af-auto__field",children:[a.jsx("span",{children:"Flow"}),a.jsx(Pv,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:_0(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 _0(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 b0(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 wh(e){if(em(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 x0(e){const t=e.value,n=d=>e.onChange({...t,...d}),s=d=>`${e.idBase}-email-${d}`,o=fl(nm(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:ph,step:1,disabled:u,value:String(t.maxBatch??Zh),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 k0(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(Ur,{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 S0={active:"play",paused:"pause",completed:"check",failed:"error",archived:"archive"};function j0(e){const t=String(e.status),n=S0[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:mj[t]??t}),n?a.jsx(ue,{name:n,size:e.iconSize??11,className:"af-auto__status-icon"}):null]})}const ny="Discuss this run",Iu=e=>a.jsx("div",{className:"af-auto-text","data-unformatted":"true",children:e});function N0(e){return ml(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function C0(e){const t=e.path.split(new RegExp("(?<=[/\\\\_-])"));return a.jsx("code",{className:"af-auto__path-text",children:t.map((n,s)=>a.jsxs(wt.Fragment,{children:[n,s<t.length-1?a.jsx("wbr",{}):null]},s))})}function Fv(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 E0(e){const t=e.summary,n=Sj(t),s=Fv(t,e.triggerSources),o=jj(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(j0,{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:[ev(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:tv(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(ue,{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:$j(t)})]})]})}function A0(e){var u,d;const t=e.definition,n=e.renderText??Iu,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(ue,{name:"chevronRight",size:14,className:"af-auto__definition-chevron"}),a.jsx(ue,{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," · ",ev(t.trigger,e.served,{connections:e.triggerConnections,mailboxes:e.mailboxes}),hl(t.trigger)?a.jsx("div",{className:"af-auto__hint","data-def":"email_rule",children:lv(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:[tv(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:bj(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:_j(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(C0,{path:t.workspace_root})})]}):null,a.jsx("dt",{children:"Revision"}),a.jsx("dd",{"data-def":"revision",children:t.revision})]})]})}const pl=qh,vh=pl.labels,zv={active:"play",pause:"pause",resume:"play",run_now:pl.icons.run_now.name,stop_current:"stop",revise:"edit",archive:"archive",unarchive:"unarchive",discuss:"chat"},_h=pl.hints,$0=pl.run_now_next_run_line,T0=pl.run_now_growing_line;function il(e,t){const n=[_h[e]];return e==="run_now"&&t&&(t.next_run_local&&n.push($0.replace("{time}",vv(t.next_run_local,t.time_zone))),t.context_mode==="growing"&&n.push(T0)),n.join(`
58
- `)}function R0(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=>vh[p]).join(", ")}: ${u}`});for(const p of d)l[p]=m}),{lines:o,describedBy:l}}function _n(e){return a.jsxs(a.Fragment,{children:[a.jsx(ue,{name:e.icon,size:14,className:"af-auto__btn-icon"}),a.jsx("span",{children:e.label})]})}function I0(e){const t=To(e.summary,e.occurrences,e.busy),n=e.summary.status==="archived",o=R0(t,["active","run_now","stop_current","revise",n?"unarchive":"archive"],e.idBase??`af-auto-${e.summary.automation_id}`),l=(u,d,f)=>{const m=il(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(_n,{icon:zv[u],label:(f==null?void 0:f.label)??vh[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(Ur,{className:"af-auto__switch",action:"active",label:vh.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:il("active",e.summary),onChange:()=>e.onCommand(dv(e.summary))},"active"),l("run_now",()=>e.onCommand(Mt.run_now)),l("stop_current",()=>e.onCommand(Mt.stop_current)),l("revise",e.onToggleRevise,{pressed:e.reviseOpen,action:"edit"}),n?l("unarchive",()=>e.onCommand(Mt.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(ue,{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(ue,{name:"x",size:12})}):null]}):null})]}),o.lines.length?a.jsxs("p",{className:"af-auto__reasons",children:[a.jsx(ue,{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(Mt.archive),children:a.jsx(_n,{icon:"archive",label:"Archive"})}),a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"archive-cancel",onClick:e.onCancelArchive,children:a.jsx(_n,{icon:"x",label:"Keep it"})})]})]}):null]})}const sy=[["m","minutes"],["h","hours"],["d","days"]];function M0(e,t){const n=k=>{const j=e.elements.namedItem(k);return j&&typeof j.value=="string"?j.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 Bv(e){var S;const t=fv(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(((S=t.calendar)==null?void 0:S.kind)??null),[_,v]=y.useState(t.calendar?ey(t.calendar):null),C=p&&_?Cv(p,_):null,x=(()=>{if(!C)return null;const I=rm(C);if(!I.config)return null;const M=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 M=="string"?{time_zone:M}:{}}}})(),k=Av(x,e.previewSchedule),j=t.every?fl(t.every):null,A=j&&j.unit==="s"?[["s","seconds"],...sy]:sy,T=`af-auto-revise-${e.summary.automation_id}`,N=em(e.emailStatus),E=hl(e.summary.trigger);return a.jsxs("form",{className:"af-auto__revise","aria-labelledby":`${T}-heading`,onSubmit:I=>{I.preventDefault(),e.onSubmit({...M0(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:`${T}-heading`,hidden:!0,children:"Edit automation"}):a.jsxs("h3",{className:"af-auto__form-title",id:`${T}-heading`,children:[a.jsx(ue,{name:"edit",size:14})," ",e.heading??"Edit automation"]}),e.definition&&e.workflowPickerOptions?a.jsx(Dv,{target:n||e.definition.target,options:e.workflowPickerOptions,onChange:s}):null,a.jsxs("label",{className:"af-auto__field",htmlFor:`${T}-title`,children:[a.jsx("span",{children:"Title"}),a.jsx("input",{id:`${T}-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:`${T}-prompt`,children:[a.jsx("span",{children:"Task"}),a.jsx("textarea",{id:`${T}-prompt`,name:"prompt",defaultValue:t.prompt,rows:Math.min(10,Math.max(3,t.prompt.split(`
60
- `).length+1)),required:!0})]}):null,j?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:j.amount,"aria-label":"Interval amount"}),a.jsx("select",{name:"every_unit",defaultValue:j.unit,"aria-label":"Interval unit",children:A.map(([I,M])=>a.jsx("option",{value:I,children:M},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:wv.map(I=>a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:`${T}-calendar-kind`,value:I,checked:C.kind===I,disabled:e.busy,onChange:()=>g(I)})," ",dt[`kind_${I}`]]},I))}),a.jsx(Ev,{value:C,onChange:I=>v(M=>am(M??ey(I),I)),idBase:T,disabled:e.busy}),a.jsx($v,{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:mv})]})})]}),t.toolApproval?a.jsxs("fieldset",{className:"af-auto__field",children:[a.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?a.jsx(Tv,{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(wh,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),a.jsx(Ak,{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(_n,{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(_n,{icon:"x",label:"Cancel"})}):null]})]})}function L0(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 O0(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 P0="What the agent received";function bh(e,t){const n=e.elements.namedItem(t);return n&&typeof n.value=="string"?n.value.trim():""}function D0(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??Iu,l=u=>a.jsxs("div",{className:"af-auto-wait__prompt",id:n,children:[a.jsx("span",{className:"af-auto-wait__kind",children:kv[t.kind]??"Waiting"}),t.prompt?o(t.prompt):a.jsxs("span",{children:[" ",u]})]});if(t.kind==="tool_approval"){const u=Hj(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(_n,{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(_n,{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=Kj(bh(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(_n,{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=bh(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(_n,{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 F0(e){const{row:t,tone:n,badge:s,statusText:o}=e.view,l=`af-auto-occ-${t.run_id}`,u=e.renderText??Iu,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,j)=>e.renderTurn?e.renderTurn({kind:k,role:k==="trigger"?"user":"assistant",text:j,index:t.index,runId:t.run_id}):u(j),p=e.renderTurn?" af-auto-turn--card":"",g=typeof e.task=="string"?e.task.trim():"",_=L0(t.user_turn,g)!==null,v=O0(t),C=mh(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 ${iu(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(ue,{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:P0}),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:iu(t.finished_at),children:[" · ",mh(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 j;return(j=e.onOpenResource)==null?void 0:j.call(e,{kind:"artifact",url:k.url,name:k.name,mimeType:k.mime_type,runId:t.run_id})},children:[a.jsx(ue,{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(D0,{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(_n,{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(_n,{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(_n,{icon:"folder",label:"Workspace"})}):null]})]}),e.discussOpen?a.jsxs("form",{className:"af-auto-discuss","aria-label":`${ny}, from run ${t.index}`,onSubmit:k=>{k.preventDefault();const j=bh(k.currentTarget,"prompt");j&&e.onDiscussSubmit(t.index,j)},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(_n,{icon:"send",label:"Start discussion"})}),a.jsx("button",{type:"button",className:"af-auto__btn","data-action":"discuss-cancel",onClick:e.onDiscussCancel,children:a.jsx(_n,{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:_h.discuss,"aria-description":_h.discuss,"aria-describedby":f?`${l}-discuss-why`:void 0,onClick:()=>e.onDiscussOpen(t.index),children:a.jsx(_n,{icon:zv.discuss,label:ny})}),f?a.jsx("span",{className:"af-auto__reasons",id:`${l}-discuss-why`,children:f}):null]})]})]})}const z0=5e3,B0={[Mt.pause]:"Automation paused.",[Mt.resume]:"Automation active.",[Mt.run_now]:"Run requested.",[Mt.stop_current]:"Stop requested.",[Mt.unarchive]:"Unarchived: it is paused until you make it active."};function W0(e){var we,Se;const{summary:t,busy:n}=e,s=e.renderText??Iu,o=y.useId(),l=y.useRef(null),[u,d]=y.useState(!1),f=e.editOpen!==void 0,p=To(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 xe;f||d(Q),(xe=v.current)==null||xe.call(v,Q)},[x,k]=y.useState([]),[j,A]=y.useState(!1),[T,N]=y.useState(null),[E,S]=y.useState(null),[I,M]=y.useState(null);y.useEffect(()=>{if(!I)return;const Q=setTimeout(()=>M(null),z0);return()=>clearTimeout(Q)},[I]),y.useEffect(()=>{var xe;if(!p)return;k([]);const Q=Zg(l.current,['.af-auto__revise [name="title"]']);Q==null||Q.focus(),(xe=Q==null?void 0:Q.scrollIntoView)==null||xe.call(Q,{block:"nearest"})},[p,t.automation_id]);const[B,G]=y.useState(null);y.useEffect(()=>{var Q;B&&((Q=Zg(l.current,[...B,".af-auto__notice",".af-auto__title"]))==null||Q.focus(),G(null))},[B]);const Z=y.useRef(null);Z.current||(Z.current=new Sv(e.newId??jv));const oe=Z.current,z=Q=>S(N0(Q)),F=(Q,xe,ve)=>{S(null),M(null),xe(oe.idFor(Q)).then(Fe=>{oe.settle(Q,{ok:!0}),ve(Fe)},Fe=>{oe.settle(Q,{ok:!1,error:Fe}),z(Fe)})},L=Aj(t),q=y.useRef(e.onSeen);q.current=e.onSeen;const V=y.useRef(null);V.current||(V.current=new qj),y.useEffect(()=>{const Q=V.current,xe=L?`${t.automation_id}|${L}`:null;if(!L||!Q.next(xe,t))return;const ve=t;q.current(L).then(()=>Q.succeeded(xe),Fe=>{Q.failed(xe,ve),z(Fe)})});const Y=To(t,e.occurrences,n),J=Ej(e.occurrences),W=(Se=(we=e.definition)==null?void 0:we.target.input_data)==null?void 0:Se.prompt,R=Q=>e.occurrenceEvents&&Q in e.occurrenceEvents?uj(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,se=E??e.error??null,ce=se?Oo(se):null,ae=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(E0,{summary:t,workflowLabel:e.workflowName,triggerSources:e.triggerSources,titleId:o,nowMs:e.nowMs,onOpenWorkspace:e.onOpenWorkspace,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}),a.jsx(I0,{summary:t,occurrences:e.occurrences,busy:n,confirmingArchive:j,reviseOpen:p,notice:I,onDismissNotice:()=>M(null),idBase:`${o}-ctl`,onCommand:Q=>F(`command:${Q}`,xe=>e.onCommand(Q,void 0,{command_id:xe}),()=>{Q===Mt.archive?(A(!1),M("Archive requested."),G(['[data-action="archive"]'])):M(B0[Q]??"Command sent.")}),onToggleRevise:()=>{k([]),C(!p)},onAskArchive:()=>A(!0),onCancelArchive:()=>{A(!1),G(['[data-action="archive"]'])}})]}),p&&_?a.jsx(Bv,{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),G(['[data-action="edit"]'])},onSubmit:Q=>{const xe=_.summary,ve=hv(xe,Q,_.definition);if(ve===null){k(["Nothing changed."]);return}if("errors"in ve){k(ve.errors);return}k([]),F(`revise:${xe.revision}:${JSON.stringify(ve)}`,async Fe=>{const Xe=Q.target&&ve.target?{...ve,target:await(e.prepareTarget?e.prepareTarget(ve.target):b0(ve.target,e.workflowPickerOptions))}:ve;return e.onRevise(Xe,xe.revision,{command_id:Fe})},()=>{M("Saved; applies from the next run."),C(!1),G(['[data-action="edit"]'])})}}):e.definition?a.jsx(A0,{definition:e.definition,renderText:s,served:t,triggerConnections:e.triggerConnections,mailboxes:e.mailboxes}):null,ce?a.jsxs("div",{className:"af-auto__error",role:"alert","data-code":se==null?void 0:se.code,children:[a.jsx(ue,{name:"error",size:14,className:"af-auto__btn-icon"}),a.jsxs("span",{className:"af-auto__error-text",children:[a.jsx("strong",{children:ce.title})," ",a.jsx("span",{children:ce.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:()=>S(null),children:a.jsx(ue,{name:"x",size:12})}):null]}):null,ae.items.length||ae.waits.length?a.jsx("section",{className:"af-auto__attention","aria-label":"Needs attention",children:a.jsxs("ul",{children:[ae.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," · ",iu(Q.at)]}),Q.body?a.jsx("div",{className:"af-auto__attention-body",children:s(Q.body)}):null]},Q.cursor)),ae.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:kv[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(_n,{icon:"history",label:`Load earlier runs (${K} more)`})}):null,J.length?a.jsx("ol",{className:"af-auto__timeline","aria-label":"Runs",children:J.map(Q=>{const xe=`[data-index="${Q.row.index}"]`;return a.jsx(F0,{view:Q,busy:n,eventCard:R(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?ve=>{var Fe;S(null);try{Promise.resolve((Fe=e.onOpenResource)==null?void 0:Fe.call(e,ve)).catch(z)}catch(Xe){z(Xe)}}:void 0,discussOpen:T===Q.row.index,onOpenRun:e.onOpenRun,onAnswerWait:(ve,Fe,Xe)=>{S(null),e.onAnswerWait(ve,Fe,Xe).then(()=>M("Answer sent."),z)},onWaitError:ve=>S({status:0,code:"invalid_payload",message:ve}),onDiscussOpen:N,onDiscussCancel:()=>{N(null),G([`${xe} [data-action="discuss"]`])},onDiscussSubmit:(ve,Fe)=>F(`discuss:${ve}:${Fe}`,Xe=>e.onDiscuss(ve,Fe,{request_id:Xe}),()=>{N(null),M("Discussion started in a new conversation."),G([`${xe} [data-action="discuss"]`])})},Q.row.run_id)})}):a.jsx("p",{className:"af-auto__empty",children:"No runs yet."})]})}function U0(e,t){return e==="email"||!Wj(t.when)?null:xv({...t}).trigger}function V0(e){return e==="daily"||e==="weekly"||e==="monthly"||e==="once"}function G0(e){var te,be;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??$u((te=e.target)==null?void 0:te.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=P=>f(ie=>({...ie,value:P})),[g,_]=y.useState(e.initialPrompt??""),[v,C]=y.useState("every"),[x,k]=y.useState(Nv),j=Cv(v==="weekly"||v==="monthly"?v:"daily",x),[A,T]=y.useState(tm),[N,E]=y.useState(!1),[S,I]=y.useState(tl),[M,B]=y.useState("24"),[G,Z]=y.useState("h"),[oe,z]=y.useState(""),[F,L]=y.useState(String(ol)),[q,V]=y.useState("independent"),[Y,J]=y.useState("auto"),[W,R]=y.useState(e.initialTitle??""),[K,se]=y.useState(""),[ce,ae]=y.useState(""),[we,Se]=y.useState(""),[Q,xe]=y.useState([]),ve=y.useRef(null);ve.current||(ve.current=new Sv(()=>(e.newRequestId??jv)())),y.useEffect(()=>{var Oe;if(!e.open)return;const P=document.activeElement;(Oe=o.current)==null||Oe.focus();const ie=Ae=>{if(!Ae.defaultPrevented){if(Ae.key==="Escape"){Ae.preventDefault(),l.current();return}Dw(Ae,s.current,document.activeElement)}};return window.addEventListener("keydown",ie),()=>{window.removeEventListener("keydown",ie),P&&typeof P.focus=="function"&&P.focus()}},[e.open]);const Fe=v==="once"?{kind:"once",at:oe}:v==="daily"||v==="weekly"||v==="monthly"?j:{kind:"every",amount:Number(M),unit:G},Xe={...v==="every"&&K?{startAt:K}:{},...v!=="once"&&ce.trim()?{count:Number(ce)}:{},...v!=="once"&&we?{until:we}:{}},Ve=Av(e.open?U0(v,{when:Fe,...Xe}):null,e.previewSchedule);if(!e.open)return null;const Je=em(e.emailStatus),me=v==="email"&&Je,Me=v==="email"&&!Je?"every":v,st=Me==="daily"||Me==="weekly"||Me==="monthly",tt=P=>C(P),$t={prompt:g,when:v==="once"?{kind:"once",at:oe}:st?j:{kind:"every",amount:Number(M),unit:G},...me?{trigger:"email",email:{...A,usesModel:e.targetUsesModel!==!1}}:{},...Je&&N?{notifyEmail:!0}:{},...Je&&S.mode==="list"?{emailRecipients:S}:{},context:q,growingMaxTokens:Number(F),toolApproval:Y,title:W,...Me==="every"&&K?{startAt:K}:{},...(Me==="every"||st)&&ce.trim()?{count:Number(ce)}:{},...(Me==="every"||st)&&we?{until:we}:{}},le=Uj($t),de=e.busy===!0,je=e.error?Oo(e.error):null,_e=P=>`${n}-${P}`,ge=P=>{P.preventDefault();const ie=Vj($t,{target:e.target,requestId:""});if(!ie.ok){xe(ie.errors);return}xe([]);const Oe=ve.current,Ae=e.availableTools===void 0?ie.body:{...ie.body,target:{...ie.body.target,input_data:Jh(ie.body.target.input_data||{},m)}},Ye=JSON.stringify(Ae),$e={...Ae,request_id:Oe.idFor(Ye)};Promise.resolve(e.onSubmit($e)).then(()=>Oe.settle(Ye,{ok:!0}),Ge=>Oe.settle(Ye,{ok:!1,error:Ge}))};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:P=>P.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:ge,"aria-busy":de,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:_e("prompt"),children:[a.jsx("span",{children:"Task"}),a.jsx("textarea",{id:_e("prompt"),ref:o,rows:3,value:g,onChange:P=>_(P.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:_e("kind"),value:"every",checked:Me==="every",onChange:()=>tt("every")})," ",dt.kind_every]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("kind"),value:"daily",checked:v==="daily",onChange:()=>tt("daily")})," ",dt.kind_daily]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("kind"),value:"weekly",checked:v==="weekly",onChange:()=>tt("weekly")})," ",dt.kind_weekly]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("kind"),value:"monthly",checked:v==="monthly",onChange:()=>tt("monthly")})," ",dt.kind_monthly]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("kind"),value:"once",checked:v==="once",onChange:()=>tt("once")})," ",dt.kind_once]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("kind"),value:"email",checked:me,disabled:!Je,onChange:()=>tt("email")})," ",et.trigger_label]})]}),Je?null:a.jsx(wh,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),me?a.jsx(x0,{value:{...A,usesModel:e.targetUsesModel!==!1},onChange:T,idBase:n}):st?a.jsx(Ev,{value:j,onChange:P=>k(ie=>am(ie,P)),idBase:n,disabled:de}):Me==="every"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"af-auto__row af-schedule__presets",role:"group","aria-label":"Presets",children:Dj.map(P=>P.when.kind==="every"?a.jsx("button",{type:"button",className:"af-auto__btn af-auto__btn--quiet","aria-pressed":Number(M)===P.when.amount&&G===P.when.unit,onClick:()=>{P.when.kind==="every"&&(B(String(P.when.amount)),Z(P.when.unit))},children:P.label},P.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:M,onChange:P=>B(P.target.value),"aria-label":"Interval amount"}),a.jsxs("select",{value:G,onChange:P=>Z(P.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:_e("once"),children:[a.jsx("span",{children:dt.once_label}),a.jsx("input",{id:_e("once"),type:"datetime-local",value:oe,onChange:P=>z(P.target.value)})]}),Me!=="email"?a.jsx($v,{state:Ve,onOpenPreferences:e.onOpenPreferences,showZone:V0(Me)}):a.jsx("p",{className:"af-schedule__preview","aria-live":"polite","data-preview":"true",children:le?`Runs ${le}.`:me?"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:_e("ctx"),value:"independent",checked:q==="independent",onChange:()=>V("independent")})," Independent — each run starts fresh"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("ctx"),value:"growing",checked:q==="growing",onChange:()=>V("growing")})," Growing — each run sees the previous runs"]}),q==="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:de,value:F,onChange:P=>L(P.target.value)}),a.jsx("span",{className:"af-auto__hint",children:mv})]}):null]}),a.jsxs("fieldset",{className:"af-auto__field","data-field":"tool-approval",children:[a.jsx("legend",{children:"Tools"}),e.availableTools!==void 0?a.jsx(Tv,{availableTools:e.availableTools,value:m,onChange:p,disabled:de}):null,a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("tools"),value:"auto",checked:Y==="auto",onChange:()=>J("auto")})," Run without asking"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:_e("tools"),value:"ask",checked:Y==="ask",onChange:()=>J("ask")})," Ask me before each tool call (the run waits for you)"]}),me?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:[Gj,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"}),Je?null:a.jsx(wh,{status:e.emailStatus,onOpenMyEmail:e.onOpenMyEmail}),a.jsx(k0,{notifyEmail:Je&&N,onNotifyEmailChange:E,recipients:Je?S:tl,onRecipientsChange:I,disabled:!Je,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:_e("title"),children:[a.jsx("span",{children:"Title"}),a.jsx("input",{id:_e("title"),value:W,maxLength:120,onChange:P=>R(P.target.value),placeholder:"Defaults to the task's first line"})]}),Me==="every"||st?a.jsxs(a.Fragment,{children:[Me==="every"?a.jsxs("label",{className:"af-auto__field",htmlFor:_e("start"),children:[a.jsx("span",{children:"First run at (UTC; empty = now)"}),a.jsx("input",{id:_e("start"),type:"datetime-local",value:K,onChange:P=>se(P.target.value)})]}):null,a.jsxs("label",{className:"af-auto__field",htmlFor:_e("count"),children:[a.jsx("span",{children:"Stop after this many runs"}),a.jsx("input",{id:_e("count"),type:"number",min:1,step:1,value:ce,onChange:P=>ae(P.target.value)})]}),a.jsxs("label",{className:"af-auto__field",htmlFor:_e("until"),children:[a.jsx("span",{children:"Stop at (UTC)"}),a.jsx("input",{id:_e("until"),type:"datetime-local",value:we,onChange:P=>Se(P.target.value)})]})]}):null]}),Q.length?a.jsx("ul",{className:"af-auto__form-errors",role:"alert",children:Q.map(P=>a.jsx("li",{children:P},P))}):null,je?a.jsxs("div",{className:"af-auto__error",role:"alert","data-code":(be=e.error)==null?void 0:be.code,children:[a.jsx("strong",{children:je.title})," ",a.jsx("span",{children:je.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:de,children:"Create automation"})]})]})]})})}const cu=6e4,xh=60*cu,ry=24*xh;function uu(e){const t=Math.abs(e);return Number.isFinite(t)?t<cu?"<1 min":t<xh?`${Math.floor(t/cu)} min`:t<2*ry?`${Math.floor(t/xh)} h`:`${Math.floor(t/ry)} d`:""}function H0(e,t,n){return e.source_id==="schedule"?Ij(t,e.source_version):e.source_id==="manual"?"manual":hl(e)?"on new email":Xh(e,n==null?void 0:n.connections,n==null?void 0:n.mailboxes,t)}function Xc(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function K0(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?Xc(e.last_occurrence.fired_at):null;return l===null?"":`waiting since ${uu(Math.max(0,t-l))}`}if(e.current_occurrence)return"running now";const n=e.last_occurrence,s=Xc(n==null?void 0:n.finished_at)??Xc(n==null?void 0:n.fired_at);return s===null?"last never":`last ${uu(Math.max(0,t-s))} ago`}function J0(e,t){const n=Xc(e.next_run_at);return n===null?null:n-t<cu?"next due now":`next in ${uu(n-t)}`}function Wv(e,t){const n=H0(e.trigger,e),s=K0(e,t),o=J0(e,t);return{cadence:n,last:s,next:o,line:[n,s,o].filter(Boolean).join(" · ")}}const An={min:300,max:960,default:420,step:16,bigStep:64};function du(e,t=An.min,n=An.max,s=An.default){return Number.isFinite(e)?Math.round(Math.min(n,Math.max(t,e))):Math.min(n,Math.max(t,s))}function q0(e,t,n,s=An.min,o=An.max,l="right"){const u=n?An.bigStep:An.step,d=l==="left"?"ArrowRight":"ArrowLeft",f=l==="left"?"ArrowLeft":"ArrowRight";return t===d?du(e+u,s,o):t===f?du(e-u,s,o):t==="Home"?s:t==="End"?o:null}function Y0(e,t,n,s=An.min,o=An.max){return du(n==="left"?e+t:e-t,s,o)}function Q0(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 X0(e,t){return e===t?null:t}function nl(e){return e.side==="left"?"left":"right"}function ay(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&&nl(o)===t?s:null}function Z0(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 eN(e,t,n){return e.id===t||e.keepAlive==="always"||n.has(e.id)}function tN(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 nN(e){return JSON.stringify({v:1,widths:e.widths,active:e.active,...e.legacyWidth!==void 0?{legacy:e.legacyWidth}:{}})}function oy(e,t,n){const s=t.minWidth??(n==null?void 0:n.min)??An.min,o=t.maxWidth??(n==null?void 0:n.max)??An.max,l=t.defaultWidth??(n==null?void 0:n.width)??An.default,u=e.widths[t.id]??e.legacyWidth;return du(u??l,s,o,l)}function sN(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&&nl(l)===t?o:null}function rN(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 Uv=y.createContext(void 0);function aN(e){const t=y.useContext(Uv);return t===void 0?a.jsx(a.Fragment,{children:e.children}):t===null?null:ul.createPortal(e.children,t)}class iy extends wt.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(ue,{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 oN(e){if(!e||typeof window>"u")return{widths:{},active:{}};try{return tN(window.localStorage.getItem(e))}catch{return{widths:{},active:{}}}}function ly(e,t){if(!(!e||typeof window>"u"))try{window.localStorage.setItem(e,nN(t))}catch{}}function iN(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(iy,{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(ue,{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(Uv.Provider,{value:n,children:t.errorBoundary===!1?o:a.jsx(iy,{label:t.label,children:o})})})]})}function lN(e){const{side:t,panels:n,activeId:s,overlay:o,onActiveChange:l}=e,u=n.find(F=>F.id===s)||null,d=n.filter(F=>F.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):An.default,x=y.useRef(C);x.current=C;const k=(u==null?void 0:u.minWidth)??An.min,j=(u==null?void 0:u.maxWidth)??An.max;y.useEffect(()=>{s&&m(F=>F.has(s)?F:new Set([...F,s]))},[s]);const A=u?u.id:null,T=y.useRef(l);T.current=l,y.useEffect(()=>{if(!o||!A)return;const F=L=>{L.key!=="Escape"||L.defaultPrevented||(L.preventDefault(),T.current(null))};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[o,A]),y.useEffect(()=>{var F,L,q;if(o)if(A)!_.current&&typeof document<"u"&&(_.current=document.activeElement),(F=g.current)==null||F.focus({preventScroll:!0});else{const V=_.current;_.current=null;const Y=typeof document<"u"?document.activeElement:null;V&&(!Y||Y===document.body||(L=g.current)!=null&&L.contains(Y))&&((q=V.focus)==null||q.call(V))}},[o,A]);const N=F=>{var Y,J;const L=Array.from(((Y=p.current)==null?void 0:Y.querySelectorAll('[role="tab"]'))||[]),q=L.findIndex(W=>W===document.activeElement),V=Q0(L.length,q<0?0:q,F.key);V!==null&&(F.preventDefault(),(J=L[V])==null||J.focus())},E=F=>{if(!u)return;const L=q0(x.current,F.key,F.shiftKey,k,j,t);L!==null&&(F.preventDefault(),e.setWidth(u,L,!0))},S=F=>{var L,q;F.button!==0&&F.pointerType==="mouse"||(v.current={startX:F.clientX,startW:x.current,pointerId:F.pointerId},(q=(L=F.currentTarget).setPointerCapture)==null||q.call(L,F.pointerId),F.preventDefault())},I=F=>{const L=v.current;!L||L.pointerId!==F.pointerId||!u||e.setWidth(u,Y0(L.startW,F.clientX-L.startX,t,k,j),!1)},M=F=>{var q,V;const L=v.current;!L||L.pointerId!==F.pointerId||(v.current=null,(V=(q=F.currentTarget).releasePointerCapture)==null||V.call(q,F.pointerId),u&&e.setWidth(u,x.current,!0))},B=!!u,G=e.railLabelStyle==="vertical-text",Z=o&&e.top!==void 0,oe={"--af-rail-panel-width":`${C}px`,"--af-panel-w":`${C}px`,...e.top!==void 0?{"--af-drawers-top":e.top}:{}},z=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(F=>{const L=F.id===s,q=`${L?`Collapse ${F.label}`:F.label}${F.hint?` · ${F.hint}`:""}`;return a.jsxs("button",{type:"button",role:"tab",id:`${e.idBase}-tab-${F.id}`,"aria-selected":L,"aria-controls":`${e.idBase}-panel-${F.id}`,"aria-label":F.label,title:q,className:`af-rail__tab${G?" af-rail__tab--text":""}${L?" is-active":""}`,"data-rail":F.id,onClick:V=>{_.current=V.currentTarget,l(X0(s,F.id))},children:[G?a.jsx("span",{className:"af-rail__vlabel","aria-hidden":"true",children:F.label}):a.jsx(ue,{name:F.icon,size:19}),typeof F.badge=="number"&&F.badge>0?a.jsx("span",{className:"af-rail__badge","aria-hidden":"true",children:F.badge>99?"99+":F.badge}):F.badge===!0?a.jsx("span",{className:"af-rail__dot","aria-hidden":"true"}):null]},F.id)})}):null;return a.jsxs("div",{className:`af-rail${t==="left"?" af-rail--left":""}${B?" af-rail--open":" af-rail--collapsed"}${o?" af-rail--overlay":" af-rail--docked"}${Z?" af-rail--anchored":""}${z?"":" af-rail--no-rail"}${G?" af-rail--vertical-text":""}${e.className?` ${e.className}`:""}`,style:oe,"data-active":s||"","data-side":t,children:[t==="left"?z:null,o&&B?a.jsx("div",{className:"af-rail__backdrop","aria-hidden":"true",onClick:()=>l(null)}):null,a.jsxs("div",{className:"af-rail__panel-wrap",hidden:!B,style:!o&&B?{width:C}:void 0,children:[!o&&B?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":j,"aria-valuenow":C,tabIndex:0,title:"Drag to resize",onKeyDown:E,onPointerDown:S,onPointerMove:I,onPointerUp:M,onPointerCancel:M}):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(F=>a.jsx(iN,{panel:F,idBase:e.idBase,open:F.id===s,mounted:eN(F,s,f),overlay:o,side:t,onCollapse:()=>l(null)},F.id))})]}),t==="right"?z:null]})}function cN(e){const t=Yc(e.overlayBelow||qc.md),n=e.overlay??t,s=e.idBase||"af-rail",{panels:o,onActiveChange:l,storageKey:u}=e,[d,f]=y.useState(()=>oN(u)),m=y.useRef(d);m.current=d;const p=y.useRef(e.onResize);p.current=e.onResize;const g=o.filter(S=>nl(S)==="left"),_=o.filter(S=>nl(S)==="right"),v=ay(e.active,"left",o),C=ay(e.active,"right",o),x=y.useCallback(S=>oy(d,S),[d]),k=y.useCallback((S,I,M)=>{var G;const B={...m.current,widths:{...m.current.widths,[S.id]:oy({widths:{[S.id]:I}},S)}};m.current=B,f(B),M&&(ly(u,B),(G=p.current)==null||G.call(p,S.id,B.widths[S.id]))},[u]),j=y.useRef(!1);y.useEffect(()=>{if(!j.current&&(j.current=!0,e.restoreActive!==!1))for(const S of["left","right"]){const I=S==="left"?v:C,M=sN(m.current,S,n,o);!I&&M&&l(M,S)}},[]);const A=y.useRef(!1);y.useEffect(()=>{if(!A.current){A.current=!0;return}if(n||!u)return;const S={...m.current,active:{left:v,right:C}};m.current=S,ly(u,S)},[v,C,n,u]),y.useEffect(()=>{const S=Z0(e.request);if(!S)return;const I=o.find(B=>B.id===S.id);if(!I)return;const M=nl(I);(M==="left"?v:C)!==S.id&&l(S.id,M)},[e.request]);const T=n?rN(e.topOffset):void 0,N=e.railLabelStyle||"icon",E=(S,I,M)=>I.length?a.jsx(lN,{side:S,panels:I,activeId:M,onActiveChange:B=>l(B,S),overlay:n,width:x,setWidth:k,ariaLabel:g.length&&_.length?`${e.ariaLabel} (${S})`:e.ariaLabel,idBase:s,railLabelStyle:N,top:T,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 Vv=72;function uN(e,t=Vv){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 Bc(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 dN(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function fN(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:uN(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 Gv(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:_}=fN(e.src,e.peaks),v=g??new Array(Vv).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())},[]),j=y.useCallback(N=>{const E=t.current;!E||!Number.isFinite(N)||(E.currentTime=N,u(N))},[]),A=N=>{var S;const E=(S=n.current)==null?void 0:S.getBoundingClientRect();!E||!d||j(dN(N-E.left,E.width,d))},T=N=>{if(!d)return;const E=N.key==="ArrowRight"||N.key==="ArrowUp"?5:N.key==="ArrowLeft"||N.key==="ArrowDown"?-5:0;E?(N.preventDefault(),j(Math.min(d,Math.max(0,l+E)))):N.key==="Home"?(N.preventDefault(),j(0)):N.key==="End"?(N.preventDefault(),j(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(ue,{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":`${Bc(l)} of ${Bc(d)}`,title:_||void 0,"data-waveform":g?"decoded":"flat",onKeyDown:T,onPointerDown:N=>{var E,S;(S=(E=N.currentTarget).setPointerCapture)==null||S.call(E,N.pointerId),A(N.clientX)},onPointerMove:N=>{N.buttons&1&&A(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 S=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-S/2,width:1.4,height:S,rx:.6},E)})})}),a.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[Bc(l)," / ",Bc(d)]}),m?a.jsx("p",{className:"af-audio__error",role:"alert",children:m}):null]})}const ka=e=>new Set(e.split(/\s+/).filter(Boolean)),hN=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"),mN=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"),pN=ka("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),gN=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"),cy=ka("true false null yes no on off"),yN={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:hN},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:mN},shell:{line:["#"],strings:['"',"'"],keywords:pN},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:gN},data:{line:["#"],strings:['"',"'"],keywords:cy},json:{line:[],strings:['"'],keywords:cy},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:ka("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:ka("")}},wN={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 om(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 wN[o]||""}const vN=e=>e>="0"&&e<="9",_N=e=>/[A-Za-z_$]/.test(e),uy=e=>/[A-Za-z0-9_$]/.test(e);function Hv(e,t){const n=String(e??""),s=yN[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(vN(f)&&!(d>0&&uy(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(_N(f)){let p=d+1;for(;p<n.length&&uy(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 Wc({text:e,language:t="",lineNumbers:n=!0,className:s,ariaLabel:o}){const l=om(t),u=Hv(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?bN(u).map((f,m)=>a.jsxs("span",{className:"af-code__line","data-line":m+1,children:[f.map((p,g)=>dy(p,g)),`
66
- `]},m)):u.map((f,m)=>dy(f,m))})})}function dy(e,t){return e.kind==="plain"?a.jsx(wt.Fragment,{children:e.text},t):a.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function bN(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 Kv=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Hi=6e4,Ki=60*Hi,Uc=24*Ki;function gl(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)?gl(Number(t)):Date.parse(t)}function fy(e){return e<10?`0${e}`:String(e)}function hy(e,t){const n=gl(e);if(!Number.isFinite(n))return"";const s=new Date(n),o=s.getFullYear()===new Date(t).getFullYear();return`${Kv[s.getMonth()]} ${s.getDate()}${o?"":`, ${s.getFullYear()}`}`}function Po(e){const t=gl(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${Kv[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${fy(n.getHours())}:${fy(n.getMinutes())}`}function Ro(e,t){const n=gl(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const s=t-n;if(s<0){const l=-s;if(l<Hi)return"due now";if(l<Ki)return`in ${Math.round(l/Hi)} min`;if(l<Uc)return`in ${Math.round(l/Ki)} h`;const u=Math.round(l/Uc);return u<7?`in ${u} ${u===1?"day":"days"}`:hy(n,t)}if(s<Hi)return"just now";if(s<Ki)return`${Math.floor(s/Hi)} min ago`;if(s<Uc)return`${Math.floor(s/Ki)} h ago`;const o=Math.floor(s/Uc);return o===1?"yesterday":o<7?`${o} days ago`:hy(n,t)}const xN=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),kN=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),SN=new Set("mp4 m4v webm mov ogv mkv".split(" ")),jN=new Set("mts cts".split(" ")),NN=new Set(["video/mp2t"]),CN=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function EN(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function ll(e,t=""){const n=EN(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":xN.has(n)?"image":kN.has(n)?"audio":SN.has(n)?"video":om(e)||jN.has(n)?"code":CN.has(n)?"text":s.startsWith("image/")&&s!=="image/svg+xml"?"image":s.startsWith("audio/")?"audio":s.startsWith("video/")&&!NN.has(s)?"video":s.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(s)?"code":"binary"}function fu(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function yl(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 AN(e){const t=e.kind??ll(e.name,e.contentType),n=yl(e.sizeBytes),s=e.modified!==void 0?Ro(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(ue,{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:Po(e.modified),dateTime:new Date(gl(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(ue,{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(ue,{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($N,{kind:t,p:e})]})})]})}function $N({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(Li,{});case"audio":return t.url?a.jsx(Gv,{src:t.url,name:t.name}):a.jsx(Li,{});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(Li,{});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(Li,{});case"markdown":return t.renderMarkdown?a.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):a.jsx(Wc,{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(Wc,{text:s,language:"json"})]})}case"code":return a.jsx(Wc,{text:n,language:t.name});case"text":return a.jsx(Wc,{text:n,language:"",lineNumbers:!1});default:return a.jsx(Li,{})}}function Li(){return a.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}function Ji(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 kh(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."},$n=ct;function TN(e){return e==="any_except_denied"?$n.postureAnyExceptDenied:$n.postureAllowedOnly}function RN(e){return e==="any_except_denied"?$n.postureAnyExceptDeniedHelp:$n.postureAllowedOnlyHelp}function my(e){return e==="ro"?$n.accessRead:e==="deny"?$n.accessDenied:$n.accessReadWrite}function IN(e){return e==="gateway"?$n.gatewayHelp:e==="account"?$n.accountHelp:e==="session"?$n.sessionHelp:$n.runHelp}const py={deny:0,ro:1,rw:2},Tf=["rw","ro","deny"];function MN(e){if(e===null)return{allowed:[...Tf],reasons:{}};const t=e==="deny"?$n.capRefused:$n.capReadOnly,n=Tf.filter(o=>py[o]<=py[e]),s={};for(const o of Tf)n.includes(o)||(s[o]=t);return{allowed:n,reasons:s}}function LN(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}=MN(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:`${$n.gatewayPrefix} ${d.gateway_summary}`,summary:e==="gateway"?n.summary:d.summary,locked:l}}function ON(e,t){return t==="any_except_denied"?"deny":e==="gateway"?"rw":"ro"}function wl(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 PN(e,t,n,s){return wl(e,{...t,folders:t.folders.map(o=>o.path===n?{path:n,mode:s}:o)})}function DN(e,t,n){return wl(e,{...t,posture:n})}function FN(e,t,n){return wl(e,{...t,default_mode:n})}function zN(e,t,n,s){const o=String(n).trim();return wl(e,{...t,folders:[...t.folders,{path:o,mode:ON(e,t.posture)}]})}function BN(e,t,n){return wl(e,{...t,folders:t.folders.filter(s=>s.path!==n)})}function WN(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 Jv(e){let t=String(e||"");for(;t.endsWith("/");)t=t.slice(0,-1);return t}function UN(e,t=Wr){const n=Jv(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 VN(e="me",t=Wr){return`${Jv(t)}/workspace/effective/${encodeURIComponent(e)}`}const Sh=e=>e==="ro"||e==="rw"||e==="deny",qv=e=>e==="ro"||e==="rw",Yv=e=>e==="allowed_only"||e==="any_except_denied",GN=e=>Array.isArray(e)&&e.every(t=>t&&typeof t.path=="string"&&Sh(t.mode)),hu="The gateway answered with an older workspace model (it needs the round-11 workspace API).";function HN(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(hu);if(!(Yv(s.posture)&&qv(s.default_mode)&&GN(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"}). ${hu}`);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 Qv(e){const t=e&&typeof e=="object"?e:{};if("shared_workspace"in t)throw new Error(hu);if(!(Yv(t.posture)&&(qv(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"&&Sh(s.mode)&&Sh(s.cap))))throw new Error(`The gateway answered without the effective workspaces (posture, default_mode, folders with cap, summary, gateway_summary). ${hu}`);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 gy(e,t){const n=HN(e,t),s=e;return{policy:n,effective:t==="gateway"?null:Qv(s.effective),...typeof s.can_edit=="boolean"?{can_edit:s.can_edit}:{}}}function yy(e,t,n=Wr){const s=UN(t,n);return{path:s,load:async()=>gy(await e(s,{method:"GET"}),t.level),save:async o=>gy(await e(s,{method:"PUT",body:o}),t.level)}}function jh(e,t="me",n=Wr){const s=VN(t,n);return async(o,l)=>Qv(await e(s,{method:"POST",body:l?{workspace:o,session:l}:{workspace:o}}))}function im(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 wy(e){const t=im(e).trim()||"The gateway refused the change.";return`${t}${/[.!?]$/.test(t)?"":"."} ${$n.notSaved}`}const KN=e=>!!e&&typeof e=="object"&&"policy"in e&&"effective"in e;function JN(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 lm(e){Lo();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"?JN(e.value,e.effective):e.state,x=e.level==="run"?e.effective:e.state,k=p&&p.base===x?p.value:C,j=k?LN(v,k):null,A=L=>{if(e.level==="run"){const q=e,V=L.configured===!1?null:{posture:L.posture,default_mode:L.default_mode,folders:L.folders};return Promise.resolve(q.onChange(V))}return e.save(L)};async function T(L,q){if(n!==null||_)return!1;s(L),d(null),l(V=>{const Y={...V};return delete Y[L],Y});try{const V=await A(q);return KN(V)&&g({base:x,value:V}),d(L),!0}catch(V){return l(Y=>({...Y,[L]:wy(V)})),!1}finally{s(null)}}const N=L=>o[L]?a.jsx("span",{className:"af-workspace__refusal",role:"alert","data-workspace":"refusal",children:o[L]}):u===L?a.jsx("span",{className:"af-workspace__saved",role:"status","data-workspace":"saved",children:ct.saved}):null,E=(L,q)=>a.jsx("span",{className:"af-workspace__access-tag","data-workspace":"access","data-access":L,"data-af-tip":q,tabIndex:q?0:void 0,children:my(L)}),S=(L,q,V,Y,J)=>a.jsx("span",{className:"af-workspace__access",role:"group","aria-label":L,"data-workspace":J,"data-access":q,children:V.map(W=>{const R=!!W.reason||!!_;return a.jsx("button",{type:"button",className:"af-workspace__access-btn","aria-pressed":q===W.value?"true":"false","aria-disabled":R?"true":void 0,"data-af-tip":W.reason||void 0,"data-action":`${J}-${W.value}`,onClick:()=>R||n!==null||W.value===q?void 0:Y(W.value),children:W.text},W.value)})}),I=L=>{if(L.builtin)return E("deny",ct.builtinRefused);if(!L.editable||!k)return E(L.mode);const q=k.policy;return a.jsxs(a.Fragment,{children:[S(`${ct.accessLabel} ${L.path}`,L.mode,["rw","ro","deny"].map(V=>({value:V,text:my(V),reason:L.reasons[V]})),V=>void T(L.path,PN(v,q,L.path,V)),"workspace-mode"),a.jsx("button",{type:"button",className:"af-workspace__icon-btn","data-action":"workspace-remove","aria-label":`${ct.remove} ${L.path}`,"data-af-tip":`${ct.remove} ${L.path}`,"aria-disabled":_||n!==null?"true":void 0,onClick:()=>_||n!==null?void 0:void T(L.path,BN(v,q,L.path)),children:a.jsx(ue,{name:"x",size:16})})]})};async function M(L){if(!k||!j||!j.canAdd)return;const q=L.trim();q&&await T("add",zN(v,k.policy,q))&&m("")}async function B(){if(!e.choose||n!==null||_)return;let L;try{L=await e.choose()}catch(q){l(V=>({...V,add:wy(q)}));return}L&&await M(L)}const G=j?j.rows.filter(L=>L.mode!=="deny"):[],Z=j?j.rows.filter(L=>L.mode==="deny"):[],oe=L=>a.jsxs("li",{className:"af-workspace__row","data-workspace":L.builtin?"builtin":"row","data-path":L.path,"data-mode":L.mode,"data-cap":L.cap??void 0,children:[a.jsx("code",{className:"af-workspace__path",children:L.path}),a.jsx("span",{className:"af-workspace__controls",children:I(L)}),N(L.path)]},`${L.builtin?"builtin:":""}${L.path}`),z=v==="account"?ct.followGateway:ct.useDefault,F=v==="account"?ct.followGatewayHelp:ct.useDefaultHelp;return a.jsx(Ji,{id:t,className:`af-workspace af-workspace--${v}${e.className?` ${e.className}`:""}`,title:v==="gateway"?ct.gatewayTitle:ct.title,help:IN(v),children:e.loadError?a.jsx("p",{className:"af-workspace__refusal",role:"alert","data-workspace":"load-error",children:e.loadError}):!j||!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":j.following?"true":"false",children:[j.gatewayLine?a.jsx("p",{className:"af-workspace__gateway","data-workspace":"gateway-line",children:j.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(Ur,{variant:"row",label:z,description:F,checked:j.following,busy:n==="follow",unavailableReason:_||(j.locked?ct.locked:null),reasonVisible:!1,describedBy:_?`${t}-blocked`:void 0,action:v==="account"?"workspace-follow-gateway":"workspace-use-default",onChange:L=>void T("follow",WN(k,L))}),N("follow")]}):null,a.jsxs("div",{className:"af-workspace__posture","data-workspace":"posture","data-posture":j.posture,children:[j.following||j.locked?a.jsx("span",{className:"af-workspace__badge",children:TN(j.posture)}):S(ct.postureLabel,j.posture,[{value:"allowed_only",text:ct.postureAllowedOnly},{value:"any_except_denied",text:ct.postureAnyExceptDenied}],L=>void T("posture",DN(v,k.policy,L)),"workspace-posture"),a.jsx("span",{className:"af-workspace__note","data-workspace":"posture-help",children:RN(j.posture)}),N("posture")]}),a.jsxs("ul",{className:"af-workspace__list","aria-label":ct.title,"data-workspace":"list",children:[G.length?a.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-allowed",children:ct.allowedTitle}):null,G.map(oe),Z.length?a.jsx("li",{className:"af-workspace__caption","data-workspace":"caption-refused",children:ct.deniedTitle}):null,Z.map(oe),j.everythingElse?a.jsxs("li",{className:"af-workspace__row","data-workspace":"everything-else","data-mode":j.everythingElse.mode,children:[a.jsx("span",{className:"af-workspace__name",children:ct.everythingElse}),a.jsx("span",{className:"af-workspace__controls",children:j.everythingElse.editable?S(`${ct.accessLabel} ${ct.everythingElse}`,j.everythingElse.mode,[{value:"rw",text:ct.accessReadWrite},{value:"ro",text:ct.accessRead}],L=>void T("everything-else",FN(v,k.policy,L)),"workspace-default"):E(j.everythingElse.mode)}),N("everything-else")]}):null,j.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:L=>m(L.target.value),onKeyDown:L=>{L.key==="Enter"?(L.preventDefault(),M(f)):L.key==="Escape"&&(L.preventDefault(),m(""),l(q=>{const V={...q};return delete V.add,V}))}}),a.jsx("button",{type:"button",className:"af-workspace__add-btn","data-action":"workspace-add",disabled:!!_||!f.trim()||n!==null,onClick:()=>void M(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 B(),children:ct.choose}):null,N("add")]}):null]}),j.posture==="allowed_only"&&!G.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:j.summary}),e.footer?a.jsx("div",{className:"af-workspace__footer",children:e.footer}):null]})})}const Rf=e=>`${Math.round(e*100)} %`,qN="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function YN(e){var S,I,M;const t=!!e.unavailableReason,n=e.outputSelectable??Jw(),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=B=>e.onChange({...m,...B}),g=ba(m.reply_volume),_=m.reply_muted===!0,v=e.showMute!==!1||_,C=e.listDevices||zw,x=y.useRef(C);x.current=C;const k=()=>{n&&x.current("audiooutput").then(B=>f.current&&l(B)).catch(()=>f.current&&l({devices:[],labelled:!1}))};y.useEffect(()=>{t||k()},[n,t,e.devicesKey]);const j=()=>{d({text:"Playing a short chime…",tone:"info"}),NS({deviceId:n&&m.output_device||"",volume:g}).then(()=>{if(!f.current)return;const B="Chime played. Heard nothing? Pick another output or raise the volume.";d({text:_?`${B} Replies are muted: unmute them to hear them.`:B,tone:"ok"})}).catch(B=>f.current&&d({text:`The speaker test failed: ${String((B==null?void 0:B.message)||B).replace(/\.$/,"")}.`,tone:"error"}))},A=m.output_device||"",T=[{value:"",label:"System default"},...o.devices.map(B=>({value:B.id,label:B.label})),...A&&!o.devices.some(B=>B.id===A)?[{value:A,label:"Saved speaker (not connected)"}]:[]],N=((S=e.labels)==null?void 0:S.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:qN,trailing:a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:t,onClick:j,children:((M=e.labels)==null?void 0:M.test)||"Test"}),children:a.jsx(xn,{ariaLabel:N,placeholder:"System default",value:n?A:"",options:T,disabled:t||!n,searchable:!1,onOpen:k,onChange:B=>p({output_device:B})})}),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 (${Rf(g)})`:Rf(g),onChange:B=>p({reply_volume:Number(B.currentTarget.value)/100})}),a.jsx("span",{className:"af-voice-range__value","data-voice-volume":_?"muted":"on",children:_?"Muted":Rf(g)})]})]})}function QN(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 Xv(e){const t=QN(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 If=e=>`${Math.round(e*100)} %`;function cm(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function XN(e){var Z,oe,z;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 _=Ww(),v=e.value,C=F=>e.onChange({...v,...F}),x=cm(v.input_gain),k=e.listDevices||zw,j=y.useRef(k);j.current=k;const A=()=>{j.current("audioinput").then(F=>g.current&&o(F)).catch(()=>g.current&&o({devices:[],labelled:!1}))};y.useEffect(()=>{t||A()},[t]);const T=()=>{u(""),jS().then(()=>{var F;A(),(F=e.onDevicesChanged)==null||F.call(e)}).catch(F=>g.current&&u(ou(F)))},N=()=>{f({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),Gw({deviceId:v.input_device||"",ms:3e3,gain:x,onLevel:F=>g.current&&p(F)}).then(async({blob:F,peak:L})=>{var q,V,Y;if(g.current){if(L<Vw){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 Hw(F,{deviceId:((q=e.playOn)==null?void 0:q.deviceId)||"",volume:(V=e.playOn)==null?void 0:V.volume}),g.current&&(f({phase:"idle",message:`The microphone works (peak level ${If(L)}).`,tone:"ok"}),A(),(Y=e.onDevicesChanged)==null||Y.call(e))}}).catch(F=>g.current&&f({phase:"idle",message:ou(F),tone:"error"}))},E=v.input_device||"",S=[{value:"",label:"System default"},...s.devices.map(F=>({value:F.id,label:F.label})),...E&&!s.devices.some(F=>F.id===E)?[{value:E,label:"Saved microphone (not connected)"}]:[]],I=d.phase!=="idle",M=d.phase==="recording",B=((Z=e.labels)==null?void 0:Z.device)||"Input device",G=((oe=e.labels)==null?void 0:oe.gain)||"Input level";return a.jsxs("div",{className:`af-voice-input${e.className?` ${e.className}`:""}`,"data-voice-input":!0,children:[a.jsx(zr,{label:B,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…":((z=e.labels)==null?void 0:z.test)||"Test"}),children:a.jsx(xn,{ariaLabel:B,placeholder:"System default",value:E,options:S,disabled:t,searchable:!1,onOpen:A,onChange:F=>C({input_device:F})})}),a.jsx(Xv,{source:M?null:e.levelSource,level:M?m:e.level,origin:M?"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:T,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:G,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":If(x),onChange:F=>C({input_gain:Number(F.currentTarget.value)/100})}),a.jsx("span",{className:"af-voice-range__value",children:If(x)})]}):null]})}function ZN(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:cm(e.input_gain),capture_mode:$o(e.capture_mode)}}const e1=["provider","model","voice","profile","speed","quality_preset","instructions"];function Zv(e){const t={};for(const n of e1){const s=e[n];s!==void 0&&s!==""&&s!==null&&(t[n]=s)}return t}function t1(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 n1=[{value:"",label:"Detect automatically"},...Object.keys(Yw).map(e=>({value:e,label:xa(e)}))],s1=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function r1(e){return[e.provider,e.model,e.profile||e.voice].filter(Boolean).join(" · ")}function a1(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const o1=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],vy=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 i1(e){var ae,we,Se,Q,xe,ve,Fe,Xe,Ve,Je;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),[j,A]=y.useState(null),T=e.outputSelectable??Jw(),N=e.value,E=e.nested?"flat":"card",S=me=>e.onChange({...N,...me}),I=ba(N.reply_volume),M=cm(N.input_gain),B=s.tts!==!1&&!e.ttsSlot,G=s.stt!==!1,Z=B||G||!!e.ttsSlot,oe=e.voiceLibrary||e.createVoice;y.useEffect(()=>{if(n)return;let me=!0;return o.current().then(Me=>me&&f(Me||{})).catch(()=>me&&f({})),_||l.current().then(Me=>me&&p({value:Me||{},failed:!1})).catch(()=>me&&p({value:null,failed:!0})),()=>{me=!1}},[n,_]);const z=N.stt_provider||((we=(ae=g.value)==null?void 0:ae.stt)!=null&&we.configured?String(g.value.stt.provider||""):""),F=!!e.fetchLanguages;y.useEffect(()=>{const me=u.current;if(n||!me||s.microphone===!1)return;let Me=!0;return me("stt",z||void 0).then(st=>Me&&A(Array.isArray(st)?st.map(tt=>String(tt).toLowerCase()).filter(Boolean):[])).catch(()=>Me&&A(null)),()=>{Me=!1}},[n,F,z,s.microphone]);const L=Ug(g.value,"tts",g.failed),q=Ug(g.value,"stt",g.failed),V=[(Se=g.value)==null?void 0:Se.tts,(Q=g.value)==null?void 0:Q.stt].map(me=>me&&!me.configured?me.note:"").filter(Boolean),Y=[(xe=g.value)==null?void 0:xe.tts,(ve=g.value)==null?void 0:ve.stt].map(me=>{var Me;return me&&me.configured?String(((Me=me.hint)==null?void 0:Me.sentence)||"").trim():""}).filter(Boolean),J=!!((Xe=(Fe=d.controls)==null?void 0:Fe.quality_preset)!=null&&Xe.supported),W={deviceId:T&&N.output_device||"",volume:I},R=j&&j.length?[{value:"",label:"Detect automatically"},...j.map(me=>({value:me,label:xa(me)}))]:[...n1],K=N.stt_language||"";K&&!R.some(me=>me.value===K)&&R.push({value:K,label:`${xa(K)} (saved)`});const se=$o(N.capture_mode??((Ve=e.captureDefaults)==null?void 0:Ve.capture_mode)),ce=N.auto_send??((Je=e.captureDefaults)==null?void 0:Je.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(Ji,{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,B?a.jsx(kh,{label:"Text → speech",setting:"tts",defaultSummary:L,overrideSummary:r1(N),overrideOwner:t,open:v==="tts",onToggle:()=>C(v==="tts"?"":"tts"),onReset:()=>S({provider:"",model:"",voice:"",profile:""}),disabled:n,children:a.jsx(DS,{value:N,onChange:me=>e.onChange({...N,...me}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:oe,previewVoice:e.previewVoice?(me,Me,st)=>e.previewVoice({...N,...me},Me,st):void 0,previewOn:W,recordFrom:{deviceId:N.input_device||"",gain:M}})}):null,G?a.jsx(kh,{label:"Speech → text",setting:"stt",defaultSummary:q,overrideSummary:a1(N),overrideOwner:t,open:v==="stt",onToggle:()=>C(v==="stt"?"":"stt"),onReset:()=>S({stt_provider:"",stt_model:""}),disabled:n,children:a.jsx(ju,{value:{provider:N.stt_provider||"",model:N.stt_model||""},onChange:me=>S({stt_provider:me.provider,stt_model:me.model}),fetchProviders:async()=>{const me=await o.current();return vy(me.stt_providers).map(Me=>({name:Me}))},fetchModels:async me=>{var st;const Me=await o.current(me);return vy(((st=Me.stt_models_by_provider)==null?void 0:st[me])||Me.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,V.map(me=>a.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:me},me)),Y.map(me=>a.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:me},me))]}):null,s.output!==!1?a.jsx(Ji,{variant:E,title:"Output",children:a.jsx(YN,{value:N,onChange:e.onChange,listDevices:e.listDevices,outputSelectable:T,showMute:s.mute===!0,unavailableReason:e.unavailableReason,devicesKey:x})}):null,s.microphone!==!1?a.jsxs(Ji,{variant:E,title:"Microphone",children:[a.jsx(XN,{value:N,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:W,onDevicesChanged:()=>k(me=>me+1),unavailableReason:e.unavailableReason}),a.jsx(zr,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:a.jsx(xn,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:K,options:R,disabled:n,searchable:!1,onChange:me=>S({stt_language:me})})}),s.capture===!0?a.jsxs(a.Fragment,{children:[a.jsx(zr,{label:"Microphone button",setting:"capture-mode",children:a.jsx(xn,{ariaLabel:"Microphone button",value:se,options:s1,disabled:n,searchable:!1,onChange:me=>S({capture_mode:me==="toggle"?"toggle":"hold"})})}),a.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"auto-send",children:a.jsx(Ur,{label:"Send what you say automatically",description:"Off: what you say lands in the message box for you to review.",variant:"row",checked:ce,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:me=>S({auto_send:me})})})]}):null]}):null,s.replies!==!1?a.jsxs(Ji,{variant:E,title:"Replies",children:[a.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:a.jsx(Ur,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:N.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:me=>S({read_aloud:me})})}),a.jsx(zr,{label:"Voice latency",setting:"latency",help:J?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:a.jsx(xn,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:J&&N.quality_preset||"",options:o1,disabled:n||!J,searchable:!1,onChange:me=>S({quality_preset:me})})})]}):null]})}const Nh="@gateway-default";function l1(e){return[{value:Nh,label:dt.time_zone_default.replace("{time_zone}",e.gateway_default)},...e.choices.map(t=>({value:t,label:t}))]}function c1(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(ru,{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(xn,{id:e.id,value:t.value??Nh,options:l1(t),searchable:!0,searchPlaceholder:dt.time_zone_search,ariaLabel:t.label,disabled:e.disabled,onChange:n=>e.onChange(n&&n!==Nh?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 u1(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 d1(e){const{voice:t}=e,n=$o(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 G,Z;u.current=!1,(o.current||d.current)&&((Z=(G=f.current).cancel_voice_ptt_recording)==null||Z.call(G)),o.current=!1}),[]),y.useEffect(()=>{if(!(!_||!t.add_transcript_listener))return t.add_transcript_listener((G,Z)=>{var oe;return(oe=m.current)==null?void 0:oe.call(m,G,Z)})},[t.add_transcript_listener,_]),y.useEffect(()=>{if(!p)return;const G=setTimeout(()=>g(!1),4e3);return()=>clearTimeout(G)},[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 G=f.current;v||G.voice_ptt_busy||o.current||(o.current=!0,l.current=Date.now(),g(!1),G.start_voice_ptt_recording().then(()=>{var Z,oe;(!o.current||!u.current)&&((oe=(Z=f.current).cancel_voice_ptt_recording)==null||oe.call(Z))}))},j=()=>{var G,Z;if(o.current){if(o.current=!1,Date.now()-l.current<Kw){(Z=(G=f.current).cancel_voice_ptt_recording)==null||Z.call(G),u.current&&g(!0);return}f.current.stop_voice_ptt_recording()}},A=()=>{var G,Z;o.current&&(o.current=!1,(Z=(G=f.current).cancel_voice_ptt_recording)==null||Z.call(G))};y.useEffect(()=>{if(n==="hold")return window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j),window.addEventListener("blur",A),()=>{window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),window.removeEventListener("blur",A)}},[n]);const T=()=>{const G=f.current;if(G.voice_ptt_recording){G.stop_voice_ptt_recording();return}v||G.voice_ptt_busy||(g(!1),G.start_voice_ptt_recording())},N=t.voice_ptt_since||0,E=u1(!!N),S=e.label||(n==="hold"?Ir.hold:Ir.toggle),I=x?n==="hold"?Ir.recordingHold:Ir.recordingToggle:S,M=x?`Recording… ${N?Fw(N,E):""}`.trim():C?SS(N||E,E,e.routeText||""):p?Ir.holdHint:"",B=n==="hold"?{onPointerDown:G=>{G.button===0&&k()},onPointerUp:j,onPointerCancel:j,onKeyDown:G=>{[" ","Enter"].includes(G.key)&&!G.repeat&&(G.preventDefault(),k())},onKeyUp:G=>{[" ","Enter"].includes(G.key)&&(G.preventDefault(),j())}}:{onClick:T};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,...B,children:a.jsx(ue,{name:C?"loader":"mic",size:15})}),x?a.jsx(Xv,{source:t,inline:!0,className:"af-voice-mic__meter"}):null,e.showStatus!==!1&&(M||v)?a.jsx("span",{role:"status",className:"af-voice-mic__status","data-voice-status":!0,children:M||v}):null]})}function f1(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 Zc=new Map,e_=()=>{try{return globalThis.localStorage||null}catch{return null}},t_=e=>{try{const t=e?JSON.parse(e):null;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}};function Mf(e){var t;return t_((t=e_())==null?void 0:t.getItem(e))}function h1(e,t){var s;const n=t&&typeof t=="object"?t:{};try{(s=e_())==null||s.setItem(e,JSON.stringify(n))}catch{}for(const o of Array.from(Zc.get(e)||[]))o(n)}function m1(e){const[t,n]=y.useState(()=>({key:e,prefs:e?Mf(e):{}})),s=t.key===e?t:{key:e,prefs:e?Mf(e):{}};s!==t&&n(s),y.useEffect(()=>{var m;if(!e)return;const l=p=>n({key:e,prefs:p});let u=Zc.get(e);u||Zc.set(e,u=new Set),u.add(l);const d=p=>{p.key!==null&&p.key!==e||n({key:e,prefs:p.key===null?Mf(e):t_(p.newValue)})},f=globalThis;return(m=f.addEventListener)==null||m.call(f,"storage",d),()=>{var p;u.delete(l),u.size||Zc.delete(e),(p=f.removeEventListener)==null||p.call(f,"storage",d)}},[e]);const o=y.useCallback(l=>{e?h1(e,l):n({key:null,prefs:l||{}})},[e]);return[s.prefs,o]}function Mu(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 So(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Qt(e){return typeof e=="string"?e.trim():""}function _y(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}function p1(e){const t=So(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=So(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=So(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=Mu(m.default_approval,"desktop"),C=_?_==="auto"?"auto":"ask":v==="auto"?"auto":"ask",x=So(m.risk),k=_y(m.risk_rank)??_y(x==null?void 0:x.rank),j=Qt(m.risk_tier)||Qt(x==null?void 0:x.tier),A=Qt(m.sandbox),T=A&&typeof m.sandboxed=="boolean"?{label:A,...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}:{},...j?{riskTier:j}:{},...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)}:{},...T?{state:T}:{}})}return d.sort((f,m)=>f.toolset===m.toolset?f.name.localeCompare(m.name):f.toolset.localeCompare(m.toolset)),d}function g1(e){const t=So(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 mu(e,t){if(!(!e||!Object.prototype.hasOwnProperty.call(e,t)))return Mu(e[t])}function um(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=mu(t.app,s.name),u=mu(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 Ch(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 n_=2;function Do(e){return e.offered&&(e.riskRank??4)<=n_&&e.modelControlledDestination!==!0}function y1(e,t,n,s){let o={...e||{}};const l=[];for(const u of t)if(u.offered){if(n==="auto"&&!Do(u)){l.push(u.name);continue}o=Ch(o,u,n,s[u.name]??u.gatewayDefault)}return{layer:o,skipped:l}}function Fo(e,t={}){const n={},s={};for(const o of e){if(!o.offered)continue;const l=mu(t.app,o.name);l!==void 0&&l!==o.gatewayDefault&&(n[o.name]=l);const u=n[o.name]??o.gatewayDefault,d=mu(t.session,o.name);d!==void 0&&d!==u&&(s[o.name]=d)}return{app:n,session:s}}function pu(e,t={}){const n=Fo(e,t);return Object.keys(n.app).length>0||Object.keys(n.session).length>0}function eu(e,t={},n={}){const s=um(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],...pu(e,t)?{tool_policy:{auto_approve_tools:[...u],require_approval_tools:[...d]}}:{},approval:{auto:u,ask:d}}}function s_(e,t){const n={...e||{}},s={...So(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 w1(e){return{enabledTools:[...e.tools],autoApproveTools:[...e.approval.auto]}}const dm="The gateway cannot store chat tool policies",v1="The gateway did not return a policy revision; refusing an unguarded write";class _1 extends Error{constructor(){super(`${dm} (it does not advertise capabilities.session_tool_policy).`),this.code="unsupported",this.name="SessionToolPolicyUnsupportedError"}}class b1 extends Error{constructor(t){super(`${v1}${t?` (${t})`:""}.`),this.code="no_revision",this.name="SessionToolPolicyRevisionError"}}class x1 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 bn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,ar=e=>typeof e=="string"?e.trim():"",Eo=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];function k1(e){const t=bn(e),n=bn(t==null?void 0:t.capabilities)??t,s=bn(n==null?void 0:n.session_tool_policy);return s?{supported:s.supported===!0,...typeof s.version=="number"?{version:s.version}:{},...ar(s.endpoint)?{endpoint:ar(s.endpoint)}:{},...Array.isArray(s.methods)?{methods:Eo(s.methods)}:{},...Array.isArray(s.approve)?{approve:Eo(s.approve)}:{},...Array.isArray(s.deny)?{deny:Eo(s.deny)}:{},...typeof s.ask=="boolean"?{ask:s.ask}:{},...ar(s.record)?{record:ar(s.record)}:{},...ar(s.reason)?{reason:ar(s.reason)}:{}}:null}const by=e=>{const t=bn(e);if(!t)return null;const n={};for(const[s,o]of Object.entries(t))typeof o=="string"&&(n[s]=o);return n};function xy(e){const t=bn(e),n=by(t==null?void 0:t.approve),s=by(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(bn).filter(u=>!!u).map(u=>({selector:String(u.selector??""),name:String(u.name??""),reason:String(u.reason??"")})):void 0,l=bn(t.set_by);return{version:t.version,session_id:t.session_id,revision:t.revision,approve:n,deny:s,ask:Eo(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 Lf(e){const t=bn(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 S1(e){const t=bn(e)??(e instanceof Error?e:void 0);if(!t)return null;const n=bn(t.body),s=bn(t.detail)??bn(n==null?void 0:n.detail)??n,o=ar(s==null?void 0:s.reason_code)||ar(t.reason_code);if(o!=="revision_conflict"&&!(t.status===409&&!o))return null;const l=s==null?void 0:s.revision;return new x1(ar(s==null?void 0:s.message),typeof l=="number"?l:void 0)}function j1(e,t,n,s={}){const o=String(t??"");if(!Aw.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=pe(ck(o));let d,f;const m=v=>f?{...v,scope:f}:v,p=async(v,C,x="")=>{if(!l)throw new _1;if(n!=null&&n.methods&&!n.methods.includes(v))throw new Error(`${dm} with ${v} (the gateway advertises ${n.methods.join(", ")}).`);try{return bn(await e(`${u}${x}`,C===void 0?{method:v}:{method:v,body:C}))}catch(k){throw S1(k)??k}},g=v=>s.client&&v.client===void 0?{...v,client:s.client}:v,_=v=>{const C=xy(v==null?void 0:v.policy);return d=C.revision,f=Lf(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:xy(v.policy);return d=typeof v.revision=="number"?v.revision:C?C.revision:void 0,f=Lf(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=Lf(C==null?void 0:C.scope),{...d===void 0?{}:{revision:d},...f?{scope:f}:{}}}}}function N1(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,_)?Mu(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 _=bn(f.request),v=bn(_==null?void 0:_.approve),C=bn(_==null?void 0:_.deny);Array.isArray(v==null?void 0:v.kinds)&&v.kinds.length&&(m.approve={kinds:Eo(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:Eo(C.kinds)})}const p=_=>[..._].sort();return{approve:{tools:p(s),...m.approve||{}},deny:{tools:p(o),...m.deny||{}},ask:p(l)}}function C1(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 E1(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 A1(e){return((e==null?void 0:e.clamped)||[]).map(t=>`Not covered: ${t.name}${t.selector&&t.selector!=="tools"?` (${t.selector})`:""} (${t.reason})`)}const $1={off:"Off",ask:"Ask",auto:"Auto",on:"On"},T1={app:"Use the gateway's",session:"Use my defaults"},R1="Off = denied for every run of this chat, automations included",I1="The gateway did not say where this policy applies",ky={app:"this app",session:"this chat"},Sy=`Auto for a whole group reaches the tools that read or make changes (risk ${n_} or lower) and whose destination the assistant does not choose. Set the others to Auto one at a time.`;function M1(e){const t=e.split("_");return t.map((n,s)=>s<t.length-1?a.jsxs(wt.Fragment,{children:[n,"_",a.jsx("wbr",{})]},s):a.jsx(wt.Fragment,{children:n},s))}function jy(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=Po(e.set_at);return!t&&!s?"":`Set${t?` by ${t}`:""}${n?` (${n})`:""}${s?` on ${s}`:""}`}function L1(e){var L,q,V,Y,J;const t={...$1,...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 R;return W.offered?((R=e.inherited)==null?void 0:R[W.name])??W.gatewayDefault:"off"},p=W=>{if(!W.offered)return"off";const R=o[W.name];return R==="off"||R==="ask"||R==="auto"?R:m(W)},g=y.useMemo(()=>{const W={};for(const R of e.catalog)W[R.name]=m(R);return W},[e.catalog,e.inherited]),_=y.useMemo(()=>{const W=l.trim().toLowerCase(),R=new Map;for(const K of e.catalog){if(W&&![K.name,K.description||"",K.toolset].some(ce=>ce.toLowerCase().includes(W)))continue;const se=R.get(K.toolset)||[];se.push(K),R.set(K.toolset,se)}return[...R.entries()].sort(([K],[se])=>K==="other"?1:se==="other"?-1:K.localeCompare(se)).map(([K,se])=>({toolset:K,items:[...se].sort((ce,ae)=>ce.offered===ae.offered?ce.name.localeCompare(ae.name):ce.offered?-1:1)}))},[e.catalog,l]),v=W=>{n||e.onChange(W)},C=W=>{const R=m(W);return R!=="off"?R:W.gatewayDefault!=="off"?W.gatewayDefault:"ask"},x=(W,R)=>v(Ch(o,W,R,m(W))),k=(W,R)=>{if(R==="on"){let K=o;for(const se of W)se.offered&&p(se)==="off"&&(K=Ch(K,se,C(se),m(se)));v(K);return}v(y1(o,W,R,g).layer)},j=e.catalog.filter(W=>W.offered),A={auto:0,ask:0};for(const W of j){const R=p(W);R==="auto"?A.auto+=1:R==="ask"&&(A.ask+=1)}const T=A.auto+A.ask,N=W=>{if(!W.offered||!Object.prototype.hasOwnProperty.call(o,W.name))return!1;const R=o[W.name];return(R==="off"||R==="ask"||R==="auto")&&R!==m(W)},E=e.catalog.filter(N).map(W=>W.name),S=Mk(e.toolMode,e.toolModeLabel,e.toolModeDetail),I=e.scope??((L=e.policy)==null?void 0:L.scope)??null,M=s?["off","on"]:["off","ask","auto"],B=W=>t[W],G=a.jsxs("div",{className:`af-tool-modes${e.className?` ${e.className}`:""}`,"data-layer":e.layer,"data-allowlist":s?"true":void 0,children:[S?a.jsxs("div",{className:`af-tool-policy__mode is-${S.tone}`,children:[a.jsx("div",{className:"af-tool-policy__mode-badge",children:"Tool mode"}),a.jsx("div",{className:"af-tool-policy__mode-value",children:S.label}),a.jsx("div",{className:"af-tool-policy__mode-detail",children:S.detail})]}):null,e.note?a.jsx("div",{className:"af-tool-policy__note",children:e.note}):null,(q=e.warnings)!=null&&q.length?a.jsx("div",{className:"af-tool-modes__warnings",role:"status","data-catalog-warnings":"",children:e.warnings.map((W,R)=>a.jsxs("div",{children:["Gateway warning: ",W]},R))}):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?`${T} of ${j.length} tools on`:`${T} of ${j.length} tools on · ${A.auto} run without asking · ${A.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:T1[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]}),(V=e.storage)!=null&&V.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:R1}):null,((J=e.storage)==null?void 0:J.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]}):I1}):null,e.policy?a.jsxs("div",{className:"af-tool-modes__policy","data-session-policy":e.policy.revision,children:[jy(e.policy)?a.jsx("div",{"data-policy-set":"",children:jy(e.policy)}):null,A1(e.policy).map((W,R)=>a.jsx("div",{"data-policy-clamped":"",children:W},R))]}):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 R=W.items.filter(ae=>ae.offered),K=new Set(R.map(ae=>s?p(ae)==="off"?"off":"on":p(ae))),se=K.size===1?[...K][0]:void 0,ce=s?[]:R.filter(ae=>!Do(ae));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}),R.length?a.jsx("span",{className:"af-tool-modes__group-state","data-group-state":se??"mixed",children:se?B(se):"Mixed"}):null,a.jsx("div",{className:"af-tool-modes__seg",role:"group","aria-label":`All ${W.toolset} tools`,children:M.map(ae=>a.jsx("button",{type:"button",className:`af-tool-modes__seg-btn${se===ae?" is-active":""}`,"aria-pressed":se===ae,"data-group-mode":`${W.toolset}:${ae}`,disabled:n||!R.length||ae==="auto"&&ce.length===R.length,title:ae==="auto"&&ce.length?Sy:void 0,onClick:()=>k(W.items,ae),children:B(ae)},ae))})]}),ce.length?a.jsxs("div",{className:"af-tool-modes__cap","data-bulk-cap":W.toolset,children:[Sy," ",ce.length===1?"1 tool here stays":`${ce.length} tools here stay`," as it is: ",ce.map(ae=>ae.name).join(", "),"."]}):null,W.items.map(ae=>{const we=p(ae),Se=s&&we!=="off"?"on":we,Q=N(ae),xe=m(ae);return a.jsxs("div",{className:`af-tool-mode-row${ae.offered?"":" is-unavailable"}`,"data-tool":ae.name,"data-mode":we,"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:M1(ae.name)}),ae.riskTier?a.jsx("span",{className:"af-tool-row__badge","data-risk":ae.riskRank??"",title:ae.riskRank!==void 0?`Risk ${ae.riskRank}`:void 0,children:ae.riskTier}):null,Q?a.jsxs("span",{className:"af-tool-mode-row__default","data-default-chip":ae.name,title:e.layer==="app"||xe===ae.gatewayDefault?"The gateway's default":"Your default for this app",children:["Default: ",s?xe==="off"?t.off:t.on:B(xe)]}):null]}),ae.state?a.jsx("div",{className:"af-tool-row__state-line",children:a.jsx(ru,{content:ae.state.tooltip||"",children:a.jsx("span",{className:`af-tool-row__state${ae.state.tone?` is-${ae.state.tone}`:""}`,"data-tool-state":ae.name,tabIndex:ae.state.tooltip?0:void 0,"aria-label":ae.state.tooltip?`${ae.state.label}. ${ae.state.tooltip}`:void 0,children:ae.state.label})})}):null,ae.description?a.jsx("div",{className:"af-tool-row__desc",children:ae.description}):null,ae.whenToUse?a.jsx("div",{className:"af-tool-row__hint",children:ae.whenToUse}):null,ae.offered&&ae.defaultUnserved?a.jsx("div",{className:"af-tool-mode-row__why","data-default-unserved":ae.name,children:"The gateway did not say whether this tool asks first; Ask is assumed."}):null,ae.offered?null:a.jsx("div",{className:"af-tool-mode-row__why","data-why-disabled":ae.name,children:ae.whyDisabled?`Not offered by the gateway: ${ae.whyDisabled}`:"Not offered by the gateway."})]}),a.jsx("div",{className:"af-tool-modes__seg",role:"group","aria-label":`Mode for ${ae.name}`,children:M.map(ve=>a.jsx("button",{type:"button",className:`af-tool-modes__seg-btn${Se===ve?" is-active":""}`,"aria-pressed":Se===ve,"data-tool-mode":`${ae.name}:${ve}`,disabled:n||!ae.offered,onClick:()=>x(ae,ve==="on"?C(ae):ve),children:B(ve)},ve))})]},ae.name)})]},W.toolset)})]});if(e.rowLabel===void 0)return G;const Z=e.layer==="session"&&j.some(W=>m(W)!==W.gatewayDefault),oe=E.length?`${E.length} tool${E.length===1?"":"s"} changed`:Z?"Your defaults":"",z=E.length?ky[e.layer]:ky.app,F=e.open??d;return a.jsx(kh,{label:e.rowLabel,help:e.rowHelp,defaultSummary:s?`${T} of ${j.length} tools on`:`${T} tools on, ${A.auto} without asking`,overrideSummary:oe,overrideOwner:z,open:F,onToggle:e.onToggle??(()=>f(W=>!W)),disabled:n,setting:`tools-${e.layer}`,children:G})}const r_="Saved in this browser",O1="Saved for this chat on the gateway",P1=`${dm}, so this chat's tool choices are kept in this browser.`,D1=100;function Of(e,t,n){const s=e&&typeof e=="object"?e:{},o={};for(const[l,u]of Object.entries(s)){const d=Mu(u,t);l.trim()&&d?o[l.trim()]=d:l.trim()&&(n==null||n.push(l.trim()))}return o}function F1(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 S;try{const I=(S=s())==null?void 0:S.getItem(E);return I?JSON.parse(I):void 0}catch{return}},l=(E,S)=>{try{const I=s();if(!I)return;S===null?I.removeItem(E):I.setItem(E,JSON.stringify(S))}catch{}},u=`af.tools.sessions.${n}`,d=E=>{const S=String(E||"").trim();if(!S)throw new Error("The app layer needs the app's interface id.");return`af.tools.app.${S}.${n}`},f=E=>{const S=String(E||"").trim();if(!S)throw new Error("The session layer needs a session id.");return`af.tools.session.${n}.${S}`},m=`af.tools.session.${n}.`,p=()=>{var M;const E=o(u);if(Array.isArray(E))return E.filter(B=>typeof B=="string"&&!!B);const S=s(),I=[];try{const B=typeof(S==null?void 0:S.length)=="number"?S.length:0;for(let G=0;G<B;G+=1){const Z=(M=S==null?void 0:S.key)==null?void 0:M.call(S,G);Z&&Z.startsWith(m)&&I.push(Z.slice(m.length))}}catch{}return I},g=E=>{var M,B;const S=[],I=Of((M=o(E))==null?void 0:M.modes,t.dialect,S);return S.length&&((B=t.onDropped)==null||B.call(t,E,S)),I},_=new Map,v=new Map,C=(E,S)=>{const I=E.revision;return typeof I=="number"?I:S?S.revision:void 0},x=E=>{const S=_.get(E);if(S===void 0)throw new b1(v.has(E)?"the last read carried none":"load this chat's policy before saving it");return S},k=E=>({kind:"browser",where:r_,...E?{note:E}:{}}),j=E=>{var I;const S=((I=t.sessionPolicy)==null?void 0:I.call(t,E))??null;return(S==null?void 0:S.supported)===!0?{client:S,storage:{kind:"gateway",where:O1}}:{client:null,storage:k(S?P1:void 0)}},A=(E,S,I,M,B,G)=>(B===void 0?_.delete(E):_.set(E,B),v.set(E,I),{storage:S,layer:E1(I,M),policy:I,...G?{scope:G}:{}}),T=(E,S)=>E.scope??(S==null?void 0:S.scope),N={identityKey:n,appKey:d,sessionKey:f,readApp:E=>g(d(E)),writeApp(E,S){const I=Of(S);l(d(E),Object.keys(I).length?{modes:I}:null)},readSession:E=>g(f(E)),writeSession(E,S){const I=String(E||"").trim(),M=Of(S),B=!Object.keys(M).length;l(f(I),B?null:{modes:M});const G=p().filter(Z=>Z!==I);B||G.unshift(I);for(const Z of G.splice(D1))l(f(Z),null);l(u,G.length?G:null)},sessions:p,sessionStorage:E=>j(E).storage,async loadSession(E,S){const{client:I,storage:M}=j(E);if(!I)return{storage:M,layer:N.readSession(E),policy:null};const B=await I.get();return A(E,M,B,S,C(I,B),T(I,B))},async saveSession(E,S,I,M={}){const{client:B,storage:G}=j(E);if(!B)return N.writeSession(E,S),{storage:G,layer:N.readSession(E),policy:null};const Z=N1(S,I,{base:v.get(E)??null,inherited:M.inherited});if(C1(Z))return N.resetSession(E);const oe=await B.replace({...Z,if_revision:x(E)});return A(E,G,oe,I,C(B,oe),T(B,oe))},async resetSession(E){const{client:S,storage:I}=j(E);if(!S)return N.writeSession(E,null),{storage:I,layer:{},policy:null};const M=await S.reset(x(E));return A(E,I,null,[],typeof M.revision=="number"?M.revision:C(S,null),T(S,null))}};return N}function a_(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 z1(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function B1(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 W1(e){return e.endsWith(`
68
- `)?e:`${e}
69
- `}function U1(e){return String(e||"").trimStart().startsWith("```")}function V1(e,t){const s=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=B1(o);s.push(`## ${l}`,"");const u=String(o.content||""),d=a_(u);d!==null&&!U1(u)?s.push("```json",z1(d).trimEnd(),"```",""):s.push(W1(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 vl(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 G1(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 H1=3,K1=Number.MAX_SAFE_INTEGER;function o_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function i_(e){return Array.isArray(e)}function J1(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function jo({kind:e,children:t}){return a.jsx("span",{className:`pc-json-token ${e}`,children:t})}function q1(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(jo,{kind:"string",children:t})}function Y1(e,t,n){return e===null?a.jsx(jo,{kind:"null",children:"null"}):typeof e=="string"?a.jsx(q1,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?a.jsx(jo,{kind:"number",children:String(e)}):typeof e=="boolean"?a.jsx(jo,{kind:"boolean",children:e?"true":"false"}):a.jsx(jo,{kind:"string",children:JSON.stringify(String(e))})}function Q1(e){return i_(e)?e.length===1?"1 item":`${e.length} items`:o_(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function l_(e){const{label:t,value:n,depth:s,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:d}=e,f=s*14,m=o_(n),p=i_(n),g=m||p,_=s<o,[v,C]=y.useState(_);y.useEffect(()=>{C(_)},[_,u]);const x=t?a.jsxs(a.Fragment,{children:[a.jsx(jo,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!g)return a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[x,Y1(n,l,u),d?",":""]});const k=p?"[":"{",j=p?"]":"}",A=Q1(n),T=v?`${k}`:`${k}…${j}${A?` (${A})`:""}`,N=p?n.map((E,S)=>({key:String(S),label:void 0,value:E})):Object.entries(n).map(([E,S])=>({key:E,label:E,value:S}));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:T}),!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:j}),d?",":""]}):a.jsxs(a.Fragment,{children:[N.map((E,S)=>{const I=S===N.length-1;return a.jsx(l_,{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:j}),d?",":""]})]})}):null]})}function X1(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 Ao(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):H1,m=o.mode==="unfolded"?K1:f,p=y.useMemo(()=>typeof t=="string"?X1(t):t,[t]),g=y.useMemo(()=>J1(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 vl(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(l_,{value:p,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Z1({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=Hv(e,om(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 vl(e);s(u?"copied":"failed"),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>s("idle"),900)},children:a.jsx(ue,{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(wt.Fragment,{children:u.text},d):a.jsx("span",{className:`af-code__${u.kind}`,children:u.text},d))})})]})}function Oi(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 c_(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}const Eh="http://same-origin.invalid/";function eC(e){try{const t=new URL(e,Eh);return t.protocol==="http:"&&t.origin===new URL(Eh).origin}catch{return!1}}function u_(e){const t=String(e||"").trim();return c_(t)??(t&&eC(t)?t:void 0)}let wa=null;function tC(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??Eh;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 d_(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 Ny(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function or(e,t){const n=[],s=String(e??"");let o=0,l="";const u=()=>{if(l){for(const d of Oi(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=u_(s.slice(f+2,m));if(g&&wa&&!wa(g)){u(),n.push(d_(`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?Oi(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=c_(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:or(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?Oi(m,t):m},`code:${o}`)),o=f+1;continue}}if(d==="_"&&!Ny(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]||" ")||Ny(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),_=or(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?Oi(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?Oi(m,t):m},`em:${o}`)),o=f+1;continue}}l+=d,o+=1}return u(),n}function nC(e){return String(e??"").replace(/\r\n/g,`
72
- `).replace(/\r/g,`
73
- `).split(`
74
- `)}function tu(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 sC(e){const t=[];for(const o of e){const l=tu(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 f_(e,t,n){const s=e.items.map((o,l)=>a.jsxs("li",{children:[or(o.content,t),o.children.map((u,d)=>f_(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 rC(e,t,n){return sC(e).map((s,o)=>f_(s,t,`${n}:${o}`))}function Cy(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 Ey(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 Ay=/^(#{1,5})\s+(.*)$/;function $y(e){return e.trim().startsWith("```")}function Ty(e){return e.trimStart().startsWith(">")}function h_(e){const t=wa;wa=e.images==="link"?e.inlineImage||tC:null;try{return aC(e)}finally{wa=t}}function aC({text:e,className:t,highlight:n,highlights:s,highlightClassName:o,highlightId:l}){const u=nC(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=u_(x[2]||"");if(A&&wa&&!wa(A)){d.push(a.jsx("p",{className:"pc-md_p",children:d_(`img:${g}`,A,x[1]||"")},`p:${g}`)),g+=1;continue}if(A){const T=x[1]||"";d.push(a.jsxs("figure",{className:"pc-md_figure",children:[a.jsx("img",{className:"pc-md_img",src:A,alt:T,loading:"lazy"}),T?a.jsx("figcaption",{children:or(T,p)}):null]},`figure:${g}`)),g+=1;continue}}if($y(v)){const T=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(Z1,{code:E,lang:T},`pre:${g}`));continue}const k=v.match(Ay);if(k){const A=k[1].length,T=k[2]||"",N=or(T,p);A===1?d.push(a.jsx("h1",{children:N},`h1:${g}`)):A===2?d.push(a.jsx("h2",{children:N},`h2:${g}`)):A===3?d.push(a.jsx("h3",{children:N},`h3:${g}`)):A===4?d.push(a.jsx("h4",{children:N},`h4:${g}`)):d.push(a.jsx("h5",{children:N},`h5:${g}`)),g+=1;continue}if(Ty(v)){const A=[];for(;g<u.length&&String(u[g]??"").trimStart().startsWith(">");){const N=String(u[g]??"").trimStart();A.push(N.replace(/^>\s?/,"")),g+=1}d.push(a.jsx("blockquote",{className:"pc-md_quote",children:A.map((T,N)=>a.jsxs(wt.Fragment,{children:[or(T,p),N<A.length-1?a.jsx("br",{}):null]},`q:${g}:${N}`))},`quote:${g}`));continue}if(v.includes("|")&&g+1<u.length&&Ey(String(u[g+1]??""))){const A=Cy(v),T=Math.max(1,A.length),N=[];for(g+=2;g<u.length;){const E=String(u[g]??"");if(!E.trim()||!E.includes("|"))break;const S=Cy(E),I=[];for(let M=0;M<T;M++)I.push(S[M]??"");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:A.slice(0,T).map((E,S)=>a.jsx("th",{children:or(E,p)},`th:${g}:${S}`))})}),a.jsx("tbody",{children:N.map((E,S)=>a.jsx("tr",{children:E.map((I,M)=>a.jsx("td",{children:or(I,p)},`td:${g}:${S}:${M}`))},`tr:${g}:${S}`))})]})},`table:${g}`));continue}if(tu(v)){const A=[];for(;g<u.length;){const T=String(u[g]??"");if(!T.trim()||T.trimStart().startsWith("```"))break;if(tu(T)||/^\s{2,}\S/.test(T)){A.push(T),g+=1;continue}break}d.push(a.jsx(wt.Fragment,{children:rC(A,p,`list:${g}`)},`list:${g}`));continue}const j=[];for(;g<u.length&&String(u[g]??"").trim()&&!(j.length>0&&tu(String(u[g]??"")));){const A=String(u[g]??"");if(j.length>0&&(Ay.test(A)||$y(A)||Ty(A))||j.length>0&&A.includes("|")&&g+1<u.length&&Ey(String(u[g+1]??"")))break;j.push(A),g+=1}d.push(a.jsx("p",{className:"pc-md_p",children:j.map((A,T)=>a.jsxs(wt.Fragment,{children:[or(A,p),T<j.length-1?a.jsx("br",{}):null]},`pl:${g}:${T}`))},`p:${g}`))}const _=["pc-md",t].filter(Boolean).join(" ");return a.jsx("div",{className:_,children:d})}function m_(e){const t=String(e.text??""),n=y.useMemo(()=>a_(t),[t]),s=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?a.jsx("div",{className:s,children:a.jsx(Ao,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?a.jsx("div",{className:s,children:e.renderMarkdown(t)}):a.jsx("div",{className:s,children:a.jsx(h_,{text:t,images:e.images,inlineImage:e.inlineImage})})}const oC=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),iC=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 p_(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 lC(e,t){const n=String(t||"").split("/").pop()||"",s=n.lastIndexOf(".");if(s>0&&oC.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:iC.has(o)}function cC(e){const t=n=>!!n&&(!p_(n)||lC(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}const gu=1024*1024,uC="1 MiB",dC=25*1024*1024,g_=(e,t)=>`${pe(`runs/${encodeURIComponent(e)}/workspace`)}/content?${new URLSearchParams({path:t})}`;function y_(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 fC(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=y_(e)??n,f=d!==void 0?d>l:l>=t;return{text:o,received:l,total:d,partial:f}}function w_(e){return`Showing the first ${uC} of ${e!==void 0?yl(e):"a file of unknown size"}; download for the rest.`}function hC(e){try{return decodeURIComponent(e)}catch{return e}}function mC(e,t,n){const s=`${pe(`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(hC(p));return m.length?g_(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 pC(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=ll(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>dC){l({status:"error",kind:f,message:`Too large to preview (${yl(n.size_bytes)}); use Download.`});return}l({status:"loading",kind:f});const m=fu(f);return(async()=>{var p;try{const g=await e(g_(t,n.path),{signal:u.signal,...m?{headers:{Range:`bytes=0-${gu-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=ll(n.name,_);if(fu(v)){const C=await fC(g,gu,n.size_bytes);if(u.signal.aborted)return;l({status:"ready",kind:v,contentType:_,text:v==="markdown"?mC(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 fm(e){const{markdownImages:t,inlineImage:n,renderMarkdown:s,...o}=e;return a.jsx(AN,{...o,nowMs:e.nowMs??Date.now(),renderMarkdown:s||(l=>a.jsx(h_,{text:l,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}function gC(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:w_(e.total)}:{}}}function qi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Or(e){return typeof e=="string"?e.trim():""}function yC(e){var o;const t=qi(e);if(!t)return null;const n=qi(t.sandbox);if(n&&Or(n.kind))return n;const s=qi((o=qi(t.output))==null?void 0:o.sandbox);return s&&Or(s.kind)?s:null}function Ry(e){const t=yC(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=qi(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 wC({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 Pf=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,zn=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"";function vC(e){const t=zn(e==null?void 0:e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=Pf(e==null?void 0:e.policy),s=Pf(n==null?void 0:n.set_by),o=zn(s==null?void 0:s.user_id)||zn(s==null?void 0:s.client),l=typeof(n==null?void 0:n.revision)=="number"?n.revision:void 0,u={decision:t,...zn(e==null?void 0:e.source)?{source:zn(e==null?void 0:e.source)}:{},...l!==void 0?{revision:l}:{},...o?{setBy:o}:{},...zn(n==null?void 0:n.set_at)?{setAt:zn(n==null?void 0:n.set_at)}:{}},d=(Array.isArray(e==null?void 0:e.tool_calls)?e.tool_calls:[]).map(f=>Pf(f)).filter(f=>!!(f&&zn(f.call_id))).map(f=>({callId:zn(f.call_id),name:zn(f.name),...zn(f.matched)?{matched:zn(f.matched)}:{}}));return d.length?{provenance:u,calls:d}:null}function yu(e){if(e.decision==="denied")return"Denied by this chat's policy";const t=e.setAt?Po(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 Iy(e){const t=new Map;for(const n of e||[]){const s=zn(n==null?void 0:n.name);if(!s)continue;const o=zn(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("; ")}`:""}const cn="not reported",En=e=>e===void 0?cn:Math.round(e).toLocaleString(),wn=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`},v_=e=>e===void 0?cn:`${Math.round(e).toLocaleString()} tok/s`,_C=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",va=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,bC=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function xC(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 wu(e){const t=[],n=(e.models||[]).map(bC),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 kC(e){const t=e.modelCalls||[],n=[],s=[{label:"Input",value:En(e.inputTokens)},{label:"Output",value:En(e.outputTokens)}];if(e.reasoningTokens!==void 0&&s.push({label:"Reasoning",value:En(e.reasoningTokens),hint:"part of output"}),s.push({label:"Total",value:En(e.totalTokens)}),n.push({heading:`Usage · ${va(e.llmCalls,"model call")}`,rows:s}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,d=[{label:"Reused from cache",value:`${En(l)}${l+u?` (${_C(l,l+u)})`:""}`},{label:"Newly processed",value:En(e.fedTokens)},{label:"Outcome",value:xC(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:`${En(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${En(o[0].inputTokens)} → ${En(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),En(l.inputTokens),l.cachedTokens===void 0?"—":En(l.cachedTokens),l.fedTokens===void 0?"—":En(l.fedTokens),En(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?cn:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:wu(e)}}function Vc(e,t,n,s){if(e===void 0)return cn;const o=[wn(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${s}${n!==void 0?` at ${v_(n)}`:""}`),o.join(" · ")}function SC(e){var m,p,g;const t=e.modelCalls||[],n=[],s=e.durationMs,o=[{label:"Wall clock",value:wn(s)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?cn:`${wn(e.genTimeMs)} · ${va(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${wn(e.toolTimeMs)} · ${va(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?wn(_):"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:Vc(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:Vc(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${wn(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${v_(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?Vc(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Vc(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)}% · ${En(f.acceptedTokens)} of ${En(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:`${wn(e.toolTimeMs)} · ${va(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${wn(e.slowestToolBatch.ms)} · ${__(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?"—":`${wn(_.promptMs)}${_.promptSource==="rate"?"*":""}`,_.promptNewTokensPerSecond===void 0?"—":Math.round(_.promptNewTokensPerSecond).toLocaleString(),_.generationMs===void 0?"—":wn(_.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:`${wn(s)} wall clock`,sections:n,footer:wu(e)}}function __(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${va(e.calls,"call")} (${e.tools.join(", ")})`}function jC(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:wu(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?`${wn(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:`${wn(e.toolTimeMs)} · ${va(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${wn(e.slowestToolBatch.ms)} · ${__(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:`${va(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:wu(e)}}function Df(e,t){return e==="tokens"?kC(t):e==="time"?SC(t):jC(t)}function NC(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(wt.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 nr=8;function CC(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,j=u.current;if(!k||!j)return;const A=k.getBoundingClientRect(),T=j.offsetWidth,N=j.offsetHeight,E=window.innerWidth,S=window.innerHeight,I=A.top-nr-N,M=A.bottom+nr,B=I>=nr?I:M+N<=S-nr?M:Math.max(nr,S-nr-N),G=Math.min(Math.max(nr,A.left),Math.max(nr,E-nr-T));o({top:B,left:G})};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(NC,{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"?ul.createPortal(C,document.body):C]})}function b_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function x_(e){const t=b_(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 k_({tool:e,showCopy:t=!0}){const[n,s]=y.useState(!1),o=b_(e.arguments),l=x_(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(ue,{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:yu(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","data-approval-wait":e.approvalWait?"":void 0,title:e.approvalWait?"Timed from request to result: includes the wait for your decision.":void 0,children:[wn(m),e.approvalWait?" incl. approval wait":""]}):null,a.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:a.jsx(ue,{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:[yu(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,a.jsx(wC,{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 vl(JSON.stringify(e,null,2))),children:[a.jsx(ue,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),p?a.jsx("dl",{className:"pc-tool-activity__parameters",children:p.map(([g,_])=>a.jsxs(wt.Fragment,{children:[a.jsx("dt",{children:g}),a.jsx("dd",{children:_&&typeof _=="object"?a.jsx(Ao,{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(Ao,{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(Ao,{value:e.output})})]}):null]})]})}function hm({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(ue,{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(k_,{tool:s,showCopy:t},s.id))]})}function EC(e){const t=e.totalTokens!==void 0?Df("tokens",e):null,n=Df("tools",e),s=e.durationMs!==void 0?Df("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:wn(e.durationMs),detail:s}]:[]]}function AC(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 $C=new Set(["blob:","data:","http:","https:"]);function vu(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return $C.has(new URL(t,n).protocol)?t:void 0}catch{return}}function S_(e,t){return p_(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function TC({item:e,onOpen:t,markdown:n}){const[s,o]=y.useState(!1),l=vu(e.src),u=String(e.name||e.label||"").trim()||"File",d=cC({href:e.href?vu(e.href):void 0,src:l,contentType:e.contentType,name:e.name||e.label}),f=ll(u,e.contentType),m=fu(f),p=typeof e.text=="string";if(!l&&!d&&!p)return null;const g=yl(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(ue,{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",...S_(d,String(e.name||"").trim()||_),children:"Raw file"}):null]}),s&&!t?a.jsx(fm,{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 RC({item:e,onOpenFile:t,markdown:n}){const[s,o]=y.useState(!1);if(e.kind==="file")return a.jsx(TC,{item:e,onOpen:t,markdown:n||{}});const l=vu(e.src),u=e.href?vu(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(Gv,{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",...S_(u,String(e.name||"").trim()||m),children:m})}):null]})}function j_(e){var S,I;const t=e.message,n=y.useMemo(()=>AC(t),[t.kind,t.level,t.role,t.title]),s=String(t.ts||"").trim(),o=y.useMemo(()=>{if(!s)return"";const M=new Date(s);return Number.isFinite(M.getTime())?M.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&&((S=e.getSpeakState)==null?void 0:S.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,j=y.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(k)?k:x?EC(x):[],[e.stats,k,x]),A=Array.isArray(t.media)?t.media:[],T=String(f?f.reasoning||"":t.reasoning||""),N=!!String(t.content||"").trim();if(t.toolActivity)return a.jsx(k_,{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 M=String(t.level||"").trim().toLowerCase();return a.jsxs("div",{className:["pc-chat-hint",M==="warn"||M==="error"?`pc-chat-hint--${M}`:"",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(ue,{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 M;return(M=e.onSpeakToggle)==null?void 0:M.call(e,t)},children:a.jsx(ue,{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 M=await vl(String(t.content||""));u(M?"copied":"failed"),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>u("idle"),900)},children:a.jsx(ue,{name:"copy",size:22})}):null]})]}),T.trim()?a.jsxs("details",{className:"pc-chat-thinking",children:[a.jsx("summary",{children:"Thinking"}),a.jsx("div",{className:"pc-chat-thinking-body",children:T})]}):null,N||!f&&!A.length?a.jsx("div",{className:"pc-chat-body",children:a.jsx(m_,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,A.length?a.jsx("div",{className:"pc-chat-media",children:A.slice(0,24).map((M,B)=>a.jsx(RC,{item:M,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},M.id||`${M.kind}:${M.src}:${B}`))}):null,C.length?a.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:C.slice(0,24).map((M,B)=>{const G=String(M.label||"").trim()||"attachment",Z=String(M.target||"").trim(),oe=String(M.title||"").trim(),z=!!M.disabled||typeof M.onClick!="function";return a.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:oe||G,onClick:z?void 0:M.onClick,disabled:z,children:[a.jsx(ue,{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:G})]},M.id||`${G}:${B}`)})}):null,j.length?a.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:j.slice(0,12).map((M,B)=>{const G=String(M.label||"").trim();if(!G)return null;if(M.detail)return a.jsx(CC,{label:G,detail:M.detail,icon:M.icon,onClick:M.onClick},M.id||`${G}:${B}`);const Z=String(M.title||"").trim(),oe=typeof M.onClick=="function",z=oe?"button":"span";return a.jsxs(z,{...oe?{type:"button"}:{},className:["pc-chat-stat",oe?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:Z||void 0,onClick:oe?()=>{var F;return(F=M.onClick)==null?void 0:F.call(M)}:void 0,children:[M.icon?a.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:M.icon}):null,a.jsx("span",{className:"pc-chat-stat-label",children:G})]},M.id||`${G}:${B}`)})}):null,E!=null&&E!==!1?a.jsx("div",{className:"pc-chat-footer",children:E}):null]})}function IC(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function N_(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(IC(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(hm,{tools:p.map(x=>x.toolActivity),showCopy:(C=e.messageProps)==null?void 0:C.showCopy},v):a.jsx(j_,{message:_,...e.messageProps||{}},v)}),e.after,a.jsx("div",{ref:o})]})}const C_=wt.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 Yi(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function My(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 Ly(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function mm(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 E_(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 MC={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Pi(e){return String(e).padStart(2,"0")}function LC(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=MC[String(t||"").toLowerCase()]||s.split(".").pop()||"bin",l=`${n.getFullYear()}-${Pi(n.getMonth()+1)}-${Pi(n.getDate())} at ${Pi(n.getHours())}.${Pi(n.getMinutes())}.${Pi(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!s?"Pasted image":"Pasted file"} ${l}.${o}`}function A_(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}=mm(e);return s.map(o=>{const l=LC(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}class OC{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 Qi="llm.delta",_o="llm.delta_end";function PC(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ma(e){return typeof e=="string"&&e.trim()!==""}function DC(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function $_(e){return"reason"in e}function T_(e,t){const n=PC(e),s=n==null?void 0:n.kind,o=t||(typeof s=="string"&&s?s:n&&"reason"in n?_o:Qi),l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(t!==void 0&&t!==Qi&&t!==_o&&l(`unknown event name ${JSON.stringify(t)}`),!n)return l("the payload is not an object");s!==void 0&&s!==Qi&&s!==_o&&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`),ma(n.run_id)||l("run_id is missing"),ma(n.call_id)||l("call_id is missing"),DC(n.seq)||l("seq is not a non-negative integer");const u=t||s?(t||s)===_o:"reason"in n;n.root_run_id!==void 0&&!ma(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ma(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const d={run_id:n.run_id,...ma(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ma(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:_o,...d,reason:n.reason,...ma(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:Qi,...d,text:n.text,channel:n.channel,snapshot:n.snapshot})}function R_(e,t){if(e!==Qi&&e!==_o)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 T_(n,e)}function FC(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 zC={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 BC(e){return`This reply is not streamed: ${e?zC[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}const pm=e=>pe(`runs/${encodeURIComponent(e)}/workspace`);function WC(e){return pm(e)}function UC(e,t){return`${pm(e)}/files?${new URLSearchParams({path:t,recursive:"false"})}`}function I_(e,t){return`${pm(e)}/content?${new URLSearchParams({path:t})}`}async function zo(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 VC(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 GC(e,t,n){const s=await e(WC(t),{signal:n});if(!s.ok)throw await zo(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 HC(e,t,n,s){const o=await e(UC(t,n),{signal:s});if(!o.ok)throw await zo(o,"The folder could not be listed");return VC(await o.json(),n)}async function KC(e,t,n,s){const o=await e(I_(t,n),{signal:s});if(!o.ok)throw await zo(o,"The file could not be read");return await o.blob()}async function JC(e,t,n,s){const o=await GC(e,t,s);return{where:o,listing:o.exists?await HC(e,t,n,s):null}}function qC(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 _u(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 YC(e){return[...e].sort((t,n)=>t.type===n.type?t.name.localeCompare(n.name):t.type==="dir"?-1:1)}function QC(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 XC=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif","image/bmp","application/pdf","text/plain","application/json"]);function ZC(e){const t=String(e||"").split(";",1)[0].trim().toLowerCase();return XC.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 M_(e,t,n){const s=n==="open"?ZC(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 eE(e,t,n){const s=await e(tk(t),{signal:n.signal});if(!s.ok)throw await zo(s,`${n.name} could not be read`);M_(await s.blob(),n.name,n.mode??"open")}function tE(e){const t=String(e||"").split(/[\\/]/).filter(Boolean);return t.length?t[t.length-1]:String(e||"")}function nE(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 sE(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function gm(e){var oe;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,j]=y.useState(!1),[A,T]=y.useState(0),[N,E]=y.useState(null),S=N&&N.runId===n&&!e.onSelectFile?N.entry:null,I=pC(t,n,S,`${e.refreshKey??""}:${A}`);y.useEffect(()=>{if(!n)return;const z=new AbortController;return v(!0),m(""),(async()=>{try{const F=await JC(t,n,l,z.signal);z.signal.aborted||d({runId:n,...F})}catch(F){z.signal.aborted||m(String((F==null?void 0:F.message)||F))}finally{z.signal.aborted||v(!1)}})(),()=>z.abort()},[t,n,l,A,e.refreshKey]),y.useEffect(()=>g(""),[n]);const M=u&&u.runId===n?u:null,B=y.useCallback(async z=>{x(z.path),m("");try{M_(await KC(t,n,z.path),z.name,"download")}catch(F){m(String((F==null?void 0:F.message)||F))}finally{x("")}},[t,n]),G=(M==null?void 0:M.where.workspace_root)||"",Z=e.nowMs??Date.now();return a.jsx(rE,{title:e.title,note:e.note,where:(M==null?void 0:M.where)??null,path:l,listing:(M==null?void 0:M.listing)??null,error:f,notice:p,loading:_,fileBusy:C,selectedPath:e.onSelectFile?e.selectedPath:S==null?void 0:S.path,className:e.className,nowMs:Z,openingFolder:k,onNavigate:z=>{E(null),o({runId:n,path:z})},onRefresh:()=>T(z=>z+1),onFile:z=>void B(z),onSelectFile:e.onSelectFile??(z=>E({runId:n,entry:z})),onClose:e.onClose,onCopyPath:G?()=>{(e.copyText||sE)(G).then(z=>g(z?"Path copied.":"Could not copy; select the path instead."))}:void 0,onOpenFolder:e.onOpenFolder&&nE(M==null?void 0:M.where)?()=>{j(!0),g(""),e.onOpenFolder().then(()=>g("Folder opened on this machine.")).catch(z=>g(`Open folder failed: ${String((z==null?void 0:z.message)||z)}`)).finally(()=>j(!1))}:void 0,preview:S?a.jsx(fm,{name:S.name,path:S.path,sizeBytes:S.size_bytes,modified:S.mtime,nowMs:Z,...gC(I),actions:(oe=e.fileActions)==null?void 0:oe.call(e,S),onDownload:()=>void B(S),onClose:()=>E(null)}):null})}function rE(e){var l,u,d,f;const t=e.listing?QC(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(ue,{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(ue,{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(ue,{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:tE(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(ue,{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(ue,{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:qC(e.path).map((m,p,g)=>p===g.length-1?a.jsx("span",{"aria-current":"page",children:m.label},m.path):a.jsxs(wt.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:YC(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(ue,{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(ue,{name:"file",size:14})," ",a.jsx("span",{className:"pc-ws__label",children:m.name})]}):a.jsxs("span",{className:"pc-ws__name",children:[a.jsx(ue,{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:_u(m.size_bytes)}),m.mtime!==void 0&&Ro(m.mtime,o)?a.jsx("time",{className:"pc-ws__time",title:Po(m.mtime),"data-meta":"modified",children:Ro(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(ue,{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 aE={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},L_="docs";function oE(e){return pe(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Ff(e){return`${String(e||"app")}-docs-assistant:${Fr()}`}function iE(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}),{...aE,session_id:e.sessionId,kind:L_,input_data:t}}function O_(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 lE(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*cE(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 uE(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 zo(e,t);return e.json()}function dE(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(oE(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`),j=typeof(k==null?void 0:k.text)=="string"?k.text:"";if(!j.trim())throw new Error(`The gateway returned an empty ${d.name} documentation corpus, so nothing was asked.`);s=j}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 j=await Dr(await u(pe("attachments/upload"),{method:"POST",body:k,signal:l.signal}),`"${x.name}" could not be attached`),A=j==null?void 0:j.attachment;if(!A||typeof A.$artifact!="string"||!A.$artifact)throw new Error(`"${x.name}" could not be attached: the gateway returned no attachment reference.`);m.push(A)}const p=await Dr(await u(pe("runs/start"),{method:"POST",signal:l.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(iE({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(pe(`runs/${encodeURIComponent(g)}/ledger/stream?after=0`),{signal:_.signal,headers:{Accept:"text/event-stream"}});if(!k.ok||!k.body)return;let j="",A="";for await(const T of cE(k.body,_.signal)){const N=R_(T.event,T.data);!N||$_(N)||N.channel!=="content"||N.run_id!==g||(N.call_id!==j&&(j=N.call_id,A=""),A=N.snapshot?N.text:A+N.text,(x=l.onText)==null||x.call(l,A))}}catch{}})();try{const x=Date.now()+n;for(;;){await uE(t,l.signal);const k=await Dr(await u(pe(`runs/${encodeURIComponent(g)}`),{signal:l.signal}),"The docs-qa run could not be read"),j=String((k==null?void 0:k.status)||"").toLowerCase();if(j==="completed"){(C=l.onHistory)==null||C.call(l,(k==null?void 0:k.session_history)??null);const A=O_(k);if(!A)throw new Error(`The docs-qa run ${g} completed without an answer.`);return A}if(j==="failed"||j==="cancelled"){const A=k==null?void 0:k.error,T=typeof A=="string"?A:typeof(A==null?void 0:A.message)=="string"?A.message:"";throw new Error(`The docs-qa run ${j}${T?`: ${T}`:""}.`)}if(j==="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 fE(e,t,n={}){const s=new URLSearchParams({root_only:"true",kind:L_,limit:"500",include_ledger_len:"false"}),o=await Dr(await e(pe(`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(pe(`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 hE(e,t,n,s){var l;const o=[];for(const u of t.runIds){const[d,f]=await Promise.all([Dr(await e(pe(`runs/${encodeURIComponent(u)}/input_data`),{signal:s}),"A past question could not be read"),Dr(await e(pe(`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=O_(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 mE(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:[Ro(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(ue,{name:"archive",size:16})})]})},s.sessionId))}):a.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}const pE=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function gE(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||!Yi((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=mm(m.dataTransfer);p.files.length&&((g=e.onAddFiles)==null||g.call(e,p.files)),p.folders.length&&((_=e.onNotice)==null||_.call(e,E_(p.folders)))},children:[a.jsx(N_,{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(C_,{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=A_(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(ue,{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(ue,{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(ue,{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(ue,{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 Gc(){return new Date().toISOString()}function yE(e){Lo();const{source:t}=e,n=y.useRef(e.fetchGateway);n.current=e.fetchGateway;const s=y.useMemo(()=>e.ask||dE({fetchGateway:(z,F)=>n.current(z,F),source:t}),[e.ask,t.app,t.name]),o=y.useRef(Ff(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),[j,A]=y.useState(!1),[T,N]=y.useState({state:"loading",items:[]});y.useEffect(()=>()=>{var z;return(z=k.current)==null?void 0:z.abort()},[]);const E=y.useCallback(async()=>{N(z=>({...z,state:"loading"}));try{const z=await fE((F,L)=>n.current(F,L),t.app);N({state:"ready",items:z})}catch(z){N({state:"error",items:[],error:String((z==null?void 0:z.message)||z)})}},[t.app]),S=y.useCallback(async z=>{var F;(F=k.current)==null||F.abort(),N(L=>({...L,state:"loading"}));try{const L=await hE((q,V)=>n.current(q,V),z,t.name);o.current=z.sessionId,u(L),x(""),A(!1),N(q=>({...q,state:"ready"}))}catch(L){N(q=>({...q,state:"error",error:String((L==null?void 0:L.message)||L)}))}},[t.name]),I=y.useCallback(async z=>{try{const F=await n.current(pe(`sessions/${encodeURIComponent(z.sessionId)}/archive`),{method:"POST"});if(!F.ok)throw await zo(F,"The conversation could not be archived");o.current===z.sessionId&&(o.current=Ff(t.app),u([])),N(L=>({...L,items:L.items.filter(q=>q.sessionId!==z.sessionId)}))}catch(F){N(L=>({...L,state:"error",error:String((F==null?void 0:F.message)||F)}))}},[t.app]);y.useEffect(()=>{var z;e.connected||(z=k.current)==null||z.abort()},[e.connected]),y.useEffect(()=>()=>{for(const z of p)z.preview&&URL.revokeObjectURL(z.preview)},[]);const M=y.useCallback(z=>{x(""),g(F=>[...F,...z.map(L=>({id:Fr(),file:L,preview:pE.test(L.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(L):void 0}))])},[]),B=y.useCallback(async z=>{const F=String(z||"").trim();if(!F||_||!e.connected)return;const L=p;m(""),g([]),x("");const q=L.filter(ce=>ce.preview).map(ce=>({kind:"image",src:ce.preview,label:ce.file.name})),V=L.map(ce=>({id:ce.id,label:ce.file.name,title:ce.file.name,disabled:!0})),Y={id:`u-${Fr()}`,role:"user",content:F,ts:Gc(),...q.length?{media:q}:{},...V.length?{attachments:V}:{}},J=`a-${Fr()}`,W=[...d.current,Y],R={id:J,role:"assistant",title:t.name,content:"",ts:Gc(),live:{callId:J,reasoning:"",label:"answering"}};u([...W,R]),v(!0);const K=new AbortController;k.current=K;const se=ce=>u([...W,ce]);try{const ce=await s(F,{signal:K.signal,sessionId:o.current,files:L.map(ae=>ae.file),onText:ae=>{K.signal.aborted||se({...R,content:ae,live:{callId:J,reasoning:"",label:"streaming"}})},onHistory:ae=>x(lE(ae))});K.signal.aborted||se({id:J,role:"assistant",title:t.name,content:ce,ts:Gc()})}catch(ce){const ae=K.signal.aborted;se({id:J,role:"assistant",title:t.name,level:ae?"warn":"error",content:ae?"Stopped. Nothing more will be shown for this question.":String((ce==null?void 0:ce.message)||ce||"The docs assistant failed."),ts:Gc()})}finally{k.current===K&&(k.current=null),v(!1)}},[s,_,p,e.connected,t.name]),G=()=>{var z;(z=k.current)==null||z.abort(),o.current=Ff(t.app),u([]),g([]),m(""),x("")},Z=a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:`pc-docs-assistant__icon-btn${j?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":j,disabled:!e.connected||_,onClick:()=>{const z=!j;A(z),z&&E()},children:a.jsx(ue,{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&&!j,onClick:()=>{G(),A(!1)},children:a.jsx(ue,{name:"compose",size:16})})]}),oe=a.jsxs(a.Fragment,{children:[j?a.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:a.jsx(mE,{items:T.items,state:T.state,error:T.error,nowMs:Date.now(),activeSessionId:o.current,onOpen:z=>void S(z),onArchive:z=>void I(z)})}):null,a.jsx("div",{hidden:j,style:{display:j?"none":"contents"},children:a.jsx(gE,{source:t,messages:l,draft:f,onDraftChange:m,onSend:()=>void B(f),onStop:()=>{var z;return(z=k.current)==null?void 0:z.abort()},busy:_,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:p.map(z=>({id:z.id,name:z.file.name})),onAddFiles:M,onNotice:x,onRemoveFile:z=>g(F=>{const L=F.find(q=>q.id===z);return L!=null&&L.preview&&URL.revokeObjectURL(L.preview),F.filter(q=>q.id!==z)}),notice:C,suggestions:e.suggestions,onSuggestion:z=>void B(z),placeholder:e.placeholder})})]});return{headerActions:Z,body:oe}}function wE(e){const{headerActions:t,body:n}=yE(e);return a.jsxs("div",{className:"pc-docs-assistant-panel",children:[a.jsx(aN,{children:t}),n]})}function vE(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(wE,{source:e,fetchGateway:t,...f})}}const Oy="replay_view_v1",_E=["version","root_run_id","workflow","session_id","status","display_status","cursor","interaction","open_waits","usage","warnings"],Py=["runs","messages","activities","artifacts"],P_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function D_(e){return e==null?"None":e===!0?"True":e===!1?"False":String(e)}function bE(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 D_(e)}function Dy(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 Ah(e,t){return D_(e==="runs"?t.run_id:t.id)}function $h(e,t){return[(Array.isArray(t.order)&&t.order.length?t.order:[]).map(bE),Ah(e,t)]}function F_(e,t){const n=Math.min(e[0].length,t[0].length);for(let s=0;s<n;s+=1){const o=Dy(e[0][s],t[0][s]);if(o)return o}return e[0].length!==t[0].length?e[0].length-t[0].length:Dy(e[1],t[1])}function xE(e,t){return F_($h("messages",e),$h("messages",t))}function Th(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)=>Th(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=>P_(t,o)&&Th(e[o],t[o]))}return!1}function kE(e,t){const n=e&&Object.keys(e).length?{...e}:Object.fromEntries(Py.map(s=>[s,[]]));for(const s of _E)P_(t,s)&&(n[s]=t[s]);for(const s of Py){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)=>[Ah(s,m),p]));let f=!1;for(const m of o){const p=Ah(s,m),g=d.get(p);g===void 0?(d.set(p,u.length),u.push(m),f=!0):(Th(u[g].order??null,m.order??null)||(f=!0),u[g]=m)}if(f){const m=u.map(p=>({it:p,key:$h(s,p)}));m.sort((p,g)=>F_(p.key,g.key)),n[s]=m.map(p=>p.it)}else n[s]=u}return n}let SE=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 jE{constructor(){this.view=null,this.lastEventId=null,this.terminal=!1}adopt(t,n){var s,o,l;return this.view&&Fy((s=t.cursor)==null?void 0:s.runs,(o=this.view.cursor)==null?void 0:o.runs)?!1:(this.view=t,this.lastEventId=NE(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":Fy((u=n.cursor)==null?void 0:u.runs,(d=this.view.cursor)==null?void 0:d.runs)?"stale":(this.view=kE(this.view,n),this.lastEventId=s,"delta")}}function NE(e){return String(e||"").trim().replace(/^W\//,"").replace(/^"|"$/g,"")}function Fy(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 CE extends Error{constructor(t,n){super(`This gateway does not serve the replay view (GET runs/{id}/view answered ${t}${n?`: ${n}`:""}); AbstractGateway 0.17.0 or later serves it.`),this.name="ReplayViewUnavailableError",this.status=t}}const nu=200;async function zf(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 CE(e.status,t.trim());const n=new Error(t||`Gateway answered ${e.status}`);return n.status=e.status,n.detail=t,n}const zy=e=>`runs/${encodeURIComponent(e)}/view`;function EE(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(`${zy(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 zf(u);const f=new Uint8Array(await u.arrayBuffer()),m=JSON.parse(new TextDecoder().decode(f));if((m==null?void 0:m.version)!==Oy)throw new Error(`Unsupported replay view version ${JSON.stringify(m==null?void 0:m.version)} (this client reads ${Oy}).`);return{notModified:!1,view:m,etag:d,bytes:f.byteLength}},async listSessionTurns(n,s={}){const o=`include_session=true&include_subruns=false&ledger_max_items=1&detail=replay&session_turn_limit=${nu+1}`,l=await t(`runs/${encodeURIComponent(n)}/history_bundle?${o}`,{method:"GET",headers:{Accept:"application/json"},...s.signal?{signal:s.signal}:{}});if(!l.ok)throw await zf(l);const u=await l.json(),d=u.session&&typeof u.session=="object"?u.session:null,f=Array.isArray(d==null?void 0:d.turns)?d.turns:[],m=new Set,p=[];for(const g of f){const _=typeof(g==null?void 0:g.run_id)=="string"?g.run_id:"";!_||m.has(_)||(m.add(_),p.push({run_id:_,...typeof g.created_at=="string"?{created_at:g.created_at}:{}}))}return p},async streamView(n,s){var p;const o={Accept:"text/event-stream"};s.lastEventId&&(o["Last-Event-ID"]=s.lastEventId);const l=await t(`${zy(n)}/stream`,{method:"GET",headers:o,signal:s.signal});if(!l.ok)throw await zf(l);if(!l.body)throw new Error("The replay view stream has no body.");(p=s.onOpen)==null||p.call(s);const u=new SE,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 Ze=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"",Sa=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,By=new Set(["completed","failed","cancelled"]),AE=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 z_(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 $E(e,t){const n=Ze(e.status||t.status).toLowerCase();return n==="completed"?"completed":n==="waiting"?"waiting":n==="running"||n==="started"||n==="pending"?"running":"failed"}function TE(e){const t=Sa(e.policy_decision),n=Ze(t==null?void 0:t.decision);if(n!=="auto_approved"&&n!=="denied")return;const s=Sa(t==null?void 0:t.set_by),o=Ze(s==null?void 0:s.user_id)||Ze(s==null?void 0:s.client);return{decision:n,...Ze(e.decided_by)?{source:Ze(e.decided_by)}:{},...Ze(e.matched)?{matched:Ze(e.matched)}:{},...typeof(t==null?void 0:t.revision)=="number"?{revision:t.revision}:{},...o?{setBy:o}:{},...Ze(t==null?void 0:t.set_at)?{setAt:Ze(t==null?void 0:t.set_at)}:{}}}function RE(e,t){if(typeof e.error=="string"&&e.error.trim())return e.error.trim();const n=Sa(e.error);if(n)return Ze(n.message)||Ze(n.detail)||JSON.stringify(n);if(t==="denied")return"Denied";if(t==="cancelled")return"Cancelled"}function B_(e){return(Array.isArray(e.tool_calls)?e.tool_calls:[]).map((n,s)=>{var f;const o=$E(n,e),l=Ze(n.status||e.status).toLowerCase(),u=TE(n),d=o==="failed"?RE(n,l):void 0;return{id:`${e.id}:${Ze(n.id)||s}`,runId:e.run_id,name:Ze(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}:{},...Ze(e.started_at)?{startedAt:Ze(e.started_at)}:{},...Ze(e.ended_at)?{endedAt:Ze(e.ended_at)}:{},...((f=e.wait)==null?void 0:f.kind)==="tool_approval"&&e.wait.outcome?{approvalWait:!0}:{},...Ze(n.id)?{callId:Ze(n.id)}:{},...u?{policy:u}:{}}})}function W_(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 IE(e){const t=Ze(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=Ze(s==null?void 0:s.user_id)||Ze(s==null?void 0:s.client),l={decision:t,...Ze(e.source)?{source:Ze(e.source)}:{},...typeof(n==null?void 0:n.revision)=="number"?{revision:n.revision}:{},...o?{setBy:o}:{},...Ze(n==null?void 0:n.set_at)?{setAt:Ze(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:yu(l),ts:Ze(e.started_at)||void 0}}function ME(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(Ze(m.started_at)),g=Date.parse(Ze(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,Ze(_.status)!=="completed"||!AE.has(Ze(_.name)))continue;const v=Sa(_.arguments)||{},C=Ze(v.destination)||Ze(v.destination_path)||Ze(v.file_path)||Ze(v.path)||Ze(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 LE(e,t){const n=Array.isArray(e.order)&&typeof e.order[0]=="string"&&e.order[0]?e.order[0]:void 0,s=Ze(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 Rh(e){const t=e.root_run_id,n=ME(e),s=e.interaction?z_(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:LE(v,v.id===u?n:void 0)});const f=[],m=[],p=[];for(const v of e.activities||[])if(v.kind==="tool"){const C=B_(v);f.push(...C),C.forEach((x,k)=>d.push({order:[...v.order||[],k],id:`${v.id}:${k}`,message:W_(x)}))}else if(v.kind==="tool_policy"){const C=IE(v);C&&d.push({order:v.order,id:v.id,message:C})}else if(v.kind==="llm")for(const C of v.step_ids||[])(By.has(v.status)?p:m).push(`${v.run_id}:${C}`);d.sort((v,C)=>xE(v,C));const g=new Map((e.runs||[]).map(v=>[v.run_id,Ze(v.status).toLowerCase()])),_=Ze(e.status).toLowerCase()||"unknown";return{messages:d.map(v=>v.message),tools:f,interaction:By.has(_)?null:s,status:_,displayStatus:Ze(e.display_status),openLlmCalls:m,endedLlmCalls:p,runStatus:g,statistics:n}}const mt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},su=e=>Array.isArray(e)?e.map(mt):[],rt=e=>typeof e=="string"?e:"",Di=e=>rt(e.runtime_call_id||e.call_uid),sr=e=>rt(e.call_id||e.id);function OE(e){if(e.status!=="waiting")return!1;const t=e.result&&typeof e.result=="object"?e.result.wait:null,n=t&&typeof t.details=="object"?t.details:null;return(n==null?void 0:n.mode)==="approval_required"||(n==null?void 0:n.kind)==="tool_approval"||String((t==null?void 0:t.wait_key)||"").startsWith("tool_approval:")}function U_(e,t){const n=t.record,s=mt(n.effect);if(s.type!=="tool_calls")return[];const o=mt(n.result),l=su(mt(s.payload).tool_calls),u=l.length||n.status!=="waiting"?l:su(mt(mt(o.wait).details).tool_calls),d=su(o.results),f=u.length?u:d,m=[];return f.forEach((p,g)=>{let _=Di(p)?d.filter(S=>Di(S)===Di(p)):[];!_.length&&sr(p)&&u.filter(S=>sr(S)===sr(p)).length===1&&(_=d.filter(S=>sr(S)===sr(p)));const v=u.length?_.length===1?_[0]:u.length===d.length?d[g]:{}:p,C=Di(p)||Di(v)||`${rt(n.idempotency_key)||rt(n.step_id)||t.cursor}:${g}`,x=`${t.runId}:${C}`,k=e.get(x),j=rt(p.name||v.name)||(k==null?void 0:k.name);if(!j)return;const A=n.status==="completed"||n.status==="failed",T=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:j,arguments:N,status:A?T?"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)}:{},...Ry(v)?{sandbox:Ry(v)}:{},...sr(p)||sr(v)?{callId:sr(p)||sr(v)}:{},...k!=null&&k.approvalWait||OE(n)?{approvalWait:!0}:{},startedAt:(k==null?void 0:k.startedAt)||rt(n.started_at)||void 0,endedAt:A&&rt(n.ended_at)||(k==null?void 0:k.endedAt)};k&&["completed","failed"].includes(k.status)&&!A||(e.set(x,E),m.push(E))}),m}function bo(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Ds(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 V_(e){if(typeof e=="string")try{return mt(JSON.parse(e))}catch{return{}}return mt(e)}function ho(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function PE(e){return Ds(e,["reasoning_tokens","thinking_tokens"])??Ds(mt(e.completion_tokens_details),["reasoning_tokens"])??Ds(mt(e.output_tokens_details),["reasoning_tokens"])}function DE(e){const t=mt(typeof e=="string"&&e.trim().startsWith("{")?V_(e):e);return rt(t.error_class)}function FE(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=bo(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 sl(e){var x,k,j,A;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=FE(e),_=[],v=new Set;for(const T of e){const N=T.record,E=`${T.runId}:${N.step_id||T.cursor}:${N.status}`;if(n.has(E))continue;n.add(E);for(const Q of[N.started_at,N.ended_at]){const xe=Date.parse(rt(Q));Number.isFinite(xe)&&(l=Math.min(l,xe),u=Math.max(u,xe))}for(const Q of U_(t,T))Q.status==="waiting"&&v.add(Q.id);if(mt(N.effect).type!=="llm_call"||N.status!=="completed")continue;o.llmCalls+=1;const S=mt(N.result),I=mt(S.output),M=mt(S.usage||S.token_usage||S.tokens||I.usage||I.token_usage||I.tokens),B=Ds(M,["input_tokens","prompt_tokens","prompt","input","in"]),G=Ds(M,["output_tokens","completion_tokens","completion","output","out"]),Z=Ds(M,["total_tokens","total"])??(B!==void 0||G!==void 0?(B||0)+(G||0):void 0);Z!==void 0&&(B===void 0||G===void 0||B+G!==Z)&&(d=!0),B!==void 0&&(o.inputTokens=(o.inputTokens||0)+B),G!==void 0&&(o.outputTokens=(o.outputTokens||0)+G),Z!==void 0&&(o.totalTokens=(o.totalTokens||0)+Z);const oe=bo(S.gen_time??I.gen_time);oe!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+oe,o.timedCalls=(o.timedCalls||0)+1);const z=mt(S.metadata||I.metadata),F=mt(z.performance),L=bo(F.prompt_tokens_per_second),q=bo(F.generation_tokens_per_second),V=mt(z.prompt_cache),Y=bo(V.cached_tokens),J=bo(V.fed_tokens);if(L!==void 0||q!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,L!==void 0&&L>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+L,B!==void 0)){const Q=B/L*1e3;o.prefillMs=(o.prefillMs||0)+Q,J!==void 0&&(f+=J,m+=Q)}q!==void 0&&q>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+q,G!==void 0&&(o.decodeMs=(o.decodeMs||0)+G/q*1e3))}if(Y!==void 0||J!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(Y||0),o.fedTokens=(o.fedTokens||0)+(J||0);const Q=rt(V.outcome);if(Q){const xe=o.cacheOutcomes||[];xe.includes(Q)||xe.push(Q),o.cacheOutcomes=xe}}const W=rt(N.step_id)||void 0,R=W&&g.get(`${T.runId}:${W}`)||{},K=mt(S.route),se={runId:T.runId};W&&(se.stepId=W),rt(N.started_at)&&(se.startedAt=rt(N.started_at));const ce=rt(S.model||I.model)||rt(K.model)||R.model,ae=rt(K.provider)||rt(mt(z._provider_request).provider)||R.provider||rt(S.provider);ce&&(se.model=ce),ae&&(se.provider=ae),ce&&(o.models=ho(o.models,ce)),ae&&(o.providers=ho(o.providers,ae)),(Z===void 0||B!==void 0&&G!==void 0&&B+G===Z)&&(B!==void 0&&(se.inputTokens=B),G!==void 0&&(se.outputTokens=G)),Z!==void 0&&(se.totalTokens=Z);const we=PE(M);we!==void 0&&(se.reasoningTokens=we,o.reasoningTokens=(o.reasoningTokens||0)+we),Y!==void 0&&(se.cachedTokens=Y),J!==void 0&&(se.fedTokens=J),rt(V.outcome)&&(se.cacheOutcome=rt(V.outcome)),rt(V.backend)&&(se.cacheBackend=rt(V.backend),o.cacheBackends=ho(o.cacheBackends,se.cacheBackend)),oe!==void 0&&(se.genTimeMs=oe),L!==void 0&&L>0&&(se.promptTokensPerSecond=L),q!==void 0&&q>0&&(se.generationTokensPerSecond=q),R.ttftS!==void 0?(se.ttftMs=R.ttftS*1e3,se.promptMs=se.ttftMs,se.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+se.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):se.promptTokensPerSecond!==void 0&&B!==void 0&&(se.promptMs=B/se.promptTokensPerSecond*1e3,se.promptSource="rate"),se.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+se.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,J!==void 0&&se.promptMs>0&&(se.promptNewTokensPerSecond=J/(se.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+J,p+=se.promptMs)),se.ttftMs!==void 0&&oe!==void 0&&oe>=se.ttftMs?se.generationMs=oe-se.ttftMs:se.generationTokensPerSecond!==void 0&&G!==void 0&&(se.generationMs=G/se.generationTokensPerSecond*1e3),se.generationMs!==void 0&&G!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+se.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+G);const Se=mt(z.speculation);if(Object.keys(Se).length){const Q={};rt(Se.mode)&&(Q.mode=rt(Se.mode)),typeof Se.used=="boolean"&&(Q.used=Se.used),rt(Se.draft_kind)&&(Q.draftKind=rt(Se.draft_kind));const xe=Ds(Se,["accepted_tokens"]),ve=Ds(Se,["drafted_tokens"]),Fe=Ds(Se,["rounds"]),Xe=Ds(Se,["num_draft_tokens"]);xe!==void 0&&(Q.acceptedTokens=xe),ve!==void 0&&(Q.draftedTokens=ve),xe!==void 0&&ve&&(Q.acceptanceRate=xe/ve),Fe!==void 0&&(Q.rounds=Fe),Xe!==void 0&&(Q.draftLength=Xe),se.speculation=Q;const Ve=o.speculation||(o.speculation={calls:0,used:0});Ve.calls+=1,Q.used&&(Ve.used+=1),Q.mode&&(Ve.modes=ho(Ve.modes,Q.mode)),Q.draftKind&&(Ve.draftKinds=ho(Ve.draftKinds,Q.draftKind)),xe!==void 0&&ve!==void 0&&(Ve.acceptedTokens=(Ve.acceptedTokens||0)+xe,Ve.draftedTokens=(Ve.draftedTokens||0)+ve),Fe!==void 0&&(Ve.rounds=(Ve.rounds||0)+Fe),Xe!==void 0&&(Ve.draftLengths=ho(Ve.draftLengths,Xe))}_.push(se)}_.length&&(_.every(T=>T.startedAt)&&_.sort((T,N)=>Date.parse(T.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 T of t.values()){if(T.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(T.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(T.status))continue;o.toolCalls+=1;const N=T.status==="failed";N&&(o.toolsFailed=(o.toolsFailed||0)+1);const E=o.toolBreakdown||(o.toolBreakdown={}),S=E[T.name]||(E[T.name]={calls:0,failed:0});if(S.calls+=1,N){S.failed+=1;const Z=DE(T.output);Z&&((S.errors||(S.errors={}))[Z]=(((k=S.errors)==null?void 0:k[Z])||0)+1)}const I=Date.parse(rt(T.startedAt)),M=Date.parse(rt(T.endedAt));if(Number.isFinite(I)&&Number.isFinite(M)&&M>=I){const Z=`${T.runId}|${T.startedAt}|${T.endedAt}`,oe=C.get(Z)||{ms:M-I,calls:0,names:new Map,waited:!1};oe.calls+=1,oe.names.set(T.name,(oe.names.get(T.name)||0)+1),v.has(T.id)&&(oe.waited=!0),C.set(Z,oe)}if(T.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(T.name))continue;const B=V_(T.arguments),G=rt(B.destination||B.destination_path||B.file_path||B.path||B.filename);G&&s.add(G)}for(const T of C.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+T.ms,T.waited&&(o.toolTimeIncludesApproval=!0);const N=[...T.names.keys()].sort();(!o.slowestToolBatch||T.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:T.ms,calls:T.calls,tools:N});const E=(j=o.toolBreakdown)==null?void 0:j[N[0]];if(N.length===1&&E)E.ms=(E.ms||0)+T.ms;else for(const S of N){const I=(A=o.toolBreakdown)==null?void 0:A[S];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 zE(e){const t=mt(mt(e).ledgers);return Object.entries(t).flatMap(([n,s])=>su(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 Bf=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};function BE(e){var j,A,T,N;const t=e.view||null,n=t?Rh(t):null,{tools:s,statistics:o}=n?{tools:n.tools,statistics:n.statistics}:sl(e.records),l={toolCalls:o.toolCalls,totalTokens:o.totalTokens,startedAt:String(((j=e.run)==null?void 0:j.created_at)||"")||void 0},u=(E,S,I)=>({...l,label:E,detail:S,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:!((A=e.records)!=null&&A.length))||!!e.error))return u(e.connection==="reconnecting"?"Reconnecting":"Disconnected",String(e.error||"Live activity is unavailable"),"waiting");if(e.status==="paused"||((T=e.run)==null?void 0:T.paused)===!0)return u("Paused","Resume when you’re ready","waiting");const d=Bf((N=e.interaction)==null?void 0:N.wait),f=Bf(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 S;return E.status==="running"||p&&E.status==="waiting"&&E.runId===((S=e.interaction)==null?void 0:S.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 S=`${E.runId}:${E.record.step_id||E.record.idempotency_key||E.cursor}`,I=_.get(S);I&&["completed","failed"].includes(String(I.record.status))||_.set(S,E)}if(n!=null&&n.openLlmCalls.length||[..._.values()].reverse().find(E=>Bf(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 WE=3;function Wy(e){return`${Math.round(e).toLocaleString("en-US")} bytes`}function ym(e,t){if(!t||!(t>0)||e.size<=t)return null;let n=_u(e.size),s=_u(t);return n===s&&(n=Wy(e.size),s=Wy(t)),`${e.name||"This file"} is ${n}; the gateway accepts files up to ${s}.`}function UE(e){return`Upload failed: ${String(e||"").replace(/^[a-z_]*upload failed:?\s*/i,"").trim()||"the gateway did not say why"}`}async function VE(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 bu=e=>`${e} ${e===1?"file":"files"}`;function Uy(e,t){const n=[];return e&&n.push(`${bu(e)} attached`),t&&n.push(`${bu(t)} could not be attached`),n.join(", ")}function G_(e){const t=e.filter(o=>o.state==="queued"||o.state==="uploading").length;if(t)return`Wait for ${bu(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.`:`${bu(n.length)} were not attached. ${s?"Retry or remove":"Remove"} them before sending.`}function GE(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=(j,A)=>n(T=>T.map(N=>N.id===j?{...N,...A}:N)),p=async j=>{const A=d.current,T=S=>!f.current||d.current!==A||u.current.has(S);let N=0,E=0;await VE(j,l.current.concurrency??WE,async S=>{if(!(T(S.id)||!S.file)){m(S.id,{state:"uploading",error:void 0});try{const I=await l.current.upload(S.file);if(T(S.id))return;m(S.id,{state:"attached",ref:I,error:void 0}),N+=1}catch(I){if(T(S.id))return;m(S.id,{state:"failed",error:UE(I instanceof Error?I.message:String(I??""))}),E+=1}}}),f.current&&d.current===A&&(N||E)&&o(Uy(N,E))},g=j=>{if(!j.length)return[];const{maxBytes:A,thumbnail:T}=l.current,N=j.map(S=>{const I=ym(S,A),M=T==null?void 0:T(S);return{id:Fr(),file:S,name:S.name||"Untitled file",size:S.size,state:I?"refused":"queued",...I?{error:I}:{},...M?{thumbnailUrl:M}:{}}});n(S=>[...S,...N]);const E=N.filter(S=>S.state==="refused").length;return E&&o(Uy(0,E)),p(N.filter(S=>S.state==="queued")),N.map(S=>S.id)},_=j=>{const A=t.find(N=>N.id===j);if(!A||A.state!=="failed")return;const T={...A,state:"queued",error:void 0};n(N=>N.map(E=>E.id===j?T:E)),p([T])},v=j=>{u.current.add(j),n(A=>A.filter(T=>T.id!==j))},C=()=>{d.current+=1,n([])},x=y.useMemo(()=>t.map(({id:j,name:A,size:T,state:N,thumbnailUrl:E,error:S})=>({id:j,name:A,size:T,state:N,...E?{thumbnailUrl:E}:{},...S?{error:S}:{}})),[t]),k=y.useMemo(()=>t.filter(j=>j.state==="attached").map(j=>j.ref),[t]);return{items:x,attached:k,add:g,remove:v,retry:_,clear:C,sendBlock:G_(x),announcement:s}}const HE=new Set(["blob:","data:","http:","https:"]);function KE(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return HE.has(new URL(t,n).protocol)?t:void 0}catch{return}}function JE(e){const t=typeof e.size=="number"?_u(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 qE(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}=JE(n),u=KE(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(ue,{name:"paperclip",size:13}):a.jsx(ue,{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(ue,{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(ue,{name:"x",size:12})}):null]},n.id)})}):null}function YE(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 xo={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 Vy(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function QE(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 Ss=xo;function XE(e){var oe,z,F;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),j=y.useRef(!1),A=y.useRef(!1),T=y.useRef(!0),N=y.useRef(0);k.current!==x&&(k.current=x,j.current=!1,A.current=!1,N.current+=1);const E=!!e.disabled||d!==null||m||j.current||A.current,S=async(L,q)=>{var J;if(e.disabled||j.current||A.current)return;const V=x,Y=++N.current;j.current=!0,C(null),_(""),f(L);try{const W=await q();if(!T.current||k.current!==V||N.current!==Y)return;A.current=!0,p(!0);const R=W&&typeof W=="object"&&typeof W.outcomeNote=="string"?String(W.outcomeNote):"";_(`Response sent. Waiting for the workflow to continue.${R?` ${R}`:""}`)}catch(W){if(!T.current||k.current!==V||N.current!==Y)return;C({submission:L,message:Vy(W)}),_("The action failed. You can try again."),(J=e.onError)==null||J.call(e,W)}finally{if(!T.current||k.current!==V||N.current!==Y)return;j.current=!1,f(null)}},I=async L=>{var V;if(e.disabled||j.current||A.current)return;const q=x;try{if(await L(),!T.current||k.current!==q)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(!T.current||k.current!==q)return;_(`Could not leave this for later: ${Vy(Y)}`),(V=e.onError)==null||V.call(e,Y)}};y.useEffect(()=>{o(""),u(t.kind==="event-wait"&&t.initialPayload||""),C(null),f(null),p(!1),_("")},[x]),y.useEffect(()=>(T.current=!0,()=>{T.current=!1,N.current+=1,j.current=!1}),[]);const M=()=>{v&&S(v.submission,()=>YE(t,v.submission))},B=t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required"),G=(L,q)=>L?a.jsx("button",{type:"button",className:"pc-workflow-interaction__defer","data-decision":"defer",disabled:E,onClick:()=>void I(L),children:q}):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}),(oe=t.choices)!=null&&oe.length?a.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(L=>a.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice","data-decision":"choice",disabled:E||L.disabled,onClick:()=>void S({kind:"choice",answer:L.id},()=>t.onSubmit(L.id)),children:[a.jsx("span",{children:L.label}),L.description?a.jsx("small",{children:L.description}):null]},L.id))}):null,t.allowFreeText!==!1?a.jsxs("div",{className:"pc-workflow-interaction__entry",children:[a.jsx("textarea",{"aria-label":"Response",value:s,onChange:L=>o(L.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:n?1:2,disabled:E,onKeyDown:L=>{L.key!=="Enter"||L.shiftKey||L.nativeEvent.isComposing||L.keyCode===229||(L.preventDefault(),s.trim()&&S({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 S({kind:"free-text",answer:s},()=>t.onSubmit(s)),children:(d==null?void 0:d.kind)==="free-text"?"Sending…":t.submitLabel||Ss.submit})]}):null,t.onSkip||t.onDefer?a.jsxs("div",{className:"pc-workflow-interaction__buttons pc-workflow-interaction__buttons--secondary",children:[G(t.onDefer,t.deferLabel||Ss.keepWaiting),t.onSkip?a.jsx("button",{type:"button",className:"pc-workflow-interaction__skip","data-decision":"skip",disabled:E,onClick:()=>void S({kind:"skip"},t.onSkip),children:(d==null?void 0:d.kind)==="skip"?"Continuing…":t.skipLabel||Ss.skip}):null]}):null]});else if(t.kind==="tool-approval"){const L=String(t.disabledReason||"").trim(),q=E||!!L,V=[!L&&t.onApproveForSession&&t.approveForSessionDescription?t.approveForSessionDescription:"",!L&&t.onApproveAll&&t.approveAllDescription?t.approveAllDescription:""].filter(Boolean),Y=V.length?String(t.broadScopeSummary||"").trim():"";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:[G(t.onDefer,t.deferLabel||Ss.decideLater),a.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:E,onClick:()=>void S({kind:"deny"},t.onDeny),children:(d==null?void 0:d.kind)==="deny"?"Denying…":t.denyLabel||Ss.deny}),a.jsx("button",{type:"button",className:"pc-btn","data-decision":"approve",disabled:E,onClick:()=>void S({kind:"approve"},t.onApprove),children:(d==null?void 0:d.kind)==="approve"?"Allowing…":t.approveLabel||Ss.allowOnce}),t.onApproveForSession?a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session","data-decision":"approve-session",disabled:q,title:L||t.approveForSessionDescription||void 0,onClick:()=>void S({kind:"approve-session"},t.onApproveForSession),children:(d==null?void 0:d.kind)==="approve-session"?"Allowing…":t.approveForSessionLabel||Ss.allowForChat}):null,(t.approveKinds||[]).map(J=>a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session pc-workflow-interaction__allow-kind","data-decision":"approve-kind","data-kind":J.kind,disabled:q,title:L||t.approveForSessionDescription||void 0,onClick:()=>void S({kind:"approve-kind",toolset:J.kind},J.onApprove),children:(d==null?void 0:d.kind)==="approve-kind"&&d.toolset===J.kind?"Allowing…":J.label||Ss.allowKindForChat(J.kind)},J.kind)),t.onApproveAll?a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all","data-decision":"approve-all",disabled:q,title:L||t.approveAllDescription||void 0,onClick:()=>void S({kind:"approve-all"},t.onApproveAll),children:(d==null?void 0:d.kind)==="approve-all"?"Allowing…":t.approveAllLabel||Ss.allowAll}):null]}),Y?a.jsx("p",{className:"pc-workflow-interaction__scope","data-scope-summary":"",children:Y}):null,t.remember?a.jsxs("label",{className:"pc-workflow-interaction__remember",children:[a.jsx("input",{type:"checkbox",checked:t.remember.checked,disabled:E,onChange:J=>t.remember.onChange(J.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,(z=t.denyOptions)!=null&&z.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:Ss.denyForChatNote}),a.jsx("div",{className:"pc-workflow-interaction__buttons",children:t.denyOptions.map(J=>a.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny-chat","data-key":J.key,disabled:E,onClick:()=>void S({kind:"deny-chat",key:J.key},J.onDeny),children:(d==null?void 0:d.kind)==="deny-chat"&&d.key===J.key?"Denying…":J.label},J.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,L&&(t.onApproveAll||t.onApproveForSession||(F=t.approveKinds)!=null&&F.length)?a.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note",children:L}):null,Y&&V.length?a.jsxs("details",{className:"pc-workflow-interaction__scope-details","data-scope-details":"",children:[a.jsx("summary",{children:"What the broader choices allow"}),V.map(J=>a.jsx("p",{className:"pc-workflow-interaction__scope",children:J},J))]}):V.map(J=>a.jsx("p",{className:"pc-workflow-interaction__scope",children:J},J))]})}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:L=>u(L.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 S({kind:"event",payload:l},()=>t.onSend(l)),children:(d==null?void 0:d.kind)==="event"?"Sending…":t.sendLabel||Ss.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(ue,{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:B}),t.description?a.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),Z,v?a.jsx(QE,{message:v.message,onRetry:M,disabled:E}):null,a.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:g})]})}function mo(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function ZE(e){var _e;Lo();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 ge,te;return((te=(ge=e.steer)==null?void 0:ge.modes)==null?void 0:te[0])||"guide"}),[g,_]=y.useState(null),[v,C]=y.useState("idle"),x=y.useRef(null),k=y.useRef(!0),j=y.useRef(!1),A=y.useRef(!1),T=y.useRef(!1),N=y.useRef(0),E=y.useRef(0),S=y.useRef(0);y.useEffect(()=>(k.current=!0,()=>{var ge;k.current=!1,N.current+=1,E.current+=1,S.current+=1,j.current=!1,A.current=!1,T.current=!1,(ge=x.current)==null||ge.abort(),x.current=null}),[]);const I=!!e.blockedNotice,M=!!e.disabled||I,B=!!e.busy||t,G=t||!!e.busy&&!e.sendWhileBusy,Z=e.stopState||null,oe=(Z==null?void 0:Z.phase)==="stopping",z=e.steer&&typeof e.steer.onSteer=="function"?e.steer:null,F=z?(_e=z.modes)!=null&&_e.length?z.modes:["guide"]:[],L=F.includes(m)?m:F[0]||"guide",q=!!z&&!!e.busy,V=Array.isArray(e.attachmentItems)?e.attachmentItems:[];y.useEffect(()=>{_(null)},[!!e.busy]);const Y=typeof e.onFiles=="function",J=y.useRef(null),[W,R]=y.useState(null),[K,se]=y.useState(""),ce=y.useRef(e.onFiles);ce.current=e.onFiles;const ae=y.useRef(M);ae.current=M;const we=async(ge,te)=>{const be=ce.current;if(be){if(ae.current){f({action:"attach",message:"attachments are unavailable right now."});return}if(te.length)f({action:"attach",message:E_(te)});else if(ge.length)f(null);else{f({action:"attach",message:"the drop contained no files."});return}if(ge.length){se(`Attaching ${ge.length} ${ge.length===1?"file":"files"}…`);try{await be(ge)}catch(P){k.current&&f({action:"attach",message:mo(P)})}}}},Se=y.useRef(we);Se.current=we,y.useEffect(()=>{if(!Y||typeof window>"u")return;const ge=new OC;let te=0;const be=Ee=>!!(J.current&&Ee instanceof Node&&J.current.contains(Ee)),P=()=>{ge.reset(),te&&window.clearInterval(te),te=0,R(null)},ie=()=>{te||(te=window.setInterval(()=>{ge.active(Date.now())||P()},250))},Oe=Ee=>{var jt;if(!Yi((jt=Ee.dataTransfer)==null?void 0:jt.types))return;ge.enter(Date.now());const pt=be(Ee.target),St=My(Ee.dataTransfer);R(Pt=>Pt&&Pt.over===pt&&Pt.count===(St??Pt.count)?Pt:{count:St??(Pt==null?void 0:Pt.count)??null,over:pt}),ie()},Ae=Ee=>{var St;if(!Yi((St=Ee.dataTransfer)==null?void 0:St.types))return;Ee.preventDefault(),ge.over(Date.now());const pt=be(Ee.target);Ee.dataTransfer&&(Ee.dataTransfer.dropEffect=pt&&!ae.current?"copy":"none"),R(jt=>jt&&jt.over===pt?jt:{count:(jt==null?void 0:jt.count)??My(Ee.dataTransfer),over:pt}),ie()},Ye=Ee=>{var pt;Yi((pt=Ee.dataTransfer)==null?void 0:pt.types)&&(ge.leave(Date.now())||P())},$e=Ee=>{var js;if(!Yi((js=Ee.dataTransfer)==null?void 0:js.types))return;const pt=be(Ee.target),St=Ee.defaultPrevented&&!pt;if(Ee.preventDefault(),P(),St)return;if(!pt){f({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:jt,folders:Pt}=mm(Ee.dataTransfer);Se.current(jt,Pt)},Ge=Ee=>{Ee.key==="Escape"&&ge.depth>0&&P()};return window.addEventListener("dragenter",Oe),window.addEventListener("dragover",Ae),window.addEventListener("dragleave",Ye),window.addEventListener("drop",$e),window.addEventListener("dragend",P),window.addEventListener("blur",P),window.addEventListener("keydown",Ge),()=>{window.removeEventListener("dragenter",Oe),window.removeEventListener("dragover",Ae),window.removeEventListener("dragleave",Ye),window.removeEventListener("drop",$e),window.removeEventListener("dragend",P),window.removeEventListener("blur",P),window.removeEventListener("keydown",Ge),te&&window.clearInterval(te)}},[Y]);const Q=ge=>{if(!Y||M)return;const te=A_(ge.clipboardData);te.length&&(ge.preventDefault(),we(te,[]))},xe=W?a.jsxs("div",{className:["pc-workflow-chat__dropzone",W.over?"is-over":"",M?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[a.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:a.jsx(ue,{name:"paperclip",size:18})}),a.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[a.jsx("strong",{children:M?"Attachments are unavailable right now":Ly(W.count)}),M?null:a.jsx("span",{children:W.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,ve=W?M?"Attachments are unavailable right now":Ly(W.count):K,Fe=async ge=>{if(!z)return;const te=L,be=++N.current;j.current=!0,f(null),_(null),n(!0);try{const P=await z.onSteer(ge,te);if(!k.current||N.current!==be)return;if(!(P!=null&&P.accepted)&&!(P!=null&&P.duplicate)){f({action:"steer",message:"the gateway did not accept this message (accepted=false)."});return}_({mode:te,...typeof P.seq=="number"?{seq:P.seq}:{},duplicate:!!P.duplicate}),e.onDraftChange("")}catch(P){k.current&&N.current===be&&f({action:"steer",message:mo(P)})}finally{k.current&&N.current===be&&(j.current=!1,n(!1))}},Xe=async()=>{const ge=String(e.draft||"");if(M||j.current||!ge.trim())return;if(q)return void Fe(ge);if(!e.sendWhileBusy&&e.busy)return;const te=V.length?G_(V):null;if(te){f({action:"send",message:te});return}const be=++N.current,P=new AbortController;x.current=P,j.current=!0,f(null),_(null),n(!0);try{await e.onSend(ge,{signal:P.signal})}catch(ie){k.current&&N.current===be&&!P.signal.aborted&&f({action:"send",message:mo(ie)})}finally{x.current===P&&(x.current=null),k.current&&N.current===be&&(j.current=!1,n(!1))}},Ve=async()=>{if(M||A.current||!e.onCancel)return;const ge=++E.current;A.current=!0,f(null),o(!0);const be=x.current||new AbortController;be.abort(new DOMException("Stopped by the user","AbortError"));try{await e.onCancel(be.signal)}catch(P){k.current&&E.current===ge&&f({action:"cancel",message:mo(P)})}finally{k.current&&E.current===ge&&(A.current=!1,o(!1))}},Je=async()=>{if(M||T.current||!e.onAttach)return;const ge=++S.current;T.current=!0,f(null),u(!0);try{await e.onAttach()}catch(te){k.current&&S.current===ge&&f({action:"attach",message:mo(te)})}finally{k.current&&S.current===ge&&(T.current=!1,u(!1))}},me=()=>{d&&((d.action==="send"||d.action==="steer")&&Xe(),d.action==="cancel"&&Ve(),d.action==="attach"&&Je())},Me=e.toolbar||null,st=ge=>V1((Array.isArray(e.messages)?e.messages:[]).filter(te=>!te.toolActivity&&!te.live&&String(te.content||"").trim()),ge?{heading:ge}:void 0),tt=async ge=>{if(!M){f(null);try{await ge()}catch(te){k.current&&f({action:"toolbar",message:mo(te)})}}},$t=async()=>{const ge=await vl(st());k.current&&(C(ge?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>k.current&&C("idle"),1200))},le=Me?a.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[Me.onNewSession?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:M,onClick:()=>void tt(Me.onNewSession),children:[a.jsx(ue,{name:"plus",size:14}),a.jsx("span",{children:"New chat"})]}):null,Me.onClear?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:M,onClick:()=>void tt(Me.onClear),children:[a.jsx(ue,{name:"trash",size:14}),a.jsx("span",{children:"Clear"})]}):null,Me.copyTranscript?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"copy",onClick:()=>void $t(),children:[a.jsx(ue,{name:v==="copied"?"check":"copy",size:14}),a.jsx("span",{children:v==="copied"?"Copied":v==="failed"?"Copy failed":"Copy"})]}):null,Me.exportTranscript?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const ge=Me.exportTranscript;G1({filename:ge.filename,text:st(ge.heading),mime:"text/markdown;charset=utf-8"})},children:[a.jsx(ue,{name:"download",size:14}),a.jsx("span",{children:"Export"})]}):null]}):null,de=L==="queue"?"Queue":"Steer",je=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})`:""}. ${z!=null&&z.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:J,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||le?a.jsxs("header",{className:["pc-workflow-chat__header",le?"pc-workflow-chat__header--toolbar":""].filter(Boolean).join(" "),children:[e.header?a.jsx("div",{className:"pc-workflow-chat__header-main",children:e.header}):null,le]}):null,a.jsx("div",{className:"pc-workflow-chat__transcript",children:a.jsx(N_,{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(XE,{interaction:e.interaction,disabled:M}):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"?L==="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:me,disabled:M,children:"Try again"}):null]}):null,a.jsxs("div",{className:"pc-workflow-chat__composer",children:[a.jsx(C_,{value:e.draft,onChange:e.onDraftChange,onSubmit:()=>void Xe(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:M,busy:q?t:G,sendLabel:q?de:e.sendLabel,busyLabel:q?L==="queue"?"Queueing…":"Steering…":e.busyLabel,rows:2,leading:e.attachments||V.length?a.jsxs("div",{className:"pc-workflow-chat__attachments",children:[V.length?a.jsx(qE,{items:V,onRemove:e.onRemoveAttachment,onRetry:e.onRetryAttachment,disabled:M}):null,e.attachments]}):null,overlay:xe,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:M||l,onClick:()=>void Je(),children:[a.jsx(ue,{name:"paperclip",size:16}),a.jsx("span",{children:l?"Attaching…":"Attach"})]}):null,e.composerExtras,q&&F.length>1?a.jsx("span",{className:"pc-workflow-chat__steer-modes",role:"group","aria-label":"While the run is busy",children:F.map(ge=>a.jsx("button",{type:"button",className:"pc-workflow-chat__steer-mode","data-steer-mode":ge,"aria-pressed":L===ge,disabled:M||t,onClick:()=>p(ge),children:ge==="queue"?"Queue next turn":"Guide this run"},ge))}):null,B&&e.onCancel?a.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:M||s||oe,onClick:()=>void Ve(),children:[a.jsx(ue,{name:"x",size:14}),a.jsx("span",{children:s||oe?"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]})}),z?a.jsx("div",{className:"pc-workflow-chat__steer-status",role:"status","aria-live":"polite",children:je}):null,Y?a.jsx("div",{className:"pc-sr-only",role:"status","aria-live":"polite",children:ve}):null]}),e.footer?a.jsx("footer",{className:"pc-workflow-chat__footer",children:e.footer}):null]})}function eA(e){return e.toolApprovalGranted?null:e.interaction}const Wf={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 Re(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function Xi(e){return Array.isArray(e)?e:[]}function tA(e){const t=Ue(e);return!!(t&&(t.code==="revision_conflict"||t.reason_code==="revision_conflict"||t.status===409||t.name==="SessionToolPolicyConflict"))}function Fn(e){return Re(e==null?void 0:e.status).toLowerCase()||"unknown"}function gt(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 nA(e){const t=Ue(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Uf(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 Ih(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 po(e){const t=Ih(e);if(t)return t;if(!Ue(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function Gy(e){if(!e)return"";for(const s of["prompt","request","task","message","query","input"]){const o=Re(e[s]);if(o)return o}const t=Ue(e.context);for(const s of["task","message"]){const o=Re(t==null?void 0:t[s]);if(o)return o}const n=Xi(t==null?void 0:t.messages);for(let s=n.length-1;s>=0;s-=1){const o=Ue(n[s]);if(Re(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=Re(o==null?void 0:o.content);if(l)return l}return""}function H_(e){const t=Ue(e.result);return Ue(t==null?void 0:t.wait)}function Vf(e){return e?Re(e.reason)==="subworkflow"||Re(e.wait_key).startsWith("subworkflow:"):!1}function Hy(e,t){return!!(e&&e.runId===t.runId&&Re(e.wait.wait_key)===Re(t.wait.wait_key))}function Mh(e){return Ue(e.effect)||{}}function sA(e,t){return Re(e.run_id)||t}function Ky(e){return Re(e.ended_at)||Re(e.started_at)||void 0}function Jy(e){const t=new Set,n=m=>{const p=Re(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=Mh(e),l=Ue(o.payload);Re(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=H_(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=Re(u==null?void 0:u.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}const Gf=new WeakMap,rA=/^(live|live-end|stream-unavailable):/;function aA(e){return!!(e&&typeof e=="object"&&e.name==="ReplayViewUnavailableError")}function qy(e){const t=String(e||""),n=t.indexOf("~");return n<0?"":t.slice(n+1)}const Fi=()=>({sessionId:"",transport:null,order:[],created:new Map,turns:new Map});class oA{constructor(t,n={}){this.transport=t,this.options=n,this.snapshot={...Wf},this.subscribers=new Set,this.controller=null,this.generation=0,this.rootRunId="",this.cursors=new Map,this.seenRecords=new Set,this.seenMessages=new Set,this.watchedRuns=new Set,this.childCatchUpAttempts=new Map,this.runStates=new Map,this.historicalRuns=new Map,this.historicalRunFailures=new Map,this.commandIds=new Map,this.toolActivities=new Map,this.historicalEvidence=new Map,this.approvedWaits=new Set,this.grantedToolWaits=new Set,this.resolvedWaits=new Set,this.approvalEpoch=0,this.toolApprovalPolicy=null,this.toolApprovalSuspended=!1,this.toolApprovalStopped=!1,this.displayStatusAt=-1/0,this.stopRequested=!1,this.stopFollowing=!1,this.openLlmSteps=new Set,this.forcedStop=null,this.liveReplies=new Map,this.closedLiveCalls=new Set,this.shownLiveCalls=new Set,this.liveDirty=new Set,this.liveRenderTimer=null,this.lastLiveRender=-1/0,this.sessionToolPolicy=null,this.sessionPolicyUnavailableReason="",this.sessionPolicyState=null,this.sessionPolicyClamped=[],this.toolPolicyByCall=new Map,this.source=null,this.viewFold=null,this.viewRun=null,this.viewDigest="",this.viewAssistantIds=new Set,this.viewTerminalRuns=new Set,this.viewStreamEnded=!1,this.viewEarlier={messages:[],tools:[]},this.viewTurnCache=Fi();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=Re(n.sessionToolPolicyUnavailableReason)),this.snapshot=this.withSessionPolicy({...Wf})}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?"":Re(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=Re((s=this.snapshot.run)==null?void 0:s.session_id)||Re((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(tA(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(gt(this.snapshot.status))throw new Error("This run has already ended.");if(n.runId!==t.runId||Re(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=>Re(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.viewEarlier={messages:[],tools:[]},this.set({...Wf})}dispose(){this.reset(),this.viewTurnCache=Fi(),this.subscribers.clear()}async load(t){const n=Re(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=Fn(d);if(await this.ingestHistory(u,n,s),!this.live(s))return;if(this.set({...this.snapshot,run:d,status:m,loading:!1,...f&&!gt(m)?{interaction:this.interactionWith({runId:n,wait:f})}:{}}),d&&this.updateRunState(n,d),f)for(const p of Jy({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=Re(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${Uf(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(Re(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||Re(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:Re(s.wait.wait_key),payload:{response:t}})}answerEvent(t,n){const s=this.requireInteraction();if(n&&(s.runId!==n.runId||Re(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:Re(s.wait.wait_key),payload:t})}approve(t,n){const s=this.requireInteraction();if(gt(this.snapshot.status))throw new Error("This run has already ended.");if(n&&(s.runId!==n.runId||Re(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:Re(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||gt(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||gt(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){Uf(t)!==Uf(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}:${Re(t.wait.wait_key)}${t.stepId?`:${t.stepId}`:""}`}interactionWith(t){const n=this.snapshot.interaction;return n&&Vf(t.wait)&&!Vf(n.wait)?n:n&&Hy(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||Fn(n)!=="waiting"||Vf(s)||gt(this.snapshot.status)||this.resolvedWaits.has(`${t}:${Re(s.wait_key)}`))return;const o=this.interactionWith({runId:t,wait:s}),l=this.snapshot.interaction;l&&Hy(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||gt(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:!!Re(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=Xi((o=Ue(t.wait.details))==null?void 0:o.tool_calls);return s.length>0&&s.every(l=>{var d;const u=Re((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:Re(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(!Re(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=Gf.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(!aA(p))throw p;const g=p instanceof Error?p.message:"the gateway does not serve the replay view";return Gf.set(o,g),l(g)}if(Gf.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 jE;return m.adopt(d.view,d.etag),this.viewFold=m,this.viewDigest=qy(m.lastEventId),this.adoptView(),this.followView(t,n),this.followLiveReplies(t,n),await this.loadEarlierTurns(t,Re(d.view.session_id),n,s),!0}async loadEarlierTurns(t,n,s,o){var j;const l=this.transport.replayView;if(!l||!n)return;const u=(A,T)=>({id:A,role:"system",level:"warn",title:"History",content:T});if(!l.listSessionTurns){this.viewEarlier={messages:[u(`history:${n}:unlisted`,"Earlier turns of this conversation are not shown: this app's replay view transport cannot list the conversation's turns (createReplayViewTransport provides listSessionTurns).")],tools:[]},this.adoptView();return}const d=this.viewTurnCache.sessionId===n&&this.viewTurnCache.transport===l?this.viewTurnCache:{...Fi(),sessionId:n,transport:l};this.viewTurnCache=d;const f=(A,T=new Map,N=[])=>{const E=A.map(S=>d.turns.get(S)||T.get(S)).filter(S=>!!S);this.viewEarlier={messages:[...N,...E.flatMap(S=>S.messages)],tools:E.flatMap(S=>S.tools)}},m=d.order.indexOf(t);let p,g=!1;if(m>=0&&d.order.slice(0,m).every(A=>d.turns.has(A)))p=d.order.slice(0,m);else{const A=Re((j=this.viewRun)==null?void 0:j.created_at),T=A?d.order.filter(S=>d.turns.has(S)&&d.created.has(S)&&d.created.get(S)<A):[];T.length&&(f(T),this.adoptView());let N;try{N=await l.listSessionTurns(t,{signal:o})}catch(S){if(!this.live(s))return;if(ls(S))throw this.viewTurnCache=Fi(),S;f(T,new Map,[u(`history:${n}:unlisted`,`Earlier turns of this conversation could not be listed: ${S instanceof Error?S.message:String(S)}`)]),this.adoptView();return}if(!this.live(s))return;g=N.length>nu,g&&(N=N.slice(N.length-nu));for(const S of N)S.created_at&&d.created.set(S.run_id,S.created_at);d.order=N.map(S=>S.run_id);const E=d.order.indexOf(t);p=E>=0?d.order.slice(0,E):d.order.filter(S=>S!==t)}const _=new Map,v=p.filter(A=>!d.turns.has(A));let C=0;const x=async()=>{for(;this.live(s);){const A=v[C++];if(!A)return;try{const T=await l.getView(A,{signal:o});if(T.notModified||!T.view)throw new Error("the gateway answered without a view");const N=Rh(T.view);gt(N.status)?d.turns.set(A,{messages:N.messages,tools:N.tools}):_.set(A,{messages:[...N.messages,u(`history:${A}:open`,`This earlier turn is still ${N.status||"running"}; open it to follow or answer it.`)],tools:N.tools})}catch(T){if(!this.live(s))return;if(ls(T))throw this.viewTurnCache=Fi(),T;_.set(A,{messages:[u(`history:${A}:unavailable`,`An earlier turn could not be restored (${A.slice(0,8)}): ${T instanceof Error?T.message:String(T)}`)],tools:[]})}}};if(await Promise.all(Array.from({length:Math.min(4,v.length)},()=>x())),!this.live(s))return;const k=g?[u(`history:${n}:limit`,`Only the last ${nu} turns of this conversation are shown.`)]:[];f(p,_,k),this.adoptView()}adoptView(){var m,p,g;const t=(m=this.viewFold)==null?void 0:m.view;if(!t)return;const n=Rh(t);gt(n.status)&&t.session_id&&this.viewTurnCache.sessionId===t.session_id&&this.viewTurnCache.turns.set(t.root_run_id,{messages:n.messages,tools:n.tools}),this.toolActivities=new Map([...this.viewEarlier.tools,...n.tools].map(_=>[_.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)!gt(v)||this.viewTerminalRuns.has(_)||(this.viewTerminalRuns.add(_),this.endLiveRepliesOfRun(_,v));this.openLlmSteps=new Set(n.openLlmCalls);const s=gt(n.status),o=this.snapshot.messages.filter(_=>rA.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&&Re(d.wait.wait_key)===Re(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:[...this.viewEarlier.messages,...n.messages,...o],interaction:u,loading:!1,...s?{autoApproveTools:!1}:{}}),(this.stopRequested||this.forcedStop)&&this.recomputeStop();const f=qy((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||gt(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&&!gt(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)||gt(Fn(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:Xi(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)&&!gt(Fn(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(gt(Fn(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=Xi(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=Re(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=Gy(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 Xi(g==null?void 0:g.items))this.ingestItem(m,_)}}ingestSessionTurn(t,n,s){if(!t)return;const o=Re(t.run_id)||n,l=Ue(t.input_data)||Ue(t.input)||{},u=Re(t.prompt)||Gy(l);u&&this.addMessage({id:`turn:${o}:user`,role:"user",content:u,ts:Re(t.created_at)||void 0});const d=this.historicalRunFailures.get(o);if(d){const g=Re(t.answer)||Ih(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&&gt(Fn(s))?po(s.output):"")||(s?Re(t.answer)||Ih(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:Re(t.updated_at)||void 0})}async hydrateHistoricalSessionRuns(t,n,s){const o=[...new Set(t.map(f=>Re(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,sl(zE(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=nA(_)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:v,detail:_ instanceof Error?_.message:Re((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=sA(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=sl(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 Jy(o))m!==l&&this.catchUpAndWatch(m,this.generation)}}foldRecord(t,n,s){var p,g,_;const o=Mh(n),l=Re(o.type).toLowerCase(),u=Ue(n.result),d=Re(n.status).toLowerCase(),f=Ky(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=po(u)||po(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=Re(v.name)||Re(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 j=po(k);if(j){const A=Re((p=Ue(k))==null?void 0:p.level).toLowerCase(),T=A==="error"?"error":["warn","warning"].includes(A)?"warn":"info";this.addMessage({id:`event:${t}:${s}`,role:"system",title:"Workflow",content:j,level:T,ts:f})}}if(["abstract.status","abstractcode.status"].includes(x)){const j=Ue(k),A=j?j.status??j.text??j.value:k,T=Date.parse(f||"");!gt(this.snapshot.status)&&typeof A=="string"&&(!Number.isFinite(T)||T>=this.displayStatusAt)&&(Number.isFinite(T)&&(this.displayStatusAt=T),this.set({...this.snapshot,displayStatus:A.trim()}))}if(x==="abstract.tool_policy_decision"){const j=vC(Ue(k));if(j){this.addMessage({id:`policy:${t}:${s}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",content:yu(j.provenance),ts:f});for(const A of j.calls){const T={...j.provenance,...A.matched?{matched:A.matched}:{}};this.toolPolicyByCall.set(`${t}:${A.callId}`,T);for(const N of this.toolActivities.values())N.runId===t&&N.callId===A.callId&&this.upsertTool(N)}}}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(x)){const j=po(k);j&&this.addMessage({id:`event:${t}:${s}`,role:"system",title:"Tool activity",content:j,ts:f})}}const m=H_(n);if(d==="waiting"&&m&&!gt(this.snapshot.status)&&!gt(Fn(this.runStates.get(t)||null))&&(this.resolvedWaits.delete(`${t}:${Re(m.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:t,wait:m,...Re(n.step_id)?{stepId:Re(n.step_id)}:{}})})),l==="tool_calls")for(const v of U_(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=Re((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=Re(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(Mh(n).payload)||{},d=Ue(n.result),f=Re(u.name)||Re(d==null?void 0:d.name),m=Ue(u.payload!==void 0?u.payload:d==null?void 0:d.payload);f==="abstract.status"&&Re(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:Re(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=Re(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 W_(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=T_(n)}catch(f){this.fail(f,!1);return}const o=`${s.run_id}:${s.call_id}`;if($_(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?gt(String(((o=n.runs.find(l=>l.run_id===t))==null?void 0:o.status)||""))||t===this.rootRunId&&gt(String(n.status||"")):gt(Fn(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:BC(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:Re((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),gt(Fn(n))&&this.endLiveRepliesOfRun(t,Fn(n)),t!==this.rootRunId){gt(Fn(n))&&((l=this.snapshot.interaction)==null?void 0:l.runId)===t?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(t,n);return}const s=Fn(n),o=gt(s);if(o){const u=po(n.output);u&&this.upsertFinal(t,u,Ky(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:sl(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&&!gt(Fn(this.runStates.get(t)||null));){if(await this.waitForRetry(2e3),!this.live(n)||this.rootRunId!==t||gt(Fn(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 iA(e){const t=y.useMemo(()=>new oA(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 pa(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 Yy(e){return["session","workflow","run","global"].includes(e)?e:null}function Lr(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 lA(e,t){const n=e.wait,s=yn(n.wait_key),o=[Lr(n),Lr(pa(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,d=pa(u.result),f=pa(d==null?void 0:d.wait),m=pa(u.effect),p=pa(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(Lr(u),Lr(p),Lr(pa(p==null?void 0:p.details)),Lr(f),Lr(pa(f==null?void 0:f.details)))}return o}function Hf(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function K_(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function cA(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?K_(t,n,o):null}function uA(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=Yy(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=lA(e,Array.isArray(t)?t:[]),d=new Map;for(const _ of u){const v=Yy(_.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),j=Hf(v,_);if(j&&j!==k)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const A=K_(v,k,_.name);d.set(`${A.scope}\0${A.scopeId}\0${A.name}`,A)}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=Hf(l,_);v&&f.add(v)}if(yn(n==null?void 0:n.run_id)===e.runId){const _=Lr(n||null),v=Hf(l,_);v&&f.add(v)}const p=[...f].map(_=>cA(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 dA(e){return a.jsx(m_,{text:e,images:"link"})}const fA={trigger:"Trigger",answer:"Automation"};function J_(e,t){return a.jsx(j_,{...t,message:{id:`${e.runId}:${e.kind}`,role:e.role,content:e.text,title:fA[e.kind],runId:e.runId},images:"link"})}const hA={renderText:dA,renderTurn:J_};function mA(e){const{fetchGateway:t,messageProps:n,...s}=e,o=s.onOpenResource??(t?l=>eE(t,l.url,{name:l.name}):void 0);return a.jsx(W0,{...s,onOpenResource:o,...hA,renderTurn:l=>J_(l,n)})}function pA(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function gA(e,t,n={}){var m;if(!e)return null;const s=pA(e)?z_(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(S=>String((S==null?void 0:S.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,j=xo,A=C?{approveForSessionLabel:j.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 S;await t.approveWithPolicyChange(g,()=>{S=C()}),S&&await S.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 T=A,N=[];const E=n.sessionPolicy;if(E){const S=t.approveAllForSession,I=t.approveKindForSession,M=t.denyToolForSession,B=t.denyKindForSession,G=t.sessionPolicyStatus;if(typeof S!="function"||typeof I!="function"||typeof M!="function"||typeof B!="function"||typeof G!="function")throw new Error("presentInteraction: sessionPolicy needs a WorkflowSessionController (approveAllForSession, approveKindForSession, denyToolForSession, denyKindForSession, sessionPolicyStatus).");const Z=G.call(t),oe=E.ask?[...E.ask]:void 0,z=(V,Y)=>{var W;const J=String(((W=V==null?void 0:V.scope)==null?void 0:W[Y])||"").trim();return J?`Applies: ${J}`:j.noScopeNote},F=V=>({outcomeNote:[Iy(V==null?void 0:V.clamped),z(V,"approve")].filter(Boolean).join(" ")}),L=V=>({outcomeNote:`${j.denyForChatNote} ${z(V,"deny")}`}),q=Iy(Z.clamped);if(Z.mode==="unavailable")T={scopeNote:j.unavailablePolicyNote(Z.reason||"")};else if(Z.mode==="gateway"){const V=[...new Set(p.map(R=>{var K;return String((R==null?void 0:R.toolset)||"").trim()||String(((K=E.toolsetOf)==null?void 0:K.call(E,String((R==null?void 0:R.name)||"")))||"").trim()}).filter(Boolean))],Y=(oe||[]).map(R=>String(R).trim()).filter(Boolean),J=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(R=>Object.prototype.hasOwnProperty.call(W.deny||{},R)):[],T={approveForSessionLabel:j.allowForChat,approveForSessionDescription:V.length?`Each of ${(()=>{const R=[`“${j.allowForChat}” (every tool)`,...V.map(K=>`“${j.allowKindForChat(K)}” (that toolset only)`)];return`${R.slice(0,-1).join(", ")} or ${R[R.length-1]}`})()} approves this batch and stores a policy for this chat on the gateway: the later tool calls it covers, in every run of this chat, run without asking, until the policy is reset. ${J} Tools the gateway does not authorize stay uncovered.`:`“${j.allowForChat}” approves this batch and stores a policy for this chat on the gateway: later tool calls of every run of this chat run without asking, until the policy is reset. ${J} Tools the gateway does not authorize stay uncovered.`,broadScopeSummary:`The broader choices keep allowing later tool calls of this chat until the policy is reset. ${J}`,onApproveForSession:async()=>F(await S.call(t,g,{...E.maxRiskRank!==void 0?{maxRiskRank:E.maxRiskRank}:{},...oe?{ask:oe}:{}})),approveKinds:V.map(R=>({kind:R,label:j.allowKindForChat(R),onApprove:async()=>F(await I.call(t,g,R,oe?{ask:oe}:{}))})),denyOptions:[..._.map(R=>({key:`tool:${R}`,label:j.denyToolForChat(R),onDeny:async()=>L(await M.call(t,g,R,oe?{ask:oe}:{}))})),...V.map(R=>({key:`kind:${R}`,label:j.denyKindForChat(R),onDeny:async()=>L(await B.call(t,g,R,oe?{ask:oe}:{}))}))],...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. ${z(W,"approve")}`}:{},...q?{notCovered:q}:{}}}else T=C?{...A,scopeNote:j.localChatPolicyNote}:{approveForSessionLabel:j.allowForRun,onApproveForSession:async()=>{await S.call(t,g,{})},scopeNote:j.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(hm,{tools:p.map((S,I)=>({id:String((S==null?void 0:S.call_id)||(S==null?void 0:S.id)||I),runId:s.runId,name:(S==null?void 0:S.name)||"Tool",arguments:S==null?void 0:S.arguments,status:"waiting"}))}),a.jsxs("details",{children:[a.jsx("summary",{children:"Review full tool arguments (JSON)"}),a.jsx(Ao,{value:p.length?p:u})]})]}),approveLabel:xo.allowOnce,denyLabel:xo.deny,approveAllLabel:v?xo.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,...v?{broadScopeSummary:`“${xo.allowAll}” changes your tool permissions for future turns too.`}:{},...T,...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=uA(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 q_{constructor(){Bt(this,"_buffer","");Bt(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 yA(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 wA(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 Y_ extends Error{constructor(n,s){super(n);Bt(this,"status");Bt(this,"retry_after_s");Bt(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 wA(e);throw new Y_(`${t}: ${n}`,{status:e.status,retry_after_s:yA(e),body_text:n})}class vA{constructor(t){Bt(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(),pe("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(),pe(`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(),pe(`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(),pe(`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(),pe(`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(),pe(`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 q_,_=n.on_delta,v=n.on_delta_error;for(;;){const{value:x,done:k}=await m.read();if(k)return;const j=p.decode(x,{stream:!0});g.push(j,A=>{if(_&&v){const T=A.event||"message",N=A.data??"";let E;try{E=R_(T,N)}catch(S){v(S instanceof Error?S:new Error(String(S)),{event:T,data:N});return}if(E){_(E);return}}if(!(A.event!=="step"||!A.data))try{const T=JSON.parse(A.data);T&&typeof T.cursor=="number"&&T.record&&l(T)}catch{}})}}async list_bundles(){const t=await fetch(ut(this._cfg.base_url.trim(),pe("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(),pe("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(),pe("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(),pe("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(),pe(`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(),pe(`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(),pe(`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(),pe("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(),pe(`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(),pe(`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(),pe(`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(),pe("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(),pe("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(),pe(`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(),pe("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(),pe("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(),pe("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(),pe(`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(),pe(`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(),pe(`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(),pe("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(),pe("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(),pe("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 _l(){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 at(e,t={}){var o;if(!e.startsWith(`${Wr}/`))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(_l()))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 Y_(u||`Gateway request failed (${s.status})`,{status:s.status,body_text:l})}if(s.status!==204)return s.json()}const Vr=new vA({base_url:""});function At(e){return e instanceof Error?e.message:String(e)}function Br(){return Fr()}async function _A(e,t,n){const{blob:s}=await Vr.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 bA={app:"code",name:"AbstractCode"},xA=["How do I change the model?","Where are my files and generated outputs?","How do I schedule an automation?"],kA=(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(_l()))n.set(o,l);return fetch(e,{...t,headers:n,credentials:"same-origin"})};function SA(e){return vE(bA,kA,{connected:e,suggestions:xA,placeholder:"Ask about AbstractCode…"})}function Io({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 jA(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 NA(e,t){return t?"drawers":e?"overlay":"docked"}function CA(e,t){return t==="drawers"?e:!1}function EA(e){return e.key!=="Escape"||e.defaultPrevented||e.overlayOpen?null:e.sidebarOpen?"sidebar":null}function AA(e=typeof document<"u"?document:void 0){return!!(e!=null&&e.querySelector('[role="dialog"], [role="alertdialog"]'))}function $A(e){const t=Number.parseFloat(String(e??"").trim());return Number.isFinite(t)&&t>0}let zi=null;function TA(){var s;if(zi)return zi;if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const e=document.documentElement,t=()=>{const o=$A(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(),zi=()=>{var o;n.disconnect(),(o=window.visualViewport)==null||o.removeEventListener("resize",t),zi=null},zi}function RA(e){const t=e.isDrawer&&!e.open;return a.jsx("aside",{className:"code-sidebar","aria-label":"Conversations",...t?{inert:""}:{},children:e.children})}const Lu=(e,t)=>at(e,{method:t.method,...t.body!==void 0?{body:JSON.stringify(t.body)}:{}}),Ou="Connect to your gateway to change workspaces.";function Q_(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 yy(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(Ou);const g=await yy(n,t).save(p);return l(g),g},[f,n]);return{state:o,error:u,save:m}}function X_(e){return e.automation?a.jsx(OA,{...e,automation:e.automation}):a.jsx(IA,{...e})}function IA({connected:e,sessionId:t,onOpenDefaults:n,refreshKey:s,request:o=Lu}){const l=Q_(e,t?{level:"session",session:t}:null,o,s),u=e?t?null:"Open a conversation to choose its workspaces.":Ou;return a.jsxs(a.Fragment,{children:[a.jsx(lm,{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 MA({open:e,onClose:t,connected:n,onChanged:s,request:o=Lu}){const l=Q_(n&&e,e?{level:"account"}:null,o),u=n?null:Ou,d=y.useCallback(async f=>{const m=await l.save(f);return s==null||s(),m},[l,s]);return a.jsx(Qk,{open:e,onClose:t,title:"My default workspaces",size:"narrow",children:a.jsx(lm,{level:"account",idPrefix:"code-workspace-account",state:l.state,save:d,loadError:u??l.error,unavailableReason:u})})}function LA(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 jh(s)(t).then(g=>p&&l(g)).catch(g=>p&&d(`Could not read the workspaces: ${im(g)||At(g)}`)),()=>{p=!1}},[e,f,s]);const m=y.useCallback(async p=>{const g=await jh(s)(p);l(g),n(p)},[s,n]);return{effective:o,error:u,onChange:m}}function OA({connected:e,automation:t,idPrefix:n="code-workspace-automation",request:s=Lu}){const o=LA(e,t.value,t.onChange,s),l=e?null:Ou;return a.jsx(lm,{level:"run",idPrefix:n,value:t.value,effective:o.effective,onChange:o.onChange,loadError:l??o.error,unavailableReason:l})}const Z_="abstractcode.sidebar.panels",Bi={automations:!0,conversations:!0};function PA(e){try{const t=e==null?void 0:e.getItem(Z_);if(!t)return{...Bi};const n=JSON.parse(t);if(!n||typeof n!="object")return{...Bi};const s=n;return{automations:typeof s.automations=="boolean"?s.automations:Bi.automations,conversations:typeof s.conversations=="boolean"?s.conversations:Bi.conversations}}catch{return{...Bi}}}function DA(e,t){try{t==null||t.setItem(Z_,JSON.stringify(e))}catch{}}function FA(e,t){return{...e,[t]:!e[t]}}function xu(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function zA(){const[e,t]=y.useState(()=>PA(xu())),n=y.useCallback(s=>{t(o=>{const l=FA(o,s);return DA(l,xu()),l})},[]);return[e,n]}const wm=e=>({toggle:`code-panel-${e}-toggle`,region:`code-panel-${e}`});function eb(e){const t=wm(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(ue,{name:"chevronDown",size:14}),a.jsx("span",{children:e.label})]}),e.actions?a.jsx("span",{className:"code-panel-actions",children:e.actions}):null]})}function BA(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 WA(e){const t=wm("conversations");return a.jsxs("section",{className:"code-panel code-conversations","data-open":e.open?"true":"false",children:[a.jsx(eb,{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 UA(e){return e.split("/").filter(Boolean).pop()||"Gateway managed"}const tb="abstractcode.sidebar.archived",Qy={automations:!1,conversations:!1};function VA(e){try{const t=e==null?void 0:e.getItem(tb),n=t?JSON.parse(t):null;return!n||typeof n!="object"?{...Qy}:{automations:n.automations===!0,conversations:n.conversations===!0}}catch{return{...Qy}}}function GA(){const[e,t]=y.useState(()=>VA(xu())),n=y.useCallback(s=>{t(o=>{var u;const l={...o,[s]:!o[s]};try{(u=xu())==null||u.setItem(tb,JSON.stringify(l))}catch{}return l})},[]);return[e,n]}function nb(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(ue,{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 sb(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(ue,{name:"loader",size:12}):a.jsx(ue,{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 HA="Archive this conversation? It stays searchable and auditable; it just leaves this list.";function KA(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:HA}),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(ue,{name:"loader",size:12}):a.jsx(ue,{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 JA="abstractcode.agent.v1";function vm(e){return!!(e!=null&&e.interfaces.some(t=>[JA,"abstractassistant.agent.v1"].includes(t)))}function yt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Lh(e){return Array.isArray(e)?e:[]}function ze(e){return typeof e!="string"?void 0:e.trim()||void 0}function qA(e){return Lh(e).flatMap(t=>{const n=ze(t);return n?[n]:[]})}function rl(e,t=0){if(typeof e!="number"||!Number.isFinite(e))return;const n=Math.trunc(e);return n>=t?n:void 0}function _m(e,t){if(Array.isArray(e))return e;const n=yt(e);if(!n)return[];for(const s of t)if(Array.isArray(n[s]))return n[s];return[]}function rb(e){const t=yt(e);return t?{...t}:void 0}function Xy(e){const t=rb(e.input_schema??e.inputSchema??e.inputs_schema);if(t)return t;const n=yt(e.inputs);if(n&&("properties"in n||"type"in n||"$schema"in n))return{...n}}function YA(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 QA(e,t,n){return e?`${e}${t?`@${t}`:""}:${n}`:n}function Zy(e,t,n){var d;const s=yt(e),o=ze((s==null?void 0:s.default_bundle_id)??(s==null?void 0:s.defaultBundleId)),l=_m(e,["items","bundles"]),u=[];for(const f of l){const m=yt(f);if(!m)continue;const p=yt(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=YA(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 Lh(m.entrypoints)){const j=yt(k);if(!j||!n.includeDeprecated&&(j.deprecated===!0||j.enabled===!1))continue;const A=ze(j.flow_id??j.flowId??j.id);if(!A)continue;const T=qA(j.interfaces??j.interface_ids??j.interfaceIds);if(n.interfaceId&&!T.includes(n.interfaceId))continue;const N=ze(j.workflow_id??j.workflowId)??QA(_,v,A),E=C?C===A:Lh(m.entrypoints).length===1;u.push({id:`${t}:${N}`,workflowId:N,..._?{bundleId:_}:{},...v?{bundleVersion:v}:{},flowId:A,name:ze(j.name??j.title)??A,description:ze(j.description)??"",interfaces:T,...Xy(j)?{inputSchema:Xy(j)}:{},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 XA(e,t,n={}){const s=[...Zy(e,"private",n),...Zy(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 ZA(e){const t=yt(e);if(!t)return;const n=yt(t.workflow_selection??t.workflowSelection);if(n)return n;const s=yt(t._runtime),o=yt((s==null?void 0:s.workflow_policy)??(s==null?void 0:s.workflowPolicy));if(o)return o;const l=yt(t.input_data??t.inputData),u=yt(l==null?void 0:l._runtime);return yt((u==null?void 0:u.workflow_policy)??(u==null?void 0:u.workflowPolicy))}function e$(e,t){const n=ZA(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 t$(e){const t=yt(e)??{},n=yt(t.policy)??t,s=rl(n.max_attachment_bytes??n.maxAttachmentBytes,1);return{raw:{...n},...s!==void 0?{maxAttachmentBytes:s}:{}}}function ew(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 n$(e){var l;const t=_m(e,["items","tools"]),n=yt((l=yt(e))==null?void 0:l.command_sandbox),s=new Set,o=[];for(const u of t){const d=yt(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=rl(d.risk_rank??d.riskRank),g=rb(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}:{},...ew(d,n)?{sandboxState:ew(d,n)}:{},raw:{...d}})}return o.sort((u,d)=>u.name.localeCompare(d.name))}function s$(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 tw={waiting:4,running:3,failed:2,done:1,unknown:0};function go(e){return ze(e.updated_at??e.updatedAt??e.finished_at??e.finishedAt??e.created_at??e.createdAt)}function yo(e){if(!e)return Number.NEGATIVE_INFINITY;const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function nw(e){var u;const t=ze(e);if(t)return t;const n=yt(e);if(!n)return;const s=ze(n.prompt);if(s)return s;const o=yt(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=yt(o==null?void 0:o.context))==null?void 0:u.task)}function ku(e,t={}){const n=yt(e),s=(n==null?void 0:n.has_more)===!0||(n==null?void 0:n.hasMore)===!0,o=_m(e,["items","runs"]),l=new Map;o.forEach((d,f)=>{const m=yt(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)=>yo(go(k.run))-yo(go(x.run))||x.index-k.index),p=[...f].sort((x,k)=>{const j=ze(x.run.created_at??x.run.createdAt)??go(x.run),A=ze(k.run.created_at??k.run.createdAt)??go(k.run);return yo(j)-yo(A)||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=s$(x);tw[k]>tw[_]&&(_=k)}let v;for(const{run:x}of p){const k=ze(x.run_id??x.runId??x.id);if(v=(k?nw(t[k]):void 0)??nw(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:_,...go(m[0].run)?{updatedAt:go(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)=>yo(f.updatedAt)-yo(d.updatedAt)||d.sessionId.localeCompare(f.sessionId))}function Su(e){return e?{...e}:{}}function Wi(e){if(e!==void 0)return e.flatMap(t=>{const n=ze(t);return n?[n]:[]})}function r$(e,t,n){var x,k,j,A,T,N,E;const s=(S,I)=>{var M,B;!vm(t.workflow)&&!((B=yt((M=t.inputSchema)==null?void 0:M.properties))!=null&&B[S])||I!==void 0&&n&&(e[S]=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",Wi(t.tools)??[]);const u=Wi(t.skills);u!=null&&u.length&&(e.skills=u);const d=ze((j=t.workspace)==null?void 0:j.root);d!==void 0&&(e.workspace_root=d),s("system",ze(t.system));const f=Su(yt(e._runtime)),m=(S,I)=>{I!==void 0&&n&&(f[S]=I)};if(m("provider",o),m("model",l),m("thinking",ze(t.reasoning)),m("speculation",t.speculation),t.streamReplies!==void 0&&m("stream",FC(t.streamReplies).stream),m("system_prompt_extra",ze(t.systemPromptExtra)),t.tools!==void 0){const S=Wi(t.tools)??[],I=Array.isArray(f.allowed_tools)?f.allowed_tools:null;f.allowed_tools=I?S.filter(M=>I.includes(M)):S}if(t.review!==void 0&&t.reviewCapable!==!1){m("review_mode",t.review.enabled);const S=t.review.enabled?rl(t.review.maxRounds,1):void 0;m("review_max_rounds",S)}const p=Wi((A=t.toolPolicy)==null?void 0:A.autoApproveTools),g=Wi((T=t.toolPolicy)==null?void 0:T.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 _=Su(yt(e._limits)),v=rl((N=t.limits)==null?void 0:N.maxIterations,1),C=rl((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 a$(e){var s;const t=Su(e.schemaInputs),n=vm(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=Su(yt(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 r$(t,e,!0),t}function o$(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 i$(e,t){const n=e?Date.parse(e):NaN;return Number.isNaN(n)?"":`${uu(Math.max(0,t-n))} ago`}function ab(e){const t=o$(e.summary);if(!t)return null;const n=i$(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(Gk,{tone:"error",size:"sm",className:"code-notif-pill",title:t.at?`${t.text}
90
- ${iu(t.at)}`:t.text,children:t.text}),n?a.jsx("span",{className:"code-notif-time",children:n}):null]})}const sw=(e,t,n)=>`${e} ${e===1?t:n}`;function ob(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",sw(e.turnCount,"turn","turns")];return typeof e.toolCalls=="number"&&e.toolCalls>0&&o.push(sw(e.toolCalls,"tool","tools")),o.join(" · ")}function ib(e){return e.prompt||`Conversation ${e.sessionId.slice(0,8)}`}function l$(e){const{item:t}=e,n=ib(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:ob(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(Kh,{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 lb(e){return e.attention.pending_waits>0}function cb(){return a.jsx("span",{className:"code-waiting-badge","data-field":"waiting",children:"waiting for you"})}function ub(e){const t=To(e.summary,[],e.busy).active;return a.jsx(Ur,{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
- ${il("active",e.summary)}`:il("active",e.summary),onChange:()=>e.onToggle()})}function c$(e,t){const n=Wv(e,t);return{first:[n.cadence,n.last].filter(Boolean).join(" · "),second:n.next||"",scheduled:e.trigger.source_id==="schedule"}}function u$(e){const t=e.summary,n=c$(t,e.nowMs),s=lb(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(cb,{}):null,a.jsxs("small",{className:"code-card-meta","data-field":"timing",children:[n.scheduled?a.jsx(ue,{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(ub,{className:"code-card-switch",iconOnly:!0,summary:t,busy:e.busy,onToggle:e.onToggleActive})]}),a.jsx(ab,{summary:t,nowMs:e.nowMs,className:"code-card-notif"})]})}const d$="runs?root_only=true&archived_only=true&include_ledger_len=false&include_metrics=true&limit=200",f$=e=>`sessions/${encodeURIComponent(e)}/archive`,h$=e=>`sessions/${encodeURIComponent(e)}/unarchive`;async function m$(e,t=at){return t(pe(f$(e)),{method:"POST",body:"{}"})}function p$(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 rw(e){const t=e==null?void 0:e.archived_sessions;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function g$(e){const t=e.request??at,[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(pe(d$),{signal:p.signal}).then(async g=>{if(p.signal.aborted)return;const _=ku(g);s(_);const v={};await Promise.all(_.filter(C=>!C.prompt).slice(0,50).map(async C=>{try{v[C.firstRunId]=await t(pe(`runs/${encodeURIComponent(C.firstRunId)}/input_data`),{signal:p.signal})}catch{}})),!p.signal.aborted&&Object.keys(v).length&&s(ku(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(sb,{id:p.sessionId,title:ib(p),meta:ob(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(pe(h$(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(Io,{children:"Loading archived conversations…"})})}const Un=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},y$=["context","messages","attachments","media"];function w$(e){return y$.includes(e)}function v$(e,t){const n=Un(t);return Object.fromEntries(Object.keys(Un(e.properties)).flatMap(s=>["_runtime","_limits"].includes(s)||w$(s)||!Object.prototype.hasOwnProperty.call(n,s)?[]:[[s,structuredClone(n[s])]]))}function aw(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 _$(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 rr(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 b$(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 x$(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 Kf(e,t){var o,l,u;if(!e)return[];const n={...rr(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 db(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 No=mk(e=>at(e));function k$(e){try{const t=$w(e);return t?{provider:t.provider,model:t.model}:void 0}catch{return}}function S$(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 No;const s=e==="voice_provider",o=pe(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`:pe(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 at(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 at(`${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 j$=["gateway_default","on","off"],fb={status:"loading"};function N$(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 C$(e){return j$.includes(e)?e:"gateway_default"}function E$(e,t){return e==="on"&&t.status!=="supported"?"gateway_default":e}function A$(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 $$(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 T$(e,t){const 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 R$(e,t){return e.some(n=>n.message.id===t.message.id)?[...e]:[...e,t]}function I$(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 M$(e){return e.status==="supported"&&e.gatewayDefault!==null?`Gateway default (${e.gatewayDefault?"on":"off"})`:"Gateway default"}const Xt="@default",ln="abstractcode.agent.v1";function Fs(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 L$="gateway does not report a default agent workflow";function O$(e,t=ln){var p,g;const n=Fs(e);if(!n)return{status:"unavailable",reason:"the gateway's workflow list could not be loaded"};const s=Fs(n.default_agent_workflows);if(!s)return{status:"unavailable",reason:L$};const o=Fs(s[t]);if(!o){const _=Bn((g=Fs((p=Fs(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 P$(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 D$(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 Jf(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 F$(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 z$(e,t){return e===Xt?Ru:(t==null?void 0:t.workflowId)??e}function B$(e,t){return e===Ru||!t?Xt:`${t.registryScope}:${t.value}`}function W$(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 bm(e){var n,s;const t=Fs((s=Fs((n=Fs(e))==null?void 0:n.input_data))==null?void 0:s.workflow_selection);return Bn(t==null?void 0:t.source)}function U$(e){var t;return bm(e.restoredInputs)==="gateway_default"?Xt:(t=e.restored)==null?void 0:t.id}function V$(e){return!Fs(e)||bm(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 G$(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 H$(e){const t=Fs(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 qf=25,K$=4,J$=e=>`runs?root_only=true&include_ledger_len=false&include_metrics=true&limit=${e}`;function q$(e){const t=(e==null?void 0:e.items)??(e==null?void 0:e.runs);return Array.isArray(t)?t.length:0}async function Y$(e,t){let n=Math.max(1,t)*K$;for(;;){const s=await e(n);if((s==null?void 0:s.has_more)!==!0||q$(s)<n||ku(s).length>t)return s;n*=2}}function Q$(e,t){return{sessions:e.slice(0,t),hasMore:e.length>t}}const Yf={gatewayDefault:{status:"loading"},executable:{status:"idle",data:null,error:""},workflows:[],policy:null,tools:[],sessions:[],capabilities:{},capabilitiesLoading:!0,sessionToolPolicy:null,capabilitiesError:"",toolCatalog:[],toolWarnings:[],streaming:fb,loading:!1,sessionsLoaded:!1,errors:[],hasMore:!1,archivedSessions:0};function X$(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 Z$(e,t){const[n,s]=y.useState(Yf),o=y.useRef(qf),l=y.useRef(0),u=y.useRef(),d=y.useRef(0),f=y.useRef(),m=y.useRef({identity:"",values:{}}),p=y.useCallback(j=>Y$(A=>at(pe(J$(A)),{signal:j}),o.current),[]),g=j=>Q$(ku(j,m.current.values),o.current),_=y.useCallback(async(j,A,T)=>{const N=()=>d.current!==A||T.aborted,E=g(j).sessions.filter(S=>!S.prompt&&!(S.firstRunId in m.current.values));for(let S=0;S<E.length;S+=4){if(N()||(await Promise.all(E.slice(S,S+4).map(async I=>{try{const M=await at(pe(`runs/${encodeURIComponent(I.firstRunId)}/input_data`),{signal:T});N()||(m.current.values[I.firstRunId]=M)}catch(M){!T.aborted&&(M==null?void 0:M.status)===401&&t()}})),N()))return;s(I=>({...I,sessions:g(j).sessions}))}},[t]),v=y.useCallback(async()=>{var T;if(!e)return;const j=++d.current;(T=f.current)==null||T.abort();const A=new AbortController;f.current=A,s(N=>({...N,loading:!0}));try{const N=await p(A.signal);if(d.current!==j)return;const E=g(N);s(S=>({...S,loading:!1,sessions:E.sessions,sessionsLoaded:!0,hasMore:E.hasMore,archivedSessions:rw(N),errors:S.errors.filter(I=>!I.startsWith("Conversations: "))})),await _(N,j,A.signal)}catch(N){if(A.signal.aborted||d.current!==j)return;(N==null?void 0:N.status)===401&&t(),s(E=>({...E,loading:!1,errors:[...E.errors.filter(S=>!S.startsWith("Conversations: ")),`Conversations: ${At(N)}`]}))}},[e,p,_,t]),C=y.useCallback(async()=>{var oe,z;const j=++l.current,A=++d.current;(oe=f.current)==null||oe.abort(),(z=u.current)==null||z.abort();const T=new AbortController;if(u.current=T,m.current.identity!==e&&(m.current={identity:e,values:{}}),!e){s(Yf);return}s(F=>({...F,loading:!0,capabilitiesLoading:!0,errors:[],executable:{...F.executable,status:"loading",error:""}}));const N=F=>at(pe(F),{signal:T.signal}),E=await Promise.allSettled([N("bundles?all_versions=true&include_drafts=false"),N("workspace/policy"),N("discovery/tools"),p(T.signal),N("discovery/capabilities"),N("workflow-catalog?scope=tenant"),N("config/capability-defaults"),N(Mv(ln))]);if(l.current!==j)return;const S=F=>E[F].status==="fulfilled"?E[F].value:void 0,I=[];E.forEach((F,L)=>{var q,V;F.status==="rejected"&&(((q=F.reason)==null?void 0:q.status)===401&&t(),!(L===5&&[403,404,501].includes((V=F.reason)==null?void 0:V.status))&&L!==7&&I.push(`${["Workflows","Workspace policy","Tools","Conversations","Capabilities","Shared workflows","Gateway defaults"][L]}: ${At(F.reason)}`))});let M=[];if(E[2].status==="fulfilled")try{M=p1(S(2))}catch(F){I.push(`Tools: ${At(F)}`)}const B=d.current===A,G=g(S(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:a0(S(7),ln),error:""}}catch(F){Z={status:"error",data:null,error:String((F==null?void 0:F.message)||F)}}s(F=>({executable:Z,workflows:XA(S(0),S(5)),policy:S(1)?t$(S(1)):null,tools:n$(S(2)),sessions:B&&S(3)?G.sessions:F.sessions,sessionsLoaded:F.sessionsLoaded||!!(B&&S(3)),capabilities:X$(S(4)),capabilitiesLoading:!1,sessionToolPolicy:k1(S(4)),toolCatalog:M,toolWarnings:g1(S(2)),capabilitiesError:E[4].status==="rejected"?`Could not read the gateway's capabilities: ${At(E[4].reason)}`:"",streaming:N$(S(4),E[4].status==="rejected"?At(E[4].reason):void 0),defaultModel:k$(S(6)),gatewayDefault:O$(S(0)),loading:!1,errors:I,hasMore:B&&S(3)?G.hasMore:F.hasMore,archivedSessions:B&&S(3)?rw(S(3)):F.archivedSessions})),B&&S(3)&&await _(S(3),A,T.signal)},[e,t,p,_]);y.useEffect(()=>(o.current=qf,s(Yf),C(),()=>{var j,A;l.current+=1,d.current+=1,(j=u.current)==null||j.abort(),(A=f.current)==null||A.abort()}),[C]);const x=y.useCallback(()=>{o.current+=qf,v()},[v]),k=y.useCallback(j=>{s(A=>({...A,sessions:A.sessions.filter(T=>T.sessionId!==j),archivedSessions:A.archivedSessions+1})),v()},[v]);return{...n,refresh:C,loadMore:x,forgetSession:k}}async function Qf(e){if(e.inputSchema)return aw(e.inputSchema);if(!e.bundleId)return;const t=encodeURIComponent(e.bundleId),n=encodeURIComponent(e.flowId),s=e.registryScope==="tenant_catalog"&&e.bundleVersion?pe(`workflow-catalog/${t}/versions/${encodeURIComponent(e.bundleVersion)}/flows/${n}/input_schema?scope=tenant`):pe(`bundles/${t}/flows/${n}/input_schema${e.bundleVersion?`?bundle_version=${encodeURIComponent(e.bundleVersion)}`:""}`),o=await at(s),l=aw(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"?pe(`workflow-catalog/${t}/versions/${encodeURIComponent(u)}/flows/${n}?scope=tenant`):pe(`bundles/${t}/flows/${n}?bundle_version=${encodeURIComponent(u)}`),p=await at(m);return f(p),_$(l,p.flow)}const Xf=e=>pe(`runs/${encodeURIComponent(e)}`);function eT(e){return{getRun:(t,n)=>at(Xf(t),{signal:n}),getHistory:(t,n)=>at(`${Xf(t)}/history_bundle?include_subruns=true&include_session=true&ledger_mode=full`,{signal:n}),getLedger:(t,n,s)=>at(`${Xf(t)}/ledger?after=${n}&limit=200`,{signal:s}),streamLedger:(t,n,s,o,l,u)=>Vr.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:EE({fetch:(t,n)=>fetch(pe(t),{...n,credentials:"same-origin"})}),submitCommand:(t,n)=>at(pe("commands"),{method:"POST",body:JSON.stringify(t),signal:n})}}function Ps(e){return typeof e=="string"?e.trim():""}function tT(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=Ps(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:Ps(f.description),trustLevel:Ps(f.trust_level)||"unverified",blocked:f.blocked===!0,requiresReview:f.requires_review===!0,reasons:Array.isArray(f.reasons)?f.reasons.map(Ps).filter(Boolean):[],source:p?{source:Ps(p.source),binding:Ps(p.binding),ambiguous:p.ambiguous===!0}:void 0}]}),o=Array.isArray(t.warnings)?t.warnings.map(Ps).filter(Boolean):[],l=Ps(t.shelf),u=Ps(t.shelf_source);return{skills:s.sort((d,f)=>d.name.localeCompare(f.name)),warnings:o,...l?{shelf:l}:{},...u?{shelfSource:u}:{}}}function nT({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 sT(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 rT({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(Ur,{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:sT(e)})]}),checked:t,unavailableReason:u,describedBy:!e.blocked&&n?o:void 0,onChange:s})})}function aT({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 j=new AbortController;return m(!0),g(""),at(pe("skills"),{signal:j.signal}).then(A=>{j.signal.aborted||l(tT(A))}).catch(A=>{j.signal.aborted||g(At(A))}).finally(()=>{j.signal.aborted||m(!1)}),()=>j.abort()},[_]);const C=y.useMemo(()=>new Set(e.map(Ps).filter(Boolean)),[e]),x=y.useMemo(()=>{const j=u.trim().toLocaleLowerCase();return j?o.skills.filter(A=>`${A.name}
93
- ${A.description}
94
- ${A.trustLevel}`.toLocaleLowerCase().includes(j)):o.skills},[o.skills,u]),k=(j,A)=>{const T=A?[...C,j]:[...C].filter(N=>N!==j);t([...new Set(T)])};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:j=>d(j.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(j=>j+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((j,A)=>a.jsx("p",{children:j},`${j}:${A}`))]}):null,!f&&!p&&!o.skills.length?a.jsx(nT,{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(j=>a.jsx(rT,{skill:j,checked:C.has(j.name),disabled:n,lockedReasonId:s,onChange:A=>k(j.name,A)},j.name))]})}const oT="code-settings-locked",ir={provider:"",model:"",reasoning:"",maxIterations:"",maxTokens:"",system:"",workspace:null,toolLayer:{},skills:[],workflow:"@default",streamReplies:"gateway_default"};function iT({tab:e,value:t,onChange:n,toolCatalog:s,toolWarnings:o,toolsNotice:l,automationTools:u,disabled:d,defaultModel:f,workflowDefault:m,streaming:p=fb,lockedReasonId:g=oT,workspaceRootFixed:_,hideStreamReplies:v,lockedText:C,connected:x=!1,automationFolders:k=!1,workspaceRequest:j,sessionId:A,onOpenDefaultWorkspaces:T,workspaceRefreshKey:N}){const E=S=>n({...t,...S});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(ju,{defaultModeLabel:m?"Workflow default":"Gateway default",value:t,onChange:E,disabled:d,effectiveDefault:f,enableSpeculation:!0,inheritLabel:"Gateway default",fetchProviders:No.fetchProviders,fetchModels:No.fetchModels,fetchModelCapabilities:No.fetchModelCapabilities,...m?{defaultHint:f?`Workflow default: ${f.provider} · ${f.model}.`:void 0}:{fetchGatewayDefault:No.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:S=>E({maxIterations:S.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:S=>E({maxTokens:S.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:S=>E({system:S.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(lT,{value:t.streamReplies,onChange:S=>E({streamReplies:S}),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(X_,{connected:x,request:j,sessionId:A,onOpenDefaults:T,refreshKey:N,automation:k?{value:t.workspace,onChange:S=>E({workspace:S})}: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(L1,{catalog:s,layer:"app",value:t.toolLayer,onChange:S=>E({toolLayer:S}),onReset:()=>E({toolLayer:{}}),disabled:d,warnings:o,savedWhere:u?"Saved in this automation's definition":r_,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(aT,{value:t.skills,onChange:S=>E({skills:S}),disabled:d,lockedReasonId:g})]})}function lT({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:M$(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 ow="Your Permissions setting became per-tool defaults on this device — review them";function Zf(e){return`abstractcode.tools.migrated.v1:${e}`}function cT(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 uT(e,t){if(!Do(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 dT(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"?Do(p):uT(p,u))&&(n[p.name]="auto")}return Fo(t,{app:n}).app}function fT(e,t){const n=um(e,{app:t}),s={...t};for(const o of e)Do(o)&&n[o.name].mode==="ask"&&(s[o.name]="auto");return Fo(e,{app:s}).app}function hT(e,t){const n=um(e,{app:t}),s=e.filter(o=>Do(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 mT(e,t){const n={};for(const[s,o]of Object.entries(t))o!=="auto"&&(n[s]=o);return Fo(e,{app:n}).app}const al=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Hc=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!==""):[];function hb(e,t){const n=al(e),s=al(n._runtime),o=Array.isArray(s.allowed_tools)?Hc(s.allowed_tools):Array.isArray(n.tools)?Hc(n.tools):null,l=al(s.tool_policy),u={};for(const d of t)o&&!o.includes(d.name)&&(u[d.name]="off");for(const d of Hc(l.require_approval_tools))u[d]!=="off"&&(u[d]="ask");for(const d of Hc(l.auto_approve_tools))u[d]!=="off"&&(u[d]="auto");return Fo(t,{app:u}).app}function pT(e,t,n,s={}){const o={...al(e)};if(pu(n,{app:t}))return s_(o,eu(n,{app:t},s));const l={...al(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 mb(e){return`abstractcode.workspace.v2:${e}`}function gT(e){try{const{showAllWorkflows:t,tools:n,toolsCustomized:s,permissions:o,toolLayer:l,legacyTools:u,...d}=JSON.parse(e||"{}"),f=cT({tools:n,toolsCustomized:s,permissions:o})??(u&&typeof u=="object"?u:null),m=typeof d.workflow=="string"&&d.workflow.trim()?d.workflow.trim():ir.workflow;return{...ir,...d,workflow:m,speculation:Vh(d.speculation),streamReplies:C$(d.streamReplies),toolLayer:{},...f?{legacyTools:f}:{}}}catch{return ir}}function pb(e){try{return gT(localStorage.getItem(mb(e)))}catch{return ir}}function yT(e,t){const{workflow:n,toolLayer:s,...o}=t,l=n&&n!=="@default"?{...o,workflow:n}:o;try{localStorage.setItem(mb(e),JSON.stringify(l))}catch{}}const Oh=pe("accounts/me/preferences");function Ph(e){var n;const t=ga((n=ga(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 ga(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Dh(e,t=ln){var o;const n=ga(e);if(!n||!Array.isArray(n.apps)||!ga((o=ga(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(ga).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(ga).filter(Boolean).map(l=>({value:String(l.value),label:String(l.label??l.name??l.value),workflowId:String(l.workflow_id??"")}))}}function wT(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 vT(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 _T(e){return e instanceof Error?e.message:String(e)}function iw(e){const t=e;return typeof(t==null?void 0:t.status)=="number"?t.status:0}async function bT(e,t,n){let s,o;try{const l=await e(Oh);s=Dh(l),o=Ph(l)}catch(l){return iw(l)===404?{status:"unsupported"}:{status:"error",message:_T(l)}}if(t&&t!==Xt){let l=!0;if(s.value===null){const u=wT(t);if(u)try{const d=await e(Oh,{method:"PUT",body:JSON.stringify({default_workflow:{[ln]:u}})});s=Dh(d),o=Ph(d)}catch(d){l=iw(d)===400}}l&&n()}return{status:"ok",row:s,timeZone:o}}function xT(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 bT(at,pb(e).workflow,()=>{f&&o.current()}).then(m=>{f&&s(m)}),()=>{f=!1}},[e]);const l=y.useCallback(async f=>{const m=await at(Oh,{method:"PUT",body:JSON.stringify(f)}),p=Dh(m),g=Ph(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 kT(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 lw(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(c1,{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 ST=Nu("voice and camera")??"Voice and camera are not supported in this browser (getUserMedia unavailable).";function jT(){var t;const e=globalThis.navigator;return typeof((t=e==null?void 0:e.mediaDevices)==null?void 0:t.getUserMedia)=="function"}function NT(e){var 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 CT(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 NT(t)}async function xm(e){const t=String(e??"");return t?CT(t):!1}const ET=e=>pe(`runs/${encodeURIComponent(e)}/workspace`),cl=(e,t)=>fetch(e,{...t,credentials:"same-origin"});async function gb(e){await at(`${ET(e)}/open`,{method:"POST"})}function cw(e,t){return typeof e.size_bytes!="number"?null:ym({name:e.name,size:e.size_bytes},t)}function AT(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 $T(e,t,n,s){const o=cw(t,n);if(o)return`Not attached: ${o}`;const l=new AbortController,u=await fetch(I_(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=cw({...t,size_bytes:y_(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 AT(t.name,m)}function TT({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(gm,{fetchGateway:cl,runId:e,title:l,refreshKey:n,className:"code-workspace-browser",copyText:xm,onOpenFolder:()=>gb(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(""),$T(e,p,s,o).then(d).catch(g=>d(At(g))).finally(()=>m(""))},children:a.jsx(ue,{name:f===p.path?"loader":"paperclip",size:15})})},e):null]}):a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(ue,{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 RT=new Set(["abstract.progress","abstractcode.progress"]);function wo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ya(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function IT(e){if(!wo(e))return null;const t=wo(e.effect)?e.effect:null;if(!t||String(t.type||"")!=="emit_event")return null;const n=wo(t.payload)?t.payload:null,s=String((n==null?void 0:n.name)??(n==null?void 0:n.event_name)??"").trim();if(!RT.has(s))return null;const o=wo(e.result)?e.result:null,l=wo(o==null?void 0:o.payload)?o==null?void 0:o.payload:null,u=wo(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 MT(e){let t=null;for(const n of e||[]){const s=IT(n);s&&(t=s)}return!t||t.phase==="complete"||t.final===!0?null:t}function Co(e){return Math.round(e).toLocaleString()}function yb(e){if(!e||e.phase!=="prefill")return null;const t=ya(e.prompt_tokens),n=ya(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 wb(e){return`${Co(e.processed)} / ${Co(e.total)} tokens (${e.percent}%)`}function LT(e){if(!e)return"";if(e.phase==="prefill"){const t=yb(e);if(t)return`Prefill · ${wb(t)}`;const n=ya(e.prompt_tokens);if(n===null||n<=0)return"Prefill";const s=ya(e.cached_tokens),o=ya(e.fed_tokens),l=[];s!==null&&s>0&&l.push(`${Co(s)} cached`),o!==null&&o>0&&l.push(`${Co(o)} new`);const u=l.length?` (${l.join(", ")})`:"";return`Prefill · ${Co(n)} tokens${u}`}if(e.phase==="generate"){const t=ya(e.generated_tokens)??0,n=Math.round(t)===1?"token":"tokens",s=ya(e.tokens_per_second),o=s!==null&&s>0?` · ${Math.round(s)} tok/s`:"";return`Generating · ${Co(t)} ${n}${o}`}return""}function OT(e){return LT(MT(e))}const vb=new Set(["abstract.progress","abstractcode.progress"]),PT=new Set(["abstract.status","abstractcode.status"]);function Ke(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function km(e){const t=Ke(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 Zi(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=Ke(e);if(!n)return"";if(km(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 Pu(e){return`${e>=100?String(Math.round(e)):e.toFixed(e<1?2:1).replace(/\.0+$/,"")} s`}function _b(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 DT(e){const t=String(e||""),n=/T(\d{2}:\d{2}:\d{2})/.exec(t);return n?n[1]:""}function bb(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 uw="visual_react_agent_";function FT(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 zT(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(uw)){const s=t.slice(uw.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=FT(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 BT(e){var n;if(!Array.isArray(e)||!e.length)return"";const t=new Map;for(const s of e){const o=String(((n=Ke(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 WT(e){var d;const t=Ke(e);if(!t)return null;const n=Ke(t.effect);if(!n||String(n.type||"")!=="emit_event")return null;const s=Ke(n.payload),o=String((s==null?void 0:s.name)??(s==null?void 0:s.event_name)??"").trim();if(!vb.has(o))return null;const l=Ke((d=Ke(t.result))==null?void 0:d.payload),u=Ke(s==null?void 0:s.payload);return l||u}function UT(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?Pu(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=yb(t);return p?`prefill ${wb(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 VT(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?Pu(u):null])}function Fh(e){return e.length?String(e[e.length-1].kind||"")==="llm"?UT(e):VT(e):""}function GT(e,t,n){var j;const s=String(e.provider||"").trim(),o=bb(e.model||(t==null?void 0:t.model)),l=un(["llm",s,o])||"llm call";if(!t){const A=Ke(e.params)||{};return{title:l,detail:un([Ot(A.temperature)!==null?`temperature ${A.temperature}`:null,A.thinking?`thinking ${A.thinking}`:null,(j=Ke(A.speculation))!=null&&j.mode?`speculation ${Ke(A.speculation).mode}`:null])}}const u=Ke(t.usage)||{},d=Ke(t.metadata)||{},f=Ke(d.prompt_cache)||{},m=Ke(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=_b(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?Pu(C):null,x!==null&&x>0?`${Math.round(x)} tok/s`:null,k?`${k} tool ${k===1?"call":"calls"}`:null])}}function HT(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 KT(e,t){const n=Array.isArray(e.tool_calls)?e.tool_calls:[],s=BT(n),o=Ke(n[0]),l=o?x_(o.arguments):{label:"",value:""},u=Array.isArray(t==null?void 0:t.results)?t.results:[],d=u.filter(m=>{var p;return((p=Ke(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} ${HT(l.label,l.value)}`:null,u.length?`${d} ok`:null,f>0?`${f} failed`:null])}}function JT(e,t){var m,p;const{name:n,node:s}=zT(e.workflow_id),o=Ke(e.vars),l=o&&!km(o)?o:null,u=Ke(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=Ke((m=Ke(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?Zi(l,80):null,f&&`run ${f}`])}}function qT(e,t){const n=e.until,s=_b(t.started_at,n),o=DT(n);return{title:s!==null?`wait · delay ${Pu(s)}`:`wait · until ${o}`,detail:un([s!==null&&o?`until ${o}`:null,e.resume_to_node?`resumes at ${e.resume_to_node}`:null])}}function zh(e){var d;const t=Ke(e)||{},n=Ke(t.effect),s=String((n==null?void 0:n.type)||"").trim(),o=Ke(n==null?void 0:n.payload)||{},l=Ke(t.result);if(s==="emit_event"){const f=String(o.name??o.event_name??"").trim();if(vb.has(f))return{kind:"progress",title:"progress",detail:"",isProgress:!0,isStatus:!1,isResume:!1,hidden:!0};if(PT.has(f))return{kind:"event",title:"status",detail:Zi(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:Zi(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",...GT(o,l,t),...u};if(s==="tool_calls")return{kind:"tools",...KT(o,l),...u};if(s==="start_subworkflow")return{kind:"subflow",...JT(o,l),...u};if(s==="wait_until")return{kind:"wait",...qT(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=Ke(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=Ke(l.output)||{},m=Ke(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):Zi(f,110)),...u}}return{kind:"step",title:String(t.node_id||"workflow step"),detail:"",...u}}return{kind:"step",title:s.replace(/_/g," "),detail:Zi(o,110),...u}}function xb(e,t,n){var l,u;const s=Ke(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=Ke((l=Ke(s.result))==null?void 0:l.wait);return String(((u=Ke(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 YT(e){var o;const t=Ke(e.record)||{},n=String(((o=Ke(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 QT(e){var f;const t=e.map(m=>Ke(m.record)||{}),n=t[t.length-1]||{},s={};for(const m of t){const p=Ke((f=Ke(m.effect))==null?void 0:f.payload);if(p)for(const[g,_]of Object.entries(p))km(_)&&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 XT(e){var n,s;const t=[];for(const o of e){const l=Ke((s=Ke((n=Ke(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 ZT(e,t){return`${e}|${String(t.step_id||t.node_id||"")}`}function eR(e,t){const n=new Map;for(const l of t){const u=WT(l.record);if(!u)continue;const d=ZT(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=Fh(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=>Ke(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||""),bb(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:Fh(d),progressFinal:f.final===!0||String(f.phase||"")==="complete",entries:u.entries,progressEvents:u.entries.map(g=>Ke(g.record)||{}),merged:Ke(u.entries[u.entries.length-1].record)||{}})}return o}function kb(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=zh(x.record);if(k.isProgress){f.push(x);continue}if(k.isStatus)continue;if(k.isResume){const A=String(((C=(v=Ke((_=Ke(x.record))==null?void 0:_.effect))==null?void 0:v.payload)==null?void 0:C.wait_key)||"").trim();A&&l.push(A);continue}const j=YT(x);d.set(x,d.size),u.set(x.runId,d.size-1),s.has(j)||(s.set(j,[]),o.push(j)),s.get(j).push(x)}const m=new Set(l),p=o.map(x=>{const k=s.get(x),j=QT(k),A=zh(j),T=k[k.length-1],E=(u.get(T.runId)??-1)>(d.get(T)??1/0)||XT(k).some(I=>m.has(I)),S=xb(j,A.kind,E);return{key:x,runId:k[0].runId,cursor:k[k.length-1].cursor,kind:A.kind,title:A.kind==="run"&&n&&k[0].runId!==n?"subflow finished":A.title,detail:A.detail,status:S.status,statusLabel:S.statusLabel,nodeId:String(j.node_id||""),stepIds:[...new Set(k.map(I=>{var M;return String(((M=Ke(I.record))==null?void 0:M.step_id)||"")}).filter(Boolean))],progress:"",progressFinal:!1,entries:k,progressEvents:[],merged:j}});return eR(p,f)}const tR=new Set(["completed","failed","cancelled","denied","partly_denied"]);function nR(e){return e==="completed"||e==="denied"||e==="partly_denied"?"completed":e==="waiting"||e==="failed"||e==="cancelled"?e:"started"}function Sb(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=Ke(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 sR(e,t){var p,g,_,v,C,x;const n=e,s=t||Sb({root_run_id:n.run_id,activities:[n]}),o=String(n.effect_type||""),l=nR(String(n.status||"")),u=tR.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)||""),j=s.promptOf(k)||s.messageOf(n,["question"]);f={...j?{prompt:j}:{},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 dw(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 rR(e,t){const n=dw(e),s=dw(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 aR(e,t){var l;if(!e)return[];const n=String(e.root_run_id||""),s=Sb(e),o=[];for(const u of e.activities||[]){const d=sR(u,s),f=zh(d);f.kind==="wait"&&u.effect_type==="wait_until"&&!((l=u.wait)!=null&&l.until)&&(f.title="wait · timer",f.detail="");const m=xb(d,f.kind,!1),p=Ke(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?Fh([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)=>rR(u.order,d.order)||u.index-d.index).map(u=>u.row)}function oR(e){return((e==null?void 0:e.activities)||[]).filter(t=>Ke(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 iR=["running","waiting","failed","completed"],lR={running:"Running",failed:"Failed",completed:"Done"},cR=new Set(["waiting for you","approval needed"]);function uR(e,t){var o;if(e!=="waiting")return lR[e]||e;const n=t.filter(l=>l.status==="waiting");if(n.some(l=>cR.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 dR(e){for(const t of iR)if(e.some(n=>n.status===t))return t;return e.length?e[e.length-1].status:"completed"}function fR(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=dR(o.rows),o.statusLabel=uR(o.status,o.rows);return t}function hR(e){return e.length?e[e.length-1].key:""}function mR({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(kR,{policy:e,enabled:n&&f==="shared",runId:t,onAttach:l})}):null,a.jsx("div",{hidden:s&&f!=="session",children:a.jsx(TT,{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(CR,{runId:t,enabled:n,refreshKey:o})]}):null]})}function jb(e,t,n){return n?aR(n,s=>B_(s)):kb(e,t)}function pR({records:e,runId:t,view:n}){const s=y.useMemo(()=>jb(e,t,n),[e,t,n]);return s.length?a.jsx(Nb,{rows:s}):a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(ue,{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 gR(e,t,n){const s=jb(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 Nb({rows:e}){const t=y.useMemo(()=>fR(e),[e]),n=hR(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(ue,{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(yR,{group:l}):null]},l.key)})})}function yR({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):sl(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(vR,{row:o},o.key)),n.length?a.jsx(hm,{tools:n}):null]})}const wR={llm:"sparkle",tools:"terminal",subflow:"agent",event:"info",wait:"history",ask:"chat",message:"send",run:"playCircle",progress:"loader",step:"list"};function vR({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(ue,{name:wR[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(Ao,{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 _R(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 Vr.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 bR({occurrences:e,nowMs:t,loadRecords:n=_R,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(ue,{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:Po(g),children:Ro(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(xR,{occurrence:m,loadRecords:n,onOpenRun:s}):null]},m.run_id)})}):a.jsxs("div",{className:"code-pane-empty",children:[a.jsx(ue,{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 xR({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"?kb(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(Nb,{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(ue,{name:"chat",size:13})," ",a.jsx("span",{children:"Open as conversation"})]}):null]})}function kR({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,j]=y.useState(0),[A,T]=y.useState("");return y.useEffect(()=>{const N=new AbortController;if(m([]),v(""),x(""),!t||!e)return;g(!0);const E=window.setTimeout(()=>{const S=new URLSearchParams({limit:"100"});o.trim()?S.set("query",o.trim()):u&&S.set("path",u),at(pe(`files/${o.trim()?"search":"list"}?${S}`),{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(ue,{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:()=>j(N=>N+1),disabled:!t,children:a.jsx(ue,{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:()=>j(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:!!A,onClick:async()=>{if(E){d(N.path),l("");return}T(N.path),v("");try{await s(N.path),x(`${N.name||N.path} attached.`)}catch(S){v(At(S))}finally{T("")}},children:[a.jsx(ue,{name:E?"folder":"paperclip",size:14}),a.jsx("span",{children:N.name||N.path}),A===N.path?a.jsx(ue,{name:"loader",size:13}):a.jsx(ue,{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(ue,{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 SR(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 jR(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||SR(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 NR(e){return fu(e)?"text":e==="image"||e==="pdf"||e==="audio"?"url":"none"}function CR({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 at(pe(`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(jR))).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"}),Vr.get_run_artifact_blob(e,m.id).then(async({blob:j,content_type:A})=>{const T=NR(ll(m.name,A));if(T==="text"){const N=await j.slice(0,gu).text();x&&_({status:"ready",text:N,partial:j.size>gu,total:j.size,contentType:A})}else T==="url"?(k=URL.createObjectURL(j.type?j:new Blob([j],{type:A})),x&&_({status:"ready",url:k,partial:!1,contentType:A})):x&&_({status:"ready",partial:!1,contentType:A})}).catch(j=>x&&_({status:"error",message:`Preview failed: ${At(j)}`})),()=>{x=!1,k&&URL.revokeObjectURL(k)}},[e,m]);const C=x=>void _A(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(ue,{name:"refresh",size:14})})}),l?a.jsx("p",{role:"alert",className:"code-error-text",children:l}):null,m?a.jsx(fm,{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:w_(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(ue,{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:yl(x.size)}):null,x.created?a.jsx("time",{title:Po(x.created),children:Ro(x.created,v)}):null]}),a.jsx("button",{className:"code-icon-button","aria-label":`Download ${x.name}`,title:"Download",onClick:()=>C(x),children:a.jsx(ue,{name:"download",size:14})})]},x.id))}):l?null:a.jsx("p",{className:"code-muted",children:"Generated files and attachments appear here."})]})}const ER=[{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"}],AR="abstractcode.rail.width.v1";function $R(e){return a.jsx(cN,{className:"code-rail",ariaLabel:"Workspace panels",idBase:"code-rail",storageKey:AR,active:e.panel,onActiveChange:t=>e.onPanel(t),panels:[...ER.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}:{},Mr=e=>typeof e=="string"?e:typeof e=="number"?String(e):"",TR=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!==""):[];function Ui(e,t=[]){const n=_a(e),s=_a(n._runtime),o=_a(n._limits),l=Mr(n.provider)||Mr(s.provider),u=Mr(n.model)||Mr(s.model);return{...ir,provider:l&&u?l:"",model:l&&u?u:"",reasoning:Mr(s.thinking),...s.speculation!==void 0?{speculation:s.speculation}:{},maxIterations:Mr(o.max_iterations),maxTokens:Mr(o.max_tokens),system:Mr(s.system_prompt_extra),workspace:n.workspace&&typeof n.workspace=="object"&&Array.isArray(n.workspace.folders)?n.workspace:null,toolLayer:hb(n,t),skills:TR(n.skills),workflow:ir.workflow,streamReplies:"gateway_default"}}function Os(e,t,n){n==null||n===""||Array.isArray(n)&&!n.length?delete e[t]:e[t]=n}function fw(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function RR(e,t,n=[]){let s=_a(e);const o=_a(s._runtime),l=_a(s._limits),u=!!(t.provider&&t.model);Os(s,"provider",u?t.provider:""),Os(s,"model",u?t.model:""),Os(o,"provider",u?t.provider:""),Os(o,"model",u?t.model:""),Os(o,"thinking",t.reasoning),Os(o,"speculation",t.speculation),Os(o,"system_prompt_extra",t.system.trim()),Os(l,"max_iterations",fw(t.maxIterations)),Os(l,"max_tokens",fw(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),Os(s,"skills",t.skills);const d=hb(e,n),f=Fo(n,{app:t.toolLayer}).app;return Mo(d)!==Mo(f)&&(s=pT(s,t.toolLayer,n)),s}function IR(e,t,n=[]){const s=_a(e.target.input_data),o=RR(s,t,n);return Mo(s)===Mo(o)?null:{target:{bundle_ref:e.target.bundle_ref,flow_id:e.target.flow_id,input_data:o}}}function Mo(e){if(Array.isArray(e))return`[${e.map(Mo).join(",")}]`;if(e&&typeof e=="object"){const t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Mo(t[n])}`).join(",")}}`}return JSON.stringify(e)}const MR=700;function LR(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 Cb(e){if(ml(e)){if(e.code==="revision_conflict")return"Not saved: the automation changed elsewhere. The latest revision is shown; make the change again.";const t=Oo(e);return`Not saved: ${t.title}${t.detail?` ${t.detail}`:""}`}return`Not saved: ${String((e==null?void 0:e.message)||e)}`}function OR(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(()=>Ui(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}),j=async()=>{var S;_.current&&window.clearTimeout(_.current),_.current=null;const A=g.current;if(g.current=null,!A)return;const T=A.automationId===C.current?v.current:k.current.id===A.automationId?k.current.def:null;if(!T)return;const N=IR(T,A.prefs,s.current);if(!N)return;const E=()=>A.automationId===C.current;E()&&p({status:"saving"});try{await x.current(A.automationId,N,T.revision),E()&&p({status:"saved",revision:T.revision+1})}catch(I){if(!E())return;p({status:"error",message:Cb(I)}),f(Ui((S=v.current)==null?void 0:S.target.input_data,s.current))}};return y.useEffect(()=>{g.current&&g.current.automationId!==l&&j(),k.current={id:l,def:o},p({status:"idle"}),f(Ui(o==null?void 0:o.target.input_data,s.current))},[l]),y.useEffect(()=>{k.current={id:l,def:o},g.current||f(Ui(o==null?void 0:o.target.input_data,s.current))},[u]),y.useEffect(()=>{g.current||f(Ui(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:A=>{f(A),g.current={prefs:A,automationId:l},_.current&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>void j(),MR)}}}function PR(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:LR(e.settings.save)||"Changes are saved as a new revision and apply from the next run."})]})}function DR(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(Bv,{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=hv(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=>{ml(f)?o({status:"error",message:Cb(f)}):(o({status:"idle"}),s([String((f==null?void 0:f.message)||f)]))})}},`${e.summary.automation_id}:${t}`)})}const hw="—";function vo(e){return typeof e=="string"&&e?e:void 0}function FR(e){return e.endsWith("+00:00")||e.endsWith("Z")}function eh(e){if(!e||typeof e!="object")return e;const t=e,n={...e},s=vo(t.next_run_at)??vo(t.next_fire_at);let o=vo(t.next_run_local),l=vo(t.time_zone)??"";return!o&&!l&&s&&FR(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=vo(t.schedule_rule_text)??hw,n.schedule_text=vo(t.schedule_text)??hw,n}function zR(e){return{...e,listAutomations:async t=>{const n=await e.listAutomations(t);return{...n,items:(n.items??[]).map(eh)}},getAutomation:async t=>{const n=await e.getAutomation(t);return n!=null&&n.summary?{...n,summary:eh(n.summary)}:n},createAutomation:async t=>{const n=await e.createAutomation(t);return n!=null&&n.summary?{...n,summary:eh(n.summary)}:n}}}const BR=3e4,Kc=50;function WR(){return QS({fetch:(e,t)=>fetch(e,{...t,credentials:"same-origin"}),baseUrl:"",headers:_l})}function UR(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 VR(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 GR(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 HR(e){return e.filter(t=>t.status!=="archived")}function KR(e){const t=e==null?void 0:e.archived_automations;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function JR(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 qR(e,t,n,s){return{command_id:e,run_id:t,type:"resume",payload:{wait_key:n,payload:s},client_id:"abstractcode-web"}}function Eb(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 cs(e){return ml(e)?e:{status:0,code:"client_error",message:e&&typeof e=="object"&&"message"in e?String(e.message):String(e)}}function th(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 YR={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 QR(e){return async(t,n,s)=>{await at(pe("commands"),{method:"POST",body:JSON.stringify(qR(e(),t,n,s))})}}class XR{constructor(t,n,s=[1500,4e3]){Bt(this,"state",{...YR});Bt(this,"listeners",new Set);Bt(this,"listSeq",0);Bt(this,"detailSeq",0);Bt(this,"sourcesLoaded",!1);Bt(this,"client");Bt(this,"previewSchedule",t=>this.client.previewSchedule(t));this.answerWaitVia=n,this.followupsMs=s,this.client=zR(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:Kc});if(s||(o=KR(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:cs(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:cs(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:Kc})]);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:th([],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:cs(l)})}}async reloadDetail(t){const[n,s]=await Promise.all([this.client.getAutomation(t),this.client.listOccurrences(t,{limit:Kc})]),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:th(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:Kc}),s=this.state.detail;if(!s||s.automationId!==t.automationId)return;this.set({detail:{...s,occurrences:th(s.occurrences,n.items),nextCursor:n.next_cursor}})}catch(n){this.set({error:cs(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 cs(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,dv(t),n)}catch(s){const o=cs(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,Mt.unarchive,n)}catch(s){const o=cs(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 cs(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:Eb(n,l)}),l}catch(l){throw cs(l)}finally{this.set({busy:!1})}}async seen(t,n){try{await this.client.markSeen(t,n)}catch(s){throw cs(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,JR(o.kind,s))})}rowControls(t){return To(t,[],this.state.busy)}reportError(t){this.set({error:cs(t)})}clearNotice(){this.set({notice:"",error:null})}}const mw={[Mt.pause]:"Automation paused.",[Mt.resume]:"Automation active.",[Mt.run_now]:"Run requested.",[Mt.stop_current]:"Stop requested.",[Mt.archive]:"Automation archived."},ZR=[{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 pw(e){const t=e&&typeof e=="object"&&"code"in e?e:null;if(t){const n=Oo(t);return{tone:"error",text:n.title,detail:n.detail}}return{tone:"error",text:e instanceof Error?e.message:String(e)}}function eI(e){const t=e.summary,n=To(t,e.occurrences,e.busy),s=e.nowMs??Date.now(),o=Wv(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,j)=>{f({tone:"busy",text:x}),k().then(()=>f({tone:"ok",text:j}),A=>f(pw(A)))},g=(x,k)=>p(k,()=>e.onCommand(x),mw[x]??"Done."),_=x=>{x==="run_now"?g(Mt.run_now,"Starting a run…"):x==="stop_current"?g(Mt.stop_current,"Stopping…"):x==="revise"?e.onEdit():x==="archive"&&u(!0)},v=t.workspace_root||"",C=e.triggerSources.length?Fv(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(ub,{variant:"inline",summary:t,busy:e.busy,onToggle:()=>p(t.status==="active"?"Pausing…":"Activating…",e.onToggleActive,mw[t.status==="active"?Mt.pause:Mt.resume])}),lb(t)?a.jsx(cb,{}):null,a.jsx("span",{className:"code-auto-header__timing","data-field":"timing",children:o.line})]}),a.jsx(ab,{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(ue,{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:UA(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(ue,{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(pw(x))),children:a.jsx(ue,{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(ue,{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(Mt.archive,"Archiving…")},children:[a.jsx(ue,{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:ZR.map(x=>{const k=n[x.id],j=il(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?j:`${k.reason??"Not available now."}
96
- ${j}`,onClick:()=>_(x.id),children:[a.jsx(ue,{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(ue,{name:d.tone==="busy"?"loader":d.tone==="ok"?"check":"error",size:13}),a.jsxs("span",{children:[d.text,d.detail?` ${d.detail}`:""]})]}):null]})}const Ab="abstractcode.automation.panels",Vi={occurrences:!0,folder:!0};function tI(e){try{const t=e==null?void 0:e.getItem(Ab);if(!t)return{...Vi};const n=JSON.parse(t);if(!n||typeof n!="object")return{...Vi};const s=n;return{occurrences:typeof s.occurrences=="boolean"?s.occurrences:Vi.occurrences,folder:typeof s.folder=="boolean"?s.folder:Vi.folder}}catch{return{...Vi}}}function nI(e,t){try{t==null||t.setItem(Ab,JSON.stringify(e))}catch{}}function sI(e,t){return{...e,[t]:!e[t]}}function gw(){try{return typeof window<"u"?window.localStorage:null}catch{return null}}function rI(){const[e,t]=y.useState(()=>tI(gw())),n=y.useCallback(s=>{t(o=>{const l=sI(o,s);return nI(l,gw()),l})},[]);return[e,n]}const Sm=e=>({toggle:`code-detail-${e}-toggle`,region:`code-detail-${e}`});function $b(e){const t=Sm(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(ue,{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 aI=".af-auto__timeline",oI=".af-auto__more";function iI(e,t,n){const s=(e==null?void 0:e.querySelector(aI))??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(oI))??null,l=o&&o.parentNode===s.parentNode?o:s;return(t.parentNode!==l.parentNode||t.nextSibling!==l)&&l.parentNode.insertBefore(t,l),!0}function lI(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=Sm("occurrences").region,d=()=>o(iI(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 cI(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 uI(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 cI(e)}}const yw=/^[a-zA-Z0-9_-]+$/;async function Tb(e){const t=String(e||"").trim();if(!t)throw new Error("session_memory_owner_run_id: session_id is required");if(yw.test(t)){const s=`session_memory_${t}`;if(yw.test(s))return s}return`session_memory_sha_${(await uI(t)).slice(0,32)}`}function Rb(){return at(pe("voice/defaults"))}function dI(e,t){const n=new URLSearchParams({compact:"true"});return e&&n.set("provider",e),t&&n.set("model",t),at(pe(`voice/voices?${n.toString()}`))}function fI(e){const t={description:e.description};return e.name&&(t.name=e.name),e.language&&(t.language=e.language),at(pe("voice/design"),{method:"POST",body:JSON.stringify(t)})}function hI(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),at(pe("voice/clones"),{method:"POST",body:n})}const mI={design:fI,clone:hI};function pI(e){return{...mI,list:()=>at(pe(sk.clones)),rename:(t,n)=>at(pe(uh(t)),{method:"PATCH",body:JSON.stringify(n)}),remove:t=>at(pe(uh(t)),{method:"DELETE"}),...e?{share:t=>at(pe(rk(t)),{method:"POST"})}:{}}}const gI="Hello, this is how I sound.";function yI(e){return async(t,n,s)=>{if(!e)throw new Error("Open a conversation to hear a voice sample.");const o=await Tb(e),l=s==null?void 0:s.signal,u=await at(pe(`runs/${encodeURIComponent(o)}/voice/tts`),{method:"POST",body:JSON.stringify({text:n||gI,request_id:Br(),timeout_s:25,...Zv(t)}),...l?{signal:l}:{}}),d=u==null?void 0:u.audio_artifact,f=String((d==null?void 0:d.$artifact)||(d==null?void 0:d.artifact_id)||(d==null?void 0:d.id)||"").trim();if(!f)throw new Error("The synthesis returned no audio.");const m=await fetch(pe(`runs/${encodeURIComponent(o)}/artifacts/${encodeURIComponent(f)}/content`),{credentials:"same-origin",headers:_l(),...l?{signal:l}:{}});if(!m.ok)throw new Error(`The voice sample could not be downloaded (HTTP ${m.status}).`);return await m.arrayBuffer()}}const Du={capture_mode:"hold",auto_send:!0};function wI({value:e,onChange:t,defaults:n,connected:s,isAdmin:o=!1,levelSource:l,sampleSessionId:u,ttsAvailable:d=!1}){return a.jsx(i1,{value:e,onChange:t,fetchCatalog:dI,fetchDefaults:Rb,defaults:n.value??void 0,overrideOwner:"this app",nested:!0,voiceLibrary:pI(o),rows:{capture:!0},captureDefaults:Du,levelSource:l??null,previewVoice:s&&d&&u?yI(u):void 0,unavailableReason:s?null:"Connect to a gateway to configure voice."})}async function vI(e,t){return e||Tb(t)}const ww=18e4;function Ib({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=MS({...ZN({...Du,...o}),tts_stream:((g=n.tts)==null?void 0:g.available)===!0&&e?async function*(v,C){m(),yield*CS({path:pe(`runs/${encodeURIComponent(e)}/voice/tts/stream`),headers:_l(),signal:C,body:{text:v,request_id:Br(),...Zv(o)}})}:void 0,transcribe:((_=n.stt)==null?void 0:_.available)===!0&&(e||t)&&l?async(v,C)=>{var S;m();const x=Number(((S=n.stt)==null?void 0:S.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",j=new File([v],`recording.${k}`,{type:C||"audio/webm"}),A=await Vr.attachments_upload(t,j);m();let T;const N=await vI(e,t);m();const E=await Promise.race([Vr.audio_transcribe(N,{audio_artifact:A,request_id:Br(),...t1(o)}),new Promise((I,M)=>{T=setTimeout(()=>M(new Error(`the gateway did not answer within ${ww/1e3} s`)),ww)})]).finally(()=>clearTimeout(T));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 vw(e,t){const n=e.trimEnd();return n?`${n}
97
- ${t}`:t}function _I({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(d1,{voice:e,mode:$o(n.capture_mode??Du.capture_mode),routeText:s,unavailableReason:jT()?null:ST,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(ue,{name:"x",size:14})}):null]})}const bI=ct.title;function _w(e){return`${bI}: ${e}`}function xI(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.folders))}function kI(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 xI(t)?t:null}function SI(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 jI=3e4,bw=new WeakMap;function NI(e,t,n=Date.now()){let s=bw.get(e);s||bw.set(e,s=new Map);const o=JSON.stringify(t),l=s.get(o);if(l&&n-l.at<jI)return l.answer;const u=jh(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 CI(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 NI(e.request,e.value).then(l=>o&&n(_w(l))).catch(l=>o&&n(_w(im(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 EI(e,t,n={following:!1,epoch:0}){const s=y.useMemo(()=>new XR(WR(),QR(Br)),[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(),BR);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 AI(e,t){const n=[];return e&&n.push(`${e} waiting for you`),t&&n.push(`${t} new`),n.join(" · ")}function Bh({error:e}){if(!e)return null;const t=Oo(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 $I(e){const t=e.open??!0,n=wm("automations"),s=e.state,o=HR(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?AI(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(eb,{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(ue,{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(ue,{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(Bh,{error:s.listError}),!s.loaded&&(e.discovering||e.available.available&&s.loading)?a.jsx(Io,{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(wt.Fragment,{children:[a.jsx(u$,{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(Bh,{error:s.rowError.error}):null]},m.automation_id)}),a.jsxs(nb,{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(Io,{children:"Loading archived automations…"})}):null,l.map(m=>{var p;return a.jsx(sb,{id:m.automation_id,title:m.title,busy:s.busy,error:((p=s.rowError)==null?void 0:p.automationId)===m.automation_id?Oo(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 TI(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,Eb(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 RI(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 xw(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 II(e){const t=e.panels.folder,n=Sm("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($b,{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 MI(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=Ib({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=TI(e.ctl,{...e.host,openWorkspace:x=>o({automationId:l,runId:x})}),[g,_]=rI(),v=y.useRef(null),C=lI(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(ue,{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(eI,{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(CI,{request:Lu,connected:e.enabled,value:kI(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:xm}),p?a.jsx(mA,{...p,hideHeader:!0,prepareTarget:e.prepareTarget,workflowPickerOptions:e.workflowPickerOptions,availableTools:e.availableTools,fetchGateway:cl,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?ul.createPortal(a.jsx($b,{panel:"occurrences",label:"Occurrences",count:n.summary.occurrence_count,open:g.occurrences,onToggle:()=>_("occurrences")}),C):null,e.enabled?a.jsx(II,{panels:g,onToggle:()=>_("folder"),title:xw(n.automationId,m,n.occurrences),own:m===n.automationId,children:a.jsx(gm,{className:"code-auto-folder",fetchGateway:cl,runId:m,title:xw(n.automationId,m,n.occurrences),refreshKey:RI(n.summary),onClose:m!==n.automationId?()=>o({automationId:l,runId:""}):void 0})}):null]}):t.error?a.jsx(Bh,{error:t.error}):a.jsx(Io,{children:"Loading automation…"})]})}function LI(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(G0,{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(Dv,{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(X_,{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?Jh(v,$u(p.target.input_data)):v,x=SI(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(cs(v)),v}finally{d.current=!1,u(!1)}}}})}const OI=()=>({cursor:0,waits:{},raised:{},seen:{},resolved:[],automationEpoch:0}),Cn=(e,t)=>typeof e[t]=="string"&&e[t]?e[t]:"",nh=(e,t)=>typeof e[t]=="number"?e[t]:0,sh=(e,t,n="")=>`${e}\0${t}\0${n}`;function PI(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=Cn(o,"run_id"),u=Cn(o,"wait_key");if(l&&u){const d=Cn(o,"step_id");if(Cn(o,"record_key")&&e.resolved.includes(Cn(o,"record_key"))||d&&e.resolved.includes(`step:${sh(l,u,d)}`))break;s.waits[sh(l,u,d)]=Cn(o,"session_id")}else if(Cn(o,"automation_id")&&nh(o,"seq")>0){const d=Cn(o,"automation_id"),f=nh(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=Cn(o,"record_key");l&&(s.resolved=[...s.resolved,l].slice(-500));const u=Cn(o,"run_id"),d=Cn(o,"wait_key");if(u&&d){const m=Cn(o,"step_id");m&&(s.resolved=[...s.resolved,`step:${sh(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=Cn(o,"automation_id");if(f){const m=Math.max(s.seen[f]||0,nh(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"&&Cn(o,"run_id")){const l=Cn(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 DI=e=>Object.keys(e.waits).length,FI=e=>Object.entries(e.raised).reduce((t,[n,s])=>t+s.filter(o=>o>(e.seen[n]||0)).length,0);class zI{constructor(t){Bt(this,"fold",OI());Bt(this,"state","stopped");Bt(this,"listeners",new Set);Bt(this,"abort",null);Bt(this,"wakeUp",null);Bt(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=PI(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(pe(`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(pe("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 q_;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 BI(e,t){const n=()=>typeof document>"u"||document.visibilityState!=="hidden",s=y.useMemo(()=>new zI({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 WI(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 UI(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=db(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(Wh,{...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(Wh,{...e,omit:t.filter(p=>!d.has(p)),rawObject:!1})]}):null]})}function VI(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 GI(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 Wh({schema:e,values:t,onChange:n,disabled:s=!1,omit:o=[],rawObject:l=!1,onEditorError:u,defaultModel:d}){const[f,m]=wt.useState("fields"),p=Object.entries((e==null?void 0:e.properties)||{}).filter(([x])=>!o.includes(x)),g=db(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 j={...k,type:b$(k)},A=g.find(I=>I.provider===x);if(A)return a.jsxs("section",{className:"code-settings-section",children:[a.jsx("h3",{children:A.title}),a.jsx(ju,{value:{provider:String(t[A.provider]||""),model:String(t[A.model]||""),...A.reasoning?{reasoning:String(t[A.reasoning]||"")}:{}},onChange:I=>n({...t,[A.provider]:I.provider,[A.model]:I.model,...A.reasoning?{[A.reasoning]:I.reasoning||""}:{}}),...S$(A.provider,j["x-abstract-type"]),fetchModelCapabilities:A.reasoning?No.fetchModelCapabilities:void 0,effectiveDefault:A.provider==="provider"?d:void 0,defaultHint:A.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 T=`workflow-input-${x}`,N=String(j.title||x).replace(/_/g," "),E=Array.isArray(e==null?void 0:e.required)&&e.required.includes(x),S=I=>{const M={...t};I===void 0?delete M[x]:M[x]=I,n(M)};return a.jsxs("div",{className:"code-field",children:[a.jsxs("label",{htmlFor:T,children:[N,E?a.jsx("span",{"aria-label":"required",children:" *"}):null]}),j.enum?a.jsxs("select",{id:T,value:t[x]===void 0?"":JSON.stringify(t[x]),disabled:s,onChange:I=>S(I.target.value?JSON.parse(I.target.value):void 0),children:[a.jsxs("option",{value:"",children:["Choose ",N]}),j.enum.map(I=>a.jsx("option",{value:JSON.stringify(I),children:String(I)},JSON.stringify(I)))]}):j.type==="boolean"?a.jsxs("select",{id:T,value:t[x]===void 0?"":String(t[x]),disabled:s,onChange:I=>S(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"})]}):j.type==="number"||j.type==="integer"?a.jsx("input",{id:T,type:"number",value:typeof t[x]=="number"?String(t[x]):"",min:j.minimum,max:j.maximum,step:j.type==="integer"?1:"any",disabled:s,onChange:I=>S(I.target.value===""?void 0:Number(I.target.value))}):j.type==="object"||j.type==="array"?a.jsx(KI,{id:T,value:t[x],disabled:s,onChange:S},x):a.jsx("textarea",{id:T,rows:2,value:String(t[x]??""),disabled:s,onChange:I=>S(I.target.value)}),j.description?a.jsx("p",{className:"code-field-help",id:`${T}-help`,children:j.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:WI,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(HI,{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 HI({value:e,onChange:t,onError:n,disabled:s}){const[o,l]=wt.useState(JSON.stringify(e,null,2)),[u,d]=wt.useState(""),f=wt.useRef(e);return wt.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=GI(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 KI({id:e,value:t,onChange:n,disabled:s}){const[o,l]=wt.useState(t===void 0?"":JSON.stringify(t,null,2)),[u,d]=wt.useState(""),f=wt.useRef(t);return wt.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 JI({active:e,paused:t,snapshot:n,onRevokeApproval:s,onCommand:o,onActivity:l,onInteraction:u,permissionsAll:d}){const f=y.useMemo(()=>BE(n),[n]),m=y.useMemo(()=>f.tone==="working"?OT(n.view?oR(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(ue,{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(ue,{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(ue,{name:"chevronRight",size:12})]}),d?a.jsxs("div",{className:"code-run-strip__consent",children:[a.jsx(ue,{name:"check",size:13}),a.jsx("span",{children:"Auto: every enabled tool · this browser"}),a.jsx("button",{onClick:s,children:"Revoke"})]}):null]})}function rh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Jc(e){return typeof e=="string"?e.trim():""}function qI(e){const t=rh(e),n=rh(t==null?void 0:t.gateway),s=rh(n==null?void 0:n.principal);return JSON.stringify([Jc((t==null?void 0:t.gateway_url)??(t==null?void 0:t.gatewayUrl)),Jc((s==null?void 0:s.tenant_id)??(s==null?void 0:s.tenantId)),Jc((s==null?void 0:s.runtime_id)??(s==null?void 0:s.runtimeId)),Jc((s==null?void 0:s.user_id)??(s==null?void 0:s.userId))||"session"])}function kw(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 YI(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 QI(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 ah(){return new DOMException("The conversation changed before the run was attached.","AbortError")}const XI=rS("abstractcode","0.13.1"),oh=e=>["completed","failed","cancelled","canceled"].includes(e);function Sw(){const e=new URLSearchParams(window.location.hash.replace(/^#/,""));return{sessionId:e.get("session")||Br(),runId:e.get("run")||""}}function Gi(e,t=""){const n=new URLSearchParams({session:e});t&&n.set("run",t),window.history.replaceState(null,"",`#${n}`)}function ZI(){var Al,$l,Tl,Ua,Rl,Il,Ml,oi,Ll,Ol,Pl,Dl,Fl,zl,Bl,Va,gr,Wl,ii,li,ci,ui;const e=Lk({appName:"AbstractCode",variant:"blocking"}),t=e.connected?qI(e.status):"",n=y.useCallback(()=>{e.refresh()},[e.refresh]),s=Z$(t,n),[o,l]=mS("abstractcode",{defaults:{theme:"observer-night"}}),[u,d]=y.useState(!1),[f,m]=y.useState(0),p=y.useCallback(()=>m(O=>O+1),[]),[g,_]=m1(t?`abstractcode.voice:${t}`:null);y.useEffect(()=>{St()},[t]);const[v,C]=y.useState(ir),x=y.useRef(v);x.current=v;const k=y.useMemo(()=>t?F1(t):null,[t]),[j,A]=y.useState({}),[T,N]=y.useState(!1);y.useEffect(()=>{A(k?k.readApp(ln):{});let O=!1;try{O=!!t&&localStorage.getItem(Zf(t))==="pending"}catch{}N(O)},[k,t]);const E=y.useCallback(O=>{A(O),k==null||k.writeApp(ln,Object.keys(O).length?O:null)},[k]),S=()=>{N(!1);try{localStorage.setItem(Zf(t),"dismissed")}catch{}},I=E$(v.streamReplies,s.streaming),[M,B]=y.useState(ir.workflow),G=y.useMemo(()=>F$(s.executable.data),[s.executable.data]),Z=y.useCallback(()=>C(O=>({...O,workflow:Xt})),[]),oe=xT(t,Z),z=oe.state.status==="ok",F=oe.state.status==="ok"?vT(oe.state.row.value,G):v.workflow,L=y.useRef(F);L.current=F;const q=y.useMemo(()=>D$(s.gatewayDefault,s.workflows),[s.gatewayDefault,s.workflows]),V=M===Xt?q:s.workflows.find(O=>O.id===M)||G.find(O=>O.id===M)||null,[Y,J]=y.useState(null),W=vm(V),[R,K]=y.useState(Sw),[se,ce]=y.useState(""),[ae,we]=y.useState(""),[Se,Q]=y.useState(""),[xe,ve]=y.useState(!1),Fe=y.useRef(!1),[Xe,Ve]=y.useState([]),Je=y.useRef(null),[me,Me]=y.useState(),st=y.useRef(me);st.current=me;const[tt,$t]=y.useState(!1),[le,de]=y.useState(""),[je,_e]=y.useState(0),[ge,te]=y.useState({}),[be,P]=y.useState(""),[ie,Oe]=y.useState(null),[Ae,Ye]=y.useState(""),[$e,Ge]=y.useState(null),Ee=Yc(qc.md);y.useEffect(()=>{Ee&&Ge(null)},[Ee]);const pt=$e!==null,St=O=>{Ee&&Ge(null)},jt=O=>{Zt(!1),Ge(O)},Pt=O=>{O?jt("workflow"):$e==="workflow"&&Ge(null)},js=Yc(qc.md),Bo=Yc(qc.lg),Yn=NA(Bo,js),zs=y.useRef(Yn),[Bs,Zt]=y.useState(!1),[ja,Wo]=zA(),[lr,Na]=GA(),Uo=VR(s.capabilities),Ns=BI(t,e.connected),Ca=Ns.state==="following",{ctl:Jt,state:Wt}=EI(t,e.connected&&Uo.available,{following:Ca,epoch:Ns.fold.automationEpoch});y.useEffect(()=>{lr.automations&&Wt.loaded&&Wt.archivedCount>0&&Wt.archived===null&&Jt.loadArchived()},[lr.automations,Wt.loaded,Wt.archivedCount,Wt.archived,Jt]);const[Ut,us]=y.useState(!1),[cr,Gr]=y.useState(!1),Vo=y.useRef(""),[Go,Fu]=y.useState(""),Cs=y.useRef(null),[Es,ds]=y.useState([]),[Ho,Qn]=y.useState(!1),[Ko,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 ne=dT(O,s.toolCatalog);if(Object.keys(ne).length){E(ne),N(!0);try{localStorage.setItem(Zf(t),"pending")}catch{}Q(`${ow} in Tools.`)}}C(({legacyTools:ne,...Ne})=>Ne)}},[v.legacyTools,k,s.loading,s.toolCatalog,t,E]);const Aa=y.useRef(null),zu=y.useMemo(()=>{var Pe,He;const O=((Pe=Aa.current)==null?void 0:Pe.runId)===R.runId?Aa.current.input:null;if(R.runId&&!ie&&!O)return{enabledTools:[],autoApproveTools:[]};const ne=ie?ie.input_data:O,Ne=(He=ne==null?void 0:ne._runtime)==null?void 0:He.allowed_tools;return w1(eu(s.toolCatalog,{app:j},{ceiling:Array.isArray(Ne)?Ne:null}))},[s.toolCatalog,j,ie,R.runId]),Jo=`${t}:${R.sessionId}:${R.runId}`,Nt=y.useRef(Jo);Nt.current=Jo;const bl=y.useRef(null),[$a,xl]=y.useState({scope:"",notes:[]}),Ta=y.useMemo(()=>eT({onDeltaError:O=>{const ne=Nt.current,Ne=T$(O,bl.current);xl(Pe=>({scope:ne,notes:R$(Pe.scope===ne?Pe.notes:[],Ne)}))}}),[]),{controller:Xn,snapshot:Qe}=iA({transport:Ta,runId:R.runId,enabled:e.connected,onAuthError:n,clientId:"abstractcode-web",authScopeKey:t,toolApprovalPolicy:zu}),As=s.sessionToolPolicy;y.useEffect(()=>{if(!(!e.connected||s.capabilitiesLoading)){if(s.capabilitiesError){Xn.setSessionToolPolicyClient(null,{reason:s.capabilitiesError});return}Xn.setSessionToolPolicyClient((As==null?void 0:As.supported)===!0&&R.sessionId?j1((O,ne)=>at(O,{method:ne.method,...ne.body===void 0?{}:{body:JSON.stringify(ne.body)}}),R.sessionId,As,{client:"abstractcode-web"}):null)}},[Xn,e.connected,s.capabilitiesLoading,s.capabilitiesError,As,R.sessionId]);const Vt=!!R.runId&&!oh(Qe.status)&&Qe.status!=="idle",qo=((Al=Qe.run)==null?void 0:Al.paused)===!0||Qe.status==="paused",Gt=Vt||xe,Ra=Qe.loading&&Ko.length?Ko:Qe.messages,Ia=Ra[Ra.length-1];bl.current=Ia!=null&&Ia.id?String(Ia.id):null;const Ws=I$(Ra,[A$(v.streamReplies,s.streaming,Ra),...$a.scope===Jo?$a.notes:[]]),fs=((Tl=($l=s.capabilities)==null?void 0:$l.assistant)==null?void 0:Tl.voice)||{},Hr=f1(e.connected?Rb:null,t),dn=Ib({scope:`${t}:${R.sessionId}:${R.runId}:${Ut}`,runId:t?R.runId:"",sessionId:R.sessionId,capability:fs,preferences:g,onTranscript:O=>{(g.auto_send??Du.auto_send)===!1?ce(ne=>vw(ne,O)):za(O)},onError:we}),Zn=[...Ws].reverse().find(O=>O.role==="assistant"),ur=Zn?String(Zn.id||Zn.content):"",Yo=y.useRef({scope:"",id:""});y.useEffect(()=>{const O=`${t}:${R.sessionId}`,ne=Yo.current;if(ne.scope!==O){Yo.current={scope:O,id:ur};return}!ur||ur===ne.id||Gt||(Yo.current={scope:O,id:ur},g.read_aloud===!0&&dn.tts_supported&&(Zn!=null&&Zn.content)&&dn.toggle_tts(ur,Zn.content))},[t,R.sessionId,ur,Gt,g.read_aloud,dn.tts_supported]);const Ma=eA(Qe),Tn=y.useMemo(()=>gA(Ma,Xn,{records:Qe.records,currentRun:Qe.run,onPermissionsAll:async()=>{E(fT(s.toolCatalog,j))},approveAllScope:"in this browser",sessionPolicy:{toolsetOf:O=>{var ne;return(ne=s.tools.find(Ne=>Ne.name===O))==null?void 0:ne.toolset},ask:Object.entries(j).filter(([,O])=>O==="ask").map(([O])=>O)}}),[Ma,Qe.records,Qe.run,Qe.sessionPolicyMode,Qe.sessionPolicy,Qe.sessionPolicyClamped,Xn,s.tools,s.toolCatalog,j,E]),Vn=W?"prompt":x$(me),dr=W||!!(Vn&&!((Ua=me==null?void 0:me.required)!=null&&Ua.some(O=>O!==Vn))),fr=String(((Rl=ie==null?void 0:ie.workspace)==null?void 0:Rl.workspace_root)||((Ml=(Il=Qe.run)==null?void 0:Il.vars)==null?void 0:Ml.workspace_root)||""),Us=y.useMemo(()=>{var O;return e$(s.workflows,{inputData:ie,runWorkflowId:(O=Qe.run)==null?void 0:O.workflow_id})},[s.workflows,ie,(oi=Qe.run)==null?void 0:oi.workflow_id]),ot=R.runId&&ie&&!s.loading&&Qe.run&&!Us&&bm(ie)!=="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===R.sessionId),Kr=(fn==null?void 0:fn.prompt)||((Ll=Ws.find(O=>O.role==="user"))==null?void 0:Ll.content)||"New conversation",La=UR((Ol=e.status)==null?void 0:Ol.gateway_url),Oa=La?()=>{window.open(La,"_blank","noopener,noreferrer")}:void 0,Pa={...Oa?{openMyEmail:Oa}:{},openConversation:(O,ne,Ne)=>{Vo.current=Ne||"",ms(O,ne)},openRun:O=>{at(pe(`runs/${encodeURIComponent(O)}`)).then(ne=>{if(!(ne!=null&&ne.session_id))throw new Error(`The gateway reported no session for run ${O}.`);ms(ne.session_id,O)}).catch(ne=>Jt.reportError(ne))}},Qo=O=>{(!Ut||Wt.selectedId!==O)&&(us(!0),Jt.select(O)),Zt(!1),Ge("workflow")},Xo=O=>{Qo(O),Ge("workspace")},Jr=async O=>{const ne=O.flow_id==="@default"?q:s.workflows.find(Ft=>`${Ft.bundleId}@${Ft.bundleVersion}`===("bundle_ref"in O?O.bundle_ref:"")&&Ft.flowId===O.flow_id);if(!ne)throw new Error("The selected workflow is no longer available. Refresh the workflow list.");const Ne=await Qf(ne);if(!Ne)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const Pe={...rr(Ne),...O.input_data},He=Kf(Ne,Pe);if(He.length)throw new Error(`${He.join(" ")} Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...O,input_data:Pe}},hs=((Pl=Wt.detail)==null?void 0:Pl.summary.title)||"Automation",es=y.useRef(""),Gn=y.useRef(t),Dt=y.useRef(0);Gn.current!==t&&(Dt.current+=1,Gn.current=t);const Vs=y.useRef(!1),Ct=y.useRef(R);Ct.current=R;const kn=GE({upload:O=>Vr.attachments_upload(Ct.current.sessionId,O),maxBytes:(Dl=s.policy)==null?void 0:Dl.maxAttachmentBytes}),Zo=[...Xe,...kn.attached],qr=[...Xe.map((O,ne)=>({id:`ref:${ne}:${O.$artifact}`,name:O.filename||O.path||"Attachment",...typeof O.size_bytes=="number"?{size:O.size_bytes}:{},state:"attached"})),...kn.items],Bu=O=>{if(!O.startsWith("ref:"))return kn.remove(O);const ne=Number(O.split(":")[1]);Ve(Ne=>Ne.filter((Pe,He)=>He!==ne))};function Da(O){return kn.add(O),O.map(ne=>{var Pe;const Ne=ym(ne,(Pe=s.policy)==null?void 0:Pe.maxAttachmentBytes);return{name:ne.name,state:Ne?"refused":"queued",...Ne?{error:Ne}:{}}})}y.useEffect(()=>{if(Fe.current=!1,ve(!1),kn.clear(),we(""),Q(""),!t){Ve([]),ce(""),ds([]),Qn(!1),Ea([]),C(ir);return}if(es.current&&es.current!==t){const ne={sessionId:Br(),runId:""};K(ne),Gi(ne.sessionId)}es.current=t,Vs.current=!0;const O=pb(t);C(O),B(O.workflow)},[t]),y.useEffect(()=>{if(t){if(Vs.current){Vs.current=!1;return}yT(t,v)}},[v,t]),y.useEffect(()=>{if(s.loading||!s.workflows.length)return;const O=W$({selection:M,preferred:F,visible:G,workflows:s.workflows,runId:R.runId});O!==M&&B(O)},[s.loading,s.workflows,G,M,F,R.runId]);const Yr=oe.state.status==="ok"?`${t}|${oe.state.row.value??""}|${G.length}`:"";y.useEffect(()=>{!Yr||R.runId||!G.length||B(L.current)},[Yr]),y.useEffect(()=>{let O=!0;if(te({}),P(""),Me(void 0),de(""),!V){$t(!1);return}return $t(!0),Qf(V).then(ne=>{O&&(Me(ne),te(rr(ne)))}).catch(ne=>{O&&de(At(ne))}).finally(()=>{O&&$t(!1)}),()=>{O=!1}},[V==null?void 0:V.id,je]),y.useEffect(()=>{if(Oe(null),Ye(""),!t||!R.runId)return;const O=new AbortController;return at(pe(`runs/${encodeURIComponent(R.runId)}/input_data`),{signal:O.signal}).then(ne=>{Oe(ne)}).catch(ne=>{O.signal.aborted||Ye(At(ne))}),()=>O.abort()},[R.runId,t]),y.useEffect(()=>{ie&&ie.flow_id===(V==null?void 0:V.flowId)&&me&&te({...rr(me),...v$(me,ie.input_data)})},[ie,me,V==null?void 0:V.flowId]),y.useEffect(()=>{!R.runId&&e.connected&&(fn!=null&&fn.latestRunId)&&K(O=>({...O,runId:fn.latestRunId}))},[R.runId,e.connected,fn==null?void 0:fn.latestRunId]),y.useEffect(()=>{Gi(R.sessionId,R.runId),Fe.current=!1,ve(!1),kn.clear(),Ve([]),te(rr(st.current)),Ea([]),Q(Vo.current),Vo.current="",we(""),ds([]),Qn(!1)},[R.sessionId]),y.useEffect(()=>{const O=()=>{const ne=Sw();Fe.current=!1,ve(!1),kn.clear(),ds([]),Qn(!1),ce(""),K(ne)};return window.addEventListener("hashchange",O),()=>window.removeEventListener("hashchange",O)},[]),y.useEffect(()=>{!R.runId||!oh(Qe.status)||s.refresh()},[R.runId,Qe.status]),y.useEffect(()=>{if(!R.runId||!ie)return;const O=U$({restoredInputs:ie,restored:Us});O&&B(O)},[R.runId,ie,Us==null?void 0:Us.id]);const Fa=R.runId?V$(ie):"",Qr=y.useCallback(()=>{const O={sessionId:Br(),runId:""};K(O),B(L.current),Gi(O.sessionId),ce(""),ds([]),Qn(!1),Zt(!1),us(!1)},[]),ms=y.useCallback((O,ne)=>{Fe.current=!1,ve(!1),kn.clear(),K({sessionId:O,runId:ne}),Gi(O,ne),Zt(!1),ds([]),Qn(!1),ce(""),us(!1)},[]);y.useEffect(()=>{const O=zs.current;zs.current=Yn,O!==Yn&&Zt(ne=>CA(ne,Yn))},[Yn]),jA(Bs,js,()=>document.querySelector(".code-sidebar"),()=>document.querySelector(".code-mobile-close")),y.useEffect(()=>{const O=ne=>{var Pe;if(EA({key:ne.key,defaultPrevented:ne.defaultPrevented,overlayOpen:pt||cr||AA(),sidebarOpen:Bs})==="sidebar"){Zt(!1),(Pe=document.querySelector(".code-mobile-nav"))==null||Pe.focus();return}(ne.metaKey||ne.ctrlKey)&&(ne.key.toLowerCase()==="k"&&(ne.preventDefault(),St(),Zt(!0),window.setTimeout(()=>{var He;return(He=Cs.current)==null?void 0:He.focus()},0)),ne.key.toLowerCase()==="n"&&ne.shiftKey&&(ne.preventDefault(),Qr()))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[Qr,Bs,cr,pt]);function Gs(O,ne,Ne=[],Pe=!1,He=V,Ft=me){let bt=a$({workflow:He||void 0,inputSchema:Ft,schemaInputs:ne,prompt:O,promptProperty:Vn,model:v,reasoning:v.reasoning||void 0,speculation:v.speculation,streamReplies:I,systemPromptExtra:v.system||void 0,attachments:Ne,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 pu(s.toolCatalog,{app:j})&&(bt=s_(bt,eu(s.toolCatalog,{app:j}))),Pe&&(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(Fe.current)throw new Error("A turn is already being submitted.");if(!e.connected)throw new Error("Connect to your gateway first.");if(M===Xt&&s.gatewayDefault.status==="unavailable")throw new Error(`Gateway default: ${s.gatewayDefault.reason}. Choose a workflow from the list.`);if(!V)throw new Error("Choose a workflow first.");if(!s.policy)throw new Error("Workspace policy is unavailable. Reconnect or refresh before starting.");if(R.runId&&(!ie||Ae))throw new Error(Ae||"Wait for the gateway to restore this conversation's workspace.");if(ot)throw new Error(ot);if(tt||le)throw new Error(le||"Wait for workflow inputs to load.");if(be)throw Pt(!0),new Error(be);if(kn.sendBlock)throw new Error(kn.sendBlock);if(Vt)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 ne={...rr(me),...ge,...Vn&&O.trim()?{[Vn]:O.trim()}:{}},Ne=W?ne:VI(me,ne,Zo);for(const[ys,yr]of[["Iteration limit",v.maxIterations],["Context token limit",v.maxTokens]])if(yr&&(!Number.isInteger(Number(yr))||Number(yr)<=0))throw new Error(`${ys} must be a positive whole number.`);Fe.current=!0,ve(!0),we(""),Q("");const Pe=R.sessionId,He=R.runId,Ft=t,bt=Dt.current;let gs="";try{const ys=Gs(O,Ne,Zo),yr=Kf(me,ys);if(yr.length)throw Pt(!0),new Error(yr.join(" "));const Ga=G$({selection:M,workflow:V,sessionId:Pe,input:ys}),Ts=await at(pe("runs/start"),{method:"POST",body:JSON.stringify(Ga)});if(!Ts.run_id)throw new Error("The gateway did not return a run identifier.");if(Ct.current.sessionId!==Pe||Ct.current.runId!==He||Gn.current!==Ft||Dt.current!==bt)throw ah();return gs=String(Ts.run_id),Aa.current={runId:gs,input:ys},J({runId:gs,...H$(Ts.resolved_workflow)}),Ea([...Ws,...O.trim()?[{id:`pending:${Ts.run_id}`,role:"user",content:O.trim()}]:[]]),K({sessionId:Pe,runId:Ts.run_id}),Gi(Pe,Ts.run_id),ce(""),Ve([]),kn.clear(),Pt(!1),Ts.runner_warning&&Q(String(Ts.runner_warning)),s.refresh(),gs}finally{Ct.current.sessionId===Pe&&(Ct.current.runId===He||Ct.current.runId===gs)&&Gn.current===Ft&&Dt.current===bt&&(Fe.current=!1,ve(!1))}}async function za(O){const ne=vw(se,O);if(xe){ce(ne);return}try{await Xr(ne)}catch(Ne){ce(ne),we(At(Ne))}}async function kl(O){if(Tn)throw new Error("Answer the pending workflow request above, or queue the next turn.");const ne=R.sessionId,Ne=R.runId,Pe=Dt.current,He=await Xn.sendCommand("inject_guidance",{guidance:O});if(Ct.current.sessionId!==ne||Ct.current.runId!==Ne||Dt.current!==Pe)throw ah();return{accepted:(He==null?void 0:He.accepted)!==!1,...typeof(He==null?void 0:He.seq)=="number"?{seq:He.seq}:{},...(He==null?void 0:He.duplicate)===!0?{duplicate:!0}:{}}}function Sl(O){return ds(ne=>[...ne,{id:Br(),text:O,sessionId:R.sessionId,sourceRunId:R.runId,authEpoch:Dt.current}]),Qn(!0),{accepted:!0}}const ei=Vt&&!xe?{modes:Tn?["queue"]:["guide","queue"],parked:Qe.status==="waiting"&&!Tn,onSteer:async(O,ne)=>ne==="queue"?Sl(O):kl(O)}:void 0;async function Xr(O){if(!Vt)return ps(O);if(!(Tn?Sl(O):await kl(O)).accepted)throw new Error("The gateway did not accept this message.");ce(""),Q(Tn?"Queued for the next turn.":"Guidance queued. The workflow will read it at its next supported boundary.")}async function Ba(O){var Pe,He;const ne=String(((Pe=Qe.run)==null?void 0:Pe.run_id)||"");if(!kw(O,{sessionId:R.sessionId,runId:R.runId,snapshotRunId:ne,snapshotSessionId:String(((He=Qe.run)==null?void 0:He.session_id)||""),authEpoch:Dt.current}))throw ah();const Ne=await ps(O.text);ds(Ft=>QI(Ft,O,Ne))}y.useEffect(()=>{var Ne,Pe;if(!Ho||!Es.length||!e.connected||!ie||Ae||Fe.current)return;const O=YI(Qe.status);if(O==="wait")return;if(O==="pause"){Qn(!1);const He=["failed","error"].includes(Qe.status.toLowerCase());Q(`Queue paused because the run ${He?"failed":"was cancelled"}. Review the result, then use Run next to continue explicitly.`);return}const ne=Es[0];kw(ne,{sessionId:R.sessionId,runId:R.runId,snapshotRunId:String(((Ne=Qe.run)==null?void 0:Ne.run_id)||""),snapshotSessionId:String(((Pe=Qe.run)==null?void 0:Pe.session_id)||""),authEpoch:Dt.current})&&Ba(ne).catch(He=>{He instanceof DOMException&&He.name==="AbortError"||(Qn(!1),we(At(He)))})},[Ho,Es,Qe.status,(Fl=Qe.run)==null?void 0:Fl.run_id,(zl=Qe.run)==null?void 0:zl.session_id,e.connected,ie,Ae,R.sessionId,R.runId]);async function jl(){const O=R.sessionId,ne=R.runId,Ne=Dt.current;await Xn.cancel(),Ct.current.sessionId===O&&Ct.current.runId===ne&&Dt.current===Ne&&Q("")}const Rn=O=>{const ne=Dt.current,Ne=R.sessionId,Pe=R.runId;we(""),O().catch(He=>{He instanceof DOMException&&He.name==="AbortError"||Dt.current===ne&&Ct.current.sessionId===Ne&&Ct.current.runId===Pe&&we(At(He))})},Zr=s.sessions.filter(O=>`${O.prompt||""} ${O.sessionId}`.toLowerCase().includes(Go.toLowerCase())),[Sn,Wa]=y.useState(null),[ea,hr]=y.useState(!1),[Nl,en]=y.useState(""),Hs=(O,ne)=>{en(""),Wa({sessionId:O,where:ne})},ti=()=>{Wa(null),en("")},ta=async()=>{if(!Sn||ea)return;const{sessionId:O}=Sn;hr(!0),en("");try{await m$(O)}catch(ne){en(`Not archived: ${At(ne)}`),hr(!1);return}if(hr(!1),Wa(null),O===R.sessionId){const ne=p$(Zr,O);ne?ms(ne.sessionId,ne.latestRunId):Qr()}s.forgetSession(O)},Cl=a.jsx(KA,{busy:ea,error:Nl,onConfirm:()=>void ta(),onCancel:ti}),ni=O=>{const ne=[];(v.provider||v.model)&&!O.provider&&!O.model&&ne.push("provider","model"),Object.keys(j).length>0&&!Object.keys(O.toolLayer).length&&ne.push("tools"),O.toolLayer!==j&&E(O.toolLayer),v.maxIterations&&!O.maxIterations&&ne.push("max_iterations"),ne.length&&te(Pe=>{const He={...Pe},Ft=rr(me);for(const bt of ne)delete He[bt],Object.prototype.hasOwnProperty.call(Ft,bt)&&(He[bt]=Ft[bt]);return He}),C({...O,toolLayer:{}})},ts=(O,ne={...v,toolLayer:j},Ne=ni,Pe)=>a.jsx(iT,{tab:O,lockedReasonId:`code-${O}-locked`,value:ne,onChange:Ne,toolCatalog:s.toolCatalog,toolWarnings:s.toolWarnings,automationTools:!!Pe,toolsNotice:!Pe&&T?{text:ow,onDismiss:S}:null,connected:e.connected,automationFolders:!!Pe,defaultModel:!Pe&&ge.provider&&ge.model?{provider:String(ge.provider),model:String(ge.model)}:s.defaultModel,workflowDefault:!Pe&&!!(ge.provider&&ge.model),streaming:s.streaming,disabled:Pe?!e.connected:Gt||!e.connected,workspaceRootFixed:Pe==null?void 0:Pe.root,sessionId:Pe?void 0:R.sessionId,onOpenDefaultWorkspaces:()=>d(!0),workspaceRefreshKey:f,hideStreamReplies:!!Pe,lockedText:Pe?"Connect to a gateway to edit this automation.":void 0}),mr=a.jsx(wI,{value:g,onChange:O=>{dn.stop_tts(),_(O)},defaults:Hr,connected:e.connected,isAdmin:((gr=(Va=(Bl=e.status)==null?void 0:Bl.gateway)==null?void 0:Va.principal)==null?void 0:gr.admin)===!0,levelSource:dn,sampleSessionId:R.sessionId,ttsAvailable:((Wl=fs==null?void 0:fs.tts)==null?void 0:Wl.available)===!0}),vt=Wt.detail,$s=OR(Ut&&(vt!=null&&vt.definition)?{summary:vt.summary,definition:vt.definition}:null,(O,ne,Ne)=>Jt.revise(O,ne,Ne),s.toolCatalog),pr=(O,ne,Ne)=>{if(Ut){if(!(vt!=null&&vt.definition)||!$s)return Wt.selectedId?a.jsx(Io,{children:"Loading automation…"}):a.jsx("p",{className:"code-muted",children:"Select an automation in the sidebar."});const Pe={root:vt.definition.workspace_root||""};return a.jsxs("div",{className:"code-automation-settings",id:`code-settings-${O}`,"data-revision":$s.revision,children:[a.jsx(PR,{summary:vt.summary,settings:$s}),Ne($s.draft,$s.onChange,Pe)]})}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:Kr,children:Kr})]}),ne()]})},Wu=pr("model",()=>ts("model"),(O,ne,Ne)=>ts("model",O,ne,Ne)),Uu=pr("workflow",()=>a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"code-workflow-select","aria-busy":tt||void 0,children:[a.jsx(ue,{name:"agent",size:17}),a.jsx(Pv,{id:"code-workflow-picker",className:"code-workflow-picker",interfaceId:ln,ariaLabel:"Workflow",workflows:{...s.executable,reload:()=>void s.refresh()},value:z$(M,V),currentLabel:V&&M!==Xt&&!G.some(O=>O.id===V.id)?{name:V.name,detail:R.runId&&V.bundleVersion?`conversation version ${V.bundleVersion}`:V.bundleVersion?`@${V.bundleVersion}`:""}:null,unavailableReason:e.connected?Gt?"A run is in progress.":null:"Connect to a gateway first.",onChange:(O,ne)=>{const Ne=B$(O,ne);B(Ne),z||C(Pe=>({...Pe,workflow:Ne}))}}),M===Xt&&Jf(q)?a.jsx("span",{className:"code-workflow-resolved is-missing",role:"alert",title:Jf(q),children:Jf(q)}):null,Fa?a.jsx("span",{className:"code-workflow-resolved is-missing",role:"status",title:Fa,children:Fa}):null,Y&&Y.runId===R.runId&&Y.missing?a.jsx("span",{className:"code-workflow-resolved is-missing",role:"status",children:Y.text}):null]}),oe.state.status==="ok"?a.jsxs(a.Fragment,{children:[a.jsx(kT,{row:oe.state.row,save:oe.save,disabled:!e.connected}),a.jsx(lw,{block:oe.state.timeZone,save:oe.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:(V==null?void 0:V.description)||"Configure the values this workflow needs to run."}),tt?a.jsx("p",{role:"status",children:"Loading input schema…"}):le?null:W||Vn?a.jsx(UI,{schema:me,promptProperty:Vn,defaultModel:s.defaultModel,values:ge,onChange:te,disabled:Gt,onEditorError:P},V==null?void 0:V.id):a.jsx(Wh,{schema:me,defaultModel:s.defaultModel,values:ge,onChange:te,disabled:Gt,rawObject:!0,onEditorError:P},V==null?void 0:V.id),le?a.jsx("p",{role:"alert",className:"code-error-text",children:le}):null,dr?a.jsxs("button",{className:"code-primary-button",onClick:()=>Pt(!1),children:["Back to chat ",a.jsx(ue,{name:"chat",size:16})]}):a.jsxs("button",{className:"code-primary-button",disabled:Gt||tt||!!le||!!be||!e.connected,onClick:()=>Rn(()=>ps(se||String(ge[Vn||"prompt"]||""))),children:["Run workflow ",a.jsx(ue,{name:"playCircle",size:16})]})]})]}),()=>vt!=null&&vt.definition&&$s?a.jsxs(a.Fragment,{children:[a.jsx(DR,{summary:vt.summary,definition:vt.definition,settings:$s,busy:Wt.busy,disabled:!e.connected,emailStatus:Wt.emailStatus,onOpenMyEmail:Pa.openMyEmail,onRevise:(O,ne)=>Jt.revise(vt.automationId,O,ne),previewSchedule:Jt.previewSchedule,prepareTarget:Jr,workflowPickerOptions:{interfaceId:ln,workflows:{...s.executable,reload:()=>void s.refresh()}}}),oe.state.status==="ok"?a.jsx(lw,{block:oe.state.timeZone,save:oe.saveTimeZone,disabled:!e.connected}):null]}):null),si=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"})]}),ts("workspace")]}),(O,ne,Ne)=>ts("workspace",O,ne,Ne)),Vu=pr("tools",()=>ts("tools"),(O,ne,Ne)=>ts("tools",O,ne,Ne)),Gu=pr("skills",()=>ts("skills"),(O,ne,Ne)=>ts("skills",O,ne,Ne)),Hu=pr("voice",()=>mr,()=>mr),ri=Ut?`automation:${Wt.selectedId}`:`conversation:${R.sessionId}`,El=y.useRef({});y.useEffect(()=>{!$e||$e==="activity"||$e==="files"||El.current[$e]===ri||(El.current[$e]=ri,window.requestAnimationFrame(()=>{const O=document.querySelector(`#code-rail-panel-${$e} .af-rail__body`);O&&(O.scrollTop=0)}))},[ri,$e]);const ai=Ut?{count:0,hint:""}:gR(Qe.records,R.runId,Qe.view),Ku=a.jsx($R,{panel:$e,onPanel:Ge,docs:SA(e.connected),activityBadge:ai.count,activityHint:ai.hint,content:{activity:Ut?a.jsx(bR,{occurrences:(vt==null?void 0:vt.occurrences)||[],nowMs:Date.now(),onOpenRun:Pa.openRun}):a.jsx(pR,{records:Qe.records,runId:R.runId,view:Qe.view}),files:Ut?e.connected&&Wt.selectedId?a.jsx(gm,{fetchGateway:cl,runId:Wt.selectedId,title:"Automation files",refreshKey:vt==null?void 0:vt.summary.updated_at,copyText:xm,onOpenFolder:()=>gb(Wt.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(mR,{policy:s.policy,runId:R.runId,enabled:e.connected,isAdmin:((ci=(li=(ii=e.status)==null?void 0:ii.gateway)==null?void 0:li.principal)==null?void 0:ci.admin)===!0,refreshKey:Qe.status,onAttachFiles:Da,onAttach:async O=>{const ne=R.sessionId,Ne=R.runId,Pe=Dt.current,He=await Vr.attachments_ingest(ne,O);Ct.current.sessionId===ne&&Ct.current.runId===Ne&&Dt.current===Pe&&Ve(Ft=>[...Ft,He])}})}),model:Wu,workflow:Uu,workspace:si,tools:Vu,skills:Gu,voice:Hu}},`rail:${t}`);return a.jsxs("div",{className:`code-app${Bs?" code-app--nav-open":""}`,children:[a.jsx("a",{className:"code-skip-link",href:"#code-conversation",children:"Skip to conversation"}),a.jsxs(RA,{isDrawer:js,open:Bs,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(ue,{name:"x",size:18})})]}),a.jsxs("div",{className:"code-session-search",children:[a.jsx(ue,{name:"history",size:14}),a.jsx("input",{ref:Cs,"aria-label":"Search conversations",placeholder:"Search conversations",value:Go,onChange:O=>Fu(O.target.value)}),a.jsx("kbd",{children:"⌘K"})]}),a.jsxs(BA,{panels:ja,children:[a.jsx($I,{state:Wt,attention:Ca?{needsYou:DI(Ns.fold),newResults:FI(Ns.fold)}:null,available:Uo,discovering:s.capabilitiesLoading,createDisabled:tt||!!le||!V,selectedId:Ut?Wt.selectedId:"",onSelect:O=>{us(!0),Zt(!1),Jt.select(O)},onNew:()=>Gr(!0),onRefresh:()=>void Jt.refresh(),archivedOpen:lr.automations,onToggleArchived:()=>Na("automations"),onUnarchive:O=>void Jt.unarchive(O.automation_id).catch(()=>{}),onToggleActive:O=>void Jt.toggleActive(O).catch(()=>{}),open:ja.automations,onToggle:()=>Wo("automations")}),a.jsxs(WA,{open:ja.conversations,onToggle:()=>Wo("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:Qr,children:a.jsx(ue,{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(ue,{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"})]})}),Zr.map(O=>a.jsx(l$,{item:O,selected:O.sessionId===R.sessionId,onClick:()=>ms(O.sessionId,O.latestRunId),onAskArchive:e.connected?()=>Hs(O.sessionId,"card"):void 0,confirm:(Sn==null?void 0:Sn.where)==="card"&&Sn.sessionId===O.sessionId?Cl:void 0},O.sessionId)),s.sessionsLoaded&&!Zr.length?a.jsx("p",{className:"code-history-empty",children:Go?"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(Io,{children:"Loading conversations…"}):null,s.hasMore?a.jsx("button",{className:"code-load-more",onClick:s.loadMore,children:"Load more conversations"}):null,a.jsx(nb,{list:"conversations",count:s.archivedSessions,open:lr.conversations,onToggle:()=>Na("conversations"),children:a.jsx(g$,{enabled:e.connected&&lr.conversations,revision:s.archivedSessions,onOpen:O=>{Zt(!1),ms(O.sessionId,O.latestRunId)},onUnarchived:()=>void s.refresh()})})]})]})]}),Bs?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(ue,{name:"list",size:19})}),a.jsxs("div",{className:"code-breadcrumb",children:[a.jsx("span",{children:Ut?"Automations":"Conversations"}),a.jsx("span",{"aria-hidden":"true",children:"/"}),a.jsx("strong",{title:Ut?hs:Kr,children:Ut?hs:Kr})]}),!Ut&&fn&&e.connected?a.jsx(Kh,{className:"code-conversation-menu",label:"Conversation actions",title:"More actions",items:[{id:"archive",label:"Archive",danger:!0,onSelect:()=>Hs(fn.sessionId,"header")}]}):null,a.jsx(xS,{docs:{open:$e==="docs",onToggle:()=>{Ge(O=>O==="docs"?null:"docs"),Zt(!1)},label:"Docs assistant"},appearance:{value:o,onChange:l},about:{identity:XI,fetch:cl},identity:"menu",connection:e})]}),a.jsxs("div",{className:"code-content",children:[Ut?a.jsx(MI,{prepareTarget:Jr,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:fs,voicePreferences:g,enabled:e.connected,onClose:()=>us(!1),onEdit:Qo,onEditWorkspaces:Xo}):a.jsxs("main",{className:"code-conversation",id:"code-conversation",tabIndex:-1,children:[ae||Qe.error||Ae?a.jsxs("div",{className:"code-alert",role:"alert",children:[a.jsx(ue,{name:"warning",size:16}),a.jsx("span",{children:ae||Qe.error||Ae}),Qe.error||Ae?a.jsx("button",{onClick:()=>{Ae?window.location.reload():Rn(()=>Xn.load(R.runId))},children:"Reconnect"}):a.jsx("button",{"aria-label":"Dismiss error",onClick:()=>we(""),children:a.jsx(ue,{name:"x",size:14})})]}):null,(Sn==null?void 0:Sn.where)==="header"&&Sn.sessionId===R.sessionId?a.jsx("div",{className:"code-archive-confirm-bar",children:Cl}):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,ot?a.jsxs("div",{className:"code-alert",role:"alert",children:[a.jsx("span",{children:ot}),a.jsx("button",{onClick:Qr,children:"New conversation"})]}):null,le?a.jsxs("div",{className:"code-alert",role:"alert",children:[a.jsxs("span",{children:["Workflow inputs: ",le]}),a.jsx("button",{onClick:()=>_e(O=>O+1),children:"Retry"})]}):null,Se?a.jsxs("div",{className:"code-notice",role:"status",children:[Se,a.jsx("button",{"aria-label":"Dismiss notice",onClick:()=>Q(""),children:a.jsx(ue,{name:"x",size:13})})]}):null,Vt||oh(Qe.status)?a.jsx(JI,{active:Vt,paused:qo,snapshot:Qe,permissionsAll:hT(s.toolCatalog,j),onInteraction:Tn&&!qo?()=>{var Ne;const O=document.querySelector(".code-conversation .pc-chat-thread"),ne=O==null?void 0:O.querySelector(".pc-workflow-interaction");!O||!ne||(O.scrollTop+=ne.getBoundingClientRect().top-O.getBoundingClientRect().top,(Ne=ne.querySelector("h3"))==null||Ne.focus({preventScroll:!0}))}:void 0,onRevokeApproval:()=>{Xn.revokeToolApproval(),E(mT(s.toolCatalog,j))},onCommand:O=>Rn(()=>Xn.sendCommand(O,{})),onActivity:()=>{jt("activity")}}):null,a.jsx(ZE,{streamReplies:I,messages:(Tn==null?void 0:Tn.kind)==="tool-approval"?Ws.filter(O=>{var ne,Ne;return!(((ne=O.toolActivity)==null?void 0:ne.status)==="waiting"&&O.toolActivity.runId===((Ne=Qe.interaction)==null?void 0:Ne.runId))}):Ws,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:se,onDraftChange:ce,onSend:Xr,busy:Gt,busyLabel:xe?"Starting…":qo?"Paused":"Working…",steer:ei,toolbar:Ws.length?{exportTranscript:{filename:"conversation.md"}}:void 0,onCancel:jl,stopState:Qe.stop??null,disabled:!e.connected,interaction:Tn,onAttach:()=>{var O;return(O=Je.current)==null?void 0:O.click()},onFiles:O=>{Da(O)},attachmentItems:qr,onRemoveAttachment:Bu,onRetryAttachment:kn.retry,placeholder:Vt?Tn?"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:Vt?null:a.jsx(e2,{workflow:V,loading:s.loading||tt,onSuggestion:ce,onInputs:()=>Pt(!0),isAgent:dr,onRun:()=>Rn(()=>ps(se)),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(ue,{name:"terminal",size:14}),a.jsx("span",{children:fr.split("/").filter(Boolean).pop()||"Gateway workspace"})]}),e.connected?a.jsx(_I,{voice:dn,capability:fs,preferences:g,route:kS(g,Hr.value)},`${t}:${R.sessionId}:${R.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"})]})]})}),Es.length?a.jsxs("div",{className:"code-queue",children:[a.jsxs("div",{children:[a.jsxs("strong",{children:[Es.length," queued"," ",Es.length===1?"turn":"turns"]}),a.jsx(Ur,{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:Ho,onChange:Qn})]}),Es.map(O=>a.jsxs("div",{children:[a.jsx("span",{children:O.text}),Vt?null:a.jsx("button",{onClick:()=>Rn(()=>Ba(O)),children:"Run next"}),a.jsx("button",{"aria-label":"Remove queued turn",onClick:()=>ds(ne=>ne.filter(Ne=>Ne.id!==O.id)),children:a.jsx(ue,{name:"x",size:13})})]},O.id))]}):null]}),Ku]}),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:(V==null?void 0:V.name)||"No workflow selected"}),a.jsx("div",{}),a.jsx("span",{children:R.runId?`Run ${R.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:kn.announcement}),a.jsx("input",{ref:Je,hidden:!0,type:"file",multiple:!0,onChange:O=>{Da(Array.from(O.target.files||[])),O.target.value=""}}),a.jsx(LI,{connected:e.connected,workflowPickerOptions:{interfaceId:ln,workflows:{...s.executable,reload:()=>void s.refresh()}},open:cr,onClose:()=>Gr(!1),onOpenPreferences:()=>{Gr(!1),jt("workflow")},target:GR(M,V),availableTools:s.tools.filter(O=>O.enabled).map(O=>O.name),initialTools:$u(pu(s.toolCatalog,{app:j})?{...ge,tools:eu(s.toolCatalog,{app:j}).tools}:ge),buildInput:async(O,ne)=>{if(!ne)return Gs(O,{...rr(me),...ge},[],!0);const Ne=ne.flow_id==="@default"?q:s.workflows.find(bt=>`${bt.bundleId}@${bt.bundleVersion}`===("bundle_ref"in ne?ne.bundle_ref:"")&&bt.flowId===ne.flow_id);if(!Ne)throw new Error("The selected workflow is no longer available. Refresh the workflow list.");const Pe=await Qf(Ne);if(!Pe)throw new Error("Workflow inputs could not be checked. Refresh the workflow list and try again.");const He=Gs(O,rr(Pe),[],!0,Ne,Pe),Ft=Kf(Pe,He);if(Ft.length)throw new Error(Ft.join(" "));return He},workflowLabel:M===Xt?P$(s.gatewayDefault):(V==null?void 0:V.name)||"the selected workflow",initialPrompt:se||((ui=[...Ws].reverse().find(O=>O.role==="user"))==null?void 0:ui.content)||"",ctl:Jt,onOpenMyEmail:Oa,onCreated:()=>{us(!0),Zt(!1)}}),a.jsx(zk,{...e.modalProps}),a.jsx(MA,{open:u,onClose:()=>d(!1),connected:e.connected,onChanged:p})]})}function e2({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(ue,{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(ue,{name:d.icon,size:18}),a.jsxs("span",{children:[a.jsx("strong",{children:d.title}),a.jsx("small",{children:d.detail})]}),a.jsx(ue,{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 t2 extends wt.Component{constructor(){super(...arguments);Bt(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}}Jx();TA();"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("sw.js").catch(()=>{})});Wx.createRoot(document.getElementById("root")).render(a.jsx(wt.StrictMode,{children:a.jsx(t2,{children:a.jsx(ZI,{})})}));