@abstractframework/assistant 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,83 @@
1
+ var db=Object.defineProperty;var fb=(e,t,n)=>t in e?db(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bs=(e,t,n)=>fb(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 hb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var au={exports:{}},Ma={},iu={exports:{}},et={};/**
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 Lp;function pb(){if(Lp)return et;Lp=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"),g=Symbol.for("react.lazy"),v=Symbol.iterator;function w(M){return M===null||typeof M!="object"?null:(M=v&&M[v]||M["@@iterator"],typeof M=="function"?M:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,b={};function k(M,W,Y){this.props=M,this.context=W,this.refs=b,this.updater=Y||x}k.prototype.isReactComponent={},k.prototype.setState=function(M,W){if(typeof M!="object"&&typeof M!="function"&&M!=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,M,W,"setState")},k.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function $(){}$.prototype=k.prototype;function S(M,W,Y){this.props=M,this.context=W,this.refs=b,this.updater=Y||x}var N=S.prototype=new $;N.constructor=S,j(N,k.prototype),N.isPureReactComponent=!0;var C=Array.isArray,R=Object.prototype.hasOwnProperty,E={current:null},I={key:!0,ref:!0,__self:!0,__source:!0};function L(M,W,Y){var oe,de={},me=null,ee=null;if(W!=null)for(oe in W.ref!==void 0&&(ee=W.ref),W.key!==void 0&&(me=""+W.key),W)R.call(W,oe)&&!I.hasOwnProperty(oe)&&(de[oe]=W[oe]);var ce=arguments.length-2;if(ce===1)de.children=Y;else if(1<ce){for(var ye=Array(ce),Ce=0;Ce<ce;Ce++)ye[Ce]=arguments[Ce+2];de.children=ye}if(M&&M.defaultProps)for(oe in ce=M.defaultProps,ce)de[oe]===void 0&&(de[oe]=ce[oe]);return{$$typeof:e,type:M,key:me,ref:ee,props:de,_owner:E.current}}function D(M,W){return{$$typeof:e,type:M.type,key:W,ref:M.ref,props:M.props,_owner:M._owner}}function P(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function K(M){var W={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(Y){return W[Y]})}var se=/\/+/g;function Q(M,W){return typeof M=="object"&&M!==null&&M.key!=null?K(""+M.key):W.toString(36)}function z(M,W,Y,oe,de){var me=typeof M;(me==="undefined"||me==="boolean")&&(M=null);var ee=!1;if(M===null)ee=!0;else switch(me){case"string":case"number":ee=!0;break;case"object":switch(M.$$typeof){case e:case t:ee=!0}}if(ee)return ee=M,de=de(ee),M=oe===""?"."+Q(ee,0):oe,C(de)?(Y="",M!=null&&(Y=M.replace(se,"$&/")+"/"),z(de,W,Y,"",function(Ce){return Ce})):de!=null&&(P(de)&&(de=D(de,Y+(!de.key||ee&&ee.key===de.key?"":(""+de.key).replace(se,"$&/")+"/")+M)),W.push(de)),1;if(ee=0,oe=oe===""?".":oe+":",C(M))for(var ce=0;ce<M.length;ce++){me=M[ce];var ye=oe+Q(me,ce);ee+=z(me,W,Y,ye,de)}else if(ye=w(M),typeof ye=="function")for(M=ye.call(M),ce=0;!(me=M.next()).done;)me=me.value,ye=oe+Q(me,ce++),ee+=z(me,W,Y,ye,de);else if(me==="object")throw W=String(M),Error("Objects are not valid as a React child (found: "+(W==="[object Object]"?"object with keys {"+Object.keys(M).join(", ")+"}":W)+"). If you meant to render a collection of children, use an array instead.");return ee}function T(M,W,Y){if(M==null)return M;var oe=[],de=0;return z(M,oe,"","",function(me){return W.call(Y,me,de++)}),oe}function q(M){if(M._status===-1){var W=M._result;W=W(),W.then(function(Y){(M._status===0||M._status===-1)&&(M._status=1,M._result=Y)},function(Y){(M._status===0||M._status===-1)&&(M._status=2,M._result=Y)}),M._status===-1&&(M._status=0,M._result=W)}if(M._status===1)return M._result.default;throw M._result}var J={current:null},B={transition:null},O={ReactCurrentDispatcher:J,ReactCurrentBatchConfig:B,ReactCurrentOwner:E};function Z(){throw Error("act(...) is not supported in production builds of React.")}return et.Children={map:T,forEach:function(M,W,Y){T(M,function(){W.apply(this,arguments)},Y)},count:function(M){var W=0;return T(M,function(){W++}),W},toArray:function(M){return T(M,function(W){return W})||[]},only:function(M){if(!P(M))throw Error("React.Children.only expected to receive a single React element child.");return M}},et.Component=k,et.Fragment=n,et.Profiler=o,et.PureComponent=S,et.StrictMode=s,et.Suspense=f,et.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=O,et.act=Z,et.cloneElement=function(M,W,Y){if(M==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+M+".");var oe=j({},M.props),de=M.key,me=M.ref,ee=M._owner;if(W!=null){if(W.ref!==void 0&&(me=W.ref,ee=E.current),W.key!==void 0&&(de=""+W.key),M.type&&M.type.defaultProps)var ce=M.type.defaultProps;for(ye in W)R.call(W,ye)&&!I.hasOwnProperty(ye)&&(oe[ye]=W[ye]===void 0&&ce!==void 0?ce[ye]:W[ye])}var ye=arguments.length-2;if(ye===1)oe.children=Y;else if(1<ye){ce=Array(ye);for(var Ce=0;Ce<ye;Ce++)ce[Ce]=arguments[Ce+2];oe.children=ce}return{$$typeof:e,type:M.type,key:de,ref:me,props:oe,_owner:ee}},et.createContext=function(M){return M={$$typeof:u,_currentValue:M,_currentValue2:M,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},M.Provider={$$typeof:l,_context:M},M.Consumer=M},et.createElement=L,et.createFactory=function(M){var W=L.bind(null,M);return W.type=M,W},et.createRef=function(){return{current:null}},et.forwardRef=function(M){return{$$typeof:d,render:M}},et.isValidElement=P,et.lazy=function(M){return{$$typeof:g,_payload:{_status:-1,_result:M},_init:q}},et.memo=function(M,W){return{$$typeof:m,type:M,compare:W===void 0?null:W}},et.startTransition=function(M){var W=B.transition;B.transition={};try{M()}finally{B.transition=W}},et.unstable_act=Z,et.useCallback=function(M,W){return J.current.useCallback(M,W)},et.useContext=function(M){return J.current.useContext(M)},et.useDebugValue=function(){},et.useDeferredValue=function(M){return J.current.useDeferredValue(M)},et.useEffect=function(M,W){return J.current.useEffect(M,W)},et.useId=function(){return J.current.useId()},et.useImperativeHandle=function(M,W,Y){return J.current.useImperativeHandle(M,W,Y)},et.useInsertionEffect=function(M,W){return J.current.useInsertionEffect(M,W)},et.useLayoutEffect=function(M,W){return J.current.useLayoutEffect(M,W)},et.useMemo=function(M,W){return J.current.useMemo(M,W)},et.useReducer=function(M,W,Y){return J.current.useReducer(M,W,Y)},et.useRef=function(M){return J.current.useRef(M)},et.useState=function(M){return J.current.useState(M)},et.useSyncExternalStore=function(M,W,Y){return J.current.useSyncExternalStore(M,W,Y)},et.useTransition=function(){return J.current.useTransition()},et.version="18.3.1",et}var Ip;function $d(){return Ip||(Ip=1,iu.exports=pb()),iu.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 Pp;function mb(){if(Pp)return Ma;Pp=1;var e=$d(),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 g,v={},w=null,x=null;m!==void 0&&(w=""+m),f.key!==void 0&&(w=""+f.key),f.ref!==void 0&&(x=f.ref);for(g in f)s.call(f,g)&&!l.hasOwnProperty(g)&&(v[g]=f[g]);if(d&&d.defaultProps)for(g in f=d.defaultProps,f)v[g]===void 0&&(v[g]=f[g]);return{$$typeof:t,type:d,key:w,ref:x,props:v,_owner:o.current}}return Ma.Fragment=n,Ma.jsx=u,Ma.jsxs=u,Ma}var Op;function gb(){return Op||(Op=1,au.exports=mb()),au.exports}var a=gb(),p=$d();const it=hb(p);var _o={},ou={exports:{}},ln={},lu={exports:{}},cu={};/**
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 Dp;function vb(){return Dp||(Dp=1,(function(e){function t(B,O){var Z=B.length;B.push(O);e:for(;0<Z;){var M=Z-1>>>1,W=B[M];if(0<o(W,O))B[M]=O,B[Z]=W,Z=M;else break e}}function n(B){return B.length===0?null:B[0]}function s(B){if(B.length===0)return null;var O=B[0],Z=B.pop();if(Z!==O){B[0]=Z;e:for(var M=0,W=B.length,Y=W>>>1;M<Y;){var oe=2*(M+1)-1,de=B[oe],me=oe+1,ee=B[me];if(0>o(de,Z))me<W&&0>o(ee,de)?(B[M]=ee,B[me]=Z,M=me):(B[M]=de,B[oe]=Z,M=oe);else if(me<W&&0>o(ee,Z))B[M]=ee,B[me]=Z,M=me;else break e}}return O}function o(B,O){var Z=B.sortIndex-O.sortIndex;return Z!==0?Z:B.id-O.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=[],g=1,v=null,w=3,x=!1,j=!1,b=!1,k=typeof setTimeout=="function"?setTimeout:null,$=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function N(B){for(var O=n(m);O!==null;){if(O.callback===null)s(m);else if(O.startTime<=B)s(m),O.sortIndex=O.expirationTime,t(f,O);else break;O=n(m)}}function C(B){if(b=!1,N(B),!j)if(n(f)!==null)j=!0,q(R);else{var O=n(m);O!==null&&J(C,O.startTime-B)}}function R(B,O){j=!1,b&&(b=!1,$(L),L=-1),x=!0;var Z=w;try{for(N(O),v=n(f);v!==null&&(!(v.expirationTime>O)||B&&!K());){var M=v.callback;if(typeof M=="function"){v.callback=null,w=v.priorityLevel;var W=M(v.expirationTime<=O);O=e.unstable_now(),typeof W=="function"?v.callback=W:v===n(f)&&s(f),N(O)}else s(f);v=n(f)}if(v!==null)var Y=!0;else{var oe=n(m);oe!==null&&J(C,oe.startTime-O),Y=!1}return Y}finally{v=null,w=Z,x=!1}}var E=!1,I=null,L=-1,D=5,P=-1;function K(){return!(e.unstable_now()-P<D)}function se(){if(I!==null){var B=e.unstable_now();P=B;var O=!0;try{O=I(!0,B)}finally{O?Q():(E=!1,I=null)}}else E=!1}var Q;if(typeof S=="function")Q=function(){S(se)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,T=z.port2;z.port1.onmessage=se,Q=function(){T.postMessage(null)}}else Q=function(){k(se,0)};function q(B){I=B,E||(E=!0,Q())}function J(B,O){L=k(function(){B(e.unstable_now())},O)}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(B){B.callback=null},e.unstable_continueExecution=function(){j||x||(j=!0,q(R))},e.unstable_forceFrameRate=function(B){0>B||125<B?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):D=0<B?Math.floor(1e3/B):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(f)},e.unstable_next=function(B){switch(w){case 1:case 2:case 3:var O=3;break;default:O=w}var Z=w;w=O;try{return B()}finally{w=Z}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(B,O){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var Z=w;w=B;try{return O()}finally{w=Z}},e.unstable_scheduleCallback=function(B,O,Z){var M=e.unstable_now();switch(typeof Z=="object"&&Z!==null?(Z=Z.delay,Z=typeof Z=="number"&&0<Z?M+Z:M):Z=M,B){case 1:var W=-1;break;case 2:W=250;break;case 5:W=1073741823;break;case 4:W=1e4;break;default:W=5e3}return W=Z+W,B={id:g++,callback:O,priorityLevel:B,startTime:Z,expirationTime:W,sortIndex:-1},Z>M?(B.sortIndex=Z,t(m,B),n(f)===null&&B===n(m)&&(b?($(L),L=-1):b=!0,J(C,Z-M))):(B.sortIndex=W,t(f,B),j||x||(j=!0,q(R))),B},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(B){var O=w;return function(){var Z=w;w=O;try{return B.apply(this,arguments)}finally{w=Z}}}})(cu)),cu}var Fp;function yb(){return Fp||(Fp=1,lu.exports=vb()),lu.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 Bp;function wb(){if(Bp)return ln;Bp=1;var e=$d(),t=yb();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]*$/,g={},v={};function w(r){return f.call(v,r)?!0:f.call(g,r)?!1:m.test(r)?v[r]=!0:(g[r]=!0,!1)}function x(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 j(r,i,c,h){if(i===null||typeof i>"u"||x(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 b(r,i,c,h,y,_,A){this.acceptsBooleans=i===2||i===3||i===4,this.attributeName=h,this.attributeNamespace=y,this.mustUseProperty=c,this.propertyName=r,this.type=i,this.sanitizeURL=_,this.removeEmptyString=A}var k={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){k[r]=new b(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 b(i,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){k[r]=new b(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){k[r]=new b(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 b(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){k[r]=new b(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){k[r]=new b(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){k[r]=new b(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){k[r]=new b(r,5,!1,r.toLowerCase(),null,!1,!1)});var $=/[\-:]([a-z])/g;function S(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var i=r.replace($,S);k[i]=new b(i,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var i=r.replace($,S);k[i]=new b(i,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var i=r.replace($,S);k[i]=new b(i,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){k[r]=new b(r,1,!1,r.toLowerCase(),null,!1,!1)}),k.xlinkHref=new b("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){k[r]=new b(r,1,!1,r.toLowerCase(),null,!0,!0)});function N(r,i,c,h){var y=k.hasOwnProperty(i)?k[i]:null;(y!==null?y.type!==0:h||!(2<i.length)||i[0]!=="o"&&i[0]!=="O"||i[1]!=="n"&&i[1]!=="N")&&(j(i,c,y,h)&&(c=null),h||y===null?w(i)&&(c===null?r.removeAttribute(i):r.setAttribute(i,""+c)):y.mustUseProperty?r[y.propertyName]=c===null?y.type===3?!1:"":c:(i=y.attributeName,h=y.attributeNamespace,c===null?r.removeAttribute(i):(y=y.type,c=y===3||y===4&&c===!0?"":""+c,h?r.setAttributeNS(h,i,c):r.setAttribute(i,c))))}var C=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,R=Symbol.for("react.element"),E=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),L=Symbol.for("react.strict_mode"),D=Symbol.for("react.profiler"),P=Symbol.for("react.provider"),K=Symbol.for("react.context"),se=Symbol.for("react.forward_ref"),Q=Symbol.for("react.suspense"),z=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),J=Symbol.for("react.offscreen"),B=Symbol.iterator;function O(r){return r===null||typeof r!="object"?null:(r=B&&r[B]||r["@@iterator"],typeof r=="function"?r:null)}var Z=Object.assign,M;function W(r){if(M===void 0)try{throw Error()}catch(c){var i=c.stack.trim().match(/\n( *(at )?)/);M=i&&i[1]||""}return`
34
+ `+M+r}var Y=!1;function oe(r,i){if(!r||Y)return"";Y=!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(le){var h=le}Reflect.construct(r,[],i)}else{try{i.call()}catch(le){h=le}r.call(i.prototype)}else{try{throw Error()}catch(le){h=le}r()}}catch(le){if(le&&h&&typeof le.stack=="string"){for(var y=le.stack.split(`
35
+ `),_=h.stack.split(`
36
+ `),A=y.length-1,F=_.length-1;1<=A&&0<=F&&y[A]!==_[F];)F--;for(;1<=A&&0<=F;A--,F--)if(y[A]!==_[F]){if(A!==1||F!==1)do if(A--,F--,0>F||y[A]!==_[F]){var H=`
37
+ `+y[A].replace(" at new "," at ");return r.displayName&&H.includes("<anonymous>")&&(H=H.replace("<anonymous>",r.displayName)),H}while(1<=A&&0<=F);break}}}finally{Y=!1,Error.prepareStackTrace=c}return(r=r?r.displayName||r.name:"")?W(r):""}function de(r){switch(r.tag){case 5:return W(r.type);case 16:return W("Lazy");case 13:return W("Suspense");case 19:return W("SuspenseList");case 0:case 2:case 15:return r=oe(r.type,!1),r;case 11:return r=oe(r.type.render,!1),r;case 1:return r=oe(r.type,!0),r;default:return""}}function me(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 E:return"Portal";case D:return"Profiler";case L:return"StrictMode";case Q:return"Suspense";case z:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case K:return(r.displayName||"Context")+".Consumer";case P:return(r._context.displayName||"Context")+".Provider";case se:var i=r.render;return r=r.displayName,r||(r=i.displayName||i.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case T:return i=r.displayName||null,i!==null?i:me(r.type)||"Memo";case q:i=r._payload,r=r._init;try{return me(r(i))}catch{}}return null}function ee(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 me(i);case 8:return i===L?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof i=="function")return i.displayName||i.name||null;if(typeof i=="string")return i}return null}function ce(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function ye(r){var i=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(i==="checkbox"||i==="radio")}function Ce(r){var i=ye(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 y=c.get,_=c.set;return Object.defineProperty(r,i,{configurable:!0,get:function(){return y.call(this)},set:function(A){h=""+A,_.call(this,A)}}),Object.defineProperty(r,i,{enumerable:c.enumerable}),{getValue:function(){return h},setValue:function(A){h=""+A},stopTracking:function(){r._valueTracker=null,delete r[i]}}}}function ze(r){r._valueTracker||(r._valueTracker=Ce(r))}function Ve(r){if(!r)return!1;var i=r._valueTracker;if(!i)return!0;var c=i.getValue(),h="";return r&&(h=ye(r)?r.checked?"true":"false":r.value),r=h,r!==c?(i.setValue(r),!0):!1}function Ee(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 Z({},i,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:c??r._wrapperState.initialChecked})}function Ue(r,i){var c=i.defaultValue==null?"":i.defaultValue,h=i.checked!=null?i.checked:i.defaultChecked;c=ce(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 ne(r,i){i=i.checked,i!=null&&N(r,"checked",i,!1)}function $e(r,i){ne(r,i);var c=ce(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")?Ge(r,i.type,c):i.hasOwnProperty("defaultValue")&&Ge(r,i.type,ce(i.defaultValue)),i.checked==null&&i.defaultChecked!=null&&(r.defaultChecked=!!i.defaultChecked)}function Pe(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 Ge(r,i,c){(i!=="number"||Ee(r.ownerDocument)!==r)&&(c==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+c&&(r.defaultValue=""+c))}var G=Array.isArray;function fe(r,i,c,h){if(r=r.options,i){i={};for(var y=0;y<c.length;y++)i["$"+c[y]]=!0;for(c=0;c<r.length;c++)y=i.hasOwnProperty("$"+r[c].value),r[c].selected!==y&&(r[c].selected=y),y&&h&&(r[c].defaultSelected=!0)}else{for(c=""+ce(c),i=null,y=0;y<r.length;y++){if(r[y].value===c){r[y].selected=!0,h&&(r[y].defaultSelected=!0);return}i!==null||r[y].disabled||(i=r[y])}i!==null&&(i.selected=!0)}}function te(r,i){if(i.dangerouslySetInnerHTML!=null)throw Error(n(91));return Z({},i,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function pe(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(G(c)){if(1<c.length)throw Error(n(93));c=c[0]}i=c}i==null&&(i=""),c=i}r._wrapperState={initialValue:ce(c)}}function Se(r,i){var c=ce(i.value),h=ce(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 Ze(r){var i=r.textContent;i===r._wrapperState.initialValue&&i!==""&&i!==null&&(r.value=i)}function Ye(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 rt(r,i){return r==null||r==="http://www.w3.org/1999/xhtml"?Ye(i):r==="http://www.w3.org/2000/svg"&&i==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var V,he=(function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(i,c,h,y){MSApp.execUnsafeLocalFunction(function(){return r(i,c,h,y)})}:r})(function(r,i){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=i;else{for(V=V||document.createElement("div"),V.innerHTML="<svg>"+i.valueOf().toString()+"</svg>",i=V.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;i.firstChild;)r.appendChild(i.firstChild)}});function Je(r,i){if(i){var c=r.firstChild;if(c&&c===r.lastChild&&c.nodeType===3){c.nodeValue=i;return}}r.textContent=i}var Oe={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},_t=["Webkit","ms","Moz","O"];Object.keys(Oe).forEach(function(r){_t.forEach(function(i){i=i+r.charAt(0).toUpperCase()+r.substring(1),Oe[i]=Oe[r]})});function Nt(r,i,c){return i==null||typeof i=="boolean"||i===""?"":c||typeof i!="number"||i===0||Oe.hasOwnProperty(r)&&Oe[r]?(""+i).trim():i+"px"}function zt(r,i){r=r.style;for(var c in i)if(i.hasOwnProperty(c)){var h=c.indexOf("--")===0,y=Nt(c,i[c],h);c==="float"&&(c="cssFloat"),h?r.setProperty(c,y):r[c]=y}}var An=Z({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 ht(r,i){if(i){if(An[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 Tt(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 U=null;function ie(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var ue=null,we=null,Ne=null;function Te(r){if(r=ya(r)){if(typeof ue!="function")throw Error(n(280));var i=r.stateNode;i&&(i=Li(i),ue(r.stateNode,r.type,i))}}function Fe(r){we?Ne?Ne.push(r):Ne=[r]:we=r}function xe(){if(we){var r=we,i=Ne;if(Ne=we=null,Te(r),i)for(r=0;r<i.length;r++)Te(i[r])}}function Be(r,i){return r(i)}function Ke(){}var ot=!1;function Ut(r,i,c){if(ot)return r(i,c);ot=!0;try{return Be(r,i,c)}finally{ot=!1,(we!==null||Ne!==null)&&(Ke(),xe())}}function tt(r,i){var c=r.stateNode;if(c===null)return null;var h=Li(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 bt=!1;if(d)try{var Lt={};Object.defineProperty(Lt,"passive",{get:function(){bt=!0}}),window.addEventListener("test",Lt,Lt),window.removeEventListener("test",Lt,Lt)}catch{bt=!1}function $n(r,i,c,h,y,_,A,F,H){var le=Array.prototype.slice.call(arguments,3);try{i.apply(c,le)}catch(ve){this.onError(ve)}}var hn=!1,zn=null,hi=!1,jl=null,yw={onError:function(r){hn=!0,zn=r}};function ww(r,i,c,h,y,_,A,F,H){hn=!1,zn=null,$n.apply(yw,arguments)}function _w(r,i,c,h,y,_,A,F,H){if(ww.apply(this,arguments),hn){if(hn){var le=zn;hn=!1,zn=null}else throw Error(n(198));hi||(hi=!0,jl=le)}}function Wr(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 nf(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 rf(r){if(Wr(r)!==r)throw Error(n(188))}function bw(r){var i=r.alternate;if(!i){if(i=Wr(r),i===null)throw Error(n(188));return i!==r?null:r}for(var c=r,h=i;;){var y=c.return;if(y===null)break;var _=y.alternate;if(_===null){if(h=y.return,h!==null){c=h;continue}break}if(y.child===_.child){for(_=y.child;_;){if(_===c)return rf(y),r;if(_===h)return rf(y),i;_=_.sibling}throw Error(n(188))}if(c.return!==h.return)c=y,h=_;else{for(var A=!1,F=y.child;F;){if(F===c){A=!0,c=y,h=_;break}if(F===h){A=!0,h=y,c=_;break}F=F.sibling}if(!A){for(F=_.child;F;){if(F===c){A=!0,c=_,h=y;break}if(F===h){A=!0,h=_,c=y;break}F=F.sibling}if(!A)throw Error(n(189))}}if(c.alternate!==h)throw Error(n(190))}if(c.tag!==3)throw Error(n(188));return c.stateNode.current===c?r:i}function sf(r){return r=bw(r),r!==null?af(r):null}function af(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var i=af(r);if(i!==null)return i;r=r.sibling}return null}var of=t.unstable_scheduleCallback,lf=t.unstable_cancelCallback,xw=t.unstable_shouldYield,kw=t.unstable_requestPaint,xt=t.unstable_now,jw=t.unstable_getCurrentPriorityLevel,Sl=t.unstable_ImmediatePriority,cf=t.unstable_UserBlockingPriority,pi=t.unstable_NormalPriority,Sw=t.unstable_LowPriority,uf=t.unstable_IdlePriority,mi=null,Un=null;function Nw(r){if(Un&&typeof Un.onCommitFiberRoot=="function")try{Un.onCommitFiberRoot(mi,r,void 0,(r.current.flags&128)===128)}catch{}}var Rn=Math.clz32?Math.clz32:Tw,Cw=Math.log,Ew=Math.LN2;function Tw(r){return r>>>=0,r===0?32:31-(Cw(r)/Ew|0)|0}var gi=64,vi=4194304;function ea(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 yi(r,i){var c=r.pendingLanes;if(c===0)return 0;var h=0,y=r.suspendedLanes,_=r.pingedLanes,A=c&268435455;if(A!==0){var F=A&~y;F!==0?h=ea(F):(_&=A,_!==0&&(h=ea(_)))}else A=c&~y,A!==0?h=ea(A):_!==0&&(h=ea(_));if(h===0)return 0;if(i!==0&&i!==h&&(i&y)===0&&(y=h&-h,_=i&-i,y>=_||y===16&&(_&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-Rn(i),y=1<<c,h|=r[c],i&=~y;return h}function Aw(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 $w(r,i){for(var c=r.suspendedLanes,h=r.pingedLanes,y=r.expirationTimes,_=r.pendingLanes;0<_;){var A=31-Rn(_),F=1<<A,H=y[A];H===-1?((F&c)===0||(F&h)!==0)&&(y[A]=Aw(F,i)):H<=i&&(r.expiredLanes|=F),_&=~F}}function Nl(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function df(){var r=gi;return gi<<=1,(gi&4194240)===0&&(gi=64),r}function Cl(r){for(var i=[],c=0;31>c;c++)i.push(r);return i}function ta(r,i,c){r.pendingLanes|=i,i!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,i=31-Rn(i),r[i]=c}function Rw(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 y=31-Rn(c),_=1<<y;i[y]=0,h[y]=-1,r[y]=-1,c&=~_}}function El(r,i){var c=r.entangledLanes|=i;for(r=r.entanglements;c;){var h=31-Rn(c),y=1<<h;y&i|r[h]&i&&(r[h]|=i),c&=~y}}var lt=0;function ff(r){return r&=-r,1<r?4<r?(r&268435455)!==0?16:536870912:4:1}var hf,Tl,pf,mf,gf,Al=!1,wi=[],ur=null,dr=null,fr=null,na=new Map,ra=new Map,hr=[],Mw="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 vf(r,i){switch(r){case"focusin":case"focusout":ur=null;break;case"dragenter":case"dragleave":dr=null;break;case"mouseover":case"mouseout":fr=null;break;case"pointerover":case"pointerout":na.delete(i.pointerId);break;case"gotpointercapture":case"lostpointercapture":ra.delete(i.pointerId)}}function sa(r,i,c,h,y,_){return r===null||r.nativeEvent!==_?(r={blockedOn:i,domEventName:c,eventSystemFlags:h,nativeEvent:_,targetContainers:[y]},i!==null&&(i=ya(i),i!==null&&Tl(i)),r):(r.eventSystemFlags|=h,i=r.targetContainers,y!==null&&i.indexOf(y)===-1&&i.push(y),r)}function Lw(r,i,c,h,y){switch(i){case"focusin":return ur=sa(ur,r,i,c,h,y),!0;case"dragenter":return dr=sa(dr,r,i,c,h,y),!0;case"mouseover":return fr=sa(fr,r,i,c,h,y),!0;case"pointerover":var _=y.pointerId;return na.set(_,sa(na.get(_)||null,r,i,c,h,y)),!0;case"gotpointercapture":return _=y.pointerId,ra.set(_,sa(ra.get(_)||null,r,i,c,h,y)),!0}return!1}function yf(r){var i=Vr(r.target);if(i!==null){var c=Wr(i);if(c!==null){if(i=c.tag,i===13){if(i=nf(c),i!==null){r.blockedOn=i,gf(r.priority,function(){pf(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 _i(r){if(r.blockedOn!==null)return!1;for(var i=r.targetContainers;0<i.length;){var c=Rl(r.domEventName,r.eventSystemFlags,i[0],r.nativeEvent);if(c===null){c=r.nativeEvent;var h=new c.constructor(c.type,c);U=h,c.target.dispatchEvent(h),U=null}else return i=ya(c),i!==null&&Tl(i),r.blockedOn=c,!1;i.shift()}return!0}function wf(r,i,c){_i(r)&&c.delete(i)}function Iw(){Al=!1,ur!==null&&_i(ur)&&(ur=null),dr!==null&&_i(dr)&&(dr=null),fr!==null&&_i(fr)&&(fr=null),na.forEach(wf),ra.forEach(wf)}function aa(r,i){r.blockedOn===i&&(r.blockedOn=null,Al||(Al=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Iw)))}function ia(r){function i(y){return aa(y,r)}if(0<wi.length){aa(wi[0],r);for(var c=1;c<wi.length;c++){var h=wi[c];h.blockedOn===r&&(h.blockedOn=null)}}for(ur!==null&&aa(ur,r),dr!==null&&aa(dr,r),fr!==null&&aa(fr,r),na.forEach(i),ra.forEach(i),c=0;c<hr.length;c++)h=hr[c],h.blockedOn===r&&(h.blockedOn=null);for(;0<hr.length&&(c=hr[0],c.blockedOn===null);)yf(c),c.blockedOn===null&&hr.shift()}var ys=C.ReactCurrentBatchConfig,bi=!0;function Pw(r,i,c,h){var y=lt,_=ys.transition;ys.transition=null;try{lt=1,$l(r,i,c,h)}finally{lt=y,ys.transition=_}}function Ow(r,i,c,h){var y=lt,_=ys.transition;ys.transition=null;try{lt=4,$l(r,i,c,h)}finally{lt=y,ys.transition=_}}function $l(r,i,c,h){if(bi){var y=Rl(r,i,c,h);if(y===null)Jl(r,i,h,xi,c),vf(r,h);else if(Lw(y,r,i,c,h))h.stopPropagation();else if(vf(r,h),i&4&&-1<Mw.indexOf(r)){for(;y!==null;){var _=ya(y);if(_!==null&&hf(_),_=Rl(r,i,c,h),_===null&&Jl(r,i,h,xi,c),_===y)break;y=_}y!==null&&h.stopPropagation()}else Jl(r,i,h,null,c)}}var xi=null;function Rl(r,i,c,h){if(xi=null,r=ie(h),r=Vr(r),r!==null)if(i=Wr(r),i===null)r=null;else if(c=i.tag,c===13){if(r=nf(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 xi=r,null}function _f(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(jw()){case Sl:return 1;case cf:return 4;case pi:case Sw:return 16;case uf:return 536870912;default:return 16}default:return 16}}var pr=null,Ml=null,ki=null;function bf(){if(ki)return ki;var r,i=Ml,c=i.length,h,y="value"in pr?pr.value:pr.textContent,_=y.length;for(r=0;r<c&&i[r]===y[r];r++);var A=c-r;for(h=1;h<=A&&i[c-h]===y[_-h];h++);return ki=y.slice(r,1<h?1-h:void 0)}function ji(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 Si(){return!0}function xf(){return!1}function pn(r){function i(c,h,y,_,A){this._reactName=c,this._targetInst=y,this.type=h,this.nativeEvent=_,this.target=A,this.currentTarget=null;for(var F in r)r.hasOwnProperty(F)&&(c=r[F],this[F]=c?c(_):_[F]);return this.isDefaultPrevented=(_.defaultPrevented!=null?_.defaultPrevented:_.returnValue===!1)?Si:xf,this.isPropagationStopped=xf,this}return Z(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=Si)},stopPropagation:function(){var c=this.nativeEvent;c&&(c.stopPropagation?c.stopPropagation():typeof c.cancelBubble!="unknown"&&(c.cancelBubble=!0),this.isPropagationStopped=Si)},persist:function(){},isPersistent:Si}),i}var ws={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ll=pn(ws),oa=Z({},ws,{view:0,detail:0}),Dw=pn(oa),Il,Pl,la,Ni=Z({},oa,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Dl,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!==la&&(la&&r.type==="mousemove"?(Il=r.screenX-la.screenX,Pl=r.screenY-la.screenY):Pl=Il=0,la=r),Il)},movementY:function(r){return"movementY"in r?r.movementY:Pl}}),kf=pn(Ni),Fw=Z({},Ni,{dataTransfer:0}),Bw=pn(Fw),zw=Z({},oa,{relatedTarget:0}),Ol=pn(zw),Uw=Z({},ws,{animationName:0,elapsedTime:0,pseudoElement:0}),Ww=pn(Uw),Vw=Z({},ws,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),qw=pn(Vw),Hw=Z({},ws,{data:0}),jf=pn(Hw),Gw={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Kw={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"},Jw={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Yw(r){var i=this.nativeEvent;return i.getModifierState?i.getModifierState(r):(r=Jw[r])?!!i[r]:!1}function Dl(){return Yw}var Qw=Z({},oa,{key:function(r){if(r.key){var i=Gw[r.key]||r.key;if(i!=="Unidentified")return i}return r.type==="keypress"?(r=ji(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?Kw[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Dl,charCode:function(r){return r.type==="keypress"?ji(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?ji(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),Xw=pn(Qw),Zw=Z({},Ni,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Sf=pn(Zw),e_=Z({},oa,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Dl}),t_=pn(e_),n_=Z({},ws,{propertyName:0,elapsedTime:0,pseudoElement:0}),r_=pn(n_),s_=Z({},Ni,{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}),a_=pn(s_),i_=[9,13,27,32],Fl=d&&"CompositionEvent"in window,ca=null;d&&"documentMode"in document&&(ca=document.documentMode);var o_=d&&"TextEvent"in window&&!ca,Nf=d&&(!Fl||ca&&8<ca&&11>=ca),Cf=" ",Ef=!1;function Tf(r,i){switch(r){case"keyup":return i_.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Af(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var _s=!1;function l_(r,i){switch(r){case"compositionend":return Af(i);case"keypress":return i.which!==32?null:(Ef=!0,Cf);case"textInput":return r=i.data,r===Cf&&Ef?null:r;default:return null}}function c_(r,i){if(_s)return r==="compositionend"||!Fl&&Tf(r,i)?(r=bf(),ki=Ml=pr=null,_s=!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 Nf&&i.locale!=="ko"?null:i.data;default:return null}}var u_={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 $f(r){var i=r&&r.nodeName&&r.nodeName.toLowerCase();return i==="input"?!!u_[r.type]:i==="textarea"}function Rf(r,i,c,h){Fe(h),i=$i(i,"onChange"),0<i.length&&(c=new Ll("onChange","change",null,c,h),r.push({event:c,listeners:i}))}var ua=null,da=null;function d_(r){Yf(r,0)}function Ci(r){var i=Ss(r);if(Ve(i))return r}function f_(r,i){if(r==="change")return i}var Mf=!1;if(d){var Bl;if(d){var zl="oninput"in document;if(!zl){var Lf=document.createElement("div");Lf.setAttribute("oninput","return;"),zl=typeof Lf.oninput=="function"}Bl=zl}else Bl=!1;Mf=Bl&&(!document.documentMode||9<document.documentMode)}function If(){ua&&(ua.detachEvent("onpropertychange",Pf),da=ua=null)}function Pf(r){if(r.propertyName==="value"&&Ci(da)){var i=[];Rf(i,da,r,ie(r)),Ut(d_,i)}}function h_(r,i,c){r==="focusin"?(If(),ua=i,da=c,ua.attachEvent("onpropertychange",Pf)):r==="focusout"&&If()}function p_(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return Ci(da)}function m_(r,i){if(r==="click")return Ci(i)}function g_(r,i){if(r==="input"||r==="change")return Ci(i)}function v_(r,i){return r===i&&(r!==0||1/r===1/i)||r!==r&&i!==i}var Mn=typeof Object.is=="function"?Object.is:v_;function fa(r,i){if(Mn(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 y=c[h];if(!f.call(i,y)||!Mn(r[y],i[y]))return!1}return!0}function Of(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function Df(r,i){var c=Of(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=Of(c)}}function Ff(r,i){return r&&i?r===i?!0:r&&r.nodeType===3?!1:i&&i.nodeType===3?Ff(r,i.parentNode):"contains"in r?r.contains(i):r.compareDocumentPosition?!!(r.compareDocumentPosition(i)&16):!1:!1}function Bf(){for(var r=window,i=Ee();i instanceof r.HTMLIFrameElement;){try{var c=typeof i.contentWindow.location.href=="string"}catch{c=!1}if(c)r=i.contentWindow;else break;i=Ee(r.document)}return i}function Ul(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 y_(r){var i=Bf(),c=r.focusedElem,h=r.selectionRange;if(i!==c&&c&&c.ownerDocument&&Ff(c.ownerDocument.documentElement,c)){if(h!==null&&Ul(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 y=c.textContent.length,_=Math.min(h.start,y);h=h.end===void 0?_:Math.min(h.end,y),!r.extend&&_>h&&(y=h,h=_,_=y),y=Df(c,_);var A=Df(c,h);y&&A&&(r.rangeCount!==1||r.anchorNode!==y.node||r.anchorOffset!==y.offset||r.focusNode!==A.node||r.focusOffset!==A.offset)&&(i=i.createRange(),i.setStart(y.node,y.offset),r.removeAllRanges(),_>h?(r.addRange(i),r.extend(A.node,A.offset)):(i.setEnd(A.node,A.offset),r.addRange(i)))}}for(i=[],r=c;r=r.parentNode;)r.nodeType===1&&i.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof c.focus=="function"&&c.focus(),c=0;c<i.length;c++)r=i[c],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var w_=d&&"documentMode"in document&&11>=document.documentMode,bs=null,Wl=null,ha=null,Vl=!1;function zf(r,i,c){var h=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Vl||bs==null||bs!==Ee(h)||(h=bs,"selectionStart"in h&&Ul(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}),ha&&fa(ha,h)||(ha=h,h=$i(Wl,"onSelect"),0<h.length&&(i=new Ll("onSelect","select",null,i,c),r.push({event:i,listeners:h}),i.target=bs)))}function Ei(r,i){var c={};return c[r.toLowerCase()]=i.toLowerCase(),c["Webkit"+r]="webkit"+i,c["Moz"+r]="moz"+i,c}var xs={animationend:Ei("Animation","AnimationEnd"),animationiteration:Ei("Animation","AnimationIteration"),animationstart:Ei("Animation","AnimationStart"),transitionend:Ei("Transition","TransitionEnd")},ql={},Uf={};d&&(Uf=document.createElement("div").style,"AnimationEvent"in window||(delete xs.animationend.animation,delete xs.animationiteration.animation,delete xs.animationstart.animation),"TransitionEvent"in window||delete xs.transitionend.transition);function Ti(r){if(ql[r])return ql[r];if(!xs[r])return r;var i=xs[r],c;for(c in i)if(i.hasOwnProperty(c)&&c in Uf)return ql[r]=i[c];return r}var Wf=Ti("animationend"),Vf=Ti("animationiteration"),qf=Ti("animationstart"),Hf=Ti("transitionend"),Gf=new Map,Kf="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 mr(r,i){Gf.set(r,i),l(i,[r])}for(var Hl=0;Hl<Kf.length;Hl++){var Gl=Kf[Hl],__=Gl.toLowerCase(),b_=Gl[0].toUpperCase()+Gl.slice(1);mr(__,"on"+b_)}mr(Wf,"onAnimationEnd"),mr(Vf,"onAnimationIteration"),mr(qf,"onAnimationStart"),mr("dblclick","onDoubleClick"),mr("focusin","onFocus"),mr("focusout","onBlur"),mr(Hf,"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 pa="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(" "),x_=new Set("cancel close invalid load scroll toggle".split(" ").concat(pa));function Jf(r,i,c){var h=r.type||"unknown-event";r.currentTarget=c,_w(h,i,void 0,r),r.currentTarget=null}function Yf(r,i){i=(i&4)!==0;for(var c=0;c<r.length;c++){var h=r[c],y=h.event;h=h.listeners;e:{var _=void 0;if(i)for(var A=h.length-1;0<=A;A--){var F=h[A],H=F.instance,le=F.currentTarget;if(F=F.listener,H!==_&&y.isPropagationStopped())break e;Jf(y,F,le),_=H}else for(A=0;A<h.length;A++){if(F=h[A],H=F.instance,le=F.currentTarget,F=F.listener,H!==_&&y.isPropagationStopped())break e;Jf(y,F,le),_=H}}}if(hi)throw r=jl,hi=!1,jl=null,r}function pt(r,i){var c=i[tc];c===void 0&&(c=i[tc]=new Set);var h=r+"__bubble";c.has(h)||(Qf(i,r,2,!1),c.add(h))}function Kl(r,i,c){var h=0;i&&(h|=4),Qf(c,r,h,i)}var Ai="_reactListening"+Math.random().toString(36).slice(2);function ma(r){if(!r[Ai]){r[Ai]=!0,s.forEach(function(c){c!=="selectionchange"&&(x_.has(c)||Kl(c,!1,r),Kl(c,!0,r))});var i=r.nodeType===9?r:r.ownerDocument;i===null||i[Ai]||(i[Ai]=!0,Kl("selectionchange",!1,i))}}function Qf(r,i,c,h){switch(_f(i)){case 1:var y=Pw;break;case 4:y=Ow;break;default:y=$l}c=y.bind(null,i,c,r),y=void 0,!bt||i!=="touchstart"&&i!=="touchmove"&&i!=="wheel"||(y=!0),h?y!==void 0?r.addEventListener(i,c,{capture:!0,passive:y}):r.addEventListener(i,c,!0):y!==void 0?r.addEventListener(i,c,{passive:y}):r.addEventListener(i,c,!1)}function Jl(r,i,c,h,y){var _=h;if((i&1)===0&&(i&2)===0&&h!==null)e:for(;;){if(h===null)return;var A=h.tag;if(A===3||A===4){var F=h.stateNode.containerInfo;if(F===y||F.nodeType===8&&F.parentNode===y)break;if(A===4)for(A=h.return;A!==null;){var H=A.tag;if((H===3||H===4)&&(H=A.stateNode.containerInfo,H===y||H.nodeType===8&&H.parentNode===y))return;A=A.return}for(;F!==null;){if(A=Vr(F),A===null)return;if(H=A.tag,H===5||H===6){h=_=A;continue e}F=F.parentNode}}h=h.return}Ut(function(){var le=_,ve=ie(c),_e=[];e:{var ge=Gf.get(r);if(ge!==void 0){var Ae=Ll,Le=r;switch(r){case"keypress":if(ji(c)===0)break e;case"keydown":case"keyup":Ae=Xw;break;case"focusin":Le="focus",Ae=Ol;break;case"focusout":Le="blur",Ae=Ol;break;case"beforeblur":case"afterblur":Ae=Ol;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":Ae=kf;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Ae=Bw;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Ae=t_;break;case Wf:case Vf:case qf:Ae=Ww;break;case Hf:Ae=r_;break;case"scroll":Ae=Dw;break;case"wheel":Ae=a_;break;case"copy":case"cut":case"paste":Ae=qw;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Ae=Sf}var Ie=(i&4)!==0,kt=!Ie&&r==="scroll",re=Ie?ge!==null?ge+"Capture":null:ge;Ie=[];for(var X=le,ae;X!==null;){ae=X;var ke=ae.stateNode;if(ae.tag===5&&ke!==null&&(ae=ke,re!==null&&(ke=tt(X,re),ke!=null&&Ie.push(ga(X,ke,ae)))),kt)break;X=X.return}0<Ie.length&&(ge=new Ae(ge,Le,null,c,ve),_e.push({event:ge,listeners:Ie}))}}if((i&7)===0){e:{if(ge=r==="mouseover"||r==="pointerover",Ae=r==="mouseout"||r==="pointerout",ge&&c!==U&&(Le=c.relatedTarget||c.fromElement)&&(Vr(Le)||Le[Kn]))break e;if((Ae||ge)&&(ge=ve.window===ve?ve:(ge=ve.ownerDocument)?ge.defaultView||ge.parentWindow:window,Ae?(Le=c.relatedTarget||c.toElement,Ae=le,Le=Le?Vr(Le):null,Le!==null&&(kt=Wr(Le),Le!==kt||Le.tag!==5&&Le.tag!==6)&&(Le=null)):(Ae=null,Le=le),Ae!==Le)){if(Ie=kf,ke="onMouseLeave",re="onMouseEnter",X="mouse",(r==="pointerout"||r==="pointerover")&&(Ie=Sf,ke="onPointerLeave",re="onPointerEnter",X="pointer"),kt=Ae==null?ge:Ss(Ae),ae=Le==null?ge:Ss(Le),ge=new Ie(ke,X+"leave",Ae,c,ve),ge.target=kt,ge.relatedTarget=ae,ke=null,Vr(ve)===le&&(Ie=new Ie(re,X+"enter",Le,c,ve),Ie.target=ae,Ie.relatedTarget=kt,ke=Ie),kt=ke,Ae&&Le)t:{for(Ie=Ae,re=Le,X=0,ae=Ie;ae;ae=ks(ae))X++;for(ae=0,ke=re;ke;ke=ks(ke))ae++;for(;0<X-ae;)Ie=ks(Ie),X--;for(;0<ae-X;)re=ks(re),ae--;for(;X--;){if(Ie===re||re!==null&&Ie===re.alternate)break t;Ie=ks(Ie),re=ks(re)}Ie=null}else Ie=null;Ae!==null&&Xf(_e,ge,Ae,Ie,!1),Le!==null&&kt!==null&&Xf(_e,kt,Le,Ie,!0)}}e:{if(ge=le?Ss(le):window,Ae=ge.nodeName&&ge.nodeName.toLowerCase(),Ae==="select"||Ae==="input"&&ge.type==="file")var De=f_;else if($f(ge))if(Mf)De=g_;else{De=p_;var qe=h_}else(Ae=ge.nodeName)&&Ae.toLowerCase()==="input"&&(ge.type==="checkbox"||ge.type==="radio")&&(De=m_);if(De&&(De=De(r,le))){Rf(_e,De,c,ve);break e}qe&&qe(r,ge,le),r==="focusout"&&(qe=ge._wrapperState)&&qe.controlled&&ge.type==="number"&&Ge(ge,"number",ge.value)}switch(qe=le?Ss(le):window,r){case"focusin":($f(qe)||qe.contentEditable==="true")&&(bs=qe,Wl=le,ha=null);break;case"focusout":ha=Wl=bs=null;break;case"mousedown":Vl=!0;break;case"contextmenu":case"mouseup":case"dragend":Vl=!1,zf(_e,c,ve);break;case"selectionchange":if(w_)break;case"keydown":case"keyup":zf(_e,c,ve)}var He;if(Fl)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 _s?Tf(r,c)&&(Qe="onCompositionEnd"):r==="keydown"&&c.keyCode===229&&(Qe="onCompositionStart");Qe&&(Nf&&c.locale!=="ko"&&(_s||Qe!=="onCompositionStart"?Qe==="onCompositionEnd"&&_s&&(He=bf()):(pr=ve,Ml="value"in pr?pr.value:pr.textContent,_s=!0)),qe=$i(le,Qe),0<qe.length&&(Qe=new jf(Qe,r,null,c,ve),_e.push({event:Qe,listeners:qe}),He?Qe.data=He:(He=Af(c),He!==null&&(Qe.data=He)))),(He=o_?l_(r,c):c_(r,c))&&(le=$i(le,"onBeforeInput"),0<le.length&&(ve=new jf("onBeforeInput","beforeinput",null,c,ve),_e.push({event:ve,listeners:le}),ve.data=He))}Yf(_e,i)})}function ga(r,i,c){return{instance:r,listener:i,currentTarget:c}}function $i(r,i){for(var c=i+"Capture",h=[];r!==null;){var y=r,_=y.stateNode;y.tag===5&&_!==null&&(y=_,_=tt(r,c),_!=null&&h.unshift(ga(r,_,y)),_=tt(r,i),_!=null&&h.push(ga(r,_,y))),r=r.return}return h}function ks(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function Xf(r,i,c,h,y){for(var _=i._reactName,A=[];c!==null&&c!==h;){var F=c,H=F.alternate,le=F.stateNode;if(H!==null&&H===h)break;F.tag===5&&le!==null&&(F=le,y?(H=tt(c,_),H!=null&&A.unshift(ga(c,H,F))):y||(H=tt(c,_),H!=null&&A.push(ga(c,H,F)))),c=c.return}A.length!==0&&r.push({event:i,listeners:A})}var k_=/\r\n?/g,j_=/\u0000|\uFFFD/g;function Zf(r){return(typeof r=="string"?r:""+r).replace(k_,`
38
+ `).replace(j_,"")}function Ri(r,i,c){if(i=Zf(i),Zf(r)!==i&&c)throw Error(n(425))}function Mi(){}var Yl=null,Ql=null;function Xl(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 Zl=typeof setTimeout=="function"?setTimeout:void 0,S_=typeof clearTimeout=="function"?clearTimeout:void 0,eh=typeof Promise=="function"?Promise:void 0,N_=typeof queueMicrotask=="function"?queueMicrotask:typeof eh<"u"?function(r){return eh.resolve(null).then(r).catch(C_)}:Zl;function C_(r){setTimeout(function(){throw r})}function ec(r,i){var c=i,h=0;do{var y=c.nextSibling;if(r.removeChild(c),y&&y.nodeType===8)if(c=y.data,c==="/$"){if(h===0){r.removeChild(y),ia(i);return}h--}else c!=="$"&&c!=="$?"&&c!=="$!"||h++;c=y}while(c);ia(i)}function gr(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 th(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 js=Math.random().toString(36).slice(2),Wn="__reactFiber$"+js,va="__reactProps$"+js,Kn="__reactContainer$"+js,tc="__reactEvents$"+js,E_="__reactListeners$"+js,T_="__reactHandles$"+js;function Vr(r){var i=r[Wn];if(i)return i;for(var c=r.parentNode;c;){if(i=c[Kn]||c[Wn]){if(c=i.alternate,i.child!==null||c!==null&&c.child!==null)for(r=th(r);r!==null;){if(c=r[Wn])return c;r=th(r)}return i}r=c,c=r.parentNode}return null}function ya(r){return r=r[Wn]||r[Kn],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function Ss(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(n(33))}function Li(r){return r[va]||null}var nc=[],Ns=-1;function vr(r){return{current:r}}function mt(r){0>Ns||(r.current=nc[Ns],nc[Ns]=null,Ns--)}function ft(r,i){Ns++,nc[Ns]=r.current,r.current=i}var yr={},Wt=vr(yr),nn=vr(!1),qr=yr;function Cs(r,i){var c=r.type.contextTypes;if(!c)return yr;var h=r.stateNode;if(h&&h.__reactInternalMemoizedUnmaskedChildContext===i)return h.__reactInternalMemoizedMaskedChildContext;var y={},_;for(_ in c)y[_]=i[_];return h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=y),y}function rn(r){return r=r.childContextTypes,r!=null}function Ii(){mt(nn),mt(Wt)}function nh(r,i,c){if(Wt.current!==yr)throw Error(n(168));ft(Wt,i),ft(nn,c)}function rh(r,i,c){var h=r.stateNode;if(i=i.childContextTypes,typeof h.getChildContext!="function")return c;h=h.getChildContext();for(var y in h)if(!(y in i))throw Error(n(108,ee(r)||"Unknown",y));return Z({},c,h)}function Pi(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||yr,qr=Wt.current,ft(Wt,r),ft(nn,nn.current),!0}function sh(r,i,c){var h=r.stateNode;if(!h)throw Error(n(169));c?(r=rh(r,i,qr),h.__reactInternalMemoizedMergedChildContext=r,mt(nn),mt(Wt),ft(Wt,r)):mt(nn),ft(nn,c)}var Jn=null,Oi=!1,rc=!1;function ah(r){Jn===null?Jn=[r]:Jn.push(r)}function A_(r){Oi=!0,ah(r)}function wr(){if(!rc&&Jn!==null){rc=!0;var r=0,i=lt;try{var c=Jn;for(lt=1;r<c.length;r++){var h=c[r];do h=h(!0);while(h!==null)}Jn=null,Oi=!1}catch(y){throw Jn!==null&&(Jn=Jn.slice(r+1)),of(Sl,wr),y}finally{lt=i,rc=!1}}return null}var Es=[],Ts=0,Di=null,Fi=0,bn=[],xn=0,Hr=null,Yn=1,Qn="";function Gr(r,i){Es[Ts++]=Fi,Es[Ts++]=Di,Di=r,Fi=i}function ih(r,i,c){bn[xn++]=Yn,bn[xn++]=Qn,bn[xn++]=Hr,Hr=r;var h=Yn;r=Qn;var y=32-Rn(h)-1;h&=~(1<<y),c+=1;var _=32-Rn(i)+y;if(30<_){var A=y-y%5;_=(h&(1<<A)-1).toString(32),h>>=A,y-=A,Yn=1<<32-Rn(i)+y|c<<y|h,Qn=_+r}else Yn=1<<_|c<<y|h,Qn=r}function sc(r){r.return!==null&&(Gr(r,1),ih(r,1,0))}function ac(r){for(;r===Di;)Di=Es[--Ts],Es[Ts]=null,Fi=Es[--Ts],Es[Ts]=null;for(;r===Hr;)Hr=bn[--xn],bn[xn]=null,Qn=bn[--xn],bn[xn]=null,Yn=bn[--xn],bn[xn]=null}var mn=null,gn=null,gt=!1,Ln=null;function oh(r,i){var c=Nn(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 lh(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,mn=r,gn=gr(i.firstChild),!0):!1;case 6:return i=r.pendingProps===""||i.nodeType!==3?null:i,i!==null?(r.stateNode=i,mn=r,gn=null,!0):!1;case 13:return i=i.nodeType!==8?null:i,i!==null?(c=Hr!==null?{id:Yn,overflow:Qn}:null,r.memoizedState={dehydrated:i,treeContext:c,retryLane:1073741824},c=Nn(18,null,null,0),c.stateNode=i,c.return=r,r.child=c,mn=r,gn=null,!0):!1;default:return!1}}function ic(r){return(r.mode&1)!==0&&(r.flags&128)===0}function oc(r){if(gt){var i=gn;if(i){var c=i;if(!lh(r,i)){if(ic(r))throw Error(n(418));i=gr(c.nextSibling);var h=mn;i&&lh(r,i)?oh(h,c):(r.flags=r.flags&-4097|2,gt=!1,mn=r)}}else{if(ic(r))throw Error(n(418));r.flags=r.flags&-4097|2,gt=!1,mn=r}}}function ch(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;mn=r}function Bi(r){if(r!==mn)return!1;if(!gt)return ch(r),gt=!0,!1;var i;if((i=r.tag!==3)&&!(i=r.tag!==5)&&(i=r.type,i=i!=="head"&&i!=="body"&&!Xl(r.type,r.memoizedProps)),i&&(i=gn)){if(ic(r))throw uh(),Error(n(418));for(;i;)oh(r,i),i=gr(i.nextSibling)}if(ch(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){gn=gr(r.nextSibling);break e}i--}else c!=="$"&&c!=="$!"&&c!=="$?"||i++}r=r.nextSibling}gn=null}}else gn=mn?gr(r.stateNode.nextSibling):null;return!0}function uh(){for(var r=gn;r;)r=gr(r.nextSibling)}function As(){gn=mn=null,gt=!1}function lc(r){Ln===null?Ln=[r]:Ln.push(r)}var $_=C.ReactCurrentBatchConfig;function wa(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 y=h,_=""+r;return i!==null&&i.ref!==null&&typeof i.ref=="function"&&i.ref._stringRef===_?i.ref:(i=function(A){var F=y.refs;A===null?delete F[_]:F[_]=A},i._stringRef=_,i)}if(typeof r!="string")throw Error(n(284));if(!c._owner)throw Error(n(290,r))}return r}function zi(r,i){throw r=Object.prototype.toString.call(i),Error(n(31,r==="[object Object]"?"object with keys {"+Object.keys(i).join(", ")+"}":r))}function dh(r){var i=r._init;return i(r._payload)}function fh(r){function i(re,X){if(r){var ae=re.deletions;ae===null?(re.deletions=[X],re.flags|=16):ae.push(X)}}function c(re,X){if(!r)return null;for(;X!==null;)i(re,X),X=X.sibling;return null}function h(re,X){for(re=new Map;X!==null;)X.key!==null?re.set(X.key,X):re.set(X.index,X),X=X.sibling;return re}function y(re,X){return re=Cr(re,X),re.index=0,re.sibling=null,re}function _(re,X,ae){return re.index=ae,r?(ae=re.alternate,ae!==null?(ae=ae.index,ae<X?(re.flags|=2,X):ae):(re.flags|=2,X)):(re.flags|=1048576,X)}function A(re){return r&&re.alternate===null&&(re.flags|=2),re}function F(re,X,ae,ke){return X===null||X.tag!==6?(X=Zc(ae,re.mode,ke),X.return=re,X):(X=y(X,ae),X.return=re,X)}function H(re,X,ae,ke){var De=ae.type;return De===I?ve(re,X,ae.props.children,ke,ae.key):X!==null&&(X.elementType===De||typeof De=="object"&&De!==null&&De.$$typeof===q&&dh(De)===X.type)?(ke=y(X,ae.props),ke.ref=wa(re,X,ae),ke.return=re,ke):(ke=fo(ae.type,ae.key,ae.props,null,re.mode,ke),ke.ref=wa(re,X,ae),ke.return=re,ke)}function le(re,X,ae,ke){return X===null||X.tag!==4||X.stateNode.containerInfo!==ae.containerInfo||X.stateNode.implementation!==ae.implementation?(X=eu(ae,re.mode,ke),X.return=re,X):(X=y(X,ae.children||[]),X.return=re,X)}function ve(re,X,ae,ke,De){return X===null||X.tag!==7?(X=ts(ae,re.mode,ke,De),X.return=re,X):(X=y(X,ae),X.return=re,X)}function _e(re,X,ae){if(typeof X=="string"&&X!==""||typeof X=="number")return X=Zc(""+X,re.mode,ae),X.return=re,X;if(typeof X=="object"&&X!==null){switch(X.$$typeof){case R:return ae=fo(X.type,X.key,X.props,null,re.mode,ae),ae.ref=wa(re,null,X),ae.return=re,ae;case E:return X=eu(X,re.mode,ae),X.return=re,X;case q:var ke=X._init;return _e(re,ke(X._payload),ae)}if(G(X)||O(X))return X=ts(X,re.mode,ae,null),X.return=re,X;zi(re,X)}return null}function ge(re,X,ae,ke){var De=X!==null?X.key:null;if(typeof ae=="string"&&ae!==""||typeof ae=="number")return De!==null?null:F(re,X,""+ae,ke);if(typeof ae=="object"&&ae!==null){switch(ae.$$typeof){case R:return ae.key===De?H(re,X,ae,ke):null;case E:return ae.key===De?le(re,X,ae,ke):null;case q:return De=ae._init,ge(re,X,De(ae._payload),ke)}if(G(ae)||O(ae))return De!==null?null:ve(re,X,ae,ke,null);zi(re,ae)}return null}function Ae(re,X,ae,ke,De){if(typeof ke=="string"&&ke!==""||typeof ke=="number")return re=re.get(ae)||null,F(X,re,""+ke,De);if(typeof ke=="object"&&ke!==null){switch(ke.$$typeof){case R:return re=re.get(ke.key===null?ae:ke.key)||null,H(X,re,ke,De);case E:return re=re.get(ke.key===null?ae:ke.key)||null,le(X,re,ke,De);case q:var qe=ke._init;return Ae(re,X,ae,qe(ke._payload),De)}if(G(ke)||O(ke))return re=re.get(ae)||null,ve(X,re,ke,De,null);zi(X,ke)}return null}function Le(re,X,ae,ke){for(var De=null,qe=null,He=X,Qe=X=0,Rt=null;He!==null&&Qe<ae.length;Qe++){He.index>Qe?(Rt=He,He=null):Rt=He.sibling;var at=ge(re,He,ae[Qe],ke);if(at===null){He===null&&(He=Rt);break}r&&He&&at.alternate===null&&i(re,He),X=_(at,X,Qe),qe===null?De=at:qe.sibling=at,qe=at,He=Rt}if(Qe===ae.length)return c(re,He),gt&&Gr(re,Qe),De;if(He===null){for(;Qe<ae.length;Qe++)He=_e(re,ae[Qe],ke),He!==null&&(X=_(He,X,Qe),qe===null?De=He:qe.sibling=He,qe=He);return gt&&Gr(re,Qe),De}for(He=h(re,He);Qe<ae.length;Qe++)Rt=Ae(He,re,Qe,ae[Qe],ke),Rt!==null&&(r&&Rt.alternate!==null&&He.delete(Rt.key===null?Qe:Rt.key),X=_(Rt,X,Qe),qe===null?De=Rt:qe.sibling=Rt,qe=Rt);return r&&He.forEach(function(Er){return i(re,Er)}),gt&&Gr(re,Qe),De}function Ie(re,X,ae,ke){var De=O(ae);if(typeof De!="function")throw Error(n(150));if(ae=De.call(ae),ae==null)throw Error(n(151));for(var qe=De=null,He=X,Qe=X=0,Rt=null,at=ae.next();He!==null&&!at.done;Qe++,at=ae.next()){He.index>Qe?(Rt=He,He=null):Rt=He.sibling;var Er=ge(re,He,at.value,ke);if(Er===null){He===null&&(He=Rt);break}r&&He&&Er.alternate===null&&i(re,He),X=_(Er,X,Qe),qe===null?De=Er:qe.sibling=Er,qe=Er,He=Rt}if(at.done)return c(re,He),gt&&Gr(re,Qe),De;if(He===null){for(;!at.done;Qe++,at=ae.next())at=_e(re,at.value,ke),at!==null&&(X=_(at,X,Qe),qe===null?De=at:qe.sibling=at,qe=at);return gt&&Gr(re,Qe),De}for(He=h(re,He);!at.done;Qe++,at=ae.next())at=Ae(He,re,Qe,at.value,ke),at!==null&&(r&&at.alternate!==null&&He.delete(at.key===null?Qe:at.key),X=_(at,X,Qe),qe===null?De=at:qe.sibling=at,qe=at);return r&&He.forEach(function(ub){return i(re,ub)}),gt&&Gr(re,Qe),De}function kt(re,X,ae,ke){if(typeof ae=="object"&&ae!==null&&ae.type===I&&ae.key===null&&(ae=ae.props.children),typeof ae=="object"&&ae!==null){switch(ae.$$typeof){case R:e:{for(var De=ae.key,qe=X;qe!==null;){if(qe.key===De){if(De=ae.type,De===I){if(qe.tag===7){c(re,qe.sibling),X=y(qe,ae.props.children),X.return=re,re=X;break e}}else if(qe.elementType===De||typeof De=="object"&&De!==null&&De.$$typeof===q&&dh(De)===qe.type){c(re,qe.sibling),X=y(qe,ae.props),X.ref=wa(re,qe,ae),X.return=re,re=X;break e}c(re,qe);break}else i(re,qe);qe=qe.sibling}ae.type===I?(X=ts(ae.props.children,re.mode,ke,ae.key),X.return=re,re=X):(ke=fo(ae.type,ae.key,ae.props,null,re.mode,ke),ke.ref=wa(re,X,ae),ke.return=re,re=ke)}return A(re);case E:e:{for(qe=ae.key;X!==null;){if(X.key===qe)if(X.tag===4&&X.stateNode.containerInfo===ae.containerInfo&&X.stateNode.implementation===ae.implementation){c(re,X.sibling),X=y(X,ae.children||[]),X.return=re,re=X;break e}else{c(re,X);break}else i(re,X);X=X.sibling}X=eu(ae,re.mode,ke),X.return=re,re=X}return A(re);case q:return qe=ae._init,kt(re,X,qe(ae._payload),ke)}if(G(ae))return Le(re,X,ae,ke);if(O(ae))return Ie(re,X,ae,ke);zi(re,ae)}return typeof ae=="string"&&ae!==""||typeof ae=="number"?(ae=""+ae,X!==null&&X.tag===6?(c(re,X.sibling),X=y(X,ae),X.return=re,re=X):(c(re,X),X=Zc(ae,re.mode,ke),X.return=re,re=X),A(re)):c(re,X)}return kt}var $s=fh(!0),hh=fh(!1),Ui=vr(null),Wi=null,Rs=null,cc=null;function uc(){cc=Rs=Wi=null}function dc(r){var i=Ui.current;mt(Ui),r._currentValue=i}function fc(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 Ms(r,i){Wi=r,cc=Rs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&i)!==0&&(sn=!0),r.firstContext=null)}function kn(r){var i=r._currentValue;if(cc!==r)if(r={context:r,memoizedValue:i,next:null},Rs===null){if(Wi===null)throw Error(n(308));Rs=r,Wi.dependencies={lanes:0,firstContext:r}}else Rs=Rs.next=r;return i}var Kr=null;function hc(r){Kr===null?Kr=[r]:Kr.push(r)}function ph(r,i,c,h){var y=i.interleaved;return y===null?(c.next=c,hc(i)):(c.next=y.next,y.next=c),i.interleaved=c,Xn(r,h)}function Xn(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 _r=!1;function pc(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function mh(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 Zn(r,i){return{eventTime:r,lane:i,tag:0,payload:null,callback:null,next:null}}function br(r,i,c){var h=r.updateQueue;if(h===null)return null;if(h=h.shared,(st&2)!==0){var y=h.pending;return y===null?i.next=i:(i.next=y.next,y.next=i),h.pending=i,Xn(r,c)}return y=h.interleaved,y===null?(i.next=i,hc(h)):(i.next=y.next,y.next=i),h.interleaved=i,Xn(r,c)}function Vi(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,El(r,c)}}function gh(r,i){var c=r.updateQueue,h=r.alternate;if(h!==null&&(h=h.updateQueue,c===h)){var y=null,_=null;if(c=c.firstBaseUpdate,c!==null){do{var A={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};_===null?y=_=A:_=_.next=A,c=c.next}while(c!==null);_===null?y=_=i:_=_.next=i}else y=_=i;c={baseState:h.baseState,firstBaseUpdate:y,lastBaseUpdate:_,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 qi(r,i,c,h){var y=r.updateQueue;_r=!1;var _=y.firstBaseUpdate,A=y.lastBaseUpdate,F=y.shared.pending;if(F!==null){y.shared.pending=null;var H=F,le=H.next;H.next=null,A===null?_=le:A.next=le,A=H;var ve=r.alternate;ve!==null&&(ve=ve.updateQueue,F=ve.lastBaseUpdate,F!==A&&(F===null?ve.firstBaseUpdate=le:F.next=le,ve.lastBaseUpdate=H))}if(_!==null){var _e=y.baseState;A=0,ve=le=H=null,F=_;do{var ge=F.lane,Ae=F.eventTime;if((h&ge)===ge){ve!==null&&(ve=ve.next={eventTime:Ae,lane:0,tag:F.tag,payload:F.payload,callback:F.callback,next:null});e:{var Le=r,Ie=F;switch(ge=i,Ae=c,Ie.tag){case 1:if(Le=Ie.payload,typeof Le=="function"){_e=Le.call(Ae,_e,ge);break e}_e=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Ie.payload,ge=typeof Le=="function"?Le.call(Ae,_e,ge):Le,ge==null)break e;_e=Z({},_e,ge);break e;case 2:_r=!0}}F.callback!==null&&F.lane!==0&&(r.flags|=64,ge=y.effects,ge===null?y.effects=[F]:ge.push(F))}else Ae={eventTime:Ae,lane:ge,tag:F.tag,payload:F.payload,callback:F.callback,next:null},ve===null?(le=ve=Ae,H=_e):ve=ve.next=Ae,A|=ge;if(F=F.next,F===null){if(F=y.shared.pending,F===null)break;ge=F,F=ge.next,ge.next=null,y.lastBaseUpdate=ge,y.shared.pending=null}}while(!0);if(ve===null&&(H=_e),y.baseState=H,y.firstBaseUpdate=le,y.lastBaseUpdate=ve,i=y.shared.interleaved,i!==null){y=i;do A|=y.lane,y=y.next;while(y!==i)}else _===null&&(y.shared.lanes=0);Qr|=A,r.lanes=A,r.memoizedState=_e}}function vh(r,i,c){if(r=i.effects,i.effects=null,r!==null)for(i=0;i<r.length;i++){var h=r[i],y=h.callback;if(y!==null){if(h.callback=null,h=c,typeof y!="function")throw Error(n(191,y));y.call(h)}}}var _a={},Vn=vr(_a),ba=vr(_a),xa=vr(_a);function Jr(r){if(r===_a)throw Error(n(174));return r}function mc(r,i){switch(ft(xa,i),ft(ba,r),ft(Vn,_a),r=i.nodeType,r){case 9:case 11:i=(i=i.documentElement)?i.namespaceURI:rt(null,"");break;default:r=r===8?i.parentNode:i,i=r.namespaceURI||null,r=r.tagName,i=rt(i,r)}mt(Vn),ft(Vn,i)}function Ls(){mt(Vn),mt(ba),mt(xa)}function yh(r){Jr(xa.current);var i=Jr(Vn.current),c=rt(i,r.type);i!==c&&(ft(ba,r),ft(Vn,c))}function gc(r){ba.current===r&&(mt(Vn),mt(ba))}var vt=vr(0);function Hi(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 vc=[];function yc(){for(var r=0;r<vc.length;r++)vc[r]._workInProgressVersionPrimary=null;vc.length=0}var Gi=C.ReactCurrentDispatcher,wc=C.ReactCurrentBatchConfig,Yr=0,yt=null,Ct=null,At=null,Ki=!1,ka=!1,ja=0,R_=0;function Vt(){throw Error(n(321))}function _c(r,i){if(i===null)return!1;for(var c=0;c<i.length&&c<r.length;c++)if(!Mn(r[c],i[c]))return!1;return!0}function bc(r,i,c,h,y,_){if(Yr=_,yt=i,i.memoizedState=null,i.updateQueue=null,i.lanes=0,Gi.current=r===null||r.memoizedState===null?P_:O_,r=c(h,y),ka){_=0;do{if(ka=!1,ja=0,25<=_)throw Error(n(301));_+=1,At=Ct=null,i.updateQueue=null,Gi.current=D_,r=c(h,y)}while(ka)}if(Gi.current=Qi,i=Ct!==null&&Ct.next!==null,Yr=0,At=Ct=yt=null,Ki=!1,i)throw Error(n(300));return r}function xc(){var r=ja!==0;return ja=0,r}function qn(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return At===null?yt.memoizedState=At=r:At=At.next=r,At}function jn(){if(Ct===null){var r=yt.alternate;r=r!==null?r.memoizedState:null}else r=Ct.next;var i=At===null?yt.memoizedState:At.next;if(i!==null)At=i,Ct=r;else{if(r===null)throw Error(n(310));Ct=r,r={memoizedState:Ct.memoizedState,baseState:Ct.baseState,baseQueue:Ct.baseQueue,queue:Ct.queue,next:null},At===null?yt.memoizedState=At=r:At=At.next=r}return At}function Sa(r,i){return typeof i=="function"?i(r):i}function kc(r){var i=jn(),c=i.queue;if(c===null)throw Error(n(311));c.lastRenderedReducer=r;var h=Ct,y=h.baseQueue,_=c.pending;if(_!==null){if(y!==null){var A=y.next;y.next=_.next,_.next=A}h.baseQueue=y=_,c.pending=null}if(y!==null){_=y.next,h=h.baseState;var F=A=null,H=null,le=_;do{var ve=le.lane;if((Yr&ve)===ve)H!==null&&(H=H.next={lane:0,action:le.action,hasEagerState:le.hasEagerState,eagerState:le.eagerState,next:null}),h=le.hasEagerState?le.eagerState:r(h,le.action);else{var _e={lane:ve,action:le.action,hasEagerState:le.hasEagerState,eagerState:le.eagerState,next:null};H===null?(F=H=_e,A=h):H=H.next=_e,yt.lanes|=ve,Qr|=ve}le=le.next}while(le!==null&&le!==_);H===null?A=h:H.next=F,Mn(h,i.memoizedState)||(sn=!0),i.memoizedState=h,i.baseState=A,i.baseQueue=H,c.lastRenderedState=h}if(r=c.interleaved,r!==null){y=r;do _=y.lane,yt.lanes|=_,Qr|=_,y=y.next;while(y!==r)}else y===null&&(c.lanes=0);return[i.memoizedState,c.dispatch]}function jc(r){var i=jn(),c=i.queue;if(c===null)throw Error(n(311));c.lastRenderedReducer=r;var h=c.dispatch,y=c.pending,_=i.memoizedState;if(y!==null){c.pending=null;var A=y=y.next;do _=r(_,A.action),A=A.next;while(A!==y);Mn(_,i.memoizedState)||(sn=!0),i.memoizedState=_,i.baseQueue===null&&(i.baseState=_),c.lastRenderedState=_}return[_,h]}function wh(){}function _h(r,i){var c=yt,h=jn(),y=i(),_=!Mn(h.memoizedState,y);if(_&&(h.memoizedState=y,sn=!0),h=h.queue,Sc(kh.bind(null,c,h,r),[r]),h.getSnapshot!==i||_||At!==null&&At.memoizedState.tag&1){if(c.flags|=2048,Na(9,xh.bind(null,c,h,y,i),void 0,null),$t===null)throw Error(n(349));(Yr&30)!==0||bh(c,i,y)}return y}function bh(r,i,c){r.flags|=16384,r={getSnapshot:i,value:c},i=yt.updateQueue,i===null?(i={lastEffect:null,stores:null},yt.updateQueue=i,i.stores=[r]):(c=i.stores,c===null?i.stores=[r]:c.push(r))}function xh(r,i,c,h){i.value=c,i.getSnapshot=h,jh(i)&&Sh(r)}function kh(r,i,c){return c(function(){jh(i)&&Sh(r)})}function jh(r){var i=r.getSnapshot;r=r.value;try{var c=i();return!Mn(r,c)}catch{return!0}}function Sh(r){var i=Xn(r,1);i!==null&&Dn(i,r,1,-1)}function Nh(r){var i=qn();return typeof r=="function"&&(r=r()),i.memoizedState=i.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Sa,lastRenderedState:r},i.queue=r,r=r.dispatch=I_.bind(null,yt,r),[i.memoizedState,r]}function Na(r,i,c,h){return r={tag:r,create:i,destroy:c,deps:h,next:null},i=yt.updateQueue,i===null?(i={lastEffect:null,stores:null},yt.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 Ch(){return jn().memoizedState}function Ji(r,i,c,h){var y=qn();yt.flags|=r,y.memoizedState=Na(1|i,c,void 0,h===void 0?null:h)}function Yi(r,i,c,h){var y=jn();h=h===void 0?null:h;var _=void 0;if(Ct!==null){var A=Ct.memoizedState;if(_=A.destroy,h!==null&&_c(h,A.deps)){y.memoizedState=Na(i,c,_,h);return}}yt.flags|=r,y.memoizedState=Na(1|i,c,_,h)}function Eh(r,i){return Ji(8390656,8,r,i)}function Sc(r,i){return Yi(2048,8,r,i)}function Th(r,i){return Yi(4,2,r,i)}function Ah(r,i){return Yi(4,4,r,i)}function $h(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 Rh(r,i,c){return c=c!=null?c.concat([r]):null,Yi(4,4,$h.bind(null,i,r),c)}function Nc(){}function Mh(r,i){var c=jn();i=i===void 0?null:i;var h=c.memoizedState;return h!==null&&i!==null&&_c(i,h[1])?h[0]:(c.memoizedState=[r,i],r)}function Lh(r,i){var c=jn();i=i===void 0?null:i;var h=c.memoizedState;return h!==null&&i!==null&&_c(i,h[1])?h[0]:(r=r(),c.memoizedState=[r,i],r)}function Ih(r,i,c){return(Yr&21)===0?(r.baseState&&(r.baseState=!1,sn=!0),r.memoizedState=c):(Mn(c,i)||(c=df(),yt.lanes|=c,Qr|=c,r.baseState=!0),i)}function M_(r,i){var c=lt;lt=c!==0&&4>c?c:4,r(!0);var h=wc.transition;wc.transition={};try{r(!1),i()}finally{lt=c,wc.transition=h}}function Ph(){return jn().memoizedState}function L_(r,i,c){var h=Sr(r);if(c={lane:h,action:c,hasEagerState:!1,eagerState:null,next:null},Oh(r))Dh(i,c);else if(c=ph(r,i,c,h),c!==null){var y=Qt();Dn(c,r,h,y),Fh(c,i,h)}}function I_(r,i,c){var h=Sr(r),y={lane:h,action:c,hasEagerState:!1,eagerState:null,next:null};if(Oh(r))Dh(i,y);else{var _=r.alternate;if(r.lanes===0&&(_===null||_.lanes===0)&&(_=i.lastRenderedReducer,_!==null))try{var A=i.lastRenderedState,F=_(A,c);if(y.hasEagerState=!0,y.eagerState=F,Mn(F,A)){var H=i.interleaved;H===null?(y.next=y,hc(i)):(y.next=H.next,H.next=y),i.interleaved=y;return}}catch{}finally{}c=ph(r,i,y,h),c!==null&&(y=Qt(),Dn(c,r,h,y),Fh(c,i,h))}}function Oh(r){var i=r.alternate;return r===yt||i!==null&&i===yt}function Dh(r,i){ka=Ki=!0;var c=r.pending;c===null?i.next=i:(i.next=c.next,c.next=i),r.pending=i}function Fh(r,i,c){if((c&4194240)!==0){var h=i.lanes;h&=r.pendingLanes,c|=h,i.lanes=c,El(r,c)}}var Qi={readContext:kn,useCallback:Vt,useContext:Vt,useEffect:Vt,useImperativeHandle:Vt,useInsertionEffect:Vt,useLayoutEffect:Vt,useMemo:Vt,useReducer:Vt,useRef:Vt,useState:Vt,useDebugValue:Vt,useDeferredValue:Vt,useTransition:Vt,useMutableSource:Vt,useSyncExternalStore:Vt,useId:Vt,unstable_isNewReconciler:!1},P_={readContext:kn,useCallback:function(r,i){return qn().memoizedState=[r,i===void 0?null:i],r},useContext:kn,useEffect:Eh,useImperativeHandle:function(r,i,c){return c=c!=null?c.concat([r]):null,Ji(4194308,4,$h.bind(null,i,r),c)},useLayoutEffect:function(r,i){return Ji(4194308,4,r,i)},useInsertionEffect:function(r,i){return Ji(4,2,r,i)},useMemo:function(r,i){var c=qn();return i=i===void 0?null:i,r=r(),c.memoizedState=[r,i],r},useReducer:function(r,i,c){var h=qn();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=L_.bind(null,yt,r),[h.memoizedState,r]},useRef:function(r){var i=qn();return r={current:r},i.memoizedState=r},useState:Nh,useDebugValue:Nc,useDeferredValue:function(r){return qn().memoizedState=r},useTransition:function(){var r=Nh(!1),i=r[0];return r=M_.bind(null,r[1]),qn().memoizedState=r,[i,r]},useMutableSource:function(){},useSyncExternalStore:function(r,i,c){var h=yt,y=qn();if(gt){if(c===void 0)throw Error(n(407));c=c()}else{if(c=i(),$t===null)throw Error(n(349));(Yr&30)!==0||bh(h,i,c)}y.memoizedState=c;var _={value:c,getSnapshot:i};return y.queue=_,Eh(kh.bind(null,h,_,r),[r]),h.flags|=2048,Na(9,xh.bind(null,h,_,c,i),void 0,null),c},useId:function(){var r=qn(),i=$t.identifierPrefix;if(gt){var c=Qn,h=Yn;c=(h&~(1<<32-Rn(h)-1)).toString(32)+c,i=":"+i+"R"+c,c=ja++,0<c&&(i+="H"+c.toString(32)),i+=":"}else c=R_++,i=":"+i+"r"+c.toString(32)+":";return r.memoizedState=i},unstable_isNewReconciler:!1},O_={readContext:kn,useCallback:Mh,useContext:kn,useEffect:Sc,useImperativeHandle:Rh,useInsertionEffect:Th,useLayoutEffect:Ah,useMemo:Lh,useReducer:kc,useRef:Ch,useState:function(){return kc(Sa)},useDebugValue:Nc,useDeferredValue:function(r){var i=jn();return Ih(i,Ct.memoizedState,r)},useTransition:function(){var r=kc(Sa)[0],i=jn().memoizedState;return[r,i]},useMutableSource:wh,useSyncExternalStore:_h,useId:Ph,unstable_isNewReconciler:!1},D_={readContext:kn,useCallback:Mh,useContext:kn,useEffect:Sc,useImperativeHandle:Rh,useInsertionEffect:Th,useLayoutEffect:Ah,useMemo:Lh,useReducer:jc,useRef:Ch,useState:function(){return jc(Sa)},useDebugValue:Nc,useDeferredValue:function(r){var i=jn();return Ct===null?i.memoizedState=r:Ih(i,Ct.memoizedState,r)},useTransition:function(){var r=jc(Sa)[0],i=jn().memoizedState;return[r,i]},useMutableSource:wh,useSyncExternalStore:_h,useId:Ph,unstable_isNewReconciler:!1};function In(r,i){if(r&&r.defaultProps){i=Z({},i),r=r.defaultProps;for(var c in r)i[c]===void 0&&(i[c]=r[c]);return i}return i}function Cc(r,i,c,h){i=r.memoizedState,c=c(h,i),c=c==null?i:Z({},i,c),r.memoizedState=c,r.lanes===0&&(r.updateQueue.baseState=c)}var Xi={isMounted:function(r){return(r=r._reactInternals)?Wr(r)===r:!1},enqueueSetState:function(r,i,c){r=r._reactInternals;var h=Qt(),y=Sr(r),_=Zn(h,y);_.payload=i,c!=null&&(_.callback=c),i=br(r,_,y),i!==null&&(Dn(i,r,y,h),Vi(i,r,y))},enqueueReplaceState:function(r,i,c){r=r._reactInternals;var h=Qt(),y=Sr(r),_=Zn(h,y);_.tag=1,_.payload=i,c!=null&&(_.callback=c),i=br(r,_,y),i!==null&&(Dn(i,r,y,h),Vi(i,r,y))},enqueueForceUpdate:function(r,i){r=r._reactInternals;var c=Qt(),h=Sr(r),y=Zn(c,h);y.tag=2,i!=null&&(y.callback=i),i=br(r,y,h),i!==null&&(Dn(i,r,h,c),Vi(i,r,h))}};function Bh(r,i,c,h,y,_,A){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(h,_,A):i.prototype&&i.prototype.isPureReactComponent?!fa(c,h)||!fa(y,_):!0}function zh(r,i,c){var h=!1,y=yr,_=i.contextType;return typeof _=="object"&&_!==null?_=kn(_):(y=rn(i)?qr:Wt.current,h=i.contextTypes,_=(h=h!=null)?Cs(r,y):yr),i=new i(c,_),r.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,i.updater=Xi,r.stateNode=i,i._reactInternals=r,h&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=y,r.__reactInternalMemoizedMaskedChildContext=_),i}function Uh(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&&Xi.enqueueReplaceState(i,i.state,null)}function Ec(r,i,c,h){var y=r.stateNode;y.props=c,y.state=r.memoizedState,y.refs={},pc(r);var _=i.contextType;typeof _=="object"&&_!==null?y.context=kn(_):(_=rn(i)?qr:Wt.current,y.context=Cs(r,_)),y.state=r.memoizedState,_=i.getDerivedStateFromProps,typeof _=="function"&&(Cc(r,i,_,c),y.state=r.memoizedState),typeof i.getDerivedStateFromProps=="function"||typeof y.getSnapshotBeforeUpdate=="function"||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(i=y.state,typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount(),i!==y.state&&Xi.enqueueReplaceState(y,y.state,null),qi(r,c,y,h),y.state=r.memoizedState),typeof y.componentDidMount=="function"&&(r.flags|=4194308)}function Is(r,i){try{var c="",h=i;do c+=de(h),h=h.return;while(h);var y=c}catch(_){y=`
39
+ Error generating stack: `+_.message+`
40
+ `+_.stack}return{value:r,source:i,stack:y,digest:null}}function Tc(r,i,c){return{value:r,source:null,stack:c??null,digest:i??null}}function Ac(r,i){try{console.error(i.value)}catch(c){setTimeout(function(){throw c})}}var F_=typeof WeakMap=="function"?WeakMap:Map;function Wh(r,i,c){c=Zn(-1,c),c.tag=3,c.payload={element:null};var h=i.value;return c.callback=function(){ao||(ao=!0,qc=h),Ac(r,i)},c}function Vh(r,i,c){c=Zn(-1,c),c.tag=3;var h=r.type.getDerivedStateFromError;if(typeof h=="function"){var y=i.value;c.payload=function(){return h(y)},c.callback=function(){Ac(r,i)}}var _=r.stateNode;return _!==null&&typeof _.componentDidCatch=="function"&&(c.callback=function(){Ac(r,i),typeof h!="function"&&(kr===null?kr=new Set([this]):kr.add(this));var A=i.stack;this.componentDidCatch(i.value,{componentStack:A!==null?A:""})}),c}function qh(r,i,c){var h=r.pingCache;if(h===null){h=r.pingCache=new F_;var y=new Set;h.set(i,y)}else y=h.get(i),y===void 0&&(y=new Set,h.set(i,y));y.has(c)||(y.add(c),r=Z_.bind(null,r,i,c),i.then(r,r))}function Hh(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 Gh(r,i,c,h,y){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=Zn(-1,1),i.tag=2,br(c,i,1))),c.lanes|=1),r):(r.flags|=65536,r.lanes=y,r)}var B_=C.ReactCurrentOwner,sn=!1;function Yt(r,i,c,h){i.child=r===null?hh(i,null,c,h):$s(i,r.child,c,h)}function Kh(r,i,c,h,y){c=c.render;var _=i.ref;return Ms(i,y),h=bc(r,i,c,h,_,y),c=xc(),r!==null&&!sn?(i.updateQueue=r.updateQueue,i.flags&=-2053,r.lanes&=~y,er(r,i,y)):(gt&&c&&sc(i),i.flags|=1,Yt(r,i,h,y),i.child)}function Jh(r,i,c,h,y){if(r===null){var _=c.type;return typeof _=="function"&&!Xc(_)&&_.defaultProps===void 0&&c.compare===null&&c.defaultProps===void 0?(i.tag=15,i.type=_,Yh(r,i,_,h,y)):(r=fo(c.type,null,h,i,i.mode,y),r.ref=i.ref,r.return=i,i.child=r)}if(_=r.child,(r.lanes&y)===0){var A=_.memoizedProps;if(c=c.compare,c=c!==null?c:fa,c(A,h)&&r.ref===i.ref)return er(r,i,y)}return i.flags|=1,r=Cr(_,h),r.ref=i.ref,r.return=i,i.child=r}function Yh(r,i,c,h,y){if(r!==null){var _=r.memoizedProps;if(fa(_,h)&&r.ref===i.ref)if(sn=!1,i.pendingProps=h=_,(r.lanes&y)!==0)(r.flags&131072)!==0&&(sn=!0);else return i.lanes=r.lanes,er(r,i,y)}return $c(r,i,c,h,y)}function Qh(r,i,c){var h=i.pendingProps,y=h.children,_=r!==null?r.memoizedState:null;if(h.mode==="hidden")if((i.mode&1)===0)i.memoizedState={baseLanes:0,cachePool:null,transitions:null},ft(Os,vn),vn|=c;else{if((c&1073741824)===0)return r=_!==null?_.baseLanes|c:c,i.lanes=i.childLanes=1073741824,i.memoizedState={baseLanes:r,cachePool:null,transitions:null},i.updateQueue=null,ft(Os,vn),vn|=r,null;i.memoizedState={baseLanes:0,cachePool:null,transitions:null},h=_!==null?_.baseLanes:c,ft(Os,vn),vn|=h}else _!==null?(h=_.baseLanes|c,i.memoizedState=null):h=c,ft(Os,vn),vn|=h;return Yt(r,i,y,c),i.child}function Xh(r,i){var c=i.ref;(r===null&&c!==null||r!==null&&r.ref!==c)&&(i.flags|=512,i.flags|=2097152)}function $c(r,i,c,h,y){var _=rn(c)?qr:Wt.current;return _=Cs(i,_),Ms(i,y),c=bc(r,i,c,h,_,y),h=xc(),r!==null&&!sn?(i.updateQueue=r.updateQueue,i.flags&=-2053,r.lanes&=~y,er(r,i,y)):(gt&&h&&sc(i),i.flags|=1,Yt(r,i,c,y),i.child)}function Zh(r,i,c,h,y){if(rn(c)){var _=!0;Pi(i)}else _=!1;if(Ms(i,y),i.stateNode===null)eo(r,i),zh(i,c,h),Ec(i,c,h,y),h=!0;else if(r===null){var A=i.stateNode,F=i.memoizedProps;A.props=F;var H=A.context,le=c.contextType;typeof le=="object"&&le!==null?le=kn(le):(le=rn(c)?qr:Wt.current,le=Cs(i,le));var ve=c.getDerivedStateFromProps,_e=typeof ve=="function"||typeof A.getSnapshotBeforeUpdate=="function";_e||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==h||H!==le)&&Uh(i,A,h,le),_r=!1;var ge=i.memoizedState;A.state=ge,qi(i,h,A,y),H=i.memoizedState,F!==h||ge!==H||nn.current||_r?(typeof ve=="function"&&(Cc(i,c,ve,h),H=i.memoizedState),(F=_r||Bh(i,c,F,h,ge,H,le))?(_e||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(i.flags|=4194308)):(typeof A.componentDidMount=="function"&&(i.flags|=4194308),i.memoizedProps=h,i.memoizedState=H),A.props=h,A.state=H,A.context=le,h=F):(typeof A.componentDidMount=="function"&&(i.flags|=4194308),h=!1)}else{A=i.stateNode,mh(r,i),F=i.memoizedProps,le=i.type===i.elementType?F:In(i.type,F),A.props=le,_e=i.pendingProps,ge=A.context,H=c.contextType,typeof H=="object"&&H!==null?H=kn(H):(H=rn(c)?qr:Wt.current,H=Cs(i,H));var Ae=c.getDerivedStateFromProps;(ve=typeof Ae=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(F!==_e||ge!==H)&&Uh(i,A,h,H),_r=!1,ge=i.memoizedState,A.state=ge,qi(i,h,A,y);var Le=i.memoizedState;F!==_e||ge!==Le||nn.current||_r?(typeof Ae=="function"&&(Cc(i,c,Ae,h),Le=i.memoizedState),(le=_r||Bh(i,c,le,h,ge,Le,H)||!1)?(ve||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(h,Le,H),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(h,Le,H)),typeof A.componentDidUpdate=="function"&&(i.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(i.flags|=1024)):(typeof A.componentDidUpdate!="function"||F===r.memoizedProps&&ge===r.memoizedState||(i.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===r.memoizedProps&&ge===r.memoizedState||(i.flags|=1024),i.memoizedProps=h,i.memoizedState=Le),A.props=h,A.state=Le,A.context=H,h=le):(typeof A.componentDidUpdate!="function"||F===r.memoizedProps&&ge===r.memoizedState||(i.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||F===r.memoizedProps&&ge===r.memoizedState||(i.flags|=1024),h=!1)}return Rc(r,i,c,h,_,y)}function Rc(r,i,c,h,y,_){Xh(r,i);var A=(i.flags&128)!==0;if(!h&&!A)return y&&sh(i,c,!1),er(r,i,_);h=i.stateNode,B_.current=i;var F=A&&typeof c.getDerivedStateFromError!="function"?null:h.render();return i.flags|=1,r!==null&&A?(i.child=$s(i,r.child,null,_),i.child=$s(i,null,F,_)):Yt(r,i,F,_),i.memoizedState=h.state,y&&sh(i,c,!0),i.child}function ep(r){var i=r.stateNode;i.pendingContext?nh(r,i.pendingContext,i.pendingContext!==i.context):i.context&&nh(r,i.context,!1),mc(r,i.containerInfo)}function tp(r,i,c,h,y){return As(),lc(y),i.flags|=256,Yt(r,i,c,h),i.child}var Mc={dehydrated:null,treeContext:null,retryLane:0};function Lc(r){return{baseLanes:r,cachePool:null,transitions:null}}function np(r,i,c){var h=i.pendingProps,y=vt.current,_=!1,A=(i.flags&128)!==0,F;if((F=A)||(F=r!==null&&r.memoizedState===null?!1:(y&2)!==0),F?(_=!0,i.flags&=-129):(r===null||r.memoizedState!==null)&&(y|=1),ft(vt,y&1),r===null)return oc(i),r=i.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?((i.mode&1)===0?i.lanes=1:r.data==="$!"?i.lanes=8:i.lanes=1073741824,null):(A=h.children,r=h.fallback,_?(h=i.mode,_=i.child,A={mode:"hidden",children:A},(h&1)===0&&_!==null?(_.childLanes=0,_.pendingProps=A):_=ho(A,h,0,null),r=ts(r,h,c,null),_.return=i,r.return=i,_.sibling=r,i.child=_,i.child.memoizedState=Lc(c),i.memoizedState=Mc,r):Ic(i,A));if(y=r.memoizedState,y!==null&&(F=y.dehydrated,F!==null))return z_(r,i,A,h,F,y,c);if(_){_=h.fallback,A=i.mode,y=r.child,F=y.sibling;var H={mode:"hidden",children:h.children};return(A&1)===0&&i.child!==y?(h=i.child,h.childLanes=0,h.pendingProps=H,i.deletions=null):(h=Cr(y,H),h.subtreeFlags=y.subtreeFlags&14680064),F!==null?_=Cr(F,_):(_=ts(_,A,c,null),_.flags|=2),_.return=i,h.return=i,h.sibling=_,i.child=h,h=_,_=i.child,A=r.child.memoizedState,A=A===null?Lc(c):{baseLanes:A.baseLanes|c,cachePool:null,transitions:A.transitions},_.memoizedState=A,_.childLanes=r.childLanes&~c,i.memoizedState=Mc,h}return _=r.child,r=_.sibling,h=Cr(_,{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 Ic(r,i){return i=ho({mode:"visible",children:i},r.mode,0,null),i.return=r,r.child=i}function Zi(r,i,c,h){return h!==null&&lc(h),$s(i,r.child,null,c),r=Ic(i,i.pendingProps.children),r.flags|=2,i.memoizedState=null,r}function z_(r,i,c,h,y,_,A){if(c)return i.flags&256?(i.flags&=-257,h=Tc(Error(n(422))),Zi(r,i,A,h)):i.memoizedState!==null?(i.child=r.child,i.flags|=128,null):(_=h.fallback,y=i.mode,h=ho({mode:"visible",children:h.children},y,0,null),_=ts(_,y,A,null),_.flags|=2,h.return=i,_.return=i,h.sibling=_,i.child=h,(i.mode&1)!==0&&$s(i,r.child,null,A),i.child.memoizedState=Lc(A),i.memoizedState=Mc,_);if((i.mode&1)===0)return Zi(r,i,A,null);if(y.data==="$!"){if(h=y.nextSibling&&y.nextSibling.dataset,h)var F=h.dgst;return h=F,_=Error(n(419)),h=Tc(_,h,void 0),Zi(r,i,A,h)}if(F=(A&r.childLanes)!==0,sn||F){if(h=$t,h!==null){switch(A&-A){case 4:y=2;break;case 16:y=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:y=32;break;case 536870912:y=268435456;break;default:y=0}y=(y&(h.suspendedLanes|A))!==0?0:y,y!==0&&y!==_.retryLane&&(_.retryLane=y,Xn(r,y),Dn(h,r,y,-1))}return Qc(),h=Tc(Error(n(421))),Zi(r,i,A,h)}return y.data==="$?"?(i.flags|=128,i.child=r.child,i=eb.bind(null,r),y._reactRetry=i,null):(r=_.treeContext,gn=gr(y.nextSibling),mn=i,gt=!0,Ln=null,r!==null&&(bn[xn++]=Yn,bn[xn++]=Qn,bn[xn++]=Hr,Yn=r.id,Qn=r.overflow,Hr=i),i=Ic(i,h.children),i.flags|=4096,i)}function rp(r,i,c){r.lanes|=i;var h=r.alternate;h!==null&&(h.lanes|=i),fc(r.return,i,c)}function Pc(r,i,c,h,y){var _=r.memoizedState;_===null?r.memoizedState={isBackwards:i,rendering:null,renderingStartTime:0,last:h,tail:c,tailMode:y}:(_.isBackwards=i,_.rendering=null,_.renderingStartTime=0,_.last=h,_.tail=c,_.tailMode=y)}function sp(r,i,c){var h=i.pendingProps,y=h.revealOrder,_=h.tail;if(Yt(r,i,h.children,c),h=vt.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&&rp(r,c,i);else if(r.tag===19)rp(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(ft(vt,h),(i.mode&1)===0)i.memoizedState=null;else switch(y){case"forwards":for(c=i.child,y=null;c!==null;)r=c.alternate,r!==null&&Hi(r)===null&&(y=c),c=c.sibling;c=y,c===null?(y=i.child,i.child=null):(y=c.sibling,c.sibling=null),Pc(i,!1,y,c,_);break;case"backwards":for(c=null,y=i.child,i.child=null;y!==null;){if(r=y.alternate,r!==null&&Hi(r)===null){i.child=y;break}r=y.sibling,y.sibling=c,c=y,y=r}Pc(i,!0,c,null,_);break;case"together":Pc(i,!1,null,null,void 0);break;default:i.memoizedState=null}return i.child}function eo(r,i){(i.mode&1)===0&&r!==null&&(r.alternate=null,i.alternate=null,i.flags|=2)}function er(r,i,c){if(r!==null&&(i.dependencies=r.dependencies),Qr|=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=Cr(r,r.pendingProps),i.child=c,c.return=i;r.sibling!==null;)r=r.sibling,c=c.sibling=Cr(r,r.pendingProps),c.return=i;c.sibling=null}return i.child}function U_(r,i,c){switch(i.tag){case 3:ep(i),As();break;case 5:yh(i);break;case 1:rn(i.type)&&Pi(i);break;case 4:mc(i,i.stateNode.containerInfo);break;case 10:var h=i.type._context,y=i.memoizedProps.value;ft(Ui,h._currentValue),h._currentValue=y;break;case 13:if(h=i.memoizedState,h!==null)return h.dehydrated!==null?(ft(vt,vt.current&1),i.flags|=128,null):(c&i.child.childLanes)!==0?np(r,i,c):(ft(vt,vt.current&1),r=er(r,i,c),r!==null?r.sibling:null);ft(vt,vt.current&1);break;case 19:if(h=(c&i.childLanes)!==0,(r.flags&128)!==0){if(h)return sp(r,i,c);i.flags|=128}if(y=i.memoizedState,y!==null&&(y.rendering=null,y.tail=null,y.lastEffect=null),ft(vt,vt.current),h)break;return null;case 22:case 23:return i.lanes=0,Qh(r,i,c)}return er(r,i,c)}var ap,Oc,ip,op;ap=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}},Oc=function(){},ip=function(r,i,c,h){var y=r.memoizedProps;if(y!==h){r=i.stateNode,Jr(Vn.current);var _=null;switch(c){case"input":y=je(r,y),h=je(r,h),_=[];break;case"select":y=Z({},y,{value:void 0}),h=Z({},h,{value:void 0}),_=[];break;case"textarea":y=te(r,y),h=te(r,h),_=[];break;default:typeof y.onClick!="function"&&typeof h.onClick=="function"&&(r.onclick=Mi)}ht(c,h);var A;c=null;for(le in y)if(!h.hasOwnProperty(le)&&y.hasOwnProperty(le)&&y[le]!=null)if(le==="style"){var F=y[le];for(A in F)F.hasOwnProperty(A)&&(c||(c={}),c[A]="")}else le!=="dangerouslySetInnerHTML"&&le!=="children"&&le!=="suppressContentEditableWarning"&&le!=="suppressHydrationWarning"&&le!=="autoFocus"&&(o.hasOwnProperty(le)?_||(_=[]):(_=_||[]).push(le,null));for(le in h){var H=h[le];if(F=y!=null?y[le]:void 0,h.hasOwnProperty(le)&&H!==F&&(H!=null||F!=null))if(le==="style")if(F){for(A in F)!F.hasOwnProperty(A)||H&&H.hasOwnProperty(A)||(c||(c={}),c[A]="");for(A in H)H.hasOwnProperty(A)&&F[A]!==H[A]&&(c||(c={}),c[A]=H[A])}else c||(_||(_=[]),_.push(le,c)),c=H;else le==="dangerouslySetInnerHTML"?(H=H?H.__html:void 0,F=F?F.__html:void 0,H!=null&&F!==H&&(_=_||[]).push(le,H)):le==="children"?typeof H!="string"&&typeof H!="number"||(_=_||[]).push(le,""+H):le!=="suppressContentEditableWarning"&&le!=="suppressHydrationWarning"&&(o.hasOwnProperty(le)?(H!=null&&le==="onScroll"&&pt("scroll",r),_||F===H||(_=[])):(_=_||[]).push(le,H))}c&&(_=_||[]).push("style",c);var le=_;(i.updateQueue=le)&&(i.flags|=4)}},op=function(r,i,c,h){c!==h&&(i.flags|=4)};function Ca(r,i){if(!gt)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 qt(r){var i=r.alternate!==null&&r.alternate.child===r.child,c=0,h=0;if(i)for(var y=r.child;y!==null;)c|=y.lanes|y.childLanes,h|=y.subtreeFlags&14680064,h|=y.flags&14680064,y.return=r,y=y.sibling;else for(y=r.child;y!==null;)c|=y.lanes|y.childLanes,h|=y.subtreeFlags,h|=y.flags,y.return=r,y=y.sibling;return r.subtreeFlags|=h,r.childLanes=c,i}function W_(r,i,c){var h=i.pendingProps;switch(ac(i),i.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qt(i),null;case 1:return rn(i.type)&&Ii(),qt(i),null;case 3:return h=i.stateNode,Ls(),mt(nn),mt(Wt),yc(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(r===null||r.child===null)&&(Bi(i)?i.flags|=4:r===null||r.memoizedState.isDehydrated&&(i.flags&256)===0||(i.flags|=1024,Ln!==null&&(Kc(Ln),Ln=null))),Oc(r,i),qt(i),null;case 5:gc(i);var y=Jr(xa.current);if(c=i.type,r!==null&&i.stateNode!=null)ip(r,i,c,h,y),r.ref!==i.ref&&(i.flags|=512,i.flags|=2097152);else{if(!h){if(i.stateNode===null)throw Error(n(166));return qt(i),null}if(r=Jr(Vn.current),Bi(i)){h=i.stateNode,c=i.type;var _=i.memoizedProps;switch(h[Wn]=i,h[va]=_,r=(i.mode&1)!==0,c){case"dialog":pt("cancel",h),pt("close",h);break;case"iframe":case"object":case"embed":pt("load",h);break;case"video":case"audio":for(y=0;y<pa.length;y++)pt(pa[y],h);break;case"source":pt("error",h);break;case"img":case"image":case"link":pt("error",h),pt("load",h);break;case"details":pt("toggle",h);break;case"input":Ue(h,_),pt("invalid",h);break;case"select":h._wrapperState={wasMultiple:!!_.multiple},pt("invalid",h);break;case"textarea":pe(h,_),pt("invalid",h)}ht(c,_),y=null;for(var A in _)if(_.hasOwnProperty(A)){var F=_[A];A==="children"?typeof F=="string"?h.textContent!==F&&(_.suppressHydrationWarning!==!0&&Ri(h.textContent,F,r),y=["children",F]):typeof F=="number"&&h.textContent!==""+F&&(_.suppressHydrationWarning!==!0&&Ri(h.textContent,F,r),y=["children",""+F]):o.hasOwnProperty(A)&&F!=null&&A==="onScroll"&&pt("scroll",h)}switch(c){case"input":ze(h),Pe(h,_,!0);break;case"textarea":ze(h),Ze(h);break;case"select":case"option":break;default:typeof _.onClick=="function"&&(h.onclick=Mi)}h=y,i.updateQueue=h,h!==null&&(i.flags|=4)}else{A=y.nodeType===9?y:y.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=Ye(c)),r==="http://www.w3.org/1999/xhtml"?c==="script"?(r=A.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof h.is=="string"?r=A.createElement(c,{is:h.is}):(r=A.createElement(c),c==="select"&&(A=r,h.multiple?A.multiple=!0:h.size&&(A.size=h.size))):r=A.createElementNS(r,c),r[Wn]=i,r[va]=h,ap(r,i,!1,!1),i.stateNode=r;e:{switch(A=Tt(c,h),c){case"dialog":pt("cancel",r),pt("close",r),y=h;break;case"iframe":case"object":case"embed":pt("load",r),y=h;break;case"video":case"audio":for(y=0;y<pa.length;y++)pt(pa[y],r);y=h;break;case"source":pt("error",r),y=h;break;case"img":case"image":case"link":pt("error",r),pt("load",r),y=h;break;case"details":pt("toggle",r),y=h;break;case"input":Ue(r,h),y=je(r,h),pt("invalid",r);break;case"option":y=h;break;case"select":r._wrapperState={wasMultiple:!!h.multiple},y=Z({},h,{value:void 0}),pt("invalid",r);break;case"textarea":pe(r,h),y=te(r,h),pt("invalid",r);break;default:y=h}ht(c,y),F=y;for(_ in F)if(F.hasOwnProperty(_)){var H=F[_];_==="style"?zt(r,H):_==="dangerouslySetInnerHTML"?(H=H?H.__html:void 0,H!=null&&he(r,H)):_==="children"?typeof H=="string"?(c!=="textarea"||H!=="")&&Je(r,H):typeof H=="number"&&Je(r,""+H):_!=="suppressContentEditableWarning"&&_!=="suppressHydrationWarning"&&_!=="autoFocus"&&(o.hasOwnProperty(_)?H!=null&&_==="onScroll"&&pt("scroll",r):H!=null&&N(r,_,H,A))}switch(c){case"input":ze(r),Pe(r,h,!1);break;case"textarea":ze(r),Ze(r);break;case"option":h.value!=null&&r.setAttribute("value",""+ce(h.value));break;case"select":r.multiple=!!h.multiple,_=h.value,_!=null?fe(r,!!h.multiple,_,!1):h.defaultValue!=null&&fe(r,!!h.multiple,h.defaultValue,!0);break;default:typeof y.onClick=="function"&&(r.onclick=Mi)}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 qt(i),null;case 6:if(r&&i.stateNode!=null)op(r,i,r.memoizedProps,h);else{if(typeof h!="string"&&i.stateNode===null)throw Error(n(166));if(c=Jr(xa.current),Jr(Vn.current),Bi(i)){if(h=i.stateNode,c=i.memoizedProps,h[Wn]=i,(_=h.nodeValue!==c)&&(r=mn,r!==null))switch(r.tag){case 3:Ri(h.nodeValue,c,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&Ri(h.nodeValue,c,(r.mode&1)!==0)}_&&(i.flags|=4)}else h=(c.nodeType===9?c:c.ownerDocument).createTextNode(h),h[Wn]=i,i.stateNode=h}return qt(i),null;case 13:if(mt(vt),h=i.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(gt&&gn!==null&&(i.mode&1)!==0&&(i.flags&128)===0)uh(),As(),i.flags|=98560,_=!1;else if(_=Bi(i),h!==null&&h.dehydrated!==null){if(r===null){if(!_)throw Error(n(318));if(_=i.memoizedState,_=_!==null?_.dehydrated:null,!_)throw Error(n(317));_[Wn]=i}else As(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;qt(i),_=!1}else Ln!==null&&(Kc(Ln),Ln=null),_=!0;if(!_)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||(vt.current&1)!==0?Et===0&&(Et=3):Qc())),i.updateQueue!==null&&(i.flags|=4),qt(i),null);case 4:return Ls(),Oc(r,i),r===null&&ma(i.stateNode.containerInfo),qt(i),null;case 10:return dc(i.type._context),qt(i),null;case 17:return rn(i.type)&&Ii(),qt(i),null;case 19:if(mt(vt),_=i.memoizedState,_===null)return qt(i),null;if(h=(i.flags&128)!==0,A=_.rendering,A===null)if(h)Ca(_,!1);else{if(Et!==0||r!==null&&(r.flags&128)!==0)for(r=i.child;r!==null;){if(A=Hi(r),A!==null){for(i.flags|=128,Ca(_,!1),h=A.updateQueue,h!==null&&(i.updateQueue=h,i.flags|=4),i.subtreeFlags=0,h=c,c=i.child;c!==null;)_=c,r=h,_.flags&=14680066,A=_.alternate,A===null?(_.childLanes=0,_.lanes=r,_.child=null,_.subtreeFlags=0,_.memoizedProps=null,_.memoizedState=null,_.updateQueue=null,_.dependencies=null,_.stateNode=null):(_.childLanes=A.childLanes,_.lanes=A.lanes,_.child=A.child,_.subtreeFlags=0,_.deletions=null,_.memoizedProps=A.memoizedProps,_.memoizedState=A.memoizedState,_.updateQueue=A.updateQueue,_.type=A.type,r=A.dependencies,_.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),c=c.sibling;return ft(vt,vt.current&1|2),i.child}r=r.sibling}_.tail!==null&&xt()>Ds&&(i.flags|=128,h=!0,Ca(_,!1),i.lanes=4194304)}else{if(!h)if(r=Hi(A),r!==null){if(i.flags|=128,h=!0,c=r.updateQueue,c!==null&&(i.updateQueue=c,i.flags|=4),Ca(_,!0),_.tail===null&&_.tailMode==="hidden"&&!A.alternate&&!gt)return qt(i),null}else 2*xt()-_.renderingStartTime>Ds&&c!==1073741824&&(i.flags|=128,h=!0,Ca(_,!1),i.lanes=4194304);_.isBackwards?(A.sibling=i.child,i.child=A):(c=_.last,c!==null?c.sibling=A:i.child=A,_.last=A)}return _.tail!==null?(i=_.tail,_.rendering=i,_.tail=i.sibling,_.renderingStartTime=xt(),i.sibling=null,c=vt.current,ft(vt,h?c&1|2:c&1),i):(qt(i),null);case 22:case 23:return Yc(),h=i.memoizedState!==null,r!==null&&r.memoizedState!==null!==h&&(i.flags|=8192),h&&(i.mode&1)!==0?(vn&1073741824)!==0&&(qt(i),i.subtreeFlags&6&&(i.flags|=8192)):qt(i),null;case 24:return null;case 25:return null}throw Error(n(156,i.tag))}function V_(r,i){switch(ac(i),i.tag){case 1:return rn(i.type)&&Ii(),r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 3:return Ls(),mt(nn),mt(Wt),yc(),r=i.flags,(r&65536)!==0&&(r&128)===0?(i.flags=r&-65537|128,i):null;case 5:return gc(i),null;case 13:if(mt(vt),r=i.memoizedState,r!==null&&r.dehydrated!==null){if(i.alternate===null)throw Error(n(340));As()}return r=i.flags,r&65536?(i.flags=r&-65537|128,i):null;case 19:return mt(vt),null;case 4:return Ls(),null;case 10:return dc(i.type._context),null;case 22:case 23:return Yc(),null;case 24:return null;default:return null}}var to=!1,Ht=!1,q_=typeof WeakSet=="function"?WeakSet:Set,Re=null;function Ps(r,i){var c=r.ref;if(c!==null)if(typeof c=="function")try{c(null)}catch(h){wt(r,i,h)}else c.current=null}function Dc(r,i,c){try{c()}catch(h){wt(r,i,h)}}var lp=!1;function H_(r,i){if(Yl=bi,r=Bf(),Ul(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 y=h.anchorOffset,_=h.focusNode;h=h.focusOffset;try{c.nodeType,_.nodeType}catch{c=null;break e}var A=0,F=-1,H=-1,le=0,ve=0,_e=r,ge=null;t:for(;;){for(var Ae;_e!==c||y!==0&&_e.nodeType!==3||(F=A+y),_e!==_||h!==0&&_e.nodeType!==3||(H=A+h),_e.nodeType===3&&(A+=_e.nodeValue.length),(Ae=_e.firstChild)!==null;)ge=_e,_e=Ae;for(;;){if(_e===r)break t;if(ge===c&&++le===y&&(F=A),ge===_&&++ve===h&&(H=A),(Ae=_e.nextSibling)!==null)break;_e=ge,ge=_e.parentNode}_e=Ae}c=F===-1||H===-1?null:{start:F,end:H}}else c=null}c=c||{start:0,end:0}}else c=null;for(Ql={focusedElem:r,selectionRange:c},bi=!1,Re=i;Re!==null;)if(i=Re,r=i.child,(i.subtreeFlags&1028)!==0&&r!==null)r.return=i,Re=r;else for(;Re!==null;){i=Re;try{var Le=i.alternate;if((i.flags&1024)!==0)switch(i.tag){case 0:case 11:case 15:break;case 1:if(Le!==null){var Ie=Le.memoizedProps,kt=Le.memoizedState,re=i.stateNode,X=re.getSnapshotBeforeUpdate(i.elementType===i.type?Ie:In(i.type,Ie),kt);re.__reactInternalSnapshotBeforeUpdate=X}break;case 3:var ae=i.stateNode.containerInfo;ae.nodeType===1?ae.textContent="":ae.nodeType===9&&ae.documentElement&&ae.removeChild(ae.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(ke){wt(i,i.return,ke)}if(r=i.sibling,r!==null){r.return=i.return,Re=r;break}Re=i.return}return Le=lp,lp=!1,Le}function Ea(r,i,c){var h=i.updateQueue;if(h=h!==null?h.lastEffect:null,h!==null){var y=h=h.next;do{if((y.tag&r)===r){var _=y.destroy;y.destroy=void 0,_!==void 0&&Dc(i,c,_)}y=y.next}while(y!==h)}}function no(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 Fc(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 cp(r){var i=r.alternate;i!==null&&(r.alternate=null,cp(i)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(i=r.stateNode,i!==null&&(delete i[Wn],delete i[va],delete i[tc],delete i[E_],delete i[T_])),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 up(r){return r.tag===5||r.tag===3||r.tag===4}function dp(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||up(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 Bc(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=Mi));else if(h!==4&&(r=r.child,r!==null))for(Bc(r,i,c),r=r.sibling;r!==null;)Bc(r,i,c),r=r.sibling}function zc(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(zc(r,i,c),r=r.sibling;r!==null;)zc(r,i,c),r=r.sibling}var It=null,Pn=!1;function xr(r,i,c){for(c=c.child;c!==null;)fp(r,i,c),c=c.sibling}function fp(r,i,c){if(Un&&typeof Un.onCommitFiberUnmount=="function")try{Un.onCommitFiberUnmount(mi,c)}catch{}switch(c.tag){case 5:Ht||Ps(c,i);case 6:var h=It,y=Pn;It=null,xr(r,i,c),It=h,Pn=y,It!==null&&(Pn?(r=It,c=c.stateNode,r.nodeType===8?r.parentNode.removeChild(c):r.removeChild(c)):It.removeChild(c.stateNode));break;case 18:It!==null&&(Pn?(r=It,c=c.stateNode,r.nodeType===8?ec(r.parentNode,c):r.nodeType===1&&ec(r,c),ia(r)):ec(It,c.stateNode));break;case 4:h=It,y=Pn,It=c.stateNode.containerInfo,Pn=!0,xr(r,i,c),It=h,Pn=y;break;case 0:case 11:case 14:case 15:if(!Ht&&(h=c.updateQueue,h!==null&&(h=h.lastEffect,h!==null))){y=h=h.next;do{var _=y,A=_.destroy;_=_.tag,A!==void 0&&((_&2)!==0||(_&4)!==0)&&Dc(c,i,A),y=y.next}while(y!==h)}xr(r,i,c);break;case 1:if(!Ht&&(Ps(c,i),h=c.stateNode,typeof h.componentWillUnmount=="function"))try{h.props=c.memoizedProps,h.state=c.memoizedState,h.componentWillUnmount()}catch(F){wt(c,i,F)}xr(r,i,c);break;case 21:xr(r,i,c);break;case 22:c.mode&1?(Ht=(h=Ht)||c.memoizedState!==null,xr(r,i,c),Ht=h):xr(r,i,c);break;default:xr(r,i,c)}}function hp(r){var i=r.updateQueue;if(i!==null){r.updateQueue=null;var c=r.stateNode;c===null&&(c=r.stateNode=new q_),i.forEach(function(h){var y=tb.bind(null,r,h);c.has(h)||(c.add(h),h.then(y,y))})}}function On(r,i){var c=i.deletions;if(c!==null)for(var h=0;h<c.length;h++){var y=c[h];try{var _=r,A=i,F=A;e:for(;F!==null;){switch(F.tag){case 5:It=F.stateNode,Pn=!1;break e;case 3:It=F.stateNode.containerInfo,Pn=!0;break e;case 4:It=F.stateNode.containerInfo,Pn=!0;break e}F=F.return}if(It===null)throw Error(n(160));fp(_,A,y),It=null,Pn=!1;var H=y.alternate;H!==null&&(H.return=null),y.return=null}catch(le){wt(y,i,le)}}if(i.subtreeFlags&12854)for(i=i.child;i!==null;)pp(i,r),i=i.sibling}function pp(r,i){var c=r.alternate,h=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(On(i,r),Hn(r),h&4){try{Ea(3,r,r.return),no(3,r)}catch(Ie){wt(r,r.return,Ie)}try{Ea(5,r,r.return)}catch(Ie){wt(r,r.return,Ie)}}break;case 1:On(i,r),Hn(r),h&512&&c!==null&&Ps(c,c.return);break;case 5:if(On(i,r),Hn(r),h&512&&c!==null&&Ps(c,c.return),r.flags&32){var y=r.stateNode;try{Je(y,"")}catch(Ie){wt(r,r.return,Ie)}}if(h&4&&(y=r.stateNode,y!=null)){var _=r.memoizedProps,A=c!==null?c.memoizedProps:_,F=r.type,H=r.updateQueue;if(r.updateQueue=null,H!==null)try{F==="input"&&_.type==="radio"&&_.name!=null&&ne(y,_),Tt(F,A);var le=Tt(F,_);for(A=0;A<H.length;A+=2){var ve=H[A],_e=H[A+1];ve==="style"?zt(y,_e):ve==="dangerouslySetInnerHTML"?he(y,_e):ve==="children"?Je(y,_e):N(y,ve,_e,le)}switch(F){case"input":$e(y,_);break;case"textarea":Se(y,_);break;case"select":var ge=y._wrapperState.wasMultiple;y._wrapperState.wasMultiple=!!_.multiple;var Ae=_.value;Ae!=null?fe(y,!!_.multiple,Ae,!1):ge!==!!_.multiple&&(_.defaultValue!=null?fe(y,!!_.multiple,_.defaultValue,!0):fe(y,!!_.multiple,_.multiple?[]:"",!1))}y[va]=_}catch(Ie){wt(r,r.return,Ie)}}break;case 6:if(On(i,r),Hn(r),h&4){if(r.stateNode===null)throw Error(n(162));y=r.stateNode,_=r.memoizedProps;try{y.nodeValue=_}catch(Ie){wt(r,r.return,Ie)}}break;case 3:if(On(i,r),Hn(r),h&4&&c!==null&&c.memoizedState.isDehydrated)try{ia(i.containerInfo)}catch(Ie){wt(r,r.return,Ie)}break;case 4:On(i,r),Hn(r);break;case 13:On(i,r),Hn(r),y=r.child,y.flags&8192&&(_=y.memoizedState!==null,y.stateNode.isHidden=_,!_||y.alternate!==null&&y.alternate.memoizedState!==null||(Vc=xt())),h&4&&hp(r);break;case 22:if(ve=c!==null&&c.memoizedState!==null,r.mode&1?(Ht=(le=Ht)||ve,On(i,r),Ht=le):On(i,r),Hn(r),h&8192){if(le=r.memoizedState!==null,(r.stateNode.isHidden=le)&&!ve&&(r.mode&1)!==0)for(Re=r,ve=r.child;ve!==null;){for(_e=Re=ve;Re!==null;){switch(ge=Re,Ae=ge.child,ge.tag){case 0:case 11:case 14:case 15:Ea(4,ge,ge.return);break;case 1:Ps(ge,ge.return);var Le=ge.stateNode;if(typeof Le.componentWillUnmount=="function"){h=ge,c=ge.return;try{i=h,Le.props=i.memoizedProps,Le.state=i.memoizedState,Le.componentWillUnmount()}catch(Ie){wt(h,c,Ie)}}break;case 5:Ps(ge,ge.return);break;case 22:if(ge.memoizedState!==null){vp(_e);continue}}Ae!==null?(Ae.return=ge,Re=Ae):vp(_e)}ve=ve.sibling}e:for(ve=null,_e=r;;){if(_e.tag===5){if(ve===null){ve=_e;try{y=_e.stateNode,le?(_=y.style,typeof _.setProperty=="function"?_.setProperty("display","none","important"):_.display="none"):(F=_e.stateNode,H=_e.memoizedProps.style,A=H!=null&&H.hasOwnProperty("display")?H.display:null,F.style.display=Nt("display",A))}catch(Ie){wt(r,r.return,Ie)}}}else if(_e.tag===6){if(ve===null)try{_e.stateNode.nodeValue=le?"":_e.memoizedProps}catch(Ie){wt(r,r.return,Ie)}}else if((_e.tag!==22&&_e.tag!==23||_e.memoizedState===null||_e===r)&&_e.child!==null){_e.child.return=_e,_e=_e.child;continue}if(_e===r)break e;for(;_e.sibling===null;){if(_e.return===null||_e.return===r)break e;ve===_e&&(ve=null),_e=_e.return}ve===_e&&(ve=null),_e.sibling.return=_e.return,_e=_e.sibling}}break;case 19:On(i,r),Hn(r),h&4&&hp(r);break;case 21:break;default:On(i,r),Hn(r)}}function Hn(r){var i=r.flags;if(i&2){try{e:{for(var c=r.return;c!==null;){if(up(c)){var h=c;break e}c=c.return}throw Error(n(160))}switch(h.tag){case 5:var y=h.stateNode;h.flags&32&&(Je(y,""),h.flags&=-33);var _=dp(r);zc(r,_,y);break;case 3:case 4:var A=h.stateNode.containerInfo,F=dp(r);Bc(r,F,A);break;default:throw Error(n(161))}}catch(H){wt(r,r.return,H)}r.flags&=-3}i&4096&&(r.flags&=-4097)}function G_(r,i,c){Re=r,mp(r)}function mp(r,i,c){for(var h=(r.mode&1)!==0;Re!==null;){var y=Re,_=y.child;if(y.tag===22&&h){var A=y.memoizedState!==null||to;if(!A){var F=y.alternate,H=F!==null&&F.memoizedState!==null||Ht;F=to;var le=Ht;if(to=A,(Ht=H)&&!le)for(Re=y;Re!==null;)A=Re,H=A.child,A.tag===22&&A.memoizedState!==null?yp(y):H!==null?(H.return=A,Re=H):yp(y);for(;_!==null;)Re=_,mp(_),_=_.sibling;Re=y,to=F,Ht=le}gp(r)}else(y.subtreeFlags&8772)!==0&&_!==null?(_.return=y,Re=_):gp(r)}}function gp(r){for(;Re!==null;){var i=Re;if((i.flags&8772)!==0){var c=i.alternate;try{if((i.flags&8772)!==0)switch(i.tag){case 0:case 11:case 15:Ht||no(5,i);break;case 1:var h=i.stateNode;if(i.flags&4&&!Ht)if(c===null)h.componentDidMount();else{var y=i.elementType===i.type?c.memoizedProps:In(i.type,c.memoizedProps);h.componentDidUpdate(y,c.memoizedState,h.__reactInternalSnapshotBeforeUpdate)}var _=i.updateQueue;_!==null&&vh(i,_,h);break;case 3:var A=i.updateQueue;if(A!==null){if(c=null,i.child!==null)switch(i.child.tag){case 5:c=i.child.stateNode;break;case 1:c=i.child.stateNode}vh(i,A,c)}break;case 5:var F=i.stateNode;if(c===null&&i.flags&4){c=F;var H=i.memoizedProps;switch(i.type){case"button":case"input":case"select":case"textarea":H.autoFocus&&c.focus();break;case"img":H.src&&(c.src=H.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(i.memoizedState===null){var le=i.alternate;if(le!==null){var ve=le.memoizedState;if(ve!==null){var _e=ve.dehydrated;_e!==null&&ia(_e)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Ht||i.flags&512&&Fc(i)}catch(ge){wt(i,i.return,ge)}}if(i===r){Re=null;break}if(c=i.sibling,c!==null){c.return=i.return,Re=c;break}Re=i.return}}function vp(r){for(;Re!==null;){var i=Re;if(i===r){Re=null;break}var c=i.sibling;if(c!==null){c.return=i.return,Re=c;break}Re=i.return}}function yp(r){for(;Re!==null;){var i=Re;try{switch(i.tag){case 0:case 11:case 15:var c=i.return;try{no(4,i)}catch(H){wt(i,c,H)}break;case 1:var h=i.stateNode;if(typeof h.componentDidMount=="function"){var y=i.return;try{h.componentDidMount()}catch(H){wt(i,y,H)}}var _=i.return;try{Fc(i)}catch(H){wt(i,_,H)}break;case 5:var A=i.return;try{Fc(i)}catch(H){wt(i,A,H)}}}catch(H){wt(i,i.return,H)}if(i===r){Re=null;break}var F=i.sibling;if(F!==null){F.return=i.return,Re=F;break}Re=i.return}}var K_=Math.ceil,ro=C.ReactCurrentDispatcher,Uc=C.ReactCurrentOwner,Sn=C.ReactCurrentBatchConfig,st=0,$t=null,jt=null,Pt=0,vn=0,Os=vr(0),Et=0,Ta=null,Qr=0,so=0,Wc=0,Aa=null,an=null,Vc=0,Ds=1/0,tr=null,ao=!1,qc=null,kr=null,io=!1,jr=null,oo=0,$a=0,Hc=null,lo=-1,co=0;function Qt(){return(st&6)!==0?xt():lo!==-1?lo:lo=xt()}function Sr(r){return(r.mode&1)===0?1:(st&2)!==0&&Pt!==0?Pt&-Pt:$_.transition!==null?(co===0&&(co=df()),co):(r=lt,r!==0||(r=window.event,r=r===void 0?16:_f(r.type)),r)}function Dn(r,i,c,h){if(50<$a)throw $a=0,Hc=null,Error(n(185));ta(r,c,h),((st&2)===0||r!==$t)&&(r===$t&&((st&2)===0&&(so|=c),Et===4&&Nr(r,Pt)),on(r,h),c===1&&st===0&&(i.mode&1)===0&&(Ds=xt()+500,Oi&&wr()))}function on(r,i){var c=r.callbackNode;$w(r,i);var h=yi(r,r===$t?Pt:0);if(h===0)c!==null&&lf(c),r.callbackNode=null,r.callbackPriority=0;else if(i=h&-h,r.callbackPriority!==i){if(c!=null&&lf(c),i===1)r.tag===0?A_(_p.bind(null,r)):ah(_p.bind(null,r)),N_(function(){(st&6)===0&&wr()}),c=null;else{switch(ff(h)){case 1:c=Sl;break;case 4:c=cf;break;case 16:c=pi;break;case 536870912:c=uf;break;default:c=pi}c=Ep(c,wp.bind(null,r))}r.callbackPriority=i,r.callbackNode=c}}function wp(r,i){if(lo=-1,co=0,(st&6)!==0)throw Error(n(327));var c=r.callbackNode;if(Fs()&&r.callbackNode!==c)return null;var h=yi(r,r===$t?Pt:0);if(h===0)return null;if((h&30)!==0||(h&r.expiredLanes)!==0||i)i=uo(r,h);else{i=h;var y=st;st|=2;var _=xp();($t!==r||Pt!==i)&&(tr=null,Ds=xt()+500,Zr(r,i));do try{Q_();break}catch(F){bp(r,F)}while(!0);uc(),ro.current=_,st=y,jt!==null?i=0:($t=null,Pt=0,i=Et)}if(i!==0){if(i===2&&(y=Nl(r),y!==0&&(h=y,i=Gc(r,y))),i===1)throw c=Ta,Zr(r,0),Nr(r,h),on(r,xt()),c;if(i===6)Nr(r,h);else{if(y=r.current.alternate,(h&30)===0&&!J_(y)&&(i=uo(r,h),i===2&&(_=Nl(r),_!==0&&(h=_,i=Gc(r,_))),i===1))throw c=Ta,Zr(r,0),Nr(r,h),on(r,xt()),c;switch(r.finishedWork=y,r.finishedLanes=h,i){case 0:case 1:throw Error(n(345));case 2:es(r,an,tr);break;case 3:if(Nr(r,h),(h&130023424)===h&&(i=Vc+500-xt(),10<i)){if(yi(r,0)!==0)break;if(y=r.suspendedLanes,(y&h)!==h){Qt(),r.pingedLanes|=r.suspendedLanes&y;break}r.timeoutHandle=Zl(es.bind(null,r,an,tr),i);break}es(r,an,tr);break;case 4:if(Nr(r,h),(h&4194240)===h)break;for(i=r.eventTimes,y=-1;0<h;){var A=31-Rn(h);_=1<<A,A=i[A],A>y&&(y=A),h&=~_}if(h=y,h=xt()-h,h=(120>h?120:480>h?480:1080>h?1080:1920>h?1920:3e3>h?3e3:4320>h?4320:1960*K_(h/1960))-h,10<h){r.timeoutHandle=Zl(es.bind(null,r,an,tr),h);break}es(r,an,tr);break;case 5:es(r,an,tr);break;default:throw Error(n(329))}}}return on(r,xt()),r.callbackNode===c?wp.bind(null,r):null}function Gc(r,i){var c=Aa;return r.current.memoizedState.isDehydrated&&(Zr(r,i).flags|=256),r=uo(r,i),r!==2&&(i=an,an=c,i!==null&&Kc(i)),r}function Kc(r){an===null?an=r:an.push.apply(an,r)}function J_(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 y=c[h],_=y.getSnapshot;y=y.value;try{if(!Mn(_(),y))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 Nr(r,i){for(i&=~Wc,i&=~so,r.suspendedLanes|=i,r.pingedLanes&=~i,r=r.expirationTimes;0<i;){var c=31-Rn(i),h=1<<c;r[c]=-1,i&=~h}}function _p(r){if((st&6)!==0)throw Error(n(327));Fs();var i=yi(r,0);if((i&1)===0)return on(r,xt()),null;var c=uo(r,i);if(r.tag!==0&&c===2){var h=Nl(r);h!==0&&(i=h,c=Gc(r,h))}if(c===1)throw c=Ta,Zr(r,0),Nr(r,i),on(r,xt()),c;if(c===6)throw Error(n(345));return r.finishedWork=r.current.alternate,r.finishedLanes=i,es(r,an,tr),on(r,xt()),null}function Jc(r,i){var c=st;st|=1;try{return r(i)}finally{st=c,st===0&&(Ds=xt()+500,Oi&&wr())}}function Xr(r){jr!==null&&jr.tag===0&&(st&6)===0&&Fs();var i=st;st|=1;var c=Sn.transition,h=lt;try{if(Sn.transition=null,lt=1,r)return r()}finally{lt=h,Sn.transition=c,st=i,(st&6)===0&&wr()}}function Yc(){vn=Os.current,mt(Os)}function Zr(r,i){r.finishedWork=null,r.finishedLanes=0;var c=r.timeoutHandle;if(c!==-1&&(r.timeoutHandle=-1,S_(c)),jt!==null)for(c=jt.return;c!==null;){var h=c;switch(ac(h),h.tag){case 1:h=h.type.childContextTypes,h!=null&&Ii();break;case 3:Ls(),mt(nn),mt(Wt),yc();break;case 5:gc(h);break;case 4:Ls();break;case 13:mt(vt);break;case 19:mt(vt);break;case 10:dc(h.type._context);break;case 22:case 23:Yc()}c=c.return}if($t=r,jt=r=Cr(r.current,null),Pt=vn=i,Et=0,Ta=null,Wc=so=Qr=0,an=Aa=null,Kr!==null){for(i=0;i<Kr.length;i++)if(c=Kr[i],h=c.interleaved,h!==null){c.interleaved=null;var y=h.next,_=c.pending;if(_!==null){var A=_.next;_.next=y,h.next=A}c.pending=h}Kr=null}return r}function bp(r,i){do{var c=jt;try{if(uc(),Gi.current=Qi,Ki){for(var h=yt.memoizedState;h!==null;){var y=h.queue;y!==null&&(y.pending=null),h=h.next}Ki=!1}if(Yr=0,At=Ct=yt=null,ka=!1,ja=0,Uc.current=null,c===null||c.return===null){Et=1,Ta=i,jt=null;break}e:{var _=r,A=c.return,F=c,H=i;if(i=Pt,F.flags|=32768,H!==null&&typeof H=="object"&&typeof H.then=="function"){var le=H,ve=F,_e=ve.tag;if((ve.mode&1)===0&&(_e===0||_e===11||_e===15)){var ge=ve.alternate;ge?(ve.updateQueue=ge.updateQueue,ve.memoizedState=ge.memoizedState,ve.lanes=ge.lanes):(ve.updateQueue=null,ve.memoizedState=null)}var Ae=Hh(A);if(Ae!==null){Ae.flags&=-257,Gh(Ae,A,F,_,i),Ae.mode&1&&qh(_,le,i),i=Ae,H=le;var Le=i.updateQueue;if(Le===null){var Ie=new Set;Ie.add(H),i.updateQueue=Ie}else Le.add(H);break e}else{if((i&1)===0){qh(_,le,i),Qc();break e}H=Error(n(426))}}else if(gt&&F.mode&1){var kt=Hh(A);if(kt!==null){(kt.flags&65536)===0&&(kt.flags|=256),Gh(kt,A,F,_,i),lc(Is(H,F));break e}}_=H=Is(H,F),Et!==4&&(Et=2),Aa===null?Aa=[_]:Aa.push(_),_=A;do{switch(_.tag){case 3:_.flags|=65536,i&=-i,_.lanes|=i;var re=Wh(_,H,i);gh(_,re);break e;case 1:F=H;var X=_.type,ae=_.stateNode;if((_.flags&128)===0&&(typeof X.getDerivedStateFromError=="function"||ae!==null&&typeof ae.componentDidCatch=="function"&&(kr===null||!kr.has(ae)))){_.flags|=65536,i&=-i,_.lanes|=i;var ke=Vh(_,F,i);gh(_,ke);break e}}_=_.return}while(_!==null)}jp(c)}catch(De){i=De,jt===c&&c!==null&&(jt=c=c.return);continue}break}while(!0)}function xp(){var r=ro.current;return ro.current=Qi,r===null?Qi:r}function Qc(){(Et===0||Et===3||Et===2)&&(Et=4),$t===null||(Qr&268435455)===0&&(so&268435455)===0||Nr($t,Pt)}function uo(r,i){var c=st;st|=2;var h=xp();($t!==r||Pt!==i)&&(tr=null,Zr(r,i));do try{Y_();break}catch(y){bp(r,y)}while(!0);if(uc(),st=c,ro.current=h,jt!==null)throw Error(n(261));return $t=null,Pt=0,Et}function Y_(){for(;jt!==null;)kp(jt)}function Q_(){for(;jt!==null&&!xw();)kp(jt)}function kp(r){var i=Cp(r.alternate,r,vn);r.memoizedProps=r.pendingProps,i===null?jp(r):jt=i,Uc.current=null}function jp(r){var i=r;do{var c=i.alternate;if(r=i.return,(i.flags&32768)===0){if(c=W_(c,i,vn),c!==null){jt=c;return}}else{if(c=V_(c,i),c!==null){c.flags&=32767,jt=c;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Et=6,jt=null;return}}if(i=i.sibling,i!==null){jt=i;return}jt=i=r}while(i!==null);Et===0&&(Et=5)}function es(r,i,c){var h=lt,y=Sn.transition;try{Sn.transition=null,lt=1,X_(r,i,c,h)}finally{Sn.transition=y,lt=h}return null}function X_(r,i,c,h){do Fs();while(jr!==null);if((st&6)!==0)throw Error(n(327));c=r.finishedWork;var y=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 _=c.lanes|c.childLanes;if(Rw(r,_),r===$t&&(jt=$t=null,Pt=0),(c.subtreeFlags&2064)===0&&(c.flags&2064)===0||io||(io=!0,Ep(pi,function(){return Fs(),null})),_=(c.flags&15990)!==0,(c.subtreeFlags&15990)!==0||_){_=Sn.transition,Sn.transition=null;var A=lt;lt=1;var F=st;st|=4,Uc.current=null,H_(r,c),pp(c,r),y_(Ql),bi=!!Yl,Ql=Yl=null,r.current=c,G_(c),kw(),st=F,lt=A,Sn.transition=_}else r.current=c;if(io&&(io=!1,jr=r,oo=y),_=r.pendingLanes,_===0&&(kr=null),Nw(c.stateNode),on(r,xt()),i!==null)for(h=r.onRecoverableError,c=0;c<i.length;c++)y=i[c],h(y.value,{componentStack:y.stack,digest:y.digest});if(ao)throw ao=!1,r=qc,qc=null,r;return(oo&1)!==0&&r.tag!==0&&Fs(),_=r.pendingLanes,(_&1)!==0?r===Hc?$a++:($a=0,Hc=r):$a=0,wr(),null}function Fs(){if(jr!==null){var r=ff(oo),i=Sn.transition,c=lt;try{if(Sn.transition=null,lt=16>r?16:r,jr===null)var h=!1;else{if(r=jr,jr=null,oo=0,(st&6)!==0)throw Error(n(331));var y=st;for(st|=4,Re=r.current;Re!==null;){var _=Re,A=_.child;if((Re.flags&16)!==0){var F=_.deletions;if(F!==null){for(var H=0;H<F.length;H++){var le=F[H];for(Re=le;Re!==null;){var ve=Re;switch(ve.tag){case 0:case 11:case 15:Ea(8,ve,_)}var _e=ve.child;if(_e!==null)_e.return=ve,Re=_e;else for(;Re!==null;){ve=Re;var ge=ve.sibling,Ae=ve.return;if(cp(ve),ve===le){Re=null;break}if(ge!==null){ge.return=Ae,Re=ge;break}Re=Ae}}}var Le=_.alternate;if(Le!==null){var Ie=Le.child;if(Ie!==null){Le.child=null;do{var kt=Ie.sibling;Ie.sibling=null,Ie=kt}while(Ie!==null)}}Re=_}}if((_.subtreeFlags&2064)!==0&&A!==null)A.return=_,Re=A;else e:for(;Re!==null;){if(_=Re,(_.flags&2048)!==0)switch(_.tag){case 0:case 11:case 15:Ea(9,_,_.return)}var re=_.sibling;if(re!==null){re.return=_.return,Re=re;break e}Re=_.return}}var X=r.current;for(Re=X;Re!==null;){A=Re;var ae=A.child;if((A.subtreeFlags&2064)!==0&&ae!==null)ae.return=A,Re=ae;else e:for(A=X;Re!==null;){if(F=Re,(F.flags&2048)!==0)try{switch(F.tag){case 0:case 11:case 15:no(9,F)}}catch(De){wt(F,F.return,De)}if(F===A){Re=null;break e}var ke=F.sibling;if(ke!==null){ke.return=F.return,Re=ke;break e}Re=F.return}}if(st=y,wr(),Un&&typeof Un.onPostCommitFiberRoot=="function")try{Un.onPostCommitFiberRoot(mi,r)}catch{}h=!0}return h}finally{lt=c,Sn.transition=i}}return!1}function Sp(r,i,c){i=Is(c,i),i=Wh(r,i,1),r=br(r,i,1),i=Qt(),r!==null&&(ta(r,1,i),on(r,i))}function wt(r,i,c){if(r.tag===3)Sp(r,r,c);else for(;i!==null;){if(i.tag===3){Sp(i,r,c);break}else if(i.tag===1){var h=i.stateNode;if(typeof i.type.getDerivedStateFromError=="function"||typeof h.componentDidCatch=="function"&&(kr===null||!kr.has(h))){r=Is(c,r),r=Vh(i,r,1),i=br(i,r,1),r=Qt(),i!==null&&(ta(i,1,r),on(i,r));break}}i=i.return}}function Z_(r,i,c){var h=r.pingCache;h!==null&&h.delete(i),i=Qt(),r.pingedLanes|=r.suspendedLanes&c,$t===r&&(Pt&c)===c&&(Et===4||Et===3&&(Pt&130023424)===Pt&&500>xt()-Vc?Zr(r,0):Wc|=c),on(r,i)}function Np(r,i){i===0&&((r.mode&1)===0?i=1:(i=vi,vi<<=1,(vi&130023424)===0&&(vi=4194304)));var c=Qt();r=Xn(r,i),r!==null&&(ta(r,i,c),on(r,c))}function eb(r){var i=r.memoizedState,c=0;i!==null&&(c=i.retryLane),Np(r,c)}function tb(r,i){var c=0;switch(r.tag){case 13:var h=r.stateNode,y=r.memoizedState;y!==null&&(c=y.retryLane);break;case 19:h=r.stateNode;break;default:throw Error(n(314))}h!==null&&h.delete(i),Np(r,c)}var Cp;Cp=function(r,i,c){if(r!==null)if(r.memoizedProps!==i.pendingProps||nn.current)sn=!0;else{if((r.lanes&c)===0&&(i.flags&128)===0)return sn=!1,U_(r,i,c);sn=(r.flags&131072)!==0}else sn=!1,gt&&(i.flags&1048576)!==0&&ih(i,Fi,i.index);switch(i.lanes=0,i.tag){case 2:var h=i.type;eo(r,i),r=i.pendingProps;var y=Cs(i,Wt.current);Ms(i,c),y=bc(null,i,h,r,y,c);var _=xc();return i.flags|=1,typeof y=="object"&&y!==null&&typeof y.render=="function"&&y.$$typeof===void 0?(i.tag=1,i.memoizedState=null,i.updateQueue=null,rn(h)?(_=!0,Pi(i)):_=!1,i.memoizedState=y.state!==null&&y.state!==void 0?y.state:null,pc(i),y.updater=Xi,i.stateNode=y,y._reactInternals=i,Ec(i,h,r,c),i=Rc(null,i,h,!0,_,c)):(i.tag=0,gt&&_&&sc(i),Yt(null,i,y,c),i=i.child),i;case 16:h=i.elementType;e:{switch(eo(r,i),r=i.pendingProps,y=h._init,h=y(h._payload),i.type=h,y=i.tag=rb(h),r=In(h,r),y){case 0:i=$c(null,i,h,r,c);break e;case 1:i=Zh(null,i,h,r,c);break e;case 11:i=Kh(null,i,h,r,c);break e;case 14:i=Jh(null,i,h,In(h.type,r),c);break e}throw Error(n(306,h,""))}return i;case 0:return h=i.type,y=i.pendingProps,y=i.elementType===h?y:In(h,y),$c(r,i,h,y,c);case 1:return h=i.type,y=i.pendingProps,y=i.elementType===h?y:In(h,y),Zh(r,i,h,y,c);case 3:e:{if(ep(i),r===null)throw Error(n(387));h=i.pendingProps,_=i.memoizedState,y=_.element,mh(r,i),qi(i,h,null,c);var A=i.memoizedState;if(h=A.element,_.isDehydrated)if(_={element:h,isDehydrated:!1,cache:A.cache,pendingSuspenseBoundaries:A.pendingSuspenseBoundaries,transitions:A.transitions},i.updateQueue.baseState=_,i.memoizedState=_,i.flags&256){y=Is(Error(n(423)),i),i=tp(r,i,h,c,y);break e}else if(h!==y){y=Is(Error(n(424)),i),i=tp(r,i,h,c,y);break e}else for(gn=gr(i.stateNode.containerInfo.firstChild),mn=i,gt=!0,Ln=null,c=hh(i,null,h,c),i.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{if(As(),h===y){i=er(r,i,c);break e}Yt(r,i,h,c)}i=i.child}return i;case 5:return yh(i),r===null&&oc(i),h=i.type,y=i.pendingProps,_=r!==null?r.memoizedProps:null,A=y.children,Xl(h,y)?A=null:_!==null&&Xl(h,_)&&(i.flags|=32),Xh(r,i),Yt(r,i,A,c),i.child;case 6:return r===null&&oc(i),null;case 13:return np(r,i,c);case 4:return mc(i,i.stateNode.containerInfo),h=i.pendingProps,r===null?i.child=$s(i,null,h,c):Yt(r,i,h,c),i.child;case 11:return h=i.type,y=i.pendingProps,y=i.elementType===h?y:In(h,y),Kh(r,i,h,y,c);case 7:return Yt(r,i,i.pendingProps,c),i.child;case 8:return Yt(r,i,i.pendingProps.children,c),i.child;case 12:return Yt(r,i,i.pendingProps.children,c),i.child;case 10:e:{if(h=i.type._context,y=i.pendingProps,_=i.memoizedProps,A=y.value,ft(Ui,h._currentValue),h._currentValue=A,_!==null)if(Mn(_.value,A)){if(_.children===y.children&&!nn.current){i=er(r,i,c);break e}}else for(_=i.child,_!==null&&(_.return=i);_!==null;){var F=_.dependencies;if(F!==null){A=_.child;for(var H=F.firstContext;H!==null;){if(H.context===h){if(_.tag===1){H=Zn(-1,c&-c),H.tag=2;var le=_.updateQueue;if(le!==null){le=le.shared;var ve=le.pending;ve===null?H.next=H:(H.next=ve.next,ve.next=H),le.pending=H}}_.lanes|=c,H=_.alternate,H!==null&&(H.lanes|=c),fc(_.return,c,i),F.lanes|=c;break}H=H.next}}else if(_.tag===10)A=_.type===i.type?null:_.child;else if(_.tag===18){if(A=_.return,A===null)throw Error(n(341));A.lanes|=c,F=A.alternate,F!==null&&(F.lanes|=c),fc(A,c,i),A=_.sibling}else A=_.child;if(A!==null)A.return=_;else for(A=_;A!==null;){if(A===i){A=null;break}if(_=A.sibling,_!==null){_.return=A.return,A=_;break}A=A.return}_=A}Yt(r,i,y.children,c),i=i.child}return i;case 9:return y=i.type,h=i.pendingProps.children,Ms(i,c),y=kn(y),h=h(y),i.flags|=1,Yt(r,i,h,c),i.child;case 14:return h=i.type,y=In(h,i.pendingProps),y=In(h.type,y),Jh(r,i,h,y,c);case 15:return Yh(r,i,i.type,i.pendingProps,c);case 17:return h=i.type,y=i.pendingProps,y=i.elementType===h?y:In(h,y),eo(r,i),i.tag=1,rn(h)?(r=!0,Pi(i)):r=!1,Ms(i,c),zh(i,h,y),Ec(i,h,y,c),Rc(null,i,h,!0,r,c);case 19:return sp(r,i,c);case 22:return Qh(r,i,c)}throw Error(n(156,i.tag))};function Ep(r,i){return of(r,i)}function nb(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 Nn(r,i,c,h){return new nb(r,i,c,h)}function Xc(r){return r=r.prototype,!(!r||!r.isReactComponent)}function rb(r){if(typeof r=="function")return Xc(r)?1:0;if(r!=null){if(r=r.$$typeof,r===se)return 11;if(r===T)return 14}return 2}function Cr(r,i){var c=r.alternate;return c===null?(c=Nn(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 fo(r,i,c,h,y,_){var A=2;if(h=r,typeof r=="function")Xc(r)&&(A=1);else if(typeof r=="string")A=5;else e:switch(r){case I:return ts(c.children,y,_,i);case L:A=8,y|=8;break;case D:return r=Nn(12,c,i,y|2),r.elementType=D,r.lanes=_,r;case Q:return r=Nn(13,c,i,y),r.elementType=Q,r.lanes=_,r;case z:return r=Nn(19,c,i,y),r.elementType=z,r.lanes=_,r;case J:return ho(c,y,_,i);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case P:A=10;break e;case K:A=9;break e;case se:A=11;break e;case T:A=14;break e;case q:A=16,h=null;break e}throw Error(n(130,r==null?r:typeof r,""))}return i=Nn(A,c,i,y),i.elementType=r,i.type=h,i.lanes=_,i}function ts(r,i,c,h){return r=Nn(7,r,h,i),r.lanes=c,r}function ho(r,i,c,h){return r=Nn(22,r,h,i),r.elementType=J,r.lanes=c,r.stateNode={isHidden:!1},r}function Zc(r,i,c){return r=Nn(6,r,null,i),r.lanes=c,r}function eu(r,i,c){return i=Nn(4,r.children!==null?r.children:[],r.key,i),i.lanes=c,i.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},i}function sb(r,i,c,h,y){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=Cl(0),this.expirationTimes=Cl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Cl(0),this.identifierPrefix=h,this.onRecoverableError=y,this.mutableSourceEagerHydrationData=null}function tu(r,i,c,h,y,_,A,F,H){return r=new sb(r,i,c,F,H),i===1?(i=1,_===!0&&(i|=8)):i=0,_=Nn(3,null,null,i),r.current=_,_.stateNode=r,_.memoizedState={element:h,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null},pc(_),r}function ab(r,i,c){var h=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:E,key:h==null?null:""+h,children:r,containerInfo:i,implementation:c}}function Tp(r){if(!r)return yr;r=r._reactInternals;e:{if(Wr(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(rn(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(rn(c))return rh(r,c,i)}return i}function Ap(r,i,c,h,y,_,A,F,H){return r=tu(c,h,!0,r,y,_,A,F,H),r.context=Tp(null),c=r.current,h=Qt(),y=Sr(c),_=Zn(h,y),_.callback=i??null,br(c,_,y),r.current.lanes=y,ta(r,y,h),on(r,h),r}function po(r,i,c,h){var y=i.current,_=Qt(),A=Sr(y);return c=Tp(c),i.context===null?i.context=c:i.pendingContext=c,i=Zn(_,A),i.payload={element:r},h=h===void 0?null:h,h!==null&&(i.callback=h),r=br(y,i,A),r!==null&&(Dn(r,y,A,_),Vi(r,y,A)),A}function mo(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 $p(r,i){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var c=r.retryLane;r.retryLane=c!==0&&c<i?c:i}}function nu(r,i){$p(r,i),(r=r.alternate)&&$p(r,i)}function ib(){return null}var Rp=typeof reportError=="function"?reportError:function(r){console.error(r)};function ru(r){this._internalRoot=r}go.prototype.render=ru.prototype.render=function(r){var i=this._internalRoot;if(i===null)throw Error(n(409));po(r,i,null,null)},go.prototype.unmount=ru.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var i=r.containerInfo;Xr(function(){po(null,r,null,null)}),i[Kn]=null}};function go(r){this._internalRoot=r}go.prototype.unstable_scheduleHydration=function(r){if(r){var i=mf();r={blockedOn:null,target:r,priority:i};for(var c=0;c<hr.length&&i!==0&&i<hr[c].priority;c++);hr.splice(c,0,r),c===0&&yf(r)}};function su(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function vo(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Mp(){}function ob(r,i,c,h,y){if(y){if(typeof h=="function"){var _=h;h=function(){var le=mo(A);_.call(le)}}var A=Ap(i,h,r,0,null,!1,!1,"",Mp);return r._reactRootContainer=A,r[Kn]=A.current,ma(r.nodeType===8?r.parentNode:r),Xr(),A}for(;y=r.lastChild;)r.removeChild(y);if(typeof h=="function"){var F=h;h=function(){var le=mo(H);F.call(le)}}var H=tu(r,0,!1,null,null,!1,!1,"",Mp);return r._reactRootContainer=H,r[Kn]=H.current,ma(r.nodeType===8?r.parentNode:r),Xr(function(){po(i,H,c,h)}),H}function yo(r,i,c,h,y){var _=c._reactRootContainer;if(_){var A=_;if(typeof y=="function"){var F=y;y=function(){var H=mo(A);F.call(H)}}po(i,A,r,y)}else A=ob(c,i,r,y,h);return mo(A)}hf=function(r){switch(r.tag){case 3:var i=r.stateNode;if(i.current.memoizedState.isDehydrated){var c=ea(i.pendingLanes);c!==0&&(El(i,c|1),on(i,xt()),(st&6)===0&&(Ds=xt()+500,wr()))}break;case 13:Xr(function(){var h=Xn(r,1);if(h!==null){var y=Qt();Dn(h,r,1,y)}}),nu(r,1)}},Tl=function(r){if(r.tag===13){var i=Xn(r,134217728);if(i!==null){var c=Qt();Dn(i,r,134217728,c)}nu(r,134217728)}},pf=function(r){if(r.tag===13){var i=Sr(r),c=Xn(r,i);if(c!==null){var h=Qt();Dn(c,r,i,h)}nu(r,i)}},mf=function(){return lt},gf=function(r,i){var c=lt;try{return lt=r,i()}finally{lt=c}},ue=function(r,i,c){switch(i){case"input":if($e(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 y=Li(h);if(!y)throw Error(n(90));Ve(h),$e(h,y)}}}break;case"textarea":Se(r,c);break;case"select":i=c.value,i!=null&&fe(r,!!c.multiple,i,!1)}},Be=Jc,Ke=Xr;var lb={usingClientEntryPoint:!1,Events:[ya,Ss,Li,Fe,xe,Jc]},Ra={findFiberByHostInstance:Vr,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},cb={bundleType:Ra.bundleType,version:Ra.version,rendererPackageName:Ra.rendererPackageName,rendererConfig:Ra.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:C.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=sf(r),r===null?null:r.stateNode},findFiberByHostInstance:Ra.findFiberByHostInstance||ib,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 wo=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!wo.isDisabled&&wo.supportsFiber)try{mi=wo.inject(cb),Un=wo}catch{}}return ln.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=lb,ln.createPortal=function(r,i){var c=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!su(i))throw Error(n(200));return ab(r,i,null,c)},ln.createRoot=function(r,i){if(!su(r))throw Error(n(299));var c=!1,h="",y=Rp;return i!=null&&(i.unstable_strictMode===!0&&(c=!0),i.identifierPrefix!==void 0&&(h=i.identifierPrefix),i.onRecoverableError!==void 0&&(y=i.onRecoverableError)),i=tu(r,1,!1,null,null,c,!1,h,y),r[Kn]=i.current,ma(r.nodeType===8?r.parentNode:r),new ru(i)},ln.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=sf(i),r=r===null?null:r.stateNode,r},ln.flushSync=function(r){return Xr(r)},ln.hydrate=function(r,i,c){if(!vo(i))throw Error(n(200));return yo(null,r,i,!0,c)},ln.hydrateRoot=function(r,i,c){if(!su(r))throw Error(n(405));var h=c!=null&&c.hydratedSources||null,y=!1,_="",A=Rp;if(c!=null&&(c.unstable_strictMode===!0&&(y=!0),c.identifierPrefix!==void 0&&(_=c.identifierPrefix),c.onRecoverableError!==void 0&&(A=c.onRecoverableError)),i=Ap(i,null,r,1,c??null,y,!1,_,A),r[Kn]=i.current,ma(r),h)for(r=0;r<h.length;r++)c=h[r],y=c._getVersion,y=y(c._source),i.mutableSourceEagerHydrationData==null?i.mutableSourceEagerHydrationData=[c,y]:i.mutableSourceEagerHydrationData.push(c,y);return new go(i)},ln.render=function(r,i,c){if(!vo(i))throw Error(n(200));return yo(null,r,i,!1,c)},ln.unmountComponentAtNode=function(r){if(!vo(r))throw Error(n(40));return r._reactRootContainer?(Xr(function(){yo(null,null,r,!1,function(){r._reactRootContainer=null,r[Kn]=null})}),!0):!1},ln.unstable_batchedUpdates=Jc,ln.unstable_renderSubtreeIntoContainer=function(r,i,c,h){if(!vo(c))throw Error(n(200));if(r==null||r._reactInternals===void 0)throw Error(n(38));return yo(r,i,c,!1,h)},ln.version="18.3.1-next-f1338f8080-20240426",ln}var zp;function Og(){if(zp)return ou.exports;zp=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(),ou.exports=wb(),ou.exports}var Up;function _b(){if(Up)return _o;Up=1;var e=Og();return _o.createRoot=e.createRoot,_o.hydrateRoot=e.hydrateRoot,_o}var bb=_b();const Rd=[{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"]}];Rd.map(e=>({id:e.id,label:e.label}));function xb(e){const t=String(e||"").trim();return Rd.find(n=>n.id===t)}function kb(e){return`theme-${String(e||"").trim()||"dark"}`}function Wp(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(kb(e))}catch{}}const ad=[{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}],id=[{id:"compact",label:"Compact",density:.85},{id:"standard",label:"Standard",density:1},{id:"spacious",label:"Spacious",density:1.2}];function jb(e){const t=String(e).trim();return ad.find(n=>n.id===t)||ad[1]}function Sb(e){const t=String(e).trim();return id.find(n=>n.id===t)||id[1]}function Vp(e){try{const t=document.documentElement,n=jb(e.font_scale||"md"),s=Sb(e.header_density||"standard");t.style.setProperty("--font-scale",String(n.scale)),t.style.setProperty("--header-density",String(s.density))}catch{}}const Dg={md:"(max-width: 1023.98px)"};function Nb(e){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(e).matches}catch{return!1}}function Fg(e){const[t,n]=p.useState(()=>Nb(e));return p.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}var oi=Og();function zs(...e){return e.filter(Boolean).join(" ")}function tn({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:g="panel",className:v,triggerClassName:w,ariaLabel:x,id:j,includeValueOption:b=!1,onOpen:k,customOptionLabel:$,validateCustomValue:S,onChange:N,renderOption:C,renderValue:R}){const E=p.useRef(null),I=p.useRef(null),L=p.useRef(null),D=p.useRef(k),P=p.useId(),K=j||`af-select-${P.replace(/[^a-zA-Z0-9_-]/g,"")}`,se=`${K}-listbox`,[Q,z]=p.useState(!1),[T,q]=p.useState(""),[J,B]=p.useState(0),[O,Z]=p.useState("bottom"),[M,W]=p.useState({left:0,top:0,width:0});p.useEffect(()=>{D.current=k},[k]);const Y=p.useMemo(()=>{if(!b)return t;const G=String(e??"").trim();return!G||t.some(fe=>fe.value===G)?t:[...t,{value:G,label:G}]},[b,t,e]),oe=p.useMemo(()=>{const G=String(e??"");return Y.find(fe=>fe.value===G)||null},[Y,e]),de=p.useMemo(()=>(oe==null?void 0:oe.label)||String(e||"").trim()||"",[oe,e]),me=p.useMemo(()=>{const G=T.trim().toLowerCase();return G?Y.filter(fe=>fe.label.toLowerCase().includes(G)||fe.value.toLowerCase().includes(G)):Y},[Y,T]),ee=p.useMemo(()=>{if(!d)return null;const G=T.trim();if(!G||Y.some(pe=>pe.value===G))return null;const te=(S==null?void 0:S(G,{options:Y}))||"";return{value:G,label:$?$(G):`Use "${G}"`,disabled:!!te,reason:te}},[d,$,Y,T,S]),ce=p.useMemo(()=>{const G=ee?[ee,...me]:me;if(G.length>0)return G;const fe=String(e??"").trim();return o&&fe?[{value:fe,label:de||fe}]:G},[ee,me,o,de,e]),ye=p.useCallback(()=>{const G=E.current;if(!G)return;const fe=G.getBoundingClientRect(),te=Math.max(fe.width,m),pe=Math.max(8,Math.min(fe.left,window.innerWidth-te-8)),Se=window.innerHeight-fe.bottom,Ze=fe.top,Ye=Se>=220||Se>=Ze?"bottom":"top";Z(Ye);const rt=Ye==="bottom"?fe.bottom+6:fe.top-6;W({left:pe,top:rt,width:te})},[m]),Ce=p.useCallback(()=>{z(!1),q("")},[]);p.useEffect(()=>{var G;Q&&((G=D.current)==null||G.call(D))},[Q]),p.useEffect(()=>{if(!Q)return;ye();const G=()=>ye();return window.addEventListener("resize",G),window.addEventListener("scroll",G,!0),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0)}},[Q,ye]),p.useEffect(()=>{if(!Q)return;const G=fe=>{var pe,Se;const te=fe.target;te&&((pe=E.current)!=null&&pe.contains(te)||(Se=I.current)!=null&&Se.contains(te)||Ce())};return document.addEventListener("mousedown",G,!0),()=>document.removeEventListener("mousedown",G,!0)},[Q,Ce]),p.useEffect(()=>{if(!Q)return;const G=Math.max(0,ce.findIndex(fe=>fe.value===e));B(G===-1?0:G),l&&setTimeout(()=>{var fe;return(fe=L.current)==null?void 0:fe.focus()},0)},[Q,l,e,ce]);const ze=G=>{var te;const fe=ce.find(pe=>pe.value===G);fe!=null&&fe.disabled||(N(G),Ce(),(te=E.current)==null||te.focus())},Ve=G=>{var fe,te;if(G.key==="Escape")return G.preventDefault(),Ce(),(fe=E.current)==null||fe.focus(),!0;if(G.key==="Tab")return Ce(),(te=E.current)==null||te.focus(),!1;if(G.key==="ArrowDown")return G.preventDefault(),B(pe=>Math.min(pe+1,Math.max(0,ce.length-1))),!0;if(G.key==="ArrowUp")return G.preventDefault(),B(pe=>Math.max(pe-1,0)),!0;if(G.key==="Home")return G.preventDefault(),B(0),!0;if(G.key==="End")return G.preventDefault(),B(Math.max(0,ce.length-1)),!0;if(G.key==="Enter"){G.preventDefault();const pe=ce[J];return pe&&ze(pe.value),!0}return!1},Ee=G=>{if(!s){if(Q){if(Ve(G))return;if(G.key===" "&&!l){G.preventDefault();const fe=ce[J];fe&&ze(fe.value)}return}(G.key==="Enter"||G.key===" "||G.key==="ArrowDown"||G.key==="ArrowUp")&&(G.preventDefault(),z(!0))}},je=!!String(e||"").trim(),Ue=je?de:n,ne=ee!=null&&ee.disabled?ee.reason||"Unavailable":"",$e=Q&&ce.length>0?`${K}-opt-${J}`:void 0,Pe=a.jsx("span",{className:zs("af-select-value",!je&&"af-select-value--placeholder"),children:o&&!je?"Loading…":Ue}),Ge=R?R(oe,String(e||"")):Pe;return a.jsxs("span",{className:zs("af-select",g==="pin"?"af-select--pin":"af-select--panel",v),children:[a.jsxs("button",{ref:E,id:K,type:"button",className:zs("af-select-trigger",f&&je&&"af-select-trigger--clearable",w),disabled:s,onMouseDown:G=>G.stopPropagation(),onClick:G=>{G.stopPropagation(),!s&&z(fe=>!fe)},onKeyDown:Ee,role:l?void 0:"combobox","aria-haspopup":"listbox","aria-expanded":Q,"aria-controls":Q?se:void 0,"aria-activedescendant":l?void 0:$e,"aria-label":x,children:[Ge,a.jsx("span",{className:zs("af-select-caret",Q&&"af-select-caret--open"),children:"▾"})]}),f&&je?a.jsx("button",{type:"button",className:"af-select-clear-btn","aria-label":"Clear selection",disabled:s,onMouseDown:G=>{G.preventDefault(),G.stopPropagation()},onClick:G=>{var fe;G.preventDefault(),G.stopPropagation(),N(""),Ce(),(fe=E.current)==null||fe.focus()},title:"Clear",children:"×"}):null,Q?oi.createPortal(a.jsxs("div",{ref:I,className:zs("af-select-popover",O==="top"&&"af-select-popover--top"),style:{position:"fixed",left:`${M.left}px`,top:`${M.top}px`,width:`${M.width}px`},onMouseDown:G=>G.stopPropagation(),onClick:G=>G.stopPropagation(),onWheel:G=>G.stopPropagation(),onKeyDown:Ve,tabIndex:-1,children:[l?a.jsxs("div",{className:"af-select-search",children:[a.jsx("input",{ref:L,className:"af-select-search-input",value:T,onChange:G=>q(G.target.value),placeholder:u,onKeyDown:Ve,role:"combobox","aria-expanded":!0,"aria-controls":se,"aria-activedescendant":$e,"aria-invalid":!!ne,"aria-describedby":ne?`${K}-custom-error`:void 0}),ne?a.jsx("div",{id:`${K}-custom-error`,className:"af-select-custom-error",role:"alert",children:ne}):null]}):null,a.jsx("div",{className:"af-select-options",role:"listbox",id:se,"aria-label":x,children:o&&ce.length===0?a.jsx("div",{className:"af-select-empty",children:"Loading…"}):ce.length===0?a.jsx("div",{className:"af-select-empty",children:"No results"}):ce.map((G,fe)=>{var rt;const te=G.value===e,pe=fe===J,Se=String(G.group||"").trim(),Ze=fe>0?String(((rt=ce[fe-1])==null?void 0:rt.group)||"").trim():"",Ye=!!Se&&Se!==Ze;return a.jsxs(it.Fragment,{children:[Ye?a.jsx("div",{className:"af-select-group",role:"presentation",children:Se}):null,a.jsx("div",{id:`${K}-opt-${fe}`,role:"option","aria-selected":te,className:zs("af-select-option",te&&"af-select-option--selected",pe&&"af-select-option--highlighted",G.disabled&&"af-select-option--disabled"),title:G.disabled?G.reason||"Unavailable":void 0,onMouseEnter:()=>B(fe),onMouseDown:V=>{V.preventDefault(),V.stopPropagation()},onClick:()=>ze(G.value),"aria-disabled":G.disabled?!0:void 0,children:C?C(G,{selected:te,highlighted:pe}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"af-select-option-label",children:[a.jsx("span",{children:G.label}),G.reason?a.jsx("small",{className:"af-select-option-reason",children:G.reason}):null]}),te?a.jsx("span",{className:"af-select-check",children:"✓"}):null]})})]},G.value)})})]}),document.body):null]})}function Cb(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 Eb(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 od="Provided by connected pin";function Tb(e){const t=e.disabled===!0,n=e.layout||"stack",s=e.allowGatewayDefault!==!1,o=String(e.gatewayDefaultLabel||"(gateway default)"),l=e.gatewayDefaultProviderLabel||o,u=e.gatewayDefaultModelLabel||o,d=String(e.providerLabel||"Provider"),f=String(e.modelLabel||"Model"),m=String(e.providerPlaceholder||"(select)"),g=String(e.modelPlaceholder||"(select)"),v=String(e.provider||"").trim(),w=String(e.model||"").trim(),x=Cb(e.providers),j=Eb(e.models),b=typeof e.markSaved=="object"?e.markSaved:null,k=(E,I,L,D)=>e.markSaved&&!L&&!D&&(!b||b[I]===E)?`${E} (saved)`:E,$=t||!!e.loadingProviders,S=t||!!e.loadingModels,N=[...s?[{value:"",label:l}]:[],...x.map(E=>({value:E.name,label:E.display_name?`${E.display_name} (${E.name})`:E.name})),...e.markSaved&&v&&!x.some(E=>E.name===v)?[{value:v,label:k(v,"provider",e.loadingProviders,e.providerError)}]:[]],C=[...s?[{value:"",label:u}]:[],...j.map(E=>{var I;return{value:E,label:((I=e.modelDisplayNames)==null?void 0:I[E])||E}}),...e.markSaved&&w&&!j.includes(w)?[{value:w,label:k(w,"model",e.loadingModels,e.modelError)}]:[]],R=(E,I)=>a.jsxs("div",{className:"af-pmp__pinned","data-pinned":E,children:[a.jsx("span",{className:"af-pmp__pinned-text",children:od}),I?a.jsxs("span",{className:"mono muted",children:[" · ",I]}):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:d}),e.providerPinned?R("provider",v):a.jsx(tn,{value:v,options:N,placeholder:s?l:m,disabled:$,loading:!!e.loadingProviders,searchable:!0,allowCustom:e.allowCustomProvider===!0,clearable:s,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:d,onChange:E=>e.onChange({provider:String(E||"").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:f}),e.modelPinned?R("model",w):a.jsx(tn,{value:w,options:C,placeholder:s?u:g,disabled:S,loading:!!e.loadingModels,searchable:!0,allowCustom:e.allowCustomModel===!0,clearable:s,variant:"panel",triggerClassName:e.selectClassName,ariaLabel:f,onChange:E=>e.onChange({provider:v,model:String(E||"").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 Ab(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 $b(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 qp(e){const t=Ab(e);return t===!1?"off":t?String(t.num_draft_tokens):""}function Rb(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 Mb(e){const t=$b(e.capabilities),n=qp(e.value),s=(t==null?void 0:t.supported_depths.map(String))||[],o=qp(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(tn,{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(Rb(f))}),d&&!e.hideNote?a.jsx("div",{role:"status",className:"af-pmp__hint",children:d}):null]})}const Hp="api/gateway",li="api/connection/gateway";function ut(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?`${Hp}/${t}`:Hp}function Md(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}const Bg=/^(?!\.+$)[A-Za-z0-9_.:-]{1,256}$/;function Lb(e){const t=String(e??"");if(!Bg.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`}function Ib(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 Pb(e,t="Gateway default"){const n=Ib(e);return n?`${t} · ${n}`:t}const Ob="The gateway does not say which reasoning levels this model supports.",Db="Set anyway",Fb="Reasoning and MTP choices appear when the gateway can describe the selected model.",Bb="Reasoning choices appear when the gateway can describe the selected model.";function zg(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]=p.useState(!s),m=o||u||!(s&&!d),g=s&&(o||u||!d),v=p.useRef(s);p.useEffect(()=>{s&&!v.current&&f(!1),v.current=s},[s]);const[w,x]=p.useState([]),[j,b]=p.useState(!1),[k,$]=p.useState(""),[S,N]=p.useState([]),[C,R]=p.useState({}),[E,I]=p.useState(!1),[L,D]=p.useState(""),P=p.useRef(e);P.current=e;const[K,se]=p.useState({status:"idle",value:null,message:""}),Q=e.fetchGatewayDefault;p.useEffect(()=>{if(!Q||t)return;let te=!0;const pe=Se=>se(Ze=>JSON.stringify(Ze)===JSON.stringify(Se)?Ze:Se);return se(Se=>Se.status==="idle"?{...Se,status:"loading"}:Se),Q().then(Se=>{var Ze;te&&(Se?(Ze=Se.warnings)!=null&&Ze.length?pe({status:"unusable",value:Se,message:Se.warnings.join(" ")}):pe({status:"resolved",value:Se,message:""}):pe({status:"none",value:null,message:""}))}).catch(Se=>{te&&pe({status:"error",value:null,message:String((Se==null?void 0:Se.message)||Se)})}),()=>{te=!1}},[Q,t]);const z=K.status==="resolved"?K.value:null,T=p.useRef({provider:String(n.provider||"").trim(),model:String(n.model||"").trim()});p.useEffect(()=>{if(!m||l.provider||t)return;let te=!0;return b(!0),(async()=>{try{const pe=await P.current.fetchProviders();if(!te)return;x(Array.isArray(pe)?pe:[]),$("")}catch(pe){if(!te)return;x([]),$(`#FALLBACK provider discovery failed: ${String((pe==null?void 0:pe.message)||pe)}`)}finally{te&&b(!1)}})(),()=>{te=!1}},[m,l.provider,t]);const q=String(n.provider||"").trim();p.useEffect(()=>{if(!q||t||l.model){N([]),D(""),I(!1);return}let te=!0;return N([]),I(!0),D(""),(async()=>{try{const pe=await P.current.fetchModels(q);if(!te)return;const Se=[],Ze={};for(const Ye of Array.isArray(pe)?pe:[]){const rt=typeof Ye=="string"?Ye:String((Ye==null?void 0:Ye.id)||"");rt&&(Se.push(rt),typeof Ye!="string"&&(Ye!=null&&Ye.label)&&Ye.label!==rt&&(Ze[rt]=String(Ye.label)))}N(Se),R(Ze)}catch(pe){if(!te)return;N([]),D(`#FALLBACK model discovery failed: ${String((pe==null?void 0:pe.message)||pe)}`)}finally{te&&I(!1)}})(),()=>{te=!1}},[q,t,l.model]);const J=String(n.model||"").trim(),B=e.defaultModeLabel||"Gateway default",O=K.status==="none"?`${B} · none configured`:Pb(z,B),Z=e.customModeLabel||"Custom",M=e.effectiveDefault||(K.value?{provider:K.value.provider,model:K.value.model}:void 0),W=q||(M==null?void 0:M.provider)||"",Y=J||(q?"":M==null?void 0:M.model)||"",[oe,de]=p.useState({levels:[],error:"",loading:!1}),[me,ee]=p.useState(!1),ce=!!e.fetchModelCapabilities,[ye,Ce]=p.useState();p.useEffect(()=>{let te=!0;if(Ce(void 0),de({levels:[],error:"",loading:ce&&!!Y}),!(!ce||!Y||t))return P.current.fetchModelCapabilities(Y,W).then(pe=>{var V;if(!te)return;if(pe!=null&&pe.error)throw new Error(String(pe.error));Ce(pe);const Se=(pe==null?void 0:pe.capabilities)||pe||{},Ze=Se.reasoning_levels||Se.thinking_levels,Ye=Array.isArray(Ze)?[...new Set(Ze.filter(he=>typeof he=="string"&&!!he.trim()))]:[];!Ye.length&&Se.thinking_support===!0&&((V=Se.thinking_control)!=null&&V.prompt_disable_token)&&Ye.push("off","auto");const rt=typeof Se.thinking_support=="boolean"?Se.thinking_support:void 0;de({levels:Ye,support:rt,error:"",loading:!1})}).catch(pe=>{te&&de({levels:[],error:String((pe==null?void 0:pe.message)||pe),loading:!1})}),()=>{te=!1}},[W,Y,ce,t]),p.useEffect(()=>ee(!1),[W,Y]);const ze=e.inheritLabel||"Workflow / Gateway default",Ve=g&&(z!=null&&z.reasoning)?`${ze} (${z.reasoning})`:ze,Ee=!g||e.optionsInDefaultMode!==!1,je=e.reasoningLadder?[...new Set(e.reasoningLadder.filter(te=>typeof te=="string"&&te.trim()))]:null,Ue=oe.loading?"loading":oe.levels.length||oe.support===!0?"supported":oe.support===!1?"unsupported":"unknown",ne=e.unknownReasoning==="allow-override"&&!!(je!=null&&je.length),$e=String(n.reasoning||"").trim();let Pe=[],Ge=!1;if(!je)Pe=oe.levels.map(te=>({value:te,label:te}));else if(Ue==="supported"||Ue==="loading"){const te=oe.levels;Pe=[...je,...te.filter(Se=>!je.includes(Se))].map(Se=>!te.length||te.includes(Se)?{value:Se,label:Se}:{value:Se,label:Se,disabled:!0,reason:"This model does not advertise it"})}else Ue==="unknown"&&ne&&(Ge=!me,Pe=je.map(te=>({value:te,label:te})));$e&&!Pe.some(te=>te.value===$e)&&Pe.push({value:$e,label:`${$e} (saved)`});const G=(ce||ne)&&(Pe.length>0||Ue==="unknown"&&ne),fe=a.jsxs(a.Fragment,{children:[Ee&&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:od})]}):Ee&&G?a.jsxs("div",{className:"af-pmp__reasoning","data-reasoning-state":Ue,children:[a.jsx("label",{children:e.reasoningLabel||"Reasoning effort"}),a.jsx(tn,{ariaLabel:e.reasoningLabel||"Reasoning effort",placeholder:Ve,value:n.reasoning||"",options:[{value:"",label:Ve},...Pe],disabled:t||oe.loading||Ge,onChange:te=>e.onChange({...n,reasoning:te})}),Ue==="unknown"&&ne?a.jsxs("div",{className:"af-pmp__hint","data-reasoning-unknown":"",children:[Ob," ",a.jsxs("label",{className:"af-pmp__override",children:[a.jsx("input",{type:"checkbox",checked:me,disabled:t,onChange:te=>{ee(te.target.checked),!te.target.checked&&n.reasoning&&e.onChange({...n,reasoning:""})}})," ",Db]})]}):null]}):null,Ee&&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:od})]}):Ee&&e.enableSpeculation?a.jsx(Mb,{value:n.speculation,inheritLabel:ze,onChange:te=>e.onChange({...n,speculation:te}),capabilities:ye,disabled:t,loading:oe.loading,hideNote:!!oe.error}):null,Ee&&oe.error?a.jsxs("div",{role:"status",className:"af-pmp__hint","data-discovery":"unavailable",children:[e.enableSpeculation?Fb:Bb,a.jsxs("details",{className:"af-pmp__details",children:[a.jsx("summary",{children:"Technical details"}),a.jsx("span",{children:oe.error})]})]}):null]});return a.jsxs("div",{className:`af-pmp${o?" af-pmp--compact":""}${e.className?` ${e.className}`:""}`,"data-gateway-default":Q?K.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":g,className:`af-pmp__seg-btn${g?" is-active":""}`,onClick:()=>{f(!1),e.onChange({...n,provider:"",model:"",...ce?{reasoning:""}:{}})},disabled:t,title:O,"data-default-choice":"",children:O}),a.jsx("button",{type:"button",role:"tab","aria-selected":!g,className:`af-pmp__seg-btn${g?"":" is-active"}`,onClick:()=>{f(!0)},disabled:t,children:Z})]}),K.status==="error"||K.status==="unusable"?a.jsx("div",{role:"status",className:"af-pmp__hint","data-gateway-default-problem":K.status,children:K.status==="error"?`The gateway's default could not be read: ${K.message}`:`Gateway warning: ${K.message}`}):null,m?a.jsx(Tb,{provider:q,model:J,providers:w,models:S,modelDisplayNames:C,markSaved:T.current,providerPinned:l.provider,modelPinned:l.model,disabled:t,loadingProviders:j,loadingModels:E,providerError:k||void 0,modelError:L||void 0,providerLabel:e.providerLabel,modelLabel:e.modelLabel,allowGatewayDefault:o,gatewayDefaultLabel:o?O:void 0,gatewayDefaultProviderLabel:o&&(M!=null&&M.provider)?`${B} · ${M.provider}`:void 0,gatewayDefaultModelLabel:o&&(M!=null&&M.model)?`${B} · ${M.model}`:void 0,allowCustomProvider:e.allowCustom!==!1,allowCustomModel:e.allowCustom!==!1,onChange:te=>e.onChange({...n,provider:te.provider,model:te.model,...ce?{reasoning:""}:{}})}):a.jsx("div",{className:"af-pmp__hint",children:e.defaultHint||"The gateway picks its configured default provider and model for this task."}),e.optionsDisclosure?a.jsxs("details",{className:"af-pmp__options",children:[a.jsxs("summary",{children:["Reasoning & speed",n.reasoning?` · ${n.reasoning}`:""]}),fe]}):fe]})}function Gp(...e){return e.filter(Boolean).join(" ")}function zb({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:g="admin",onUserIdChange:v,token:w,tokenPlaceholder:x="Paste Gateway user token",showToken:j=!1,onTokenChange:b,onShowTokenChange:k,remember:$=!1,rememberLabel:S="Remember this browser",onRememberChange:N,loading:C=!1,submitting:R=!1,submitDisabled:E=!1,submitLabel:I="Sign in",submittingLabel:L="Signing in...",closeLabel:D="Close",signOutLabel:P="Sign out",showClose:K=!1,showSignOut:se=!1,error:Q,message:z,className:T,onSubmit:q,onClose:J,onSignOut:B}){const O=C||R,Z=O||E||!String(m||"").trim()||!String(w||"").trim(),M=W=>{W.preventDefault(),!Z&&q()};return a.jsxs("form",{className:Gp("af-gateway-signin",T),onSubmit:M,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:Gp("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:W=>f==null?void 0:f(W.target.value),placeholder:d,autoComplete:"url",disabled:O})]}):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:W=>v(W.target.value),placeholder:g,autoComplete:"username",disabled:O}),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:j?"text":"password",value:w,onChange:W=>b(W.target.value),placeholder:x,autoComplete:"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"",spellCheck:!1,disabled:O}),a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>k==null?void 0:k(!j),disabled:O,children:j?"Hide":"Show"})]}),a.jsxs("label",{className:"af-gateway-signin__checkbox",children:[a.jsx("input",{type:"checkbox",checked:!!$,onChange:W=>N==null?void 0:N(W.target.checked),disabled:O}),S]})]}),Q?a.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--error",children:Q}):null,!Q&&z?a.jsx("div",{className:"af-gateway-signin__message af-gateway-signin__message--ok",children:z}):null,a.jsxs("div",{className:"af-gateway-signin__actions",children:[K?a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:J,disabled:O,children:D}):null,se?a.jsx("button",{className:"af-gateway-signin__secondary",type:"button",onClick:()=>void(B==null?void 0:B()),disabled:O,children:P}):null,a.jsx("button",{className:"af-gateway-signin__primary",type:"submit",disabled:Z,children:R?L:I})]})]})}function Ub(e){return e==="light"?"Light":"Dark"}function Wb(e){const t=e.themes&&e.themes.length?e.themes:Rd,n=e.showSwatches!==!1,s=e.variant||"panel",o=p.useMemo(()=>{const u={};for(const d of t)u[d.id]=d;return u},[t]),l=p.useMemo(()=>t.map(u=>({value:u.id,label:u.label,group:Ub(u.group)})),[t]);return a.jsx(tn,{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],g=(m==null?void 0:m.label)||f||e.placeholder||"Select theme…",v=(m==null?void 0:m.swatches)||null,w=!f;return a.jsxs("span",{className:"af-theme-value",children:[a.jsx("span",{className:`af-theme-label ${w?"af-theme-label--placeholder":""}`.trim(),children:g}),n&&v?a.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:v.map((x,j)=>a.jsx("span",{className:"af-theme-swatch",style:{background:x}},`${f}:${j}`))}):null]})},renderOption:(u,d)=>{const f=String(u.value||"").trim(),m=o[f],g=(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&&g?a.jsx("span",{className:"af-theme-swatches","aria-hidden":"true",children:g.map((v,w)=>a.jsx("span",{className:"af-theme-swatch",style:{background:v}},`${f}:${w}`))}):null,d.selected?a.jsx("span",{className:"af-select-check",children:"✓"}):null]})]})}})}function Vb(e){const t=e.scales&&e.scales.length?e.scales:ad,n=e.variant||"panel",s=p.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return a.jsx(tn,{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 qb(e){const t=e.densities&&e.densities.length?e.densities:id,n=e.variant||"panel",s=p.useMemo(()=>t.map(o=>({value:o.id,label:o.label})),[t]);return a.jsx(tn,{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 Hb=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function Gb(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"about":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"9"}),a.jsx("circle",{cx:"12",cy:"7.5",r:"1.5",fill:"currentColor",stroke:"none"}),a.jsx("path",{d:"M12 11v6"})]});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"wrench":return a.jsx("path",{d:"M14.5 6.5 18 3a6 6 0 0 0-7.6 7.6L3 18a2.1 2.1 0 0 0 3 3l7.4-7.4A6 6 0 0 0 21 6l-3.5 3.5-3-3Z"});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 be({name:e,size:t=16,className:n,title:s,...o}){const l=s?void 0:!0,u=Hb.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,Gb(e)]})}function Kb(e){return!String(e.unavailableReason||"").trim()&&!e.busy}function Jb(e){return Kb(e)?!e.checked:null}let Yb=0;function ii(e){const{label:t,checked:n,onChange:s,description:o,reasonVisible:l=!0,describedBy:u,hint:d,busy:f=!1,variant:m="inline",ariaLabel:g,className:v,id:w,action:x}=e,j=String(e.unavailableReason||"").trim(),b=!!j,k=u||(w?`${w}-reason`:b?`af-switch-reason-${++Yb}`:void 0),$=["af-switch",m==="row"?"af-switch--row":m==="sm"?"af-switch--sm":"",b?"af-switch--unavailable":"",v||""].filter(Boolean).join(" "),S=C=>{const R=Jb({checked:n,unavailableReason:j,busy:f});if(R===null){C.preventDefault();return}s==null||s(R)},N=a.jsxs("button",{type:"button",role:"switch",id:w,className:$,"data-action":x,"aria-checked":n?"true":"false","aria-disabled":b?"true":void 0,"aria-describedby":b?k:void 0,"aria-busy":f?"true":void 0,"aria-label":g,"aria-description":o?void 0:d,title:b?d?`${j}
41
+ ${d}`:j:d,onClick:S,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!b||u?N:a.jsxs("span",{className:m==="row"?"af-switch-wrap af-switch-wrap--row":"af-switch-wrap",children:[N,a.jsx("span",{id:k,className:l?"af-switch__reason":"af-switch__reason af-switch__reason--hidden",children:j})]})}const Qb=200,Ld="data-af-tip",Ug="data-af-tip-content";function pl(e){return typeof e=="string"?e.trim():[e.title,e.description,...(e.facts||[]).map(t=>`${t.label}: ${t.value}`),...(e.sections||[]).flatMap(t=>[t.label,...t.items]),e.note].filter(Boolean).join(`
42
+ `)}function Xb(e){const t={[Ld]:pl(e)};return typeof e!="string"&&(t[Ug]=JSON.stringify(e)),t}function Zb(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.title=="string"&&!!t.title.trim()&&[t.description,t.note].every(n=>n===void 0||typeof n=="string")&&(t.facts===void 0||Array.isArray(t.facts)&&t.facts.every(n=>n&&typeof n.label=="string"&&typeof n.value=="string"))&&(t.sections===void 0||Array.isArray(t.sections)&&t.sections.every(n=>n&&typeof n.label=="string"&&Array.isArray(n.items)&&n.items.every(s=>typeof s=="string")))}function ex(e,t,n){var o;t.textContent="",t.removeAttribute("data-structured");const s=(l,u,d,f)=>{const m=e.createElement(u);return m.className=d,f!==void 0&&(m.textContent=f),l.appendChild(m),m};if(typeof n=="string"){const l=n.split(/\n+/).map(u=>u.trim()).filter(Boolean);if(l.length<=1)t.textContent=n;else for(const u of l)s(t,"p","af-tooltip__paragraph",u);return}if(t.setAttribute("data-structured","true"),s(t,"div","af-tooltip__title",n.title),n.description&&s(t,"p","af-tooltip__description",n.description),(o=n.facts)!=null&&o.length){const l=s(t,"dl","af-tooltip__facts");for(const u of n.facts){const d=s(l,"div","af-tooltip__fact");s(d,"dt","af-tooltip__label",u.label);const f=s(d,"dd","af-tooltip__value",u.value);u.tone&&["muted","success","warning","danger"].includes(u.tone)&&f.setAttribute("data-tone",u.tone)}}for(const l of n.sections||[]){if(!l.items.length)continue;const u=s(t,"div","af-tooltip__section");l.label&&s(u,"div","af-tooltip__section-title",l.label);const d=s(u,"ul","af-tooltip__list");for(const f of l.items)s(d,"li","af-tooltip__item",f)}n.note&&s(t,"p","af-tooltip__note",n.note)}function tx(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 Kp=0;function Wg(e){if(!e)return"";const t=e.getAttribute(Ug);if(t){try{const n=JSON.parse(t);if(Zb(n))return n}catch{}console.warn("#FALLBACK: invalid structured tooltip; using its plain-text fallback")}return String(e.getAttribute(Ld)||"").trim()}function uu(e,t){const n=e;if(!n||typeof n.closest!="function")return null;const s=n.closest(`[${Ld}]`);return!s||!t.contains(s)||!pl(Wg(s))?null:s}function nx(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:Qb;Kp+=1;const l=n.createElement("div");l.className="af-tooltip",l.setAttribute("role","tooltip");const u=`af-tooltip-${Kp}`;l.setAttribute("id",u),l.hidden=!0,(n.body||n.documentElement).appendChild(l);let d=null,f=null,m=null,g=null,v=!1,w=null;const x=()=>{m&&clearTimeout(m),m=null,f=null},j=()=>{g&&clearTimeout(g),g=null},b=()=>{if(!d)return;const T=d.getBoundingClientRect(),q=l.getBoundingClientRect(),J=tx(T,{width:q.width,height:q.height},{width:s.innerWidth,height:s.innerHeight});l.style.top=`${J.top}px`,l.style.left=`${J.left}px`,l.setAttribute("data-side",J.side)},k=()=>{if(x(),j(),!d)return;String(d.getAttribute("aria-describedby")||"").split(/\s+/).includes(u)&&(w?d.setAttribute("aria-describedby",w):d.removeAttribute("aria-describedby")),w=null,d=null,l.hidden=!0,l.textContent=""},$=T=>{x(),j(),d&&d!==T&&k();const q=Wg(T),J=pl(q);if(!J||T.isConnected===!1)return;if(d=T,ex(n,l,q),l.hidden=!1,String(T.getAttribute("aria-label")||"").trim()!==J){const O=T.getAttribute("aria-describedby");w=O&&O!==u?O:null,T.setAttribute("aria-describedby",w?`${w} ${u}`:u)}b()},S=T=>{j(),d!==T&&f!==T&&(x(),f=T,m=setTimeout(()=>{const q=f;m=null,f=null,q&&$(q)},o))},N=()=>{x(),d&&(j(),g=setTimeout(k,100))},C=T=>{try{if(typeof T.matches=="function")return T.matches(":focus-visible")}catch{}return v},R=T=>{if(T.pointerType==="touch")return;if(l.contains(T.target)){j();return}const J=uu(T.target,e);J&&S(J)},E=T=>{const J=T.relatedTarget||null;if(!(J&&(l.contains(J)||d&&d.contains(J)||f&&f.contains(J)))){if(f&&!d){x();return}d&&N()}},I=T=>{const q=T.relatedTarget||null;q&&(l.contains(q)||d&&d.contains(q))||N()},L=T=>{const q=uu(T.target,e);q&&C(q)&&S(q)},D=T=>{const q=uu(T.target,e);q&&(q===d||q===f)&&k()},P=()=>{v=!1,k()},K=T=>{if(T.key==="Escape"||T.key==="Esc"){d?(T.preventDefault(),k()):x();return}!T.metaKey&&!T.ctrlKey&&!T.altKey&&(v=!0)},se=T=>{T.type==="scroll"&&l.contains(T.target)||k()},Q=e;Q.addEventListener("pointerover",R),Q.addEventListener("pointerout",E),Q.addEventListener("focusin",L),Q.addEventListener("focusout",D),l.addEventListener("pointerover",R),l.addEventListener("pointerout",I),n.addEventListener("pointerdown",P,!0),s.addEventListener("keydown",K,!0),s.addEventListener("scroll",se,!0),s.addEventListener("resize",se);let z=!1;return()=>{z||(z=!0,k(),Q.removeEventListener("pointerover",R),Q.removeEventListener("pointerout",E),Q.removeEventListener("focusin",L),Q.removeEventListener("focusout",D),l.removeEventListener("pointerover",R),l.removeEventListener("pointerout",I),n.removeEventListener("pointerdown",P,!0),s.removeEventListener("keydown",K,!0),s.removeEventListener("scroll",se,!0),s.removeEventListener("resize",se),l.parentNode&&l.parentNode.removeChild(l))}}const bo=new WeakMap;function rx(e){let t=bo.get(e);t||(t={count:0,release:nx(e)},bo.set(e,t)),t.count+=1;let n=!1;return()=>{if(n)return;n=!0;const s=bo.get(e);s&&(s.count-=1,s.count<=0&&(s.release(),bo.delete(e)))}}function ci(){p.useEffect(()=>{if(!(typeof document>"u"))return rx(document)},[])}function za(e){ci();const t=it.Children.only(e.children);return pl(e.content)?it.cloneElement(t,Xb(e.content)):t}function sx(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 Vg(e){return!!(e&&e.ok===!0&&e.has_session===!0)}function ax(e){const t=e||{},n=t.connectionPath||li,s=t.variant||"dismissable",o=p.useRef(t.onStatusChange);o.current=t.onStatusChange;const l=p.useRef(s);l.current=s;const u=p.useRef(!!t.autoOpenMidSession);u.current=!!t.autoOpenMidSession;const[d,f]=p.useState(null),[m,g]=p.useState("loading"),[v,w]=p.useState(!1),x=p.useRef(!1),j=p.useRef(!1),b=p.useRef("loading"),k=p.useRef("none"),$=p.useRef(!1),S=p.useRef(0),N=p.useCallback(z=>{var q;S.current+=1,f(z),(q=o.current)==null||q.call(o,z);const T=Vg(z);if(T)g("connected"),b.current="connected",x.current=!1,k.current="none",j.current||w(!1);else if(z!==null){const J=b.current;g("disconnected"),b.current="disconnected",J!=="disconnected"&&(k.current=$.current?"signout":J==="connected"?"mid":"boot");const B=l.current==="blocking"||k.current!=="mid"||u.current;!x.current&&B&&w(!0)}z!==null&&(j.current=T)},[]),C=p.useCallback(async()=>{const z=S.current;try{const T=await ld(n);if(S.current!==z)return;N(T)}catch{if(S.current!==z)return;N(null)}},[n,N]),[R,E]=p.useState(!1),[I,L]=p.useState(null),D=p.useCallback(async()=>{E(!0),L(null),S.current+=1;let z=null;try{await Hg(n)}catch(T){z=String((T==null?void 0:T.message)||T||"Sign-out request failed")}$.current=!0;try{await C()}finally{$.current=!1}return L(z),E(!1),z===null&&b.current!=="connected"},[n,C]),P=p.useRef(!1);p.useEffect(()=>{P.current||(P.current=!0,C())},[C]);const K=p.useCallback(()=>{w(!0)},[]),se=p.useCallback(()=>{const z=b.current;s==="blocking"&&z==="disconnected"||(z==="disconnected"&&(x.current=!0),w(!1))},[s]),Q=p.useMemo(()=>({isOpen:v,onClose:se,blocking:s==="blocking"&&m!=="connected",appName:t.appName,connectionPath:n,defaultGatewayUrl:t.defaultGatewayUrl,initialStatus:d,onStatusChange:N}),[v,se,s,m,t.appName,n,t.defaultGatewayUrl,d,N]);return{status:d,phase:m,connected:m==="connected",modalOpen:v,signingOut:R,signOutError:I,openModal:K,refresh:C,signOut:D,modalProps:Q}}const ix="default";function Fr(e){return typeof e=="string"?e.trim():""}function Jp(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):void 0}function ox(e){var m;if(!e||!Vg(e))return null;const t=(m=e.gateway)==null?void 0:m.principal;if(!t||typeof t!="object")return null;const n=Fr(t.user_id);if(!n)return null;const s={userId:n},o=Fr(t.tenant_id);o&&(s.tenantId=o);const l=Fr(t.runtime_id);l&&(s.runtimeId=l);const u=Jp(t.roles);u&&(s.roles=u);const d=Jp(t.scopes);d&&(s.scopes=d);const f=Fr(t.source);return f&&(s.source=f),typeof t.admin=="boolean"&&(s.admin=t.admin),s}function qg(e){const t=Fr(e.displayName)||Fr(e.userId),n=Fr(e.tenantId);return n&&n!==ix?`${n}/${t}`:t}function Id(e){const t=Fr(e);if(!t)return"";try{return new URL(t).host||t}catch{return t}}async function ld(e=li){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 lx(e,t=li){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 Hg(e=li){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 du(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 cx(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=Id(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 ux(e){const t=e.connectionPath||li,[n,s]=p.useState(!1),[o,l]=p.useState(!1),[u,d]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{e.isOpen||m(!1)},[e.isOpen]);const[g,v]=p.useState(e.defaultGatewayUrl||"http://127.0.0.1:8080"),[w,x]=p.useState("admin"),[j,b]=p.useState(""),[k,$]=p.useState(!1),[S,N]=p.useState(!0),[C,R]=p.useState(""),[E,I]=p.useState(""),L=p.useMemo(()=>cx(u),[u]),D=Q=>{var z;d(Q),(z=e.onStatusChange)==null||z.call(e,Q)},P=p.useRef(!1);if(p.useEffect(()=>{var z;if(!e.isOpen)return;const Q=!P.current;if(P.current=!0,Q&&e.initialStatus!==void 0&&e.initialStatus!==null){const T=e.initialStatus;D(T),typeof T.gateway_url=="string"&&T.gateway_url.trim()&&v(du(T.gateway_url));const q=(z=T.gateway)==null?void 0:z.principal;q!=null&&q.user_id&&x(q.user_id);return}s(!0),R(""),ld(t).then(T=>{var J;D(T),typeof T.gateway_url=="string"&&T.gateway_url.trim()&&v(du(T.gateway_url));const q=(J=T.gateway)==null?void 0:J.principal;q!=null&&q.user_id&&x(q.user_id)}).catch(T=>R(`Failed to load connection status: ${String((T==null?void 0:T.message)||T)}`)).finally(()=>s(!1))},[e.isOpen]),p.useEffect(()=>{if(!e.isOpen)return;const Q=z=>{z.key==="Escape"&&!z.defaultPrevented&&!e.blocking&&(z.preventDefault(),e.onClose())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[e.isOpen,e.blocking,e.onClose]),!e.isOpen||f)return null;const K=async()=>{l(!0),R(""),I("");try{const Q=du(g);v(Q);const z=await lx({gateway_url:Q,gateway_user_id:w,gateway_token:j,persist:S},t);D(z),b(""),m(!0),e.onClose()}catch(Q){R(String((Q==null?void 0:Q.message)||Q))}finally{l(!1)}},se=async()=>{l(!0),R(""),I("");try{await Hg(t),b("");const Q=await ld(t).catch(()=>null);D(Q),I("Signed out. This browser no longer holds a gateway session.")}catch(Q){R(String((Q==null?void 0:Q.message)||Q))}finally{l(!1)}};return a.jsx("div",{className:"af-connect-overlay",role:"presentation",onMouseDown:Q=>{!e.blocking&&Q.target===Q.currentTarget&&e.onClose()},children:a.jsx("div",{className:"af-connect-modal",role:"dialog","aria-modal":"true","aria-label":"Gateway connection",children:a.jsx(zb,{kicker:`${e.appName||"AbstractFramework"} connection`,title:"Connect this browser to AbstractGateway",description:"Sign in with a Gateway user token. The app exchanges it for an HTTP-only browser session and never stores the raw token.",statusLabel:L.label,statusTone:L.tone,showGatewayUrl:!0,gatewayUrl:g,onGatewayUrlChange:Q=>v(Q),userId:w,onUserIdChange:x,token:j,tokenPlaceholder:u!=null&&u.has_session?"(browser session already signed in)":"Paste Gateway user token",showToken:k,onTokenChange:b,onShowTokenChange:$,remember:S,rememberLabel:"Keep this browser signed in",onRememberChange:N,loading:n,submitting:o,submittingLabel:"Signing in...",showClose:!e.blocking,onClose:e.onClose,showSignOut:!e.blocking&&!!(u!=null&&u.has_session),onSignOut:se,error:C,message:E,onSubmit:K})})})}function dx(){return globalThis.crypto}function fx(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 Ys(){const e=dx();if(e&&typeof e.randomUUID=="function")try{return e.randomUUID()}catch{}if(e&&typeof e.getRandomValues=="function")return fx(e.getRandomValues(new Uint8Array(16)));throw new Error("randomId: Web Crypto (crypto.getRandomValues) is unavailable")}function Pd(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 hx='button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function px(e,t=!1){if(!e)return null;const n=e.querySelector(".af-drawer__body")||e,s=n.querySelector("[data-autofocus]");return s||(t?e:n.querySelector("textarea:not(:disabled)")||n.querySelector(hx)||e)}function mx(){try{return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}function Yp(e){return e==="auto"?"var(--af-topbar-h, 0px)":typeof e=="number"&&Number.isFinite(e)?e:0}function gx(e){const t=e.closeOnEscape!==!1,n=p.useRef(null);p.useEffect(()=>{if(!e.open||!t)return;const u=d=>{d.key!=="Escape"||d.defaultPrevented||(d.preventDefault(),e.onClose())};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e.open,t,e.onClose]);const s=p.useRef(null),o=e.manageFocus!==!1,l=p.useRef(!1);return p.useEffect(()=>{var m;if(!l.current){l.current=!0;return}if(!o||typeof document>"u")return;const u=n.current;if(e.open){if(s.current=document.activeElement,u&&u.contains(document.activeElement))return;const g=window.setTimeout(()=>{var v;(v=px(u,mx()))==null||v.focus({preventScroll:!0})},0);return()=>window.clearTimeout(g)}const d=s.current;s.current=null;const f=document.activeElement;d&&d.isConnected&&(!f||f===document.body||u&&u.contains(f))&&((m=d.focus)==null||m.call(d,{preventScroll:!0}))},[e.open,o]),p.useEffect(()=>{const u=n.current;u&&(e.open?u.removeAttribute("inert"):u.setAttribute("inert",""))},[e.open]),a.jsxs(a.Fragment,{children:[e.backdrop&&e.open?a.jsx("div",{className:"af-drawer-backdrop","aria-hidden":"true",onClick:e.onClose,style:{top:Yp(e.topOffset)}}):null,a.jsxs("div",{ref:n,className:`af-drawer${e.side==="left"?" af-drawer--left":""}${e.topOffset?" af-drawer--offset":""}${e.open?" af-drawer--open":""}${e.className?` ${e.className}`:""}`,style:{width:e.width||420,top:Yp(e.topOffset),display:e.open?void 0:"none"},role:"complementary","aria-label":e.label,"aria-hidden":e.open?void 0:!0,tabIndex:-1,children:[e.title!==void 0?a.jsxs("div",{className:"af-drawer__header",children:[a.jsx("div",{className:"af-drawer__title",children:e.title}),a.jsxs("div",{className:"af-drawer__header-actions",children:[e.headerActions,a.jsx("button",{type:"button",className:"af-drawer__close","aria-label":"Close panel",onClick:e.onClose,children:"×"})]})]}):null,a.jsx("div",{className:"af-drawer__body",children:e.children})]})]})}const vx=["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 yx(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 wx(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 fu(e){return Array.from(e.querySelectorAll(vx)).filter(n=>!(typeof n.closest=="function"&&n.closest("[hidden], [inert], [aria-hidden='true']")||wx(n)||typeof n.getClientRects=="function"&&n.getClientRects().length===0))}const Qp=new WeakMap;function _x(e,t){const n=t.document||e.ownerDocument,s=e.querySelector(".af-modal")||e,o=n.activeElement,l=Qp.get(n)||[];Qp.set(n,l),l.push(e);const u=t.lockScroll!==!1;u&&n.documentElement.classList.add("af-modal-open");const d=()=>{const b=s.querySelector(".af-modal__body"),k=t.initialFocus||s.querySelector("[data-af-autofocus], [autofocus]")||(b?fu(b)[0]:void 0)||fu(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=b=>{if(!f())return;if(b.key==="Escape"||b.key==="Esc"){if(b.defaultPrevented||t.closeOnEscape===!1)return;b.preventDefault(),t.onClose();return}if(b.key!=="Tab")return;const k=fu(s),$=n.activeElement,S=!!$&&s.contains($);if(k.length===0){b.preventDefault(),s.focus({preventScroll:!0});return}const N=yx(k,$,b.shiftKey,S&&$!==s);N&&(b.preventDefault(),N.focus({preventScroll:!0}))},g=b=>{if(!f())return;const k=b.target;k&&!s.contains(k)&&d()};let v=!1;const w=b=>{v=b.target===e},x=b=>{const k=b.target===e&&v;v=!1,!(!k||!f()||t.closeOnBackdrop===!1)&&t.onClose()};n.addEventListener("keydown",m,!0),n.addEventListener("focusin",g,!0),e.addEventListener("mousedown",w),e.addEventListener("click",x);let j=!1;return()=>{if(j)return;j=!0,n.removeEventListener("keydown",m,!0),n.removeEventListener("focusin",g,!0),e.removeEventListener("mousedown",w),e.removeEventListener("click",x);const b=l.lastIndexOf(e);b>=0&&l.splice(b,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 Gg(e){const t=p.useId().replace(/:/g,""),n=e.id||`af-modal-${t}`,s=p.useRef(null),o=p.useRef(e.onClose);if(o.current=e.onClose,p.useEffect(()=>{if(!(!e.open||!s.current))return _x(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?oi.createPortal(l,document.body):l}function bx(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 Xp=0;function xx(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")||(Xp+=1,t.setAttribute("id",`af-menu-${Xp}`)),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 N=Array.from(t.querySelectorAll(".af-menu__item")),C=N.filter(R=>!R.hidden&&!R.hasAttribute("disabled"));for(const R of N)R.setAttribute("role","menuitem"),R.setAttribute("tabindex","-1");return C};l();let u=!1;const d=()=>{if(!u)return;const N=e.getBoundingClientRect(),C=t.getBoundingClientRect(),R=bx(N,{width:C.width,height:C.height},{width:o.innerWidth,height:o.innerHeight});t.style.top=`${R.top}px`,t.style.left=`${R.left}px`,t.setAttribute("data-placement",`${R.up?"top":"bottom"}-${R.leftward?"end":"start"}`)},f=N=>{const C=l();if(!C.length)return;const R=(N%C.length+C.length)%C.length;C[R].focus({preventScroll:!0})},m=N=>{u||(u=!0,t.hidden=!1,e.setAttribute("aria-expanded","true"),d(),f(N),s.addEventListener("pointerdown",v,!0),s.addEventListener("mousedown",v,!0),o.addEventListener("scroll",d,!0),o.addEventListener("resize",w),o.addEventListener("keydown",b,!0),n.onOpen&&n.onOpen())},g=N=>{u&&(u=!1,t.hidden=!0,e.setAttribute("aria-expanded","false"),s.removeEventListener("pointerdown",v,!0),s.removeEventListener("mousedown",v,!0),o.removeEventListener("scroll",d,!0),o.removeEventListener("resize",w),o.removeEventListener("keydown",b,!0),N&&e.focus({preventScroll:!0}),n.onClose&&n.onClose())};function v(N){const C=N.target;C&&(t.contains(C)||e.contains(C))||g(!1)}function w(){g(!1)}const x=N=>{N.preventDefault(),u?g(!0):m(0)},j=N=>{N.key==="ArrowDown"||(N.key==="Enter"||N.key===" ")&&!u?(N.preventDefault(),m(0)):N.key==="ArrowUp"&&(N.preventDefault(),m(-1))},b=N=>{if(!u||N.key!=="Escape"&&N.key!=="Esc")return;const C=N.target;C&&C!==e&&!t.contains(C)&&C!==s.body||(N.preventDefault(),g(!0))},k=N=>{if(!u)return;const R=l().indexOf(s.activeElement);N.key==="ArrowDown"?(N.preventDefault(),f(R+1)):N.key==="ArrowUp"?(N.preventDefault(),f(R<0?-1:R-1)):N.key==="Home"?(N.preventDefault(),f(0)):N.key==="End"?(N.preventDefault(),f(-1)):N.key==="Tab"&&g(!1)},$=N=>{const C=N.target,R=C&&typeof C.closest=="function"?C.closest(".af-menu__item"):null;if(!R||!t.contains(R))return;const E=s.activeElement,I=!E||E===s.body||t.contains(E);g(I)};e.addEventListener("click",x),e.addEventListener("keydown",j),t.addEventListener("keydown",k),t.addEventListener("click",$);let S=!1;return()=>{S||(S=!0,g(!1),e.removeEventListener("click",x),e.removeEventListener("keydown",j),t.removeEventListener("keydown",k),t.removeEventListener("click",$))}}function kx(e){const t=p.useRef(null),n=p.useRef(null),s=e.items.filter(l=>l&&!l.hidden),o=s.length>0;return p.useEffect(()=>{if(!(!o||!t.current||!n.current))return xx(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 jx={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"},Sx={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"}},Nx={framework:jx,apps:Sx},el=Nx;function Kg(){return{...el.framework}}function Cx(){return Object.keys(el.apps).sort()}function Ex(e,t){const n=Object.prototype.hasOwnProperty.call(el.apps,e)?el.apps[e]:void 0;if(!n)throw new Error(`appIdentity: unknown application id "${e}" (known: ${Cx().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 Tx(e,t){try{const n=await e(ut("about"),{method:"GET",headers:{Accept:"application/json"},signal:t});if(!n.ok)return hu(null,`HTTP ${n.status}`);const s=await n.json().catch(()=>null);return hu(s)}catch(n){return hu(null,String((n==null?void 0:n.message)||n||"request failed"))}}const Ax={framework:null,frameworkNote:"checking…",gateway:null,gatewayNote:"checking…"};function Js(e){return typeof e=="string"?e.trim():""}function hu(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=Js(n.abstractgateway),o=Js(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 $x(e){const t=Kg();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 Rx(e){const t=e||{},n=Js(t.framework),s=Js(t.gateway);return[["AbstractFramework",n||Js(t.frameworkNote)||"not reported"],["AbstractGateway",s||Js(t.gatewayNote)||"not connected"]]}const Mx='a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function Lx(e,t,n){if(e.key!=="Tab"||!t)return;const s=Array.from(t.querySelectorAll(Mx));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 Ix(e){const t=Kg();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:Rx(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:$x(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 Px(e){ci();const t=p.useRef(null),n=p.useRef(null),s=p.useId(),o=p.useRef(e.onClose);return o.current=e.onClose,p.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}Lx(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(Ix,{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(be,{name:"x",size:16})})})})}):null}const Vo={theme:"dark",font_scale:"md",header_density:"standard"};function Ox(e){const t=e&&typeof e=="object"?e:{};return{theme:typeof t.theme=="string"&&t.theme?t.theme:Vo.theme,font_scale:typeof t.font_scale=="string"&&t.font_scale?t.font_scale:Vo.font_scale,header_density:typeof t.header_density=="string"&&t.header_density?t.header_density:Vo.header_density}}function Dx(e){return`af_appearance_${e}_v1`}function Fx(e,t){const n=Dx(e),s=p.useMemo(()=>({...Vo,...(t==null?void 0:t.defaults)||{}}),[JSON.stringify((t==null?void 0:t.defaults)||{})]),[o,l]=p.useState(()=>{let u=s;try{const d=localStorage.getItem(n)??(t!=null&&t.legacyKey?localStorage.getItem(t.legacyKey):null);d&&(u=Ox({...s,...JSON.parse(d)}))}catch{}try{Wp(u.theme),Vp({font_scale:u.font_scale,header_density:u.header_density})}catch{}return u});return p.useEffect(()=>{Wp(o.theme),Vp({font_scale:o.font_scale,header_density:o.header_density});try{localStorage.setItem(n,JSON.stringify(o))}catch{}},[n,o]),[o,l]}function Bx(e){return p.useEffect(()=>{if(!e.open)return;const t=n=>{n.key!=="Escape"||n.defaultPrevented||(n.preventDefault(),e.onClose())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e.open,e.onClose]),e.open?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(Wb,{value:e.value.theme,onChange:t=>e.onChange({...e.value,theme:t})}),a.jsx("label",{className:"af-appearance__label",children:"Font size"}),a.jsx(Vb,{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(qb,{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 zx(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 Ux(e){return typeof e.openModal=="function"&&typeof e.signOut=="function"}function Wx(e,t){return Ux(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 Vx(e,t){const n=Id(t);return`Signed in as ${qg(e)}${n?` · gateway ${n}`:""}`}function qx(e,t,n){return`${Vx(e,t)} · ${n?"disconnecting…":"connected (Disconnect is in this menu)"}`}const pu="--af-topbar-h";function Hx(e,t=!0){p.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(pu,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(pu)===l&&o.style.removeProperty(pu)}},[e,t])}function Gx(e){const t=typeof navigator<"u"?navigator.clipboard:void 0;return!t||typeof t.writeText!="function"?null:()=>{t.writeText(e).catch(()=>{})}}function Kx(e){var C,R;const t=Wx(e.connection,e.onSignOut),{phase:n,signingOut:s}=t,[o,l]=p.useState(!1),[u,d]=p.useState(!1),[f,m]=p.useState(void 0),g=p.useRef(null);ci(),Hx(g,e.publishHeight!==!1);const v=e.about,w=e.appearance,x=!!(w&&"value"in w),j=v&&!v.versions?v.fetch:void 0,b=p.useRef(j);b.current=j,p.useEffect(()=>{const E=b.current;if(!o||!E)return;const I=typeof AbortController<"u"?new AbortController:null;let L=!0;return m(Ax),Tx(E,I==null?void 0:I.signal).then(D=>{L&&m(D)}),()=>{L=!1,I==null||I.abort()}},[o]);const k=zx(n,s),$=e.identity&&n==="connected"?ox(t.status):null,S=()=>void t.disconnect();let N=null;if($&&e.identity){const E=qg($),I=qx($,(C=t.status)==null?void 0:C.gateway_url,s),L=Gx($.userId),D=Id((R=t.status)==null?void 0:R.gateway_url);N=a.jsx(kx,{label:`Account: ${I}`,tip:I,className:"af-topbar__account",buttonClassName:"af-topbar__identity af-topbar__identity--menu",buttonContent:a.jsxs(a.Fragment,{children:[a.jsx(be,{name:"user",size:14}),a.jsx("span",{className:"af-topbar__identity-label",children:E}),a.jsx("span",{className:`af-topbar__dot af-topbar__dot--${s?"loading":"connected"}`,"data-af-identity":"menu","aria-hidden":"true"})]}),header:a.jsxs("span",{className:"af-topbar__account-head",children:[a.jsxs("span",{className:"af-topbar__account-who",children:["Signed in as ",E]}),D?a.jsxs("span",{className:"af-topbar__account-host",children:["Gateway ",D]}):null]}),items:[{id:"copy-user-id",label:"Copy user id",onSelect:L||(()=>{}),hidden:!L},{id:"disconnect",label:s?"Disconnecting…":"Disconnect",onSelect:s?()=>{}:S,danger:!0}]})}return a.jsxs("div",{ref:g,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(be,{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(be,{name:"sparkle",size:16})}):null,w?a.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--appearance","aria-label":w.label||"Appearance (theme and typography)","data-af-tip":w.label||"Appearance (theme and text size)","aria-haspopup":x?"dialog":void 0,onClick:()=>{"value"in w?d(!0):w.onOpen()},children:a.jsx(be,{name:"contrast",size:16})}):null,v?a.jsx("button",{type:"button",className:"af-topbar__btn af-topbar__btn--about","aria-label":v.label||`About ${v.identity.name}`,"data-af-tip":v.label||`About ${v.identity.name}`,"aria-haspopup":"dialog",onClick:()=>{var E;l(!0),(E=v.onOpen)==null||E.call(v)},children:a.jsx(be,{name:"about",size:16})}):null,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(be,{name:"warning",size:14}),a.jsx("span",{className:"af-topbar__signout-error-label",children:"Disconnect failed"})]}):null,N||a.jsxs("button",{type:"button",className:`af-topbar__pill af-topbar__pill--${n}`,onClick:n==="connected"?S: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})]}),v?a.jsx(Px,{open:o,onClose:()=>l(!1),identity:v.identity,versions:v.versions||(v.fetch?f:void 0),extra:v.extra}):null,w&&"value"in w?a.jsx(Bx,{open:u,onClose:()=>d(!1),value:w.value,onChange:w.onChange,title:w.title,note:w.note}):null]})}function cd(e){return e?[e.provider,e.model].map(t=>String(t||"").trim()).filter(Boolean).join(" / "):""}function Zp(e,t,n=!1){if(n)return"unknown";if(!e)return"";const s=e[t];return!s||!s.configured?"not set":cd(s)||"not set"}function Jx(e,t){var n;return e.stt_provider?cd({provider:e.stt_provider,model:e.stt_model}):(n=t==null?void 0:t.stt)!=null&&n.configured?cd(t.stt):""}function Jg(e,t){return`${Math.max(0,Math.floor((t-e)/1e3))} s`}function Yx(e,t,n){return`Transcribing… ${Jg(e,t)}${n?` · ${n}`:""}`}const ml=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function tl(e){var o;const t=Pd("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=ml())!=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 Yg(e){const t=ml();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 Qx(){const e=ml();if(!(e!=null&&e.getUserMedia))throw new Error(Pd("the microphone")||"This browser cannot record audio.");(await e.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop())}async function Qg(e){const t=ml();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 gl(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function Xg(){const e=gl();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function Zg(e,t,n=1){var d;const s=gl();if(!s)return()=>{};const o=new s,l=o.createMediaStreamSource(e);try{Promise.resolve(o.resume()).catch(()=>{})}catch{}let u;try{u=ev(o,l,t,n)}catch(f){throw l.disconnect(),(d=o.close)==null||d.call(o),f}return()=>{var f;u(),(f=o.close)==null||f.call(o)}}function ev(e,t,n,s=1){const o=e.createAnalyser();o.fftSize=1024,t.connect(o);const l=new Float32Array(o.fftSize);let u=!0;const f=setInterval(()=>{if(!u)return;o.getFloatTimeDomainData(l);let m=0;for(let g=0;g<l.length;g+=1)m+=l[g]*l[g];n(Math.min(1,Math.sqrt(m/l.length)*4*s))},50);return()=>{var m;u=!1,clearInterval(f);try{t.disconnect(o)}catch{}(m=o.disconnect)==null||m.call(o),n(0)}}const tv=.02;function em(){return Object.assign(new Error("The recording was stopped before it began."),{name:"AbortError"})}async function nv(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 em();const n=await Qg(e.deviceId);if((u=e.signal)!=null&&u.aborted)throw n.getTracks().forEach(f=>f.stop()),em();let s=0;const o=Zg(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=[],g=new Promise((w,x)=>{f.ondataavailable=j=>(j==null?void 0:j.data)&&m.push(j.data),f.onstop=()=>w(),f.onerror=j=>x((j==null?void 0:j.error)||new Error("Recording failed."))});f.start(),await new Promise(w=>{var j,b;if((j=e.signal)!=null&&j.aborted)return w();const x=setTimeout(w,e.ms??3e3);(b=e.signal)==null||b.addEventListener("abort",()=>{clearTimeout(x),w()},{once:!0})}),f.stop(),await g;const v=String(f.mimeType||"audio/webm");return{blob:new Blob(m,{type:v}),peak:s,mime:v}}finally{o(),n.getTracks().forEach(f=>f.stop()),(d=e.onLevel)==null||d.call(e,0)}}async function rv(e,t={}){var o,l,u,d;if((o=t.signal)!=null&&o.aborted)return;const n=gl();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 g=s.createGain();g.gain.value=fs(t.volume),g.connect(s.destination);const v=s.createBufferSource();v.buffer=m,v.connect(g),await new Promise(w=>{var j,b;const x=()=>{try{v.stop()}catch{}w()};v.onended=()=>{var k,$;($=(k=t.signal)==null?void 0:k.removeEventListener)==null||$.call(k,"abort",x),w()},(b=(j=t.signal)==null?void 0:j.addEventListener)==null||b.call(j,"abort",x,{once:!0}),v.start()})}finally{(d=s.close)==null||d.call(s)}}async function Xx(e={}){var s,o;const t=gl();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*fs(e.volume),d=n.currentTime+.02;[660,880].forEach((f,m)=>{const g=n.createOscillator(),v=n.createGain();g.frequency.value=f,g.connect(v),v.connect(l);const w=d+m*.22;v.gain.setValueAtTime(0,w),v.gain.linearRampToValueAtTime(u,w+.02),v.gain.exponentialRampToValueAtTime(1e-4,w+.2),g.start(w),g.stop(w+.21)}),await new Promise(f=>setTimeout(f,520))}finally{(o=n.close)==null||o.call(n)}}function fs(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}function hs(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}function tm(e){if(e==null)return"";if(typeof e=="string")return`s:${e}`;const t=Object.keys(e).filter(n=>e[n]!==void 0&&e[n]!==null&&e[n]!=="").sort();return`o:${JSON.stringify(t.map(n=>[n,e[n]]))}`}async function*Zx(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 g=await u.json().catch(()=>null);throw new Error(e0(g,u.status))}if(!u.body)throw new Error("TTS stream has no body");const d=u.body.getReader(),f=new TextDecoder;let m="";for(;;){const{done:g,value:v}=await d.read();m+=g?f.decode():f.decode(v,{stream:!0}),g&&m.trim()&&(m+=`
43
+ `);let w;for(;(w=m.indexOf(`
44
+ `))>=0;){const x=m.slice(0,w).trim();if(m=m.slice(w+1),!x)continue;let j=null;try{j=JSON.parse(x)}catch{throw new Error("TTS stream returned invalid JSON.")}if(j&&j.type==="error")throw new Error(String(j.error||"TTS stream error"));const b=j&&typeof j.audio_b64=="string"?j.audio_b64:"";if(b){const k=atob(b),$=new Uint8Array(k.length);for(let S=0;S<k.length;S+=1)$[S]=k.charCodeAt(S);yield $.buffer}if(j&&(j.type==="done"||j.type==="cancelled"))return}if(g)throw new Error("TTS stream ended before synthesis completed.")}}finally{(l=e.signal)==null||l.removeEventListener("abort",n),t.abort()}}function e0(e,t){const n=e&&typeof e=="object"?e.detail:void 0;if(n&&typeof n=="object"){const s=n.message;return typeof s=="string"&&s.trim()?s.trim():`HTTP ${t}`}return n!=null&&String(n).trim()?String(n):`HTTP ${t}`}function La(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}const sv=350;function t0(){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 n0(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function r0(){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 mu(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 s0(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 a0(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 av(){const e=globalThis,t=e==null?void 0:e.AudioContext;return!!(t&&t.prototype&&typeof t.prototype.setSinkId=="function")}const xo=new WeakMap;function i0(e,t){const n=e;if(!(typeof n.setSinkId!="function"||xo.get(e)===t)){xo.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>xo.delete(e))}catch{xo.delete(e)}}}function o0(e){const t=p.useRef(e);t.current=e;const n=U=>{var ie,ue;return(ue=(ie=t.current).on_error)==null?void 0:ue.call(ie,U)},s=p.useMemo(()=>n0()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),o=p.useMemo(()=>t0()&&typeof e.transcribe=="function",[e.transcribe]),l=p.useRef(0),u=p.useRef(new Set),d=p.useRef(null),f=p.useCallback(U=>{const ie=Math.round(Math.min(1,Math.max(0,Number(U)||0))*20)/20;if(ie!==l.current){l.current=ie;for(const ue of Array.from(u.current))ue(ie)}},[]),m=p.useCallback(()=>{const U=d.current;d.current=null,U==null||U(),f(0)},[f]),[g,v]=p.useState({key:"",status:"idle"}),w=p.useRef(g),x=p.useCallback(U=>{w.current=U,U.status!=="playing"&&m(),v(ie=>ie.key===U.key&&ie.status===U.status?ie:U)},[m]),j=p.useRef(""),b=p.useRef(""),k=p.useRef(null),$=p.useRef(null),S=p.useCallback(()=>{if(!u.current.size||d.current||w.current.status!=="playing")return;const U=k.current,ie=$.current;if(!(!U||!ie))try{d.current=ev(U,ie,ue=>f(U.state==="running"&&w.current.status==="playing"?ue:0))}catch{}},[f]),N=p.useCallback(U=>(u.current.add(U),U(l.current),S(),()=>{u.current.delete(U),u.current.size||m()}),[S,m]),C=p.useRef(null),R=p.useRef(null),E=p.useRef(0),I=p.useRef(0),L=p.useRef(0),D=p.useRef(null),P=p.useRef([]),K=p.useRef(0),se=p.useRef([]),Q=p.useRef(!0),z=p.useRef(!1),T=p.useRef(""),q=(U,ie)=>{const ue=tm(t.current.tts_voice);return ue?`${U}${ie}${ue}`:""},J=()=>{try{const U=globalThis,ie=(U==null?void 0:U.AudioContext)||(U==null?void 0:U.webkitAudioContext);if(!ie)return null;if(!k.current){const Ne=new ie,Te=Ne.createGain();Te.gain.value=1,Te.connect(Ne.destination),k.current=Ne,$.current=Te}const ue=k.current,we=$.current;if(!ue||!we)return null;i0(ue,t.current.output_device_id||""),we.gain.value=fs(t.current.volume)*(t.current.muted?0:1);try{ue.state==="suspended"&&ue.resume()}catch{}return{ctx:ue,gain:we}}catch{return null}};p.useEffect(()=>{const U=$.current;U&&(U.gain.value=fs(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const B=p.useCallback(()=>{m();const U=se.current;se.current=[];for(const ue of U){try{ue.src.onended=null}catch{}try{ue.src.stop()}catch{}try{ue.src.disconnect()}catch{}}const ie=C.current;if(C.current=null,!!ie){try{ie.onended=null}catch{}try{ie.stop()}catch{}try{ie.disconnect()}catch{}}},[m]),O=p.useCallback(()=>{var U;B(),L.current+=1,(U=D.current)==null||U.abort(),D.current=null,P.current=[],K.current=0,Q.current=!0,z.current=!1,b.current="",j.current="",R.current=null,T.current="",E.current=0,I.current=0,x({key:"",status:"idle"})},[B,x]),Z=tm(e.tts_voice),M=p.useRef(Z);p.useEffect(()=>{M.current!==Z&&(M.current=Z,w.current.status==="paused"&&O())},[Z,O]),p.useEffect(()=>()=>{var U,ie;O();try{(U=$.current)==null||U.disconnect()}catch{}try{(ie=k.current)==null||ie.close()}catch{}k.current=null,$.current=null,R.current=null},[]);const W=async(U,ie,ue)=>{const we=L.current,Ne=J();if(!Ne)throw new Error("TTS playback is not supported in this browser");const{ctx:Te,gain:Fe}=Ne;try{Te.state==="suspended"&&await Te.resume()}catch{}if(we!==L.current)return;B();const xe=Te.createBufferSource();xe.buffer=ie,xe.connect(Fe);const Be=Number.isFinite(Number(ie.duration))?Number(ie.duration):0,Ke=Math.max(0,Math.min(Number(ue||0),Be>0?Math.max(0,Be-.01):0));I.current=Te.currentTime-Ke,E.current=Ke,C.current=xe,j.current=U,xe.onended=()=>{C.current===xe&&(C.current=null,E.current=0,I.current=0,j.current="",x({key:"",status:"idle"}))},xe.start(0,Ke),x({key:U,status:"playing"}),S()},Y=(U,ie)=>{if(ie!==L.current||z.current)return;const ue=J();if(!ue)return;const we=P.current,Ne=se.current,Te=Ne.length?Ne[Ne.length-1]:null;let Fe=Te?Te.idx+1:K.current;if(!Te&&Fe>=we.length){Q.current&&(j.current="",E.current=0,I.current=0,x({key:"",status:"idle"}));return}const{ctx:xe,gain:Be}=ue;try{xe.state==="suspended"&&xe.resume()}catch{}const Ke=Number(xe.currentTime||0);let ot=Te?Math.max(Te.at+Te.dur,Ke):Ke+.02;for(;Fe<we.length;Fe++){const Ut=we[Fe],tt=Number.isFinite(Number(Ut.duration))?Number(Ut.duration):0,bt=!Te&&Fe===K.current?Math.max(0,Math.min(Number(E.current||0),tt>0?Math.max(0,tt-.01):0)):0,Lt=xe.createBufferSource();Lt.buffer=Ut,Lt.connect(Be);const $n={src:Lt,idx:Fe,at:ot,off:bt,dur:Math.max(0,tt-bt)};Lt.onended=()=>{if(ie!==L.current)return;const hn=se.current,zn=hn.indexOf($n);zn<0||(hn.splice(zn,1),K.current=$n.idx+1,E.current=0,hn.length||Y(U,ie))},Lt.start(ot,bt),se.current.push($n),ot+=$n.dur}I.current=se.current.length?se.current[0].at-se.current[0].off:0,j.current=U,x({key:U,status:"playing"}),S()},oe=U=>{const ie=se.current;if(!ie.length)return{idx:K.current,off:0};for(const we of ie){if(U<we.at)return{idx:we.idx,off:we.off};if(U<we.at+we.dur)return{idx:we.idx,off:we.off+(U-we.at)}}return{idx:ie[ie.length-1].idx+1,off:0}},de=async(U,ie,ue)=>{var xe;const we=J();if(!we){n==null||n("This browser cannot play spoken replies.");return}B();const Ne=++L.current;(xe=D.current)==null||xe.abort();const Te=new AbortController;D.current=Te,P.current=[],K.current=0,Q.current=!1,z.current=!1,R.current=null,E.current=0,I.current=0,j.current=U,b.current=U,T.current=q(U,ie),x({key:U,status:"loading"}),n==null||n("");let Fe=null;try{for await(const Be of ue(ie,Te.signal)){if(Ne!==L.current)return;let Ke;try{Ke=await mu(we.ctx,Be),Fe||(Fe=s0(Be))}catch{if(!Fe)continue;try{Ke=await mu(we.ctx,a0(Fe,Be))}catch{continue}}if(Ne!==L.current)return;P.current.push(Ke),z.current||(b.current="",Y(U,Ne))}if(Ne!==L.current)return;if(Q.current=!0,P.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),O();return}!se.current.length&&!z.current&&Y(U,Ne)}catch(Be){if(Ne!==L.current)return;n==null||n(La("Reading aloud failed",Be)),O()}finally{D.current===Te&&(D.current=null)}},me=p.useCallback(async(U,ie)=>{var Ut;const ue=String(U||"").trim(),we=String(ie||"").trim();if(!ue||!we)return;const Ne=t.current.tts,Te=t.current.tts_stream;if(typeof Ne!="function"&&typeof Te!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Fe=J();if(!Fe){n==null||n("This browser cannot play spoken replies.");return}const xe=w.current,Be=xe.key===ue;if(Be&&xe.status==="playing"){if(se.current.length){const tt=oe(Number(Fe.ctx.currentTime||0));K.current=tt.idx,E.current=tt.off}else if(C.current){const tt=Math.max(0,Fe.ctx.currentTime-Number(I.current||0));E.current=tt}else E.current=0;z.current=!0,B(),x({key:ue,status:"paused"});return}const Ke=Be&&xe.status==="paused"&&T.current!==""&&T.current===q(ue,we);if(Be&&xe.status==="paused"&&!Ke&&O(),Ke){if(P.current.length>0){n==null||n(""),z.current=!1,x({key:ue,status:"playing"}),Y(ue,L.current);return}const tt=R.current;if(tt){n==null||n(""),z.current=!1;try{await W(ue,tt,E.current)}catch(bt){n==null||n(La("Reading aloud failed",bt)),x({key:"",status:"idle"})}return}}if(Be&&xe.status==="loading")return;if(typeof Te=="function"){await de(ue,we,Te);return}B(),L.current+=1,(Ut=D.current)==null||Ut.abort(),D.current=null;const ot=L.current;P.current=[],K.current=0,Q.current=!0,z.current=!1,R.current=null,E.current=0,I.current=0,j.current=ue,b.current=ue,T.current=q(ue,we),x({key:ue,status:"loading"}),n==null||n("");try{const tt=await Ne(we);if(b.current!==ue||L.current!==ot)return;const bt=await mu(Fe.ctx,tt);if(b.current!==ue||L.current!==ot)return;R.current=bt,E.current=0,await W(ue,bt,0)}catch(tt){if(L.current!==ot)return;b.current===ue&&(b.current="",j.current="",x({key:"",status:"idle"})),n==null||n(La("Reading aloud failed",tt))}},[]),[ee,ce]=p.useState(!1),[ye,Ce]=p.useState(!1),ze=p.useRef(!1),Ve=p.useRef(o);Ve.current=o;const Ee=p.useCallback(U=>{ze.current=U,ce(ie=>ie===U?ie:U)},[]),je=p.useRef(!1),Ue=p.useRef(null),ne=p.useRef(null),$e=p.useRef([]),Pe=p.useRef(""),Ge=p.useRef(0),G=p.useRef(!1),fe=p.useRef(!1),[te,pe]=p.useState(0),Se=p.useRef(0),Ze=p.useRef(null),Ye=p.useRef(0),rt=p.useRef(new Set),V=p.useRef(null),he=p.useCallback(U=>{const ie=Math.round(Math.min(1,Math.max(0,Number(U)||0))*20)/20;if(ie!==Ye.current){Ye.current=ie;for(const ue of Array.from(rt.current))ue(ie)}},[]),Je=p.useCallback(U=>(rt.current.add(U),U(Ye.current),()=>{rt.current.delete(U)}),[]),Oe=p.useRef(new Set),_t=p.useCallback(U=>(Oe.current.add(U),()=>{Oe.current.delete(U)}),[]);function Nt(){var ue,we;const U=V.current;V.current=null;try{U==null||U()}catch{}he(0);try{(we=(ue=Ue.current)==null?void 0:ue.getTracks)==null||we.call(ue).forEach(Ne=>{try{Ne.stop()}catch{}})}catch{}Ue.current=null;const ie=Ze.current;Ze.current=null;try{ie==null||ie.close()}catch{}}const zt=p.useCallback(()=>{Ge.current+=1,G.current=!1;const U=ne.current;if(U){U.onstop=null,U.ondataavailable=null,U.onerror=null;try{U.stop()}catch{}}ne.current=null,Nt(),Ee(!1),je.current=!1,Ce(!1),pe(0),$e.current=[]},[Ee]);p.useEffect(()=>()=>zt(),[zt]);async function An(U,ie){var Te,Fe;if(n==null||n(""),je.current)return;const ue=Se.current?Date.now()-Se.current:1/0;if(!U||!U.size||ue<sv){pe(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 we=t.current.transcribe;if(typeof we!="function"){n==null||n("Speech to text is not available on this gateway.");return}je.current=!0;const Ne=Ge.current;Ce(!0),pe(Date.now());try{const xe=await we(U,ie),Be=typeof xe=="string"||!xe?{text:String(xe||"")}:xe,Ke=String(Be.text||"").trim();if(Ne!==Ge.current)return;if(Ke){(Fe=(Te=t.current).on_transcript)==null||Fe.call(Te,Ke,{...Be,text:Ke});for(const ot of Array.from(Oe.current))ot(Ke,{...Be,text:Ke})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(xe){if(Ne===Ge.current){const Be=String((xe==null?void 0:xe.message)||xe||"").trim().replace(/\.$/,"");n==null||n(Be?`Transcription failed: ${Be}.`:"Transcription failed.")}}finally{Ne===Ge.current&&(je.current=!1,Ce(!1),pe(0))}}const ht=p.useCallback(async()=>{if(n==null||n(""),!Ve.current){n==null||n(Pd("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(je.current||G.current||ze.current||ne.current)return;$e.current=[];const U=Ge.current;G.current=!0,fe.current=!1;try{const ie=await Qg(t.current.input_device_id||"");if(U!==Ge.current){ie.getTracks().forEach(xe=>xe.stop());return}if(fe.current){fe.current=!1,ie.getTracks().forEach(xe=>xe.stop()),pe(0);return}Ue.current=ie;const ue=Number(t.current.input_gain??1);try{V.current=Zg(ie,he,Number.isFinite(ue)&&ue>0?ue:1)}catch{}const we=r0();Pe.current=we;let Ne=ie;const Te=Number(t.current.input_gain??1);if(Number.isFinite(Te)&&Te>0&&Te!==1&&Xg()){const xe=globalThis.AudioContext||globalThis.webkitAudioContext,Be=new xe,Ke=Be.createGain();Ke.gain.value=Te;const ot=Be.createMediaStreamDestination();Be.createMediaStreamSource(ie).connect(Ke),Ke.connect(ot),Ze.current=Be,Ne=ot.stream}const Fe=we?new MediaRecorder(Ne,{mimeType:we}):new MediaRecorder(Ne);ne.current=Fe,Fe.ondataavailable=xe=>{if(U===Ge.current)try{xe!=null&&xe.data&&$e.current.push(xe.data)}catch{}},Fe.onerror=()=>{U===Ge.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Fe.onstop=()=>{if(U===Ge.current){Ee(!1),Nt(),ne.current=null;try{const xe=new Blob($e.current,{type:Pe.current||""});An(xe,Pe.current)}catch(xe){n==null||n(La("The recording could not be prepared",xe))}}},Fe.start(),Se.current=Date.now(),pe(Se.current),Ee(!0)}catch(ie){if(U!==Ge.current)return;Nt(),ne.current=null,Ee(!1),pe(0),n==null||n(tl(ie))}finally{U===Ge.current&&(G.current=!1)}},[]),Tt=p.useCallback(()=>{const U=ne.current;if(G.current&&!U){fe.current=!0;return}if(!(!ze.current||!U)){Ee(!1);try{U.stop()}catch(ie){n==null||n(La("The recording could not stop",ie))}}},[]);return p.useEffect(()=>{if(!ee||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&hs(t.current.capture_mode)==="toggle")return;const U=()=>Tt();return window.addEventListener("pointerup",U),window.addEventListener("pointercancel",U),()=>{window.removeEventListener("pointerup",U),window.removeEventListener("pointercancel",U)}},[ee]),{tts_supported:s,tts_playback:g,toggle_tts:me,stop_tts:O,voice_ptt_supported:o,voice_ptt_recording:ee,voice_ptt_busy:ye,start_voice_ptt_recording:ht,stop_voice_ptt_recording:Tt,cancel_voice_ptt_recording:zt,voice_ptt_since:te,subscribe_level:Je,subscribe_playback_level:N,voice_capture_mode:hs(e.capture_mode),add_transcript_listener:_t}}const nm=["Your voices","Engine voices","Shared voices"];function l0(e){var t,n;for(const s of[e==null?void 0:e.reference_seconds,(t=e==null?void 0:e.tags)==null?void 0:t.reference_seconds,(n=e==null?void 0:e.params)==null?void 0:n.reference_seconds]){const o=typeof s=="number"?s:typeof s=="string"&&s.trim()?Number(s):NaN;if(Number.isFinite(o)&&o>0)return o}return null}function c0(e){const t=l0(e);return t===null?"":`${t.toFixed(1)} s reference`}function iv(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 vl(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 u0(e){return Array.from(new Set(e.map(vl).filter(Boolean))).sort()}function d0(e,t){if(!t)return!0;const n=vl(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 ov={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"},lv=ov,ps=e=>lv[e]||e,gu=e=>String((e==null?void 0:e.voice_id)||(e==null?void 0:e.id)||""),ko=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 f0(e){return e?Array.isArray(e.items)?e.items:[...Array.isArray(e.profiles)?e.profiles:[],...Array.isArray(e.voices)?e.voices:[]]:[]}function cv(e,t,n){const s=String(t||"").trim();if(!s)return"";const o=f0(e).filter(u=>u&&(u.id===s||u.voice_id===s||u.profile_id===s)),l=(n?o.find(u=>(u.provider||u.engine)===n):void 0)||o[0];return String((l==null?void 0:l.label)||(l==null?void 0:l.display_name)||(l==null?void 0:l.name)||"").trim()}function uv(e){const t=String(e||"").trim();return/^[0-9a-f]{16,}$/i.test(t)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)}function h0(e,t){const n=cv(t,e);if(n)return n;const s=String(e||"").trim();return uv(s)?"a saved voice":s}function p0(e){var n,s,o;if(!e)return"";const t=Array.isArray(e.voice_kinds)?e.voice_kinds:[];return e.kind!=="clone"&&!t.includes("clone")?"":String(e.model||((n=e.tags)==null?void 0:n.model_id)||((o=(s=e.params)==null?void 0:s.meta)==null?void 0:o.model_id)||"").trim()}const m0=200;function g0({value:e,onChange:t,fetchCatalog:n,intro:s,delivery:o=!0,quality:l=!0,showReset:u=!0,defaultHint:d,voiceDefaultLabel:f,createVoice:m,voiceLibrary:g,previewVoice:v,previewOn:w,recordFrom:x}){var pe,Se,Ze,Ye,rt;const j=g||m,[b,k]=p.useState({state:"idle",error:""}),$=p.useRef(0),S=p.useRef(null),N=p.useRef(null),C=p.useRef(null),R=p.useRef(null),E=p.useRef(n);E.current=n;const[I,L]=p.useState({}),[D,P]=p.useState(""),[K,se]=p.useState(!1),[Q,z]=p.useState(""),[T,q]=p.useState(0),J=p.useRef(e);J.current=e;const B=p.useRef(!0),O=()=>{var V,he;$.current+=1,R.current!==null&&clearTimeout(R.current),R.current=null,(V=S.current)==null||V.abort(),S.current=null,(he=N.current)==null||he.abort(),N.current=null};p.useEffect(()=>(B.current=!0,()=>{B.current=!1,O()}),[]);const Z=V=>JSON.stringify([V.provider||"",V.model||"",V.voice||"",V.profile||""]),M=V=>`The sample did not play: ${String((V==null?void 0:V.message)||V).replace(/\.$/,"")}.`,W=(V,he)=>{const Je=new AbortController;N.current=Je,k({state:"playing",error:""}),rv(V,{deviceId:(w==null?void 0:w.deviceId)||"",volume:w==null?void 0:w.volume,signal:Je.signal}).then(()=>B.current&&$.current===he&&k({state:"idle",error:""})).catch(Oe=>B.current&&$.current===he&&k({state:"idle",error:M(Oe)}))},Y=V=>{if(!v)return;O();const he=$.current,Je=new AbortController;S.current=Je,k({state:"loading",error:""}),v(V,void 0,{signal:Je.signal}).then(Oe=>{!B.current||$.current!==he||(S.current=null,C.current={key:Z(V),bytes:Oe},W(Oe,he))}).catch(Oe=>{!B.current||$.current!==he||(S.current=null,k({state:"idle",error:M(Oe)}))})},oe=V=>{if(!v)return;O();const he=$.current;if(C.current&&C.current.key===Z(V)){W(C.current.bytes,he);return}k({state:"loading",error:""}),R.current=setTimeout(()=>{R.current=null,B.current&&$.current===he&&Y(V)},m0)},de=()=>{if(b.state!=="idle"){O(),k({state:"idle",error:""});return}const V=J.current;if(C.current&&C.current.key===Z(V)){O(),W(C.current.bytes,$.current);return}Y(V)};p.useEffect(()=>{z("")},[e.provider]),p.useEffect(()=>{let V=!0;return se(!0),L({}),P(""),E.current(e.provider,e.model).then(he=>{V&&(L(he),P(he.error?String(he.error):""))}).catch(he=>{V&&P(String((he==null?void 0:he.message)||he))}).finally(()=>{V&&se(!1)}),()=>{V=!1}},[e.provider,e.model,T]);const me=Array.isArray(I.items)?I.items:[...Array.isArray(I.profiles)?I.profiles.map(V=>({...V,voice_kind:"profile"})):[],...Array.isArray(I.voices)?I.voices.map(V=>({...V,voice_kind:"voice"})):[]],ee=V=>JSON.stringify([V.provider||"",V.model||"",V.voice_kind==="profile"?"profile":"voice",V.id]),ce=V=>(!e.provider||!V.provider||V.provider===e.provider)&&(!e.model||!V.model||V.model===e.model),ye=V=>JSON.stringify([V.provider||"",V.voice_kind==="profile"?"profile":"voice",V.id]),Ce=new Map;for(const V of me){if(!(V!=null&&V.id))continue;const he=ye(V);Ce.has(he)||Ce.set(he,new Set),Ce.get(he).add(String(V.model||""))}const ze=V=>{var he;return(((he=Ce.get(ye(V)))==null?void 0:he.size)||0)>1},Ve=V=>ze(V)&&!e.model?JSON.stringify([V.provider||"","",V.voice_kind==="profile"?"profile":"voice",V.id]):ee(V),Ee=me.find(V=>V.id===(e.profile||e.voice)&&V.voice_kind==="profile"==!!e.profile&&ce(V))||(!e.profile&&e.voice?me.find(V=>V.id===e.voice&&V.voice_kind==="profile"&&ce(V)):void 0),je=Ee?Ve(Ee):e.profile||e.voice?JSON.stringify([e.provider||"",e.model||"",e.profile?"profile":"voice",e.profile||e.voice]):"",Ue=u0(me),ne=Ue.length>1;p.useEffect(()=>{!ne&&!K&&z("")},[ne,K]);const $e=ne?Q:"",Pe=new Set,Ge=me.filter(V=>(V==null?void 0:V.id)&&(!e.provider||!V.provider||V.provider===e.provider)&&(!ze(V)||!e.model||V.model===e.model||!Ce.get(ye(V)).has(e.model))&&(d0(V,$e)||Ve(V)===je)).filter(V=>{const he=Ve(V);return Pe.has(he)?!1:(Pe.add(he),!0)}).map(V=>{const he=vl(V);return{value:Ve(V),group:iv(V),label:`${V.label||V.name||V.id}${he?` · ${ps(he)}`:""}${!e.provider&&V.provider?` · ${V.provider}`:""}`}}).sort((V,he)=>nm.indexOf(V.group)-nm.indexOf(he.group)),G=String(((pe=Ee==null?void 0:Ee.tags)==null?void 0:pe.description)||"").trim(),fe=p0(Ee);je&&!Ge.some(V=>V.value===je)&&Ge.unshift({value:je,group:"",label:uv(e.profile||e.voice||"")?"Saved voice (not listed)":`${e.profile||e.voice} (saved)`});const te=V=>t({...e,...V});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(zg,{defaultHint:d,value:{provider:e.provider||"",model:e.model||""},onChange:V=>{O(),k({state:"idle",error:""}),t({...e,...V,voice:"",profile:""})},fetchProviders:async()=>{const V=await E.current();if(V.error&&!ko(V.tts_providers||V.providers).length)throw new Error(V.error);return ko(V.tts_providers||V.providers).map(he=>({name:he}))},fetchModels:async V=>{var zt,An;const he=await E.current(V),Je=((zt=he.tts_models_by_provider)==null?void 0:zt[V])||he.tts_models||he.models,Oe=[...Array.isArray((An=he.tts_model_details_by_provider)==null?void 0:An[V])?he.tts_model_details_by_provider[V]:[],...Array.isArray(Je)?Je.filter(ht=>ht&&typeof ht=="object"):[]],_t=new Map;for(const ht of Oe){const Tt=String((ht==null?void 0:ht.id)||"").trim();Tt&&!_t.has(Tt)&&_t.set(Tt,String(ht.label||(ht.role==="cloning"?`${Tt} (clones)`:Tt)))}return[...new Set(ko(Je).map(ht=>String(ht).trim()).filter(Boolean))].map(ht=>({id:ht,label:_t.get(ht)||ht}))},providerLabel:"Speech provider",modelLabel:"Speech model"}),ne?a.jsxs("label",{children:["Voices that speak",a.jsx(tn,{ariaLabel:"Voice language",placeholder:"Any language",value:Q,searchable:!1,options:[{value:"",label:"Any language"},...Ue.map(V=>({value:V,label:ps(V)}))],onChange:z})]}):null,a.jsxs("label",{children:["Voice / profile",a.jsxs("span",{className:"af-voice-settings__voice-row",children:[a.jsx(tn,{ariaLabel:"AI voice",placeholder:f||"Gateway / provider default",value:je,disabled:K,options:[{value:"",label:f||"Gateway / provider default"},...Ge],onChange:V=>{let he;if(!V)he={voice:"",profile:""};else{const[Je,Oe,_t,Nt]=JSON.parse(V);he={provider:Je||e.provider||"",model:Oe||(Je&&Je!==e.provider?"":e.model)||"",voice:_t==="voice"?Nt:"",profile:_t==="profile"?Nt:""}}te(he),oe({...e,...he})}}),v?a.jsx("button",{type:"button",className:"af-voice-settings__sample","data-action":"play-sample","data-state":b.state,"aria-busy":b.state==="loading","aria-label":b.state==="playing"?"Stop the sample":b.state==="loading"?"Cancel the sample":"Play a sample of this voice",title:b.state==="playing"?"Stop":b.state==="loading"?"Synthesizing… (click to cancel)":"Play a sample",disabled:K&&b.state==="idle",onClick:de,children:a.jsx("span",{"aria-hidden":"true",children:b.state==="playing"?"■":"▶"})}):null]})]}),b.error?a.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"sample",children:b.error}):null,G?a.jsx("p",{className:"af-voice-settings__description",children:G}):null,fe?a.jsxs("p",{className:"af-voice-settings__description","data-voice-note":"clone-model",children:["A cloned voice, made with ",fe,": it is always spoken with that model, whatever speech model is chosen."]}):null,K?a.jsx("p",{role:"status",children:"Loading available voices…"}):null,D?a.jsxs("p",{role:"alert",children:["Voice discovery unavailable: ",D,". Your saved choice is preserved."]}):null,!K&&!D&&e.provider&&me.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:V=>te({speed:V.target.value?Number(V.target.value):void 0}),children:[a.jsx("option",{value:"",children:"Gateway default"}),[.5,.75,1,1.25,1.5,2].map(V=>a.jsxs("option",{value:V,children:[V,"×"]},V))]})]}),l&&((Ze=(Se=I.controls)==null?void 0:Se.quality_preset)!=null&&Ze.supported)?a.jsxs("label",{children:["Quality",a.jsxs("select",{"aria-label":"Speech quality",value:e.quality_preset||"",onChange:V=>te({quality_preset:V.target.value}),children:[a.jsx("option",{value:"",children:"Gateway default"}),ko(I.controls.quality_preset.values).map(V=>a.jsx("option",{value:V,children:V},V))]})]}):null,(rt=(Ye=I.controls)==null?void 0:Ye.instructions)!=null&&rt.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:V=>te({instructions:V.target.value})})]}):null]}):null,j&&(j.design||j.clone)?a.jsx(w0,{creation:j,defaultLanguage:$e,recordFrom:x,onCreated:(V,he)=>{const Je=J.current;t({...Je,provider:he||Je.provider||"",model:"",voice:V,profile:""}),q(Oe=>Oe+1)}}):null,g!=null&&g.list?a.jsx(b0,{library:g,refreshKey:T,onChanged:()=>q(V=>V+1),onRemoved:V=>{const he=J.current;he.voice===V&&t({...he,voice:""})}}):null,u?a.jsx("button",{type:"button",onClick:()=>t({}),children:"Reset to Gateway defaults"}):null]})}const v0={value:"",label:"Detect from the recording"},y0=3e4;function w0({creation:e,defaultLanguage:t,onCreated:n,recordFrom:s,cloneRoute:o}){const[l,u]=p.useState(e.design?"design":"clone"),[d,f]=p.useState(""),[m,g]=p.useState(""),[v,w]=p.useState(t||"en"),[x,j]=p.useState(""),[b,k]=p.useState(null),[$,S]=p.useState(""),[N,C]=p.useState(!1),[R,E]=p.useState(!1),[I,L]=p.useState(0),[D,P]=p.useState({text:"",tone:"info"}),K=p.useRef(!1),se=p.useRef(!0),Q=p.useRef(null);p.useEffect(()=>(se.current=!0,()=>{var O;se.current=!1,(O=Q.current)==null||O.abort()}),[]);const z=Object.keys(lv).map(O=>({value:O,label:ps(O)})),T=l==="design"?v:x,q=()=>{if(Q.current){Q.current.abort();return}const O=new AbortController;Q.current=O;const Z=Date.now();E(!0),P({text:"Recording — read a few sentences, then press Stop.",tone:"info"}),nv({deviceId:(s==null?void 0:s.deviceId)||"",gain:s==null?void 0:s.gain,ms:y0,signal:O.signal,onLevel:M=>se.current&&L(M)}).then(({blob:M,peak:W})=>{if(se.current){if(W<tv){P({text:"The microphone recorded silence. Pick another input in the voice settings, then record again.",tone:"error"});return}k(M),P({text:`Recording ready (${Math.max(1,Math.round((Date.now()-Z)/1e3))} s).`,tone:"ok"})}}).catch(M=>{se.current&&((M==null?void 0:M.name)==="AbortError"?P({text:"Recording cancelled.",tone:"info"}):P({text:tl(M),tone:"error"}))}).finally(()=>{Q.current===O&&(Q.current=null),se.current&&(E(!1),L(0))})},J=async()=>{if(!(K.current||Q.current)){K.current=!0,C(!0),P({text:l==="design"?"Creating the voice from your description…":"Cloning the voice from your recording…",tone:"info"});try{const O=l==="design"?await e.design({description:d.trim(),name:m.trim()||void 0,language:v}):await e.clone(b,{name:m.trim()||void 0,reference_text:$.trim()||void 0,...x?{language:x}:{},...o!=null&&o.provider?{provider:o.provider}:{},...o!=null&&o.provider&&o.model?{model:o.model}:{}});if(!se.current)return;P({text:`Voice ready: ${O.name||O.voice_id}. It is selected above.`,tone:"ok"}),n(O.voice_id,O.engine||(l==="design"?"qwen3-tts":void 0))}catch(O){if(!se.current)return;P({text:`The voice was not created: ${String((O==null?void 0:O.message)||O).replace(/\.$/,"")}.`,tone:"error"})}finally{K.current=!1,se.current&&C(!1)}}},B=l==="design"?!!d.trim():!!b&&!R;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:N||R,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:N||R,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:O=>f(O.target.value)})]}):a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Recording",a.jsx("input",{"aria-label":"Voice recording",type:"file",accept:"audio/*",disabled:R,onChange:O=>{const Z=O.target.files&&O.target.files[0]||null;k(Z),Z&&P({text:"",tone:"info"})}})]}),a.jsxs("div",{className:"af-voice-create__record",children:[a.jsx("button",{type:"button","data-action":"record-sample",disabled:N,onClick:q,children:R?"Stop":"Record"}),R?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:$,onChange:O=>S(O.target.value)})]})]}),a.jsxs("label",{children:["Name",a.jsx("input",{"aria-label":"Voice name",value:m,placeholder:"My voice",onChange:O=>g(O.target.value)})]}),a.jsxs("label",{children:["Language",a.jsx(tn,{ariaLabel:"Voice language for creation",value:T,searchable:!1,options:l==="design"?z:[v0,...z],onChange:l==="design"?w:j})]}),a.jsx("button",{type:"button","data-action":"create-voice",disabled:N||!B,onClick:J,children:N?"Creating…":"Create voice"}),D.text?a.jsx("p",{className:`af-voice-note af-voice-note--${D.tone}`,role:"status","data-voice-note":"create",children:D.text}):null]})}const _0=e=>Array.isArray(e)?e:Array.isArray(e==null?void 0:e.voices)?e.voices:[],rm=e=>String((e==null?void 0:e.message)||e||"").trim().replace(/\.$/,"");function b0({library:e,refreshKey:t,onChanged:n,onRemoved:s}){const[o,l]=p.useState([]),[u,d]=p.useState({loading:!0,error:""}),[f,m]=p.useState(null),[g,v]=p.useState(""),[w,x]=p.useState(""),[j,b]=p.useState({text:"",tone:"info"}),[k,$]=p.useState(0),S=p.useRef(e);S.current=e;const N=p.useRef(!1),C=p.useRef(!0);p.useEffect(()=>(C.current=!0,()=>{C.current=!1}),[]),p.useEffect(()=>{const I=S.current.list;if(!I)return;let L=!0;return d(D=>({loading:!0,error:D.error})),I().then(D=>{L&&(l(_0(D).filter(P=>{var K;return gu(P)&&!((K=P==null?void 0:P.tags)!=null&&K.builtin)})),d({loading:!1,error:""}))}).catch(D=>L&&d({loading:!1,error:`The voices could not be listed: ${rm(D)}.`})),()=>{L=!1}},[t,k]);const R=(I,L,D,P)=>{N.current||(N.current=!0,x(I),b({text:"",tone:"info"}),L().then(()=>{C.current&&(b({text:D,tone:"ok"}),m(null),v(""),P==null||P(),$(K=>K+1),n==null||n())}).catch(K=>C.current&&b({text:`${rm(K)||"The gateway refused"}.`,tone:"error"})).finally(()=>{N.current=!1,C.current&&x("")}))},E=I=>String(I.name||I.label||gu(I));return a.jsxs("fieldset",{className:"af-voice-library","data-voice-library":!0,children:[a.jsx("legend",{children:"Manage voices"}),u.loading&&!o.length?a.jsx("p",{role:"status",children:"Loading your voices…"}):null,u.error?a.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status","data-voice-note":"library",children:u.error}):null,!u.loading&&!u.error&&!o.length?a.jsx("p",{className:"af-voice-library__empty",children:"No voices of your own yet."}):null,o.length?a.jsx("ul",{className:"af-voice-library__list",children:o.map(I=>{const L=gu(I),D=iv(I)==="Shared voices",P=vl(I),K=String(I.engine||I.provider||""),se=w===L;return a.jsxs("li",{className:"af-voice-library__item","data-voice-id":L,children:[(f==null?void 0:f.id)===L?a.jsxs("span",{className:"af-voice-library__edit",children:[a.jsx("input",{"aria-label":`New name for ${E(I)}`,value:f.name,onChange:Q=>m({id:L,name:Q.target.value})}),a.jsx("button",{type:"button","data-action":"save-voice-name",disabled:se||!f.name.trim(),onClick:()=>R(L,()=>S.current.rename(L,{name:f.name.trim()}),`Renamed to ${f.name.trim()}.`),children:"Save"}),a.jsx("button",{type:"button","data-action":"cancel-voice-name",disabled:se,onClick:()=>m(null),children:"Cancel"})]}):a.jsxs("span",{className:"af-voice-library__name",children:[E(I),a.jsx("span",{className:"af-voice-library__meta",children:[D?"Shared":"Yours",P?ps(P):"",K,c0(I)].filter(Boolean).join(" · ")})]}),g===L?a.jsxs("span",{className:"af-voice-library__confirm",role:"group","aria-label":`Delete ${E(I)}?`,children:["Delete ",E(I),"?",a.jsx("button",{type:"button","data-action":"confirm-delete-voice",disabled:se,onClick:()=>R(L,()=>S.current.remove(L),`${E(I)} was deleted.`,()=>s==null?void 0:s(L)),children:"Delete"}),a.jsx("button",{type:"button","data-action":"keep-voice",disabled:se,onClick:()=>v(""),children:"Keep"})]}):(f==null?void 0:f.id)!==L?a.jsxs("span",{className:"af-voice-library__actions",children:[e.rename?a.jsx("button",{type:"button","data-action":"rename-voice",disabled:!!w,onClick:()=>m({id:L,name:E(I)}),children:"Rename"}):null,e.remove?a.jsx("button",{type:"button","data-action":"delete-voice",disabled:!!w,onClick:()=>v(L),children:"Delete"}):null,e.share&&!D?a.jsx("button",{type:"button","data-action":"share-voice",disabled:!!w,onClick:()=>R(L,()=>S.current.share(L),`${E(I)} is shared with everyone.`),children:"Share"}):null]}):null]},L)})}):null,j.text?a.jsx("p",{className:`af-voice-note af-voice-note--${j.tone}`,role:"status","data-voice-note":"library-action",children:j.text}):null]})}const vu=ut("automations"),x0=ut("trigger-sources"),k0=ut("me/email"),j0=ut("me/email/accounts"),S0=ut("triggers/connections"),N0=ut("automations/schedule-preview");class sm 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 C0(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 yu(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 E0(){return Ys()}function T0(e){const t=e.newId??E0,n=o=>`${vu}/${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(Md(e.baseUrl,l),f),g=await m.text();let v,w=!1;if(g)try{v=JSON.parse(g),w=!0}catch{w=!1}if(!m.ok)throw new sm(C0(m.status,v));if(!w||v===null||typeof v!="object")throw new sm({status:m.status,code:"invalid_response",message:`The gateway answered ${o} ${l} with a body that is not a JSON object.`});return v}return{listAutomations:(o={})=>s("GET",`${vu}${yu({status:o.status,cursor:o.cursor,limit:o.limit})}`),getAutomation:o=>s("GET",n(o)),createAutomation:o=>s("POST",vu,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${yu({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${yu({cursor:l.cursor,limit:l.limit})}`),listTriggerSources:()=>s("GET",x0),getMyEmail:()=>s("GET",k0),listTriggerConnections:()=>s("GET",S0),listMailboxes:()=>s("GET",j0),previewSchedule:o=>s("POST",N0,{trigger:o})}}function A0(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 $0(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 R0(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 ud(e){return e.flow_id==="@default"?"@default":`${"bundle_ref"in e?e.bundle_ref:""}:${e.flow_id}`}const M0={recipients_list:"Me and these addresses"},L0={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."},dv={email:M0,schedule:L0},qo={manual:"By hand",schedule:"On a schedule",something:"When something arrives",main_mailbox:"your main mailbox"};function fv(e){const t=String(e||"");return t.startsWith("feed")?"feed":t.startsWith("webhook")?"webhook":"other"}function I0(e,t){const n=fv(t);return n==="feed"?`When ${e} has a new item`:n==="webhook"?`When ${e} is called`:`When ${e} sends something`}function hv(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 P0(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"?qo.main_mailbox:s}function O0(e,t){const n=hv(e);return n?[].find(s=>s.connection_id===n)??null:null}function D0(e,t,n,s){var d;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():qo.schedule}if(l==="manual")return qo.manual;if(l.startsWith("email"))return`When mail arrives in ${P0((d=e.config)==null?void 0:d.account,n)}`;if(hv(e)){const f=O0(e),m=fv(l),g=(f==null?void 0:f.label)||(m==="feed"?"a feed":m==="webhook"?"a webhook":"a connection");return I0(g,l)}return qo.something}const F0=/^([1-9][0-9]*)([smhd])$/,B0={s:["second","seconds"],m:["minute","minutes"],h:["hour","hours"],d:["day","days"]};function Od(e){if(typeof e!="string")return null;const t=F0.exec(e);return t?{amount:Number(t[1]),unit:t[2]}:null}function z0(e){const t=Od(e);if(!t)return`every ${e}`;const[n,s]=B0[t.unit];return t.amount===1?`every ${n}`:`every ${t.amount} ${s}`}const U0=dv.email,W0="email.received",V0=1,q0=60,am=50;function pv(e){return!!e&&e.source_id===W0&&e.source_version===V0}function H0(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 G0=/[\s<>,;:"()[\]]/;function K0(e){const t=e.trim().toLowerCase(),n=t.indexOf("@");return n<=0||n===t.length-1?!1:!t.slice(n+1).includes("@")&&!G0.test(t)}function J0(e){const t=Od(e);return t?t.amount*{s:1,m:60,h:3600,d:86400}[t.unit]:null}const wu={mode:"self",addresses:""};function im(e){if(e.mode==="self")return{recipients:["self"],errors:[]};const t=[],n=H0(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=>!K0(o));return s.length&&t.push(`${U0.recipients_list}: ${s.join(", ")} ${s.length===1?"is not an email address":"are not email addresses"}.`),n.length+1>am&&t.push(`At most ${am-1} addresses.`),{recipients:["self",...n],errors:t}}function Y0(e){const t=(e??[]).filter(n=>n!=="self");return t.length?{mode:"list",addresses:t.join(", ")}:{mode:"self",addresses:""}}function Q0(e,t=["self"]){return{channels:e?["console","email"]:["console"],...t.some(n=>n!=="self")?{recipients:t}:{}}}function X0(e){return!!e&&Array.isArray(e.channels)&&e.channels.includes("email")}const Z0=new Set(["running","waiting","backoff"]);function ek(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 Dd(e){return[...e].sort((t,n)=>t.index-n.index).map(t=>{const n=ek(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:!Z0.has(t.status)}})}const tk={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 nk(e){return{title:tk[e.code]??`The gateway refused the request (${e.code}).`,detail:e.message}}function Xs(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 mv(e,t){var l,u,d;const n=e.trigger,s=n.source_id==="schedule"||pv(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:lk(n)?dk(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??gv),prompt:typeof o=="string"?o:null,toolApproval:t?t.policy.tool_approval:null,tools:A0(t==null?void 0:t.target.input_data),notifyEmail:t?X0(t.notify):null,emailRecipients:t?Y0((d=t.notify)==null?void 0:d.recipients):null}}function rk(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=mv(e,n);if(t.every!==u.every&&t.every!==null){const m=pv(e.trigger);if(!Od(t.every))s.push("Interval must be a whole number of minutes, hours or days.");else if(m&&(J0(t.every)??0)<q0)s.push("The check interval is at least 60 seconds.");else{const g={...e.trigger.config,every:t.every};m&&delete g.start_at,o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:g}}}if(t.calendar&&u.calendar&&JSON.stringify(t.calendar)!==JSON.stringify(u.calendar)){const m=uk(t.calendar);if(!m.config)s.push(...m.errors);else{const g=e.trigger.config,v={...m.config,...typeof g.time_zone=="string"?{time_zone:g.time_zone}:{},...typeof g.count=="number"?{count:g.count}:{},...typeof g.until=="string"?{until:g.until}:{}};o.trigger={source_id:e.trigger.source_id,source_version:e.trigger.source_version,config:v}}}const d=t.context==="growing"?t.growingMaxTokens??u.growingMaxTokens:u.growingMaxTokens;if(ak(d)||s.push(sk),(t.context!==e.context_mode||d!==u.growingMaxTokens)&&(o.context=ik(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:$0(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=im(t.notifyEmail?t.emailRecipients??wu:u.emailRecipients??wu),g=im(u.emailRecipients??wu).recipients;m.errors.length?s.push(...m.errors):(t.notifyEmail!==u.notifyEmail||JSON.stringify(m.recipients)!==JSON.stringify(g))&&(o.notify=Q0(t.notifyEmail,m.recipients))}if(s.length)return{errors:s};if(n&&t.target&&ud(t.target)!==ud(n.target)){const m=((f=o.target)==null?void 0:f.input_data)||n.target.input_data;o.target={...t.target,input_data:R0(m)}}return Object.keys(o).length?o:null}const gv=5e4,sk="Max growing context must be a positive whole number of tokens.";function ak(e){return Number.isSafeInteger(e)&&e>0}function ik(e,t){return{mode:e,...t!==gv?{growing:{max_tokens:t}}:{}}}const _u=dv.schedule,vv=["mon","tue","wed","thu","fri","sat","sun"],ok=2;function lk(e){return e.source_id==="schedule"&&e.source_version===ok}const ck=/^([01][0-9]|2[0-3]):[0-5][0-9]$/;function uk(e){const t=[];if(ck.test(e.at)||t.push(_u.error_at),e.kind==="weekly"){const n=vv.filter(s=>e.days.includes(s));return n.length||t.push(_u.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(_u.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 dk(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)?vv.filter(s=>t.days.includes(s)):[]}:t.kind==="monthly"?{kind:"monthly",at:n,day:t.day==="last"?"last":Number(t.day)}:null}function dd(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}const fk={"us-en":"US English","uk-en":"UK English","wt-wt":"any region","fr-fr":"French (France)","de-de":"German (Germany)","es-es":"Spanish (Spain)","it-it":"Italian (Italy)","ca-en":"Canadian English","au-en":"Australian English","in-en":"Indian English"},hk={d:"past day",w:"past week",m:"past month",y:"past year"};function Mt(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function om(e){let t=!0;return e.replace(/"/g,()=>{const n=t?"“":"”";return t=!t,n})}function bu(e){const t=Mt(e);let n="",s="";try{const l=new URL(t);n=l.host.replace(/^www\./,""),s=l.pathname.replace(/\/+$/,"")}catch{return t}const o=s.split("/").filter(Boolean);return o.length<=2?o.length?`${n}/${o.join("/")}`:n:`${n}/${o[0]}/…/${o[o.length-1]}`}function nl(e){const t=e.replace(/[_-]+/g," ").trim();return t?t[0].toUpperCase()+t.slice(1):e}function rl(e){return e===!0?"yes":e===!1?"no":e==null?"none":Array.isArray(e)?e.map(rl).join(", "):typeof e=="object"?Object.entries(e).map(([t,n])=>`${nl(t).toLowerCase()} ${rl(n)}`).join(", "):String(e)}function lm(e){const t=[],n=e.num_results??e.max_results??e.limit;typeof n=="number"&&t.push(`${n} ${n===1?"result":"results"}`);const s=Mt(e.region).toLowerCase();s&&t.push(fk[s]??s);const o=Mt(e.time_range).toLowerCase();o&&t.push(hk[o]??o);const l=Mt(e.safe_search).toLowerCase();return l&&t.push(l==="off"?"safe search off":`${l} safe search`),t}function cm(e){const t=[];return e.include_full_content===!1&&t.push("summary only"),e.include_full_content===!0&&t.push("full content"),e.keep_links===!1&&t.push("without links"),e.keep_links===!0&&t.push("with links"),t}const pk={fetch_url:{verb:"Fetch",lead:"the page",key:e=>bu(Mt(e.url)),details:cm,noun:["page fetch","page fetches"]},skim_url:{verb:"Skim",lead:"the page",key:e=>bu(Mt(e.url)),details:cm,noun:["page skim","page skims"]},web_search:{verb:"Search",lead:"the web for",key:e=>om(Mt(e.query)),details:lm,noun:["web search","web searches"]},skim_websearch:{verb:"Search",lead:"the web for",key:e=>om(Mt(e.query)),details:lm,noun:["web search","web searches"]},read_file:{verb:"Read",lead:"the file",key:e=>Mt(e.file_path??e.path),details:()=>[],noun:["file read","file reads"]},write_file:{verb:"Write",lead:"the file",key:e=>Mt(e.file_path??e.path),details:()=>[],noun:["file write","file writes"]},edit_file:{verb:"Edit",lead:"the file",key:e=>Mt(e.file_path??e.path),details:()=>[],noun:["file edit","file edits"]},list_files:{verb:"List",lead:"the folder",key:e=>Mt(e.directory_path??e.path)||"the workspace",details:()=>[],noun:["folder listing","folder listings"]},execute_command:{verb:"Run",lead:"the command",key:e=>Mt(e.command),details:()=>[],noun:["command","commands"]},send_email:{verb:"Email",lead:"",key:e=>rl(e.to),details:e=>Mt(e.subject)?[`subject “${Mt(e.subject)}”`]:[],noun:["email","emails"]},browser_probe:{verb:"Check",lead:"the page renders",key:e=>bu(Mt(e.target))||Mt(e.target),details:()=>[],noun:["page check","page checks"]}};function Fd(e){const t=Mt(e.name)||"tool",n=e.arguments&&typeof e.arguments=="object"?e.arguments:{},s=pk[t];if(!s){const d=Object.entries(n).map(([m,g])=>({label:nl(m),value:rl(g)})),f=nl(t.includes("::")&&t.split("::").pop()||t);return{verb:f,lead:"",key:"",details:[],sentence:f,fallback:d,noun:[f.toLowerCase(),`${f.toLowerCase()} calls`]}}const o=s.key(n),l=s.details(n),u=[s.verb,s.lead,o].filter(Boolean).join(" ");return{verb:s.verb,lead:s.lead,key:o,details:l,sentence:l.length?`${u} (${l.join(", ")})`:u,fallback:null,noun:s.noun}}function mk(e){const t=Fd(e);if(t.fallback)return t.fallback.length?t.fallback.map(s=>`${s.label}: ${s.value}`).join(" · "):"no arguments";const n=[t.lead,t.key].filter(Boolean).join(" ");return t.details.length?`${n} (${t.details.join(", ")})`:n}function gk(e){const t=e.calls||[];return a.jsxs("div",{className:`af-toolwords${e.className?` ${e.className}`:""}`,children:[e.heading?a.jsx("p",{className:"af-toolwords__heading",id:e.headingId,children:a.jsx("strong",{children:e.heading})}):null,a.jsx("ul",{className:"af-toolwords__list","aria-label":e.label??"Tool calls",children:t.map((n,s)=>{const o=Fd(n),l=mk(n);return a.jsxs("li",{className:"af-toolwords__call","data-tool":n.name,title:`${o.verb} ${l}`,children:[a.jsx("span",{className:"af-toolwords__verb",title:n.name,children:o.verb})," ",a.jsx("span",{className:"af-toolwords__text",children:l})]},`${n.name}:${s}`)})})]})}const yv="@default",wv="No workflows available for this app — ask your admin.",_v={shared:"Shared",mine:"Mine"};class Tr extends Error{constructor(t){super(t),this.name="WorkflowPickerContractError"}}function vk(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 yk(e={}){return e.allVersions?"bundles?all_versions=true":"bundles"}function wk(e,t={}){return e===null?yk(t):vk(e,t)}function yn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function St(e){return typeof e=="string"?e.trim():""}const jo="update the gateway";function _k(e,t){var d,f;const n=yn(e.default_agent_workflows);if(!n)return{status:"unavailable",reason:"the gateway does not report a default workflow"};const s=yn(n[t]);if(!s)return{status:"unavailable",reason:St((f=yn((d=yn(e.default_agent_workflows_unavailable))==null?void 0:d[t]))==null?void 0:f.reason)||`no default workflow for ${t}`};const o=St(s.bundle_id),l=St(s.flow_id);if(!o||!l)return{status:"unavailable",reason:"the gateway's default workflow is missing its bundle or flow"};const u=St(s.bundle_version);return{status:"ok",name:St(s.name)||l,bundleId:o,bundleVersion:u,flowId:l,workflowId:St(s.workflow_id)||`${o}${u?`@${u}`:""}:${l}`}}function bk(e,t,n={}){var d,f;const s=yn(e);if(!s)throw new Tr("The gateway's workflow list is not a JSON object.");const o=St(s.executable_for);if(t===null){if(o)throw new Tr(`Asked for every workflow, the gateway listed only ${o}.`)}else if(o!==t)throw new Tr(o?`The gateway listed workflows for ${o}, not ${t}.`:`This gateway does not filter workflows per app (no executable_for in its answer): ${jo}.`);if(!Array.isArray(s.items))throw new Tr("The gateway's workflow list has no items.");const l=[];for(const m of s.items){const g=yn(m),v=St(g==null?void 0:g.bundle_id);if(!g||!v)throw new Tr("The gateway listed a workflow without a bundle id.");const w=yn(g.owner),x=St(w==null?void 0:w.kind);if(x!=="gateway"&&x!=="user")throw new Tr(`The gateway did not say who owns ${v} (owner missing): ${jo}.`);if(typeof g.shipped!="boolean")throw new Tr(`The gateway did not say whether ${v} ships with it (shipped missing): ${jo}.`);const j=St(g.bundle_version),b=Array.isArray(g.entrypoints)?g.entrypoints:[];for(const k of b){const $=yn(k),S=St($==null?void 0:$.flow_id);if(!$||!S)continue;const N=Array.isArray($.interfaces)?$.interfaces.map(St).filter(Boolean):[],C=Nk((d=yn(g.automation_defaults))==null?void 0:d[S]),R=$.triggerable===!0||!!C;if(t===null){if(!N.length&&!R)continue}else if(!N.includes(t))throw new Tr(`The gateway offered ${v}:${S}, which does not declare ${t}: ${jo}.`);l.push({value:St($.workflow_id)||`${v}${j?`@${j}`:""}:${S}`,bundleId:v,bundleVersion:j,flowId:S,name:St($.name)||St((f=yn(g.metadata))==null?void 0:f.name)||v,description:St($.description)||St(g.description),registryScope:St(g.registry_scope)||"private",group:x==="user"?"mine":"shared",shipped:g.shipped,interfaces:N,...t===null?{showInterfaces:!0}:{},...C?{automationTrigger:C}:{},...R?{triggerable:!0}:{}})}}const u=n.defaultInterface??t;return{interfaceId:t,entries:l,gatewayDefault:u?_k(s,u):{status:"unavailable",reason:"no interface named for the gateway default"}}}function xk(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:_v[n],entries:e.filter(s=>s.group===n).sort(t)})).filter(n=>n.entries.length>0)}const kk={"abstractcode.agent.v1":"Code agent","abstractassistant.agent.v1":"Assistant","abstractcode.coding.v1":"Coding",tools:"tools",event:"event",chat:"chat"};function jk(e){return kk[e]??e}function Sk(e,t=[]){const n=e.bundleVersion?`@${e.bundleVersion}`:"";return e.showInterfaces?!e.interfaces.length&&e.automationTrigger?[D0(e.automationTrigger),n].filter(Boolean).join(" · "):[[...new Set(e.interfaces.map(jk))].join(", "),n].filter(Boolean).join(" · "):n}function Nk(e){var l;const t=yn((l=yn(e))==null?void 0:l.trigger),n=St(t==null?void 0:t.source_id);if(!t||!n||typeof t.source_version!="number")return;const s=yn(t.config)??{},o=St(t.connection_id);return{source_id:n,source_version:t.source_version,config:s,...o?{connection_id:o}:{}}}function Ck(e){return e.value}function Ek(e){return e?e.status==="unavailable"?e.reason:`${e.name}${e.bundleVersion?` @${e.bundleVersion}`:""}`:""}function Tk(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 Ak(e,t=!0){const n=(e==null?void 0:e.entries)??[],s=[];t&&s.push({key:"default",value:yv,name:"Gateway default",detail:Ek((e==null?void 0:e.gatewayDefault)??null),group:null,entry:null});for(const o of xk(n))for(const l of o.entries)s.push({key:l.value,value:l.value,name:l.name,detail:Sk(l,n),title:Ck(l),group:o.id,entry:l});return s}async function $k(e,t,n){var l;const s=await fetch(Md(e,ut(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 Rk(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 Mk(e){const{interfaceId:t,defaultInterface:n,allVersions:s=!1,enabled:o=!0,gatewayBaseUrl:l,reloadKey:u}=e,d=p.useRef(e.request);d.current=e.request;const[f,m]=p.useState(0),[g,v]=p.useState({status:"idle",data:null,error:""});p.useEffect(()=>{if(!o){v({status:"idle",data:null,error:""});return}const x=new AbortController;v(k=>({...k,status:"loading",error:""}));const j=wk(t,{allVersions:s});return(d.current?d.current(j,{signal:x.signal}):$k(l,j,x.signal)).then(k=>{x.signal.aborted||v({status:"ready",data:bk(k,t,{defaultInterface:n}),error:""})}).catch(k=>{x.signal.aborted||v({status:"error",data:null,error:Rk(k)})}),()=>x.abort()},[t,n,s,o,l,u,f]);const w=p.useCallback(()=>m(x=>x+1),[]);return{...g,reload:w}}function Lk(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 bv(...e){return e.filter(Boolean).join(" ")}function Ik(e){const t=Mk({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=p.useId().replace(/:/g,""),l=`${o}-list`,[u,d]=p.useState(!1),[f,m]=p.useState(-1),g=p.useRef(null),v=p.useRef(null),[w,x]=p.useState({}),j=e.entryDetail,b=p.useMemo(()=>Ak(n.data,s).map(L=>{const D=L.entry&&j?j(L.entry):null;return D?{...L,detail:D}:L}),[n.data,s,j]),k=b.find(L=>L.value===e.value),$=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===yv?"Gateway default":"Choose a flow",detail:""},S=String(e.unavailableReason||"").trim(),N=!S&&n.status==="ready",C=p.useCallback(()=>{d(!1),m(-1)},[]),R=p.useCallback(()=>{if(!N)return;x(Lk(v.current)),d(!0);const L=b.findIndex(D=>D.value===e.value);m(L>=0?L:0)},[N,b,e.value]),E=p.useCallback(L=>{var D;C(),L.value!==e.value&&e.onChange(L.value,L.entry),(D=v.current)==null||D.focus()},[C,e]);p.useEffect(()=>{if(!u)return;const L=P=>{g.current&&!g.current.contains(P.target)&&C()},D=()=>C();return document.addEventListener("mousedown",L),document.addEventListener("touchstart",L),window.addEventListener("resize",D),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("touchstart",L),window.removeEventListener("resize",D)}},[u,C]),p.useEffect(()=>{var D;if(!u||f<0)return;const L=typeof document<"u"?document.getElementById(`${o}-opt-${f}`):null;(D=L==null?void 0:L.scrollIntoView)==null||D.call(L,{block:"nearest"})},[u,f,o]);const I=L=>{if(!u){["Enter"," ","ArrowDown","ArrowUp"].includes(L.key)&&(L.preventDefault(),R());return}if(L.key==="Escape"){L.preventDefault(),C();return}if(L.key==="Tab"){C();return}if(L.key==="Enter"||L.key===" "){L.preventDefault(),f>=0&&b[f]&&E(b[f]);return}const D=Tk(L.key,f,b.length);D!==null&&(L.preventDefault(),m(D))};return a.jsxs("div",{ref:g,className:bv("af-workflow-picker",e.className),"data-interface":e.interfaceId??"any",children:[a.jsxs("button",{ref:v,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":N?void 0:!0,title:S||void 0,onClick:()=>u?C():R(),onKeyDown:I,children:[a.jsxs("span",{className:"af-workflow-picker__value",id:`${o}-value`,children:[a.jsx("span",{className:"af-workflow-picker__name",children:$.name}),$.detail?a.jsx("span",{className:"af-workflow-picker__detail",children:$.detail}):null]}),a.jsx("span",{className:"af-workflow-picker__caret","aria-hidden":"true"})]}),u?a.jsx(Pk,{id:l,idBase:o,rows:b,value:e.value,highlight:f,ariaLabel:e.ariaLabel||"Workflow",style:w,onHighlight:m,onChoose:E}):null,n.status==="error"?a.jsx("span",{className:"af-workflow-picker__error",role:"alert",children:n.error}):n.status==="ready"&&b.every(L=>!L.entry)&&!s?a.jsx("span",{className:"af-workflow-picker__empty",role:"status",children:wv}):null]})}function Pk(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:bv("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:_v[l]}),u.map(d=>t(d.row,d.index))]},l)),o.length===0?a.jsx("p",{className:"af-workflow-picker__empty",children:wv}):null]})}function Ok(e){const t=ud(e.target);return a.jsxs("div",{className:"af-auto__field",children:[a.jsx("span",{children:"Flow"}),a.jsx(Ik,{...e.options,ariaLabel:"Automation flow",value:t,currentLabel:{name:Dk(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 Dk(e,t){var f,m,g;const n=((m=(f=t.workflows)==null?void 0:f.data)==null?void 0:m.entries)??[],s=n.find(v=>v.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((g=n.find(v=>v.bundleId===u&&(!d||v.flowId===d)))==null?void 0:g.name)||u||e}async function Fk(e,t){var w,x;const n=e.flow_id==="@default"?(x=(w=t.workflows)==null?void 0:w.data)==null?void 0:x.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 g={...f.defaults||{}};for(const[j,b]of Object.entries(m.properties))b&&"default"in b&&(g[j]=b.default);Object.assign(g,e.input_data||{});const v=(Array.isArray(m.required)?m.required:[]).filter(j=>g[j]===void 0);if(v.length)throw new Error(`This workflow needs additional inputs: ${v.join(", ")}. Configure a new automation from that workflow's input form, or choose a compatible workflow.`);return{...e,input_data:g}}const en={min:300,max:960,default:420,step:16,bigStep:64};function sl(e,t=en.min,n=en.max,s=en.default){return Number.isFinite(e)?Math.round(Math.min(n,Math.max(t,e))):Math.min(n,Math.max(t,s))}function Bk(e,t,n,s=en.min,o=en.max,l="right"){const u=n?en.bigStep:en.step,d=l==="left"?"ArrowRight":"ArrowLeft",f=l==="left"?"ArrowLeft":"ArrowRight";return t===d?sl(e+u,s,o):t===f?sl(e-u,s,o):t==="Home"?s:t==="End"?o:null}function zk(e,t,n,s=en.min,o=en.max){return sl(n==="left"?e+t:e-t,s,o)}function Uk(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 Wk(e,t){return e===t?null:t}function ti(e){return e.side==="left"?"left":"right"}function um(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&&ti(o)===t?s:null}function Vk(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 qk(e,t,n){return e.id===t||e.keepAlive==="always"||n.has(e.id)}function Hk(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 Gk(e){return JSON.stringify({v:1,widths:e.widths,active:e.active,...e.legacyWidth!==void 0?{legacy:e.legacyWidth}:{}})}function dm(e,t,n){const s=t.minWidth??(n==null?void 0:n.min)??en.min,o=t.maxWidth??(n==null?void 0:n.max)??en.max,l=t.defaultWidth??(n==null?void 0:n.width)??en.default,u=e.widths[t.id]??e.legacyWidth;return sl(u??l,s,o,l)}function Kk(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&&ti(l)===t?o:null}function Jk(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 xv=p.createContext(void 0);function Yk(e){const t=p.useContext(xv);return t===void 0?a.jsx(a.Fragment,{children:e.children}):t===null?null:oi.createPortal(e.children,t)}class fm extends it.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(be,{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 Qk(e){if(!e||typeof window>"u")return{widths:{},active:{}};try{return Hk(window.localStorage.getItem(e))}catch{return{widths:{},active:{}}}}function hm(e,t){if(!(!e||typeof window>"u"))try{window.localStorage.setItem(e,Gk(t))}catch{}}function Xk(e){const{panel:t}=e,[n,s]=p.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(fm,{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(be,{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(xv.Provider,{value:n,children:t.errorBoundary===!1?o:a.jsx(fm,{label:t.label,children:o})})})]})}function Zk(e){const{side:t,panels:n,activeId:s,overlay:o,onActiveChange:l}=e,u=n.find(z=>z.id===s)||null,d=n.filter(z=>z.mode!=="drawer"),[f,m]=p.useState(()=>new Set(s?[s]:[])),g=p.useRef(null),v=p.useRef(null),w=p.useRef(null),x=p.useRef(null),j=u?e.width(u):en.default,b=p.useRef(j);b.current=j;const k=(u==null?void 0:u.minWidth)??en.min,$=(u==null?void 0:u.maxWidth)??en.max;p.useEffect(()=>{s&&m(z=>z.has(s)?z:new Set([...z,s]))},[s]);const S=u?u.id:null,N=p.useRef(l);N.current=l,p.useEffect(()=>{if(!o||!S)return;const z=T=>{T.key!=="Escape"||T.defaultPrevented||(T.preventDefault(),N.current(null))};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[o,S]),p.useEffect(()=>{var z,T,q;if(o)if(S)!w.current&&typeof document<"u"&&(w.current=document.activeElement),(z=v.current)==null||z.focus({preventScroll:!0});else{const J=w.current;w.current=null;const B=typeof document<"u"?document.activeElement:null;J&&(!B||B===document.body||(T=v.current)!=null&&T.contains(B))&&((q=J.focus)==null||q.call(J))}},[o,S]);const C=z=>{var B,O;const T=Array.from(((B=g.current)==null?void 0:B.querySelectorAll('[role="tab"]'))||[]),q=T.findIndex(Z=>Z===document.activeElement),J=Uk(T.length,q<0?0:q,z.key);J!==null&&(z.preventDefault(),(O=T[J])==null||O.focus())},R=z=>{if(!u)return;const T=Bk(b.current,z.key,z.shiftKey,k,$,t);T!==null&&(z.preventDefault(),e.setWidth(u,T,!0))},E=z=>{var T,q;z.button!==0&&z.pointerType==="mouse"||(x.current={startX:z.clientX,startW:b.current,pointerId:z.pointerId},(q=(T=z.currentTarget).setPointerCapture)==null||q.call(T,z.pointerId),z.preventDefault())},I=z=>{const T=x.current;!T||T.pointerId!==z.pointerId||!u||e.setWidth(u,zk(T.startW,z.clientX-T.startX,t,k,$),!1)},L=z=>{var q,J;const T=x.current;!T||T.pointerId!==z.pointerId||(x.current=null,(J=(q=z.currentTarget).releasePointerCapture)==null||J.call(q,z.pointerId),u&&e.setWidth(u,b.current,!0))},D=!!u,P=e.railLabelStyle==="vertical-text",K=o&&e.top!==void 0,se={"--af-rail-panel-width":`${j}px`,"--af-panel-w":`${j}px`,...e.top!==void 0?{"--af-drawers-top":e.top}:{}},Q=d.length>0?a.jsx("div",{ref:g,className:"af-rail__rail",role:"tablist","aria-orientation":"vertical","aria-label":e.ariaLabel,onKeyDown:C,children:d.map(z=>{const T=z.id===s,q=`${T?`Collapse ${z.label}`:z.label}${z.hint?` · ${z.hint}`:""}`;return a.jsxs("button",{type:"button",role:"tab",id:`${e.idBase}-tab-${z.id}`,"aria-selected":T,"aria-controls":`${e.idBase}-panel-${z.id}`,"aria-label":z.label,title:q,className:`af-rail__tab${P?" af-rail__tab--text":""}${T?" is-active":""}`,"data-rail":z.id,onClick:J=>{w.current=J.currentTarget,l(Wk(s,z.id))},children:[P?a.jsx("span",{className:"af-rail__vlabel","aria-hidden":"true",children:z.label}):a.jsx(be,{name:z.icon,size:19}),typeof z.badge=="number"&&z.badge>0?a.jsx("span",{className:"af-rail__badge","aria-hidden":"true",children:z.badge>99?"99+":z.badge}):z.badge===!0?a.jsx("span",{className:"af-rail__dot","aria-hidden":"true"}):null]},z.id)})}):null;return a.jsxs("div",{className:`af-rail${t==="left"?" af-rail--left":""}${D?" af-rail--open":" af-rail--collapsed"}${o?" af-rail--overlay":" af-rail--docked"}${K?" af-rail--anchored":""}${Q?"":" af-rail--no-rail"}${P?" af-rail--vertical-text":""}${e.className?` ${e.className}`:""}`,style:se,"data-active":s||"","data-side":t,children:[t==="left"?Q:null,o&&D?a.jsx("div",{className:"af-rail__backdrop","aria-hidden":"true",onClick:()=>l(null)}):null,a.jsxs("div",{className:"af-rail__panel-wrap",hidden:!D,style:!o&&D?{width:j}:void 0,children:[!o&&D?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":$,"aria-valuenow":j,tabIndex:0,title:"Drag to resize",onKeyDown:R,onPointerDown:E,onPointerMove:I,onPointerUp:L,onPointerCancel:L}):null,a.jsx("div",{ref:v,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(z=>a.jsx(Xk,{panel:z,idBase:e.idBase,open:z.id===s,mounted:qk(z,s,f),overlay:o,side:t,onCollapse:()=>l(null)},z.id))})]}),t==="right"?Q:null]})}function e1(e){const t=Fg(e.overlayBelow||Dg.md),n=e.overlay??t,s=e.idBase||"af-rail",{panels:o,onActiveChange:l,storageKey:u}=e,[d,f]=p.useState(()=>Qk(u)),m=p.useRef(d),g=p.useRef(e.onResize);g.current=e.onResize;const v=o.filter(E=>ti(E)==="left"),w=o.filter(E=>ti(E)==="right"),x=um(e.active,"left",o),j=um(e.active,"right",o),b=p.useCallback(E=>dm(d,E),[d]),k=p.useCallback((E,I,L)=>{var P;const D={...m.current,widths:{...m.current.widths,[E.id]:dm({widths:{[E.id]:I}},E)}};m.current=D,f(D),L&&(hm(u,D),(P=g.current)==null||P.call(g,E.id,D.widths[E.id]))},[u]),$=p.useRef(!1);p.useEffect(()=>{if(!$.current&&($.current=!0,e.restoreActive!==!1))for(const E of["left","right"]){const I=E==="left"?x:j,L=Kk(m.current,E,n,o);!I&&L&&l(L,E)}},[]);const S=p.useRef(!1);p.useEffect(()=>{if(!S.current){S.current=!0;return}if(n||!u)return;const E={...m.current,active:{left:x,right:j}};m.current=E,hm(u,E)},[x,j,n,u]),p.useEffect(()=>{const E=Vk(e.request);if(!E)return;const I=o.find(D=>D.id===E.id);if(!I)return;const L=ti(I);(L==="left"?x:j)!==E.id&&l(E.id,L)},[e.request]);const N=n?Jk(e.topOffset):void 0,C=e.railLabelStyle||"icon",R=(E,I,L)=>I.length?a.jsx(Zk,{side:E,panels:I,activeId:L,onActiveChange:D=>l(D,E),overlay:n,width:b,setWidth:k,ariaLabel:v.length&&w.length?`${e.ariaLabel} (${E})`:e.ariaLabel,idBase:s,railLabelStyle:C,top:N,className:e.children===void 0?e.className:void 0}):null;return e.children===void 0&&!v.length?R("right",w,j)||a.jsx(a.Fragment,{}):a.jsxs("div",{className:`af-drawers${n?" af-drawers--overlay":""}${e.className?` ${e.className}`:""}`,children:[R("left",v,x),a.jsx("div",{className:"af-drawers__main",children:e.children}),R("right",w,j)]})}const kv=72;function t1(e,t=kv){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 g=0;for(let v=f;v<m&&v<o;v+=1){const w=Math.abs(Number(e[v])||0);w>g&&(g=w)}s[d]=g,g>u&&(u=g)}return u<=0?s:s.map(d=>d/u)}function So(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 n1(e,t,n){return!(t>0)||!(n>0)?0:Math.min(n,Math.max(0,e/t*n))}function r1(e,t){const[n,s]=p.useState({peaks:t??null,note:""});return p.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:t1(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 Bd(e){const t=p.useRef(null),n=p.useRef(null),[s,o]=p.useState(!1),[l,u]=p.useState(0),[d,f]=p.useState(null),[m,g]=p.useState(""),{peaks:v,note:w}=r1(e.src,e.peaks),x=v??new Array(kv).fill(0),j=d&&d>0?Math.min(1,l/d):0,b=e.name?`Audio ${e.name}`:"Audio",k=p.useCallback(()=>{const C=t.current;C&&(C.paused?C.play().catch(R=>g(R instanceof Error?R.message:String(R))):C.pause())},[]),$=p.useCallback(C=>{const R=t.current;!R||!Number.isFinite(C)||(R.currentTime=C,u(C))},[]),S=C=>{var E;const R=(E=n.current)==null?void 0:E.getBoundingClientRect();!R||!d||$(n1(C-R.left,R.width,d))},N=C=>{if(!d)return;const R=C.key==="ArrowRight"||C.key==="ArrowUp"?5:C.key==="ArrowLeft"||C.key==="ArrowDown"?-5:0;R?(C.preventDefault(),$(Math.min(d,Math.max(0,l+R)))):C.key==="Home"?(C.preventDefault(),$(0)):C.key==="End"?(C.preventDefault(),$(d)):(C.key===" "||C.key==="Enter")&&(C.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:C=>u(C.currentTarget.currentTime),onLoadedMetadata:C=>f(Number.isFinite(C.currentTarget.duration)?C.currentTarget.duration:null),onDurationChange:C=>f(Number.isFinite(C.currentTarget.duration)?C.currentTarget.duration:null),onError:()=>g("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 ${b}`:`Play ${b}`,title:s?"Pause":"Play",onClick:k,children:a.jsx(be,{name:s?"pause":"play",size:16})}),a.jsx("div",{ref:n,className:"af-audio__wave",role:"slider",tabIndex:0,"aria-label":`Seek in ${b}`,"aria-valuemin":0,"aria-valuemax":Math.round(d??0),"aria-valuenow":Math.round(l),"aria-valuetext":`${So(l)} of ${So(d)}`,title:w||void 0,"data-waveform":v?"decoded":"flat",onKeyDown:N,onPointerDown:C=>{var R,E;(E=(R=C.currentTarget).setPointerCapture)==null||E.call(R,C.pointerId),S(C.clientX)},onPointerMove:C=>{C.buttons&1&&S(C.clientX)},children:a.jsx("svg",{viewBox:`0 0 ${x.length*2} 32`,preserveAspectRatio:"none","aria-hidden":"true",focusable:"false",children:x.map((C,R)=>{const E=Math.max(1.5,C*30),I=(R+.5)/x.length<=j;return a.jsx("rect",{className:I?"af-audio__bar af-audio__bar--played":"af-audio__bar",x:R*2+.3,y:16-E/2,width:1.4,height:E,rx:.6},R)})})}),a.jsxs("span",{className:"af-audio__time","aria-hidden":"true",children:[So(l)," / ",So(d)]}),m?a.jsx("p",{className:"af-audio__error",role:"alert",children:m}):null]})}const ms=e=>new Set(e.split(/\s+/).filter(Boolean)),s1=ms("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"),a1=ms("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"),i1=ms("if then else elif fi for while do done case esac in function return export local readonly set unset echo exit source"),o1=ms("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"),pm=ms("true false null yes no on off"),l1={c:{line:["//"],block:["/*","*/"],strings:['"',"'","`"],keywords:s1},python:{line:["#"],strings:['"',"'"],triple:!0,keywords:a1},shell:{line:["#"],strings:['"',"'"],keywords:i1},sql:{line:["--"],block:["/*","*/"],strings:["'",'"'],keywords:o1},data:{line:["#"],strings:['"',"'"],keywords:pm},json:{line:[],strings:['"'],keywords:pm},css:{line:[],block:["/*","*/"],strings:['"',"'"],keywords:ms("")},markup:{line:[],block:["<!--","-->"],strings:['"',"'"],keywords:ms("")}},c1={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 yl(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 c1[o]||""}const u1=e=>e>="0"&&e<="9",d1=e=>/[A-Za-z_$]/.test(e),mm=e=>/[A-Za-z0-9_$]/.test(e);function zd(e,t){const n=String(e??""),s=l1[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(g=>n.startsWith(g,d))){const g=n.indexOf(`
45
+ `,d),v=g===-1?n.length:g;u("comment",n.slice(d,v)),d=v;continue}if(s.block&&n.startsWith(s.block[0],d)){const g=n.indexOf(s.block[1],d+s.block[0].length),v=g===-1?n.length:g+s.block[1].length;u("comment",n.slice(d,v)),d=v;continue}if(s.strings.includes(f)){const g=s.triple&&n.startsWith(f.repeat(3),d)?f.repeat(3):"";if(g){const x=n.indexOf(g,d+3),j=x===-1?n.length:x+3;u("string",n.slice(d,j)),d=j;continue}let v=d+1;for(;v<n.length&&n[v]!==f&&(f==="`"||n[v]!==`
46
+ `);)v+=n[v]==="\\"?2:1;const w=Math.min(n.length,v+1);u("string",n.slice(d,w)),d=w;continue}if(u1(f)&&!(d>0&&mm(n[d-1]))){let g=d+1;for(;g<n.length&&/[0-9a-fA-FxXoObB._]/.test(n[g]);)g+=1;u("number",n.slice(d,g)),d=g;continue}if(d1(f)){let g=d+1;for(;g<n.length&&mm(n[g]);)g+=1;const v=n.slice(d,g),w=t==="sql"?s.keywords.has(v.toLowerCase()):s.keywords.has(v);u(w?"keyword":"plain",v),d=g;continue}u("plain",f),d+=1}return l&&o.push({kind:"plain",text:l}),o}function No({text:e,language:t="",lineNumbers:n=!0,className:s,ariaLabel:o}){const l=yl(t),u=zd(e,l),d=n?String(e??"").split(`
47
+ `).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?f1(u).map((f,m)=>a.jsxs("span",{className:"af-code__line","data-line":m+1,children:[f.map((g,v)=>gm(g,v)),`
48
+ `]},m)):u.map((f,m)=>gm(f,m))})})}function gm(e,t){return e.kind==="plain"?a.jsx(it.Fragment,{children:e.text},t):a.jsx("span",{className:`af-code__${e.kind}`,children:e.text},t)}function f1(e){const t=[[]];for(const n of e)n.text.split(`
49
+ `).forEach((o,l)=>{l>0&&t.push([]),o&&t[t.length-1].push({kind:n.kind,text:o})});return t}const jv=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ua=6e4,Wa=60*Ua,Co=24*Wa;function ui(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)?ui(Number(t)):Date.parse(t)}function vm(e){return e<10?`0${e}`:String(e)}function ym(e,t){const n=ui(e);if(!Number.isFinite(n))return"";const s=new Date(n),o=s.getFullYear()===new Date(t).getFullYear();return`${jv[s.getMonth()]} ${s.getDate()}${o?"":`, ${s.getFullYear()}`}`}function wl(e){const t=ui(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${jv[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${vm(n.getHours())}:${vm(n.getMinutes())}`}function Sv(e,t){const n=ui(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const s=t-n;if(s<0){const l=-s;if(l<Ua)return"due now";if(l<Wa)return`in ${Math.round(l/Ua)} min`;if(l<Co)return`in ${Math.round(l/Wa)} h`;const u=Math.round(l/Co);return u<7?`in ${u} ${u===1?"day":"days"}`:ym(n,t)}if(s<Ua)return"just now";if(s<Wa)return`${Math.floor(s/Ua)} min ago`;if(s<Co)return`${Math.floor(s/Wa)} h ago`;const o=Math.floor(s/Co);return o===1?"yesterday":o<7?`${o} days ago`:ym(n,t)}const h1=new Set("png jpg jpeg gif webp bmp ico avif".split(" ")),p1=new Set("mp3 wav ogg oga opus m4a aac flac weba".split(" ")),m1=new Set("mp4 m4v webm mov ogv mkv".split(" ")),g1=new Set("mts cts".split(" ")),v1=new Set(["video/mp2t"]),y1=new Set("txt log csv tsv rst adoc org tex diff patch lock".split(" "));function w1(e){const t=String(e||"").split("/").pop()||"",n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():t.toLowerCase()}function gs(e,t=""){const n=w1(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":h1.has(n)?"image":p1.has(n)?"audio":m1.has(n)?"video":yl(e)||g1.has(n)?"code":y1.has(n)?"text":s.startsWith("image/")&&s!=="image/svg+xml"?"image":s.startsWith("audio/")?"audio":s.startsWith("video/")&&!v1.has(s)?"video":s.startsWith("text/")?"text":["application/javascript","application/xml","application/x-yaml","application/toml"].includes(s)?"code":"binary"}function Zs(e){return e==="markdown"||e==="code"||e==="json"||e==="text"}function di(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 Nv(e){const t=e.kind??gs(e.name,e.contentType),n=di(e.sizeBytes),s=e.modified!==void 0?Sv(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(be,{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:wl(e.modified),dateTime:new Date(ui(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(be,{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(be,{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(_1,{kind:t,p:e})]})})]})}function _1({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(Ia,{});case"audio":return t.url?a.jsx(Bd,{src:t.url,name:t.name}):a.jsx(Ia,{});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(Ia,{});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(Ia,{});case"markdown":return t.renderMarkdown?a.jsx("div",{className:"af-file-viewer__markdown",children:t.renderMarkdown(n)}):a.jsx(No,{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(No,{text:s,language:"json"})]})}case"code":return a.jsx(No,{text:n,language:t.name});case"text":return a.jsx(No,{text:n,language:"",lineNumbers:!1});default:return a.jsx(Ia,{})}}function Ia(){return a.jsx("p",{className:"af-file-viewer__muted",children:"No preview for this file type. Use Download to open it."})}const _l=it.createContext(!1);function Cv({label:e,children:t}){return typeof t!="string"?a.jsx("span",{className:"af-setting-row__help",children:t}):a.jsx(za,{content:t,children:a.jsx("button",{type:"button",className:"af-settings-help","aria-label":e,children:a.jsx(be,{name:"info",size:16})})})}function Eo(e){const t=it.useContext(_l),n=p.useId(),s=`${e.id||n}-title`;return a.jsxs("section",{className:`af-settings-group${e.variant==="flat"?" af-settings-group--flat":""}${e.className?` ${e.className}`:""}`,"aria-labelledby":s,id:e.id,children:[a.jsxs("div",{className:"af-settings-group__head",children:[a.jsx("h3",{className:"af-settings-group__title",id:s,children:e.title}),t&&e.help?a.jsx(Cv,{label:`About ${e.title}`,children:e.help}):null,e.aside?a.jsx("span",{className:"af-settings-group__aside",children:e.aside}):null]}),!t&&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=it.useContext(_l),n=e.htmlFor?"label":"span";return a.jsxs("div",{className:`af-setting-row${e.stack||t?" af-setting-row--stack":""}${e.className?` ${e.className}`:""}`,"data-setting":e.setting,children:[a.jsxs("div",{className:"af-setting-row__label",children:[a.jsx(n,{className:"af-setting-row__name",...e.htmlFor?{htmlFor:e.htmlFor}:{},children:e.label}),t&&e.help?a.jsx(Cv,{label:typeof e.label=="string"?`About ${e.label}`:"More information",children:e.help}):null,!t&&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 fd(e){const t=it.useContext(_l),n=!!e.overrideSummary,s=p.useId(),o=n?`${e.overrideSummary}${!t&&e.overrideOwner?` — ${e.overrideOwner}`:""}`:`Gateway default${e.defaultSummary?` · ${e.defaultSummary}`:""}`;return t?a.jsxs("div",{className:"af-override af-override--compact","data-setting":e.setting,"data-overridden":n?"true":"false",children:[a.jsxs("button",{type:"button",className:"af-override__toggle","aria-label":`Change ${e.label}`,"aria-expanded":e.open,"aria-controls":s,disabled:e.disabled,onClick:e.onToggle,children:[a.jsx("span",{className:"af-setting-row__name",children:e.label}),a.jsx(be,{name:e.open?"chevronDown":"chevronRight",size:16}),a.jsx("span",{className:"af-override__summary",children:o})]}),n&&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,a.jsx("div",{className:"af-override__editor",id:s,hidden:!e.open,children:e.open?e.children:null})]}):a.jsxs("div",{className:"af-override","data-setting":e.setting,"data-overridden":n?"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":s,disabled:e.disabled,onClick:e.onToggle,children:e.open?"Done":"Change"}),n&&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:o,children:o})}),a.jsx("div",{className:"af-override__editor",id:s,hidden:!e.open,children:e.open?e.children:null})]})}const xu=e=>`${Math.round(e*100)} %`,b1="Safari does not let a page choose the output device: replies play on the system output (change it in the system sound settings).";function x1(e){var E,I,L;const t=!!e.unavailableReason,n=e.outputSelectable??av(),s=p.useId(),[o,l]=p.useState({devices:[],labelled:!0}),[u,d]=p.useState({text:"",tone:"info"}),f=p.useRef(!0);p.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]);const m=e.value,g=D=>e.onChange({...m,...D}),v=fs(m.reply_volume),w=m.reply_muted===!0,x=e.showMute!==!1||w,j=e.listDevices||Yg,b=p.useRef(j);b.current=j;const k=()=>{n&&b.current("audiooutput").then(D=>f.current&&l(D)).catch(()=>f.current&&l({devices:[],labelled:!1}))};p.useEffect(()=>{t||k()},[n,t,e.devicesKey]);const $=()=>{d({text:"Playing a short chime…",tone:"info"}),Xx({deviceId:n&&m.output_device||"",volume:v}).then(()=>{if(!f.current)return;const D="Chime played. Heard nothing? Pick another output or raise the volume.";d({text:w?`${D} Replies are muted: unmute them to hear them.`:D,tone:"ok"})}).catch(D=>f.current&&d({text:`The speaker test failed: ${String((D==null?void 0:D.message)||D).replace(/\.$/,"")}.`,tone:"error"}))},S=m.output_device||"",N=[{value:"",label:"System default"},...o.devices.map(D=>({value:D.id,label:D.label})),...S&&!o.devices.some(D=>D.id===S)?[{value:S,label:"Saved speaker (not connected)"}]:[]],C=((E=e.labels)==null?void 0:E.device)||"Output device",R=((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:C,setting:"output-device",help:n?void 0:b1,trailing:a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-speaker",disabled:t,onClick:$,children:((L=e.labels)==null?void 0:L.test)||"Test"}),children:a.jsx(tn,{ariaLabel:C,placeholder:"System default",value:n?S:"",options:N,disabled:t||!n,searchable:!1,onOpen:k,onChange:D=>g({output_device:D})})}),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:R,setting:"reply-volume",htmlFor:s,trailing:x?a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"mute-replies",disabled:t,onClick:()=>g({reply_muted:!w}),children:w?"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(v*100),disabled:t,"aria-valuetext":w?`Muted (${xu(v)})`:xu(v),onChange:D=>g({reply_volume:Number(D.currentTarget.value)/100})}),a.jsx("span",{className:"af-voice-range__value","data-voice-volume":w?"muted":"on",children:w?"Muted":xu(v)})]})]})}function k1(e,t="microphone"){const[n,s]=p.useState(0),o=t==="playback"?e==null?void 0:e.subscribe_playback_level:e==null?void 0:e.subscribe_level;return p.useEffect(()=>{if(!o){s(0);return}return o(l=>s(Math.min(1,Math.max(0,Number(l)||0))))},[o]),n}function Ev(e){const t=k1(e.level===void 0?e.source:null,e.channel),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||(e.channel==="playback"?"Playback level":"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 ku=e=>`${Math.round(e*100)} %`;function Ud(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)||t<=0?1:Math.min(1.5,Math.max(.5,t))}function j1(e){var K,se,Q;const t=!!e.unavailableReason,n=p.useId(),[s,o]=p.useState({devices:[],labelled:!0}),[l,u]=p.useState(""),[d,f]=p.useState({phase:"idle",message:"",tone:"info"}),[m,g]=p.useState(0),v=p.useRef(!0);p.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const w=Xg(),x=e.value,j=z=>e.onChange({...x,...z}),b=Ud(x.input_gain),k=e.listDevices||Yg,$=p.useRef(k);$.current=k;const S=()=>{$.current("audioinput").then(z=>v.current&&o(z)).catch(()=>v.current&&o({devices:[],labelled:!1}))};p.useEffect(()=>{t||S()},[t]);const N=()=>{u(""),Qx().then(()=>{var z;S(),(z=e.onDevicesChanged)==null||z.call(e)}).catch(z=>v.current&&u(tl(z)))},C=()=>{f({phase:"recording",message:"Recording 3 seconds — say something.",tone:"info"}),nv({deviceId:x.input_device||"",ms:3e3,gain:b,onLevel:z=>v.current&&g(z)}).then(async({blob:z,peak:T})=>{var q,J,B;if(v.current){if(T<tv){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 rv(z,{deviceId:((q=e.playOn)==null?void 0:q.deviceId)||"",volume:(J=e.playOn)==null?void 0:J.volume}),v.current&&(f({phase:"idle",message:`The microphone works (peak level ${ku(T)}).`,tone:"ok"}),S(),(B=e.onDevicesChanged)==null||B.call(e))}}).catch(z=>v.current&&f({phase:"idle",message:tl(z),tone:"error"}))},R=x.input_device||"",E=[{value:"",label:"System default"},...s.devices.map(z=>({value:z.id,label:z.label})),...R&&!s.devices.some(z=>z.id===R)?[{value:R,label:"Saved microphone (not connected)"}]:[]],I=d.phase!=="idle",L=d.phase==="recording",D=((K=e.labels)==null?void 0:K.device)||"Input device",P=((se=e.labels)==null?void 0:se.gain)||"Input level";return a.jsxs("div",{className:`af-voice-input${e.className?` ${e.className}`:""}`,"data-voice-input":!0,children:[a.jsx(zr,{label:D,setting:"input-device",trailing:a.jsx("button",{type:"button",className:"af-setting-btn","data-action":"test-microphone",disabled:t||I,onClick:C,children:d.phase==="recording"?"Recording…":d.phase==="playing"?"Playing…":((Q=e.labels)==null?void 0:Q.test)||"Test"}),children:a.jsx(tn,{ariaLabel:D,placeholder:"System default",value:R,options:E,disabled:t,searchable:!1,onOpen:S,onChange:z=>j({input_device:z})})}),a.jsx(Ev,{source:L?null:e.levelSource,level:L?m:e.level,origin:L?"test":"live"}),d.message?a.jsx("p",{className:`af-voice-note af-voice-note--${d.tone}`,role:"status","data-voice-note":"microphone",children:d.message}):null,!s.labelled&&!t?a.jsxs("p",{className:"af-voice-note","data-voice-note":"labels",children:["Device names appear once the microphone is allowed."," ",a.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"show-device-names",onClick:N,children:"Show names"})]}):null,l?a.jsx("p",{className:"af-voice-note af-voice-note--error",role:"status",children:l}):null,w?a.jsxs(zr,{label:P,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(b*100),disabled:t,"aria-valuetext":ku(b),onChange:z=>j({input_gain:Number(z.currentTarget.value)/100})}),a.jsx("span",{className:"af-voice-range__value",children:ku(b)})]}):null]})}function Tv(e){return{output_device_id:e.output_device||"",volume:fs(e.reply_volume),muted:e.reply_muted===!0,input_device_id:e.input_device||"",input_gain:Ud(e.input_gain),capture_mode:hs(e.capture_mode),tts_voice:Wd(e)}}const S1=["provider","model","voice","profile","speed","quality_preset","instructions"];function Wd(e){const t={};for(const n of S1){const s=e[n];s!==void 0&&s!==""&&s!==null&&(t[n]=s)}return t}function N1(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 C1=[{value:"",label:"Detect automatically"},...Object.keys(ov).map(e=>({value:e,label:ps(e)}))],E1=[{value:"hold",label:"Hold to talk"},{value:"toggle",label:"Tap to talk"}];function T1(e,t){const n=e.profile||e.voice||"",s=n?String(t||"").trim()||h0(n):"";return[e.provider,e.model,s].filter(Boolean).join(" · ")}function A1(e){return[e.stt_provider,e.stt_model].filter(Boolean).join(" · ")}const $1=[{value:"",label:"Gateway default"},{value:"standard",label:"Balanced"},{value:"low",label:"Faster (lower quality)"},{value:"high",label:"Higher quality (slower)"}],wm=e=>Array.isArray(e)?e.map(t=>typeof t=="string"?t:(t==null?void 0:t.id)||(t==null?void 0:t.name)).filter(Boolean):[];function R1(e){var Ce,ze,Ve,Ee,je,Ue,ne,$e,Pe,Ge,G,fe;const t=e.overrideOwner||"this app",n=!!e.unavailableReason,s=e.rows||{},o=p.useRef(e.fetchCatalog);o.current=e.fetchCatalog;const l=p.useRef(e.fetchDefaults);l.current=e.fetchDefaults;const u=p.useRef(e.fetchLanguages);u.current=e.fetchLanguages;const[d,f]=p.useState({}),[m,g]=p.useState({value:null,failed:!1}),v=e.defaults!==void 0?{value:e.defaults,failed:!1}:m,w=e.defaults!==void 0,[x,j]=p.useState(""),[b,k]=p.useState(0),[$,S]=p.useState(null),N=e.outputSelectable??av(),C=e.value,R=e.nested?"flat":"card",E=te=>e.onChange({...C,...te}),I=fs(C.reply_volume),L=Ud(C.input_gain),D=s.tts!==!1&&!e.ttsSlot,P=s.stt!==!1,K=D||P||!!e.ttsSlot,se=e.voiceLibrary||e.createVoice;p.useEffect(()=>{if(n)return;let te=!0;return o.current().then(pe=>te&&f(pe||{})).catch(()=>te&&f({})),w||l.current().then(pe=>te&&g({value:pe||{},failed:!1})).catch(()=>te&&g({value:null,failed:!0})),()=>{te=!1}},[n,w]);const Q=C.profile||C.voice||"",[z,T]=p.useState({id:"",name:""}),q=x==="tts";p.useEffect(()=>{if(n||!Q||!D)return;let te=!0;return o.current(C.provider||void 0,C.model||void 0).then(pe=>te&&T({id:Q,name:cv(pe,Q,C.provider||void 0)})).catch(()=>te&&T({id:Q,name:""})),()=>{te=!1}},[n,Q,C.provider,C.model,D,q]);const J=T1(C,z.id===Q?z.name:""),B=C.stt_provider||((ze=(Ce=v.value)==null?void 0:Ce.stt)!=null&&ze.configured?String(v.value.stt.provider||""):""),O=!!e.fetchLanguages;p.useEffect(()=>{const te=u.current;if(n||!te||s.microphone===!1)return;let pe=!0;return te("stt",B||void 0).then(Se=>pe&&S(Array.isArray(Se)?Se.map(Ze=>String(Ze).toLowerCase()).filter(Boolean):[])).catch(()=>pe&&S(null)),()=>{pe=!1}},[n,O,B,s.microphone]);const Z=Zp(v.value,"tts",v.failed)+(e.compact&&((Ee=(Ve=v.value)==null?void 0:Ve.tts)!=null&&Ee.configured)&&v.value.tts.voice?` · ${v.value.tts.voice}`:""),M=Zp(v.value,"stt",v.failed),W=[(je=v.value)==null?void 0:je.tts,(Ue=v.value)==null?void 0:Ue.stt].map(te=>te&&!te.configured?te.note:"").filter(Boolean),Y=[(ne=v.value)==null?void 0:ne.tts,($e=v.value)==null?void 0:$e.stt].map(te=>{var pe;return te&&te.configured?String(((pe=te.hint)==null?void 0:pe.sentence)||"").trim():""}).filter(Boolean),oe=!!((Ge=(Pe=d.controls)==null?void 0:Pe.quality_preset)!=null&&Ge.supported),de={deviceId:N&&C.output_device||"",volume:I},me=$&&$.length?[{value:"",label:"Detect automatically"},...$.map(te=>({value:te,label:ps(te)}))]:[...C1],ee=C.stt_language||"";ee&&!me.some(te=>te.value===ee)&&me.push({value:ee,label:`${ps(ee)} (saved)`});const ce=hs(C.capture_mode??((G=e.captureDefaults)==null?void 0:G.capture_mode)),ye=C.auto_send??((fe=e.captureDefaults)==null?void 0:fe.auto_send)??!1;return a.jsx(_l.Provider,{value:e.compact===!0,children:a.jsxs("div",{className:`af-voice-section${e.compact?" af-voice-section--compact":""}${e.className?` ${e.className}`:""}`,children:[e.unavailableReason?a.jsx("p",{className:"af-settings-group__help",role:"status",children:e.unavailableReason}):null,K?a.jsxs(Eo,{variant:R,title:e.compact?"Voice & transcription":"Engines",help:e.compact?`Choose the speech engines for ${t}. Leave them unchanged to use Gateway defaults.`:"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,D?a.jsx(fd,{label:"Text → speech",setting:"tts",defaultSummary:Z,overrideSummary:J,overrideOwner:t,open:x==="tts",onToggle:()=>j(x==="tts"?"":"tts"),onReset:()=>E({provider:"",model:"",voice:"",profile:""}),disabled:n,children:a.jsx(g0,{value:C,onChange:te=>e.onChange({...C,...te}),fetchCatalog:e.fetchCatalog,intro:null,quality:!1,showReset:!1,voiceDefaultLabel:"Gateway default",voiceLibrary:se,previewVoice:e.previewVoice?(te,pe,Se)=>e.previewVoice({...C,...te},pe,Se):void 0,previewOn:de,recordFrom:{deviceId:C.input_device||"",gain:L}})}):null,P?a.jsx(fd,{label:"Speech → text",setting:"stt",defaultSummary:M,overrideSummary:A1(C),overrideOwner:t,open:x==="stt",onToggle:()=>j(x==="stt"?"":"stt"),onReset:()=>E({stt_provider:"",stt_model:""}),disabled:n,children:a.jsx(zg,{layout:e.compact?"compact":void 0,value:{provider:C.stt_provider||"",model:C.stt_model||""},onChange:te=>E({stt_provider:te.provider,stt_model:te.model}),fetchProviders:async()=>{const te=await o.current();return wm(te.stt_providers).map(pe=>({name:pe}))},fetchModels:async te=>{var Se;const pe=await o.current(te);return wm(((Se=pe.stt_models_by_provider)==null?void 0:Se[te])||pe.stt_models)},inheritLabel:"Gateway default",providerLabel:"Transcription provider",modelLabel:"Transcription model"})}):null,v.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,W.map(te=>a.jsx("p",{className:"af-settings-group__help","data-voice-note":"unset",children:te},te)),Y.map(te=>a.jsx("p",{className:"af-settings-group__help","data-voice-note":"hint",role:"note",children:te},te))]}):null,s.output!==!1?a.jsx(Eo,{variant:R,title:"Output",children:a.jsx(x1,{value:C,onChange:e.onChange,listDevices:e.listDevices,outputSelectable:N,showMute:s.mute===!0,unavailableReason:e.unavailableReason,devicesKey:b})}):null,s.microphone!==!1?a.jsxs(Eo,{variant:R,title:"Microphone",children:[a.jsx(j1,{value:C,onChange:e.onChange,levelSource:e.levelSource,listDevices:e.listDevices,playOn:de,onDevicesChanged:()=>k(te=>te+1),unavailableReason:e.unavailableReason}),a.jsx(zr,{label:"Spoken language",setting:"stt-language",help:"Naming it skips detection: transcription is faster.",children:a.jsx(tn,{ariaLabel:"Spoken language",placeholder:"Detect automatically",value:ee,options:me,disabled:n,searchable:!1,onChange:te=>E({stt_language:te})})}),s.capture===!0?a.jsxs(a.Fragment,{children:[a.jsx(zr,{label:"Microphone button",setting:"capture-mode",children:a.jsx(tn,{ariaLabel:"Microphone button",value:ce,options:E1,disabled:n,searchable:!1,onChange:te=>E({capture_mode:te==="toggle"?"toggle":"hold"})})}),a.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"auto-send",children:a.jsx(ii,{label:"Send what you say automatically",description:"Off: what you say lands in the message box for you to review.",variant:"row",checked:ye,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:te=>E({auto_send:te})})})]}):null]}):null,s.replies!==!1?a.jsxs(Eo,{variant:R,title:"Replies",children:[a.jsx("div",{className:"af-setting-row af-setting-row--switch","data-setting":"read-aloud",children:a.jsx(ii,{label:"Read aloud",description:"Speak each new reply.",variant:"row",checked:C.read_aloud===!0,unavailableReason:n?e.unavailableReason:null,reasonVisible:!1,onChange:te=>E({read_aloud:te})})}),a.jsx(zr,{label:"Voice latency",setting:"latency",help:oe?"Trades quality for a faster first word.":"This gateway's voice engine has no latency control.",children:a.jsx(tn,{ariaLabel:"Voice latency",placeholder:"Gateway default",value:oe&&C.quality_preset||"",options:$1,disabled:n||!oe,searchable:!1,onChange:te=>E({quality_preset:te})})})]}):null]})})}const Ar={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 M1(e){const[t,n]=p.useState(()=>Date.now());return p.useEffect(()=>{if(!e)return;n(Date.now());const s=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(s)},[e]),t}function al(e){const{voice:t}=e,n=hs(e.mode),s=t.voice_capture_mode&&t.voice_capture_mode!==n?"mode":e.onTranscript&&typeof t.add_transcript_listener!="function"?"transcript":"";p.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=p.useRef(!1),l=p.useRef(0),u=p.useRef(!0),d=p.useRef(t.voice_ptt_recording);d.current=t.voice_ptt_recording;const f=p.useRef(t);f.current=t;const m=p.useRef(e.onTranscript);m.current=e.onTranscript;const[g,v]=p.useState(!1),w=!!e.onTranscript;p.useEffect(()=>(u.current=!0,()=>{var P,K;u.current=!1,(o.current||d.current)&&((K=(P=f.current).cancel_voice_ptt_recording)==null||K.call(P)),o.current=!1}),[]),p.useEffect(()=>{if(!(!w||!t.add_transcript_listener))return t.add_transcript_listener((P,K)=>{var se;return(se=m.current)==null?void 0:se.call(m,P,K)})},[t.add_transcript_listener,w]),p.useEffect(()=>{if(!g)return;const P=setTimeout(()=>v(!1),4e3);return()=>clearTimeout(P)},[g]);const x=s==="mode"?Ar.modeMismatch:s==="transcript"?Ar.transcriptMismatch:e.unavailableReason||(t.voice_ptt_supported?null:Ar.unavailable),j=t.voice_ptt_busy,b=t.voice_ptt_recording,k=()=>{const P=f.current;x||P.voice_ptt_busy||o.current||(o.current=!0,l.current=Date.now(),v(!1),P.start_voice_ptt_recording().then(()=>{var K,se;(!o.current||!u.current)&&((se=(K=f.current).cancel_voice_ptt_recording)==null||se.call(K))}))},$=()=>{var P,K;if(o.current){if(o.current=!1,Date.now()-l.current<sv){(K=(P=f.current).cancel_voice_ptt_recording)==null||K.call(P),u.current&&v(!0);return}f.current.stop_voice_ptt_recording()}},S=()=>{var P,K;o.current&&(o.current=!1,(K=(P=f.current).cancel_voice_ptt_recording)==null||K.call(P))};p.useEffect(()=>{if(n==="hold")return window.addEventListener("pointerup",$),window.addEventListener("pointercancel",$),window.addEventListener("blur",S),()=>{window.removeEventListener("pointerup",$),window.removeEventListener("pointercancel",$),window.removeEventListener("blur",S)}},[n]);const N=()=>{const P=f.current;if(P.voice_ptt_recording){P.stop_voice_ptt_recording();return}x||P.voice_ptt_busy||(v(!1),P.start_voice_ptt_recording())},C=t.voice_ptt_since||0,R=M1(!!C),E=e.label||(n==="hold"?Ar.hold:Ar.toggle),I=b?n==="hold"?Ar.recordingHold:Ar.recordingToggle:E,L=b?`Recording… ${C?Jg(C,R):""}`.trim():j?Yx(C||R,R,e.routeText||""):g?Ar.holdHint:"",D=n==="hold"?{onPointerDown:P=>{P.button===0&&k()},onPointerUp:$,onPointerCancel:$,onKeyDown:P=>{[" ","Enter"].includes(P.key)&&!P.repeat&&(P.preventDefault(),k())},onKeyUp:P=>{[" ","Enter"].includes(P.key)&&(P.preventDefault(),$())}}:{onClick:N};return a.jsxs("span",{className:`af-voice-mic${b?" 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":b,title:x||I,disabled:!!x||j,...D,children:a.jsx(be,{name:j?"loader":"mic",size:15})}),b?a.jsx(Ev,{source:t,inline:!0,className:"af-voice-mic__meter"}):null,e.showStatus!==!1&&(L||x)?a.jsx("span",{role:"status",className:"af-voice-mic__status","data-voice-status":!0,children:L||x}):null]})}function L1(e,t=""){const n=p.useRef(e);n.current=e;const[s,o]=p.useState({value:null,failed:!1}),[l,u]=p.useState(0),d=!!e;p.useEffect(()=>{const m=n.current;if(!m){o(v=>v.value===null&&!v.failed?v:{value:null,failed:!1});return}let g=!0;return m().then(v=>g&&o({value:v||{},failed:!1})).catch(()=>g&&o({value:null,failed:!0})),()=>{g=!1}},[d,t,l]);const f=p.useCallback(()=>u(m=>m+1),[]);return{value:s.value,failed:s.failed,reload:f}}const Ho=new Map,Av=()=>{try{return globalThis.localStorage||null}catch{return null}},$v=e=>{try{const t=e?JSON.parse(e):null;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}};function ju(e){var t;return $v((t=Av())==null?void 0:t.getItem(e))}function I1(e,t){var s;const n=t&&typeof t=="object"?t:{};try{(s=Av())==null||s.setItem(e,JSON.stringify(n))}catch{}for(const o of Array.from(Ho.get(e)||[]))o(n)}function Rv(e){const[t,n]=p.useState(()=>({key:e,prefs:ju(e)})),s=t.key===e?t:{key:e,prefs:ju(e)};s!==t&&n(s),p.useEffect(()=>{var m;const l=g=>n({key:e,prefs:g});let u=Ho.get(e);u||Ho.set(e,u=new Set),u.add(l);const d=g=>{g.key!==null&&g.key!==e||n({key:e,prefs:g.key===null?ju(e):$v(g.newValue)})},f=globalThis;return(m=f.addEventListener)==null||m.call(f,"storage",d),()=>{var g;u.delete(l),u.size||Ho.delete(e),(g=f.removeEventListener)==null||g.call(f,"storage",d)}},[e]);const o=p.useCallback(l=>{I1(e,l)},[e]);return[s.prefs,o]}function Mv(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 Va(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Ot(e){return typeof e=="string"?e.trim():""}function _m(e){return typeof e=="number"&&Number.isInteger(e)?e:void 0}function Lv(e){const t=Va(e),n=t==null?void 0:t.items,s=Ot(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=Va(t==null?void 0:t.command_sandbox),l=Ot(o==null?void 0:o.sentence),u=new Set,d=[];for(const f of n){const m=Va(f),g=Ot(m==null?void 0:m.name);if(!m||!g||u.has(g))continue;u.add(g);const v=m.enabled!==!1&&m.available!==!1,w=Ot(m.approval_default).toLowerCase(),x=Mv(m.default_approval,"desktop"),j=w?w==="auto"?"auto":"ask":x==="auto"?"auto":"ask",b=Va(m.risk),k=_m(m.risk_rank)??_m(b==null?void 0:b.rank),$=Ot(m.risk_tier)||Ot(b==null?void 0:b.tier),S=Ot(m.sandbox),N=S&&typeof m.sandboxed=="boolean"?{label:S,...l?{tooltip:l}:{},tone:m.sandboxed?"ok":Ot(o==null?void 0:o.state)==="unsandboxed"?"danger":"warn"}:void 0,C=Ot(m.why_disabled)||Ot(m.enable_gate);d.push({name:g,...Ot(m.description)?{description:Ot(m.description)}:{},...Ot(m.when_to_use)?{whenToUse:Ot(m.when_to_use)}:{},toolset:Ot(m.toolset)||"other",offered:v,gatewayDefault:v?j:"off",...v&&!w&&!x?{defaultUnserved:!0}:{},...k!==void 0?{riskRank:k}:{},...$?{riskTier:$}:{},...m.model_controlled_destination===!0?{modelControlledDestination:!0}:{},...m.risk_refiner!==void 0&&m.risk_refiner!==null?{refined:!0}:{},...!v&&C?{whyDisabled:C}:{},...Ot(m.approval_note)?{approvalNote:Ot(m.approval_note)}:{},...N?{state:N}:{}})}return d.sort((f,m)=>f.toolset===m.toolset?f.name.localeCompare(m.name):f.toolset.localeCompare(m.toolset)),d}function il(e,t){if(!(!e||!Object.prototype.hasOwnProperty.call(e,t)))return Mv(e[t])}function Iv(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=il(t.app,s.name),u=il(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 P1(e,t,n){const s=Iv(e,{app:t.app}),o={};for(const[l,u]of Object.entries(s))o[l]=u.mode;return o}function hd(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 Vd=2;function Pv(e){return e.offered&&(e.riskRank??4)<=Vd&&e.modelControlledDestination!==!0}function O1(e,t,n,s){let o={...e||{}};const l=[];for(const u of t)if(u.offered){if(n==="auto"&&!Pv(u)){l.push(u.name);continue}o=hd(o,u,n,s[u.name]??u.gatewayDefault)}return{layer:o,skipped:l}}function D1(e,t={}){const n={},s={};for(const o of e){if(!o.offered)continue;const l=il(t.app,o.name);l!==void 0&&l!==o.gatewayDefault&&(n[o.name]=l);const u=n[o.name]??o.gatewayDefault,d=il(t.session,o.name);d!==void 0&&d!==u&&(s[o.name]=d)}return{app:n,session:s}}function F1(e,t={}){const n=D1(e,t);return Object.keys(n.app).length>0||Object.keys(n.session).length>0}function Ov(e,t={},n={}){const s=Iv(e,t),o=Array.isArray(n.ceiling)?new Set(n.ceiling):null,l=[],u=[],d=[];for(const f of[...e].sort((m,g)=>m.name.localeCompare(g.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],...F1(e,t)?{tool_policy:{auto_approve_tools:[...u],require_approval_tools:[...d]}}:{},approval:{auto:u,ask:d}}}function B1(e,t){const n={...e||{}},s={...Va(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 z1(e,t,n,s=[]){const o=new Map(e.map(f=>[f.name,f])),l=f=>{const m=t[f];return typeof m=="string"?m:m==null?void 0:m.mode},u=Math.max(Vd,...n.map(f=>{var m;return((m=o.get(f))==null?void 0:m.riskRank)??4})),d=new Set(s);for(const f of e)!f.offered||l(f.name)!=="ask"||f.riskTier==="outreach"||f.modelControlledDestination===!0||(f.riskRank??4)<=u&&d.add(f.name);for(const f of n){const m=o.get(f);if(!m||!m.offered||m.riskTier==="outreach")continue;const g=l(f);g&&g!=="off"&&d.add(f)}return[...d].sort()}const Dv="The gateway cannot store chat tool policies";class U1 extends Error{constructor(){super(`${Dv} (it does not advertise capabilities.session_tool_policy).`),this.code="unsupported",this.name="SessionToolPolicyUnsupportedError"}}class W1 extends Error{constructor(t,n){super(t||"This chat's tool policy was changed elsewhere. Reload it and try again."),this.code="revision_conflict",this.name="SessionToolPolicyConflictError",typeof n=="number"&&(this.revision=n)}}const _n=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,ar=e=>typeof e=="string"?e.trim():"",Go=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];function V1(e){const t=_n(e),n=_n(t==null?void 0:t.capabilities)??t,s=_n(n==null?void 0:n.session_tool_policy);return s?{supported:s.supported===!0,...typeof s.version=="number"?{version:s.version}:{},...ar(s.endpoint)?{endpoint:ar(s.endpoint)}:{},...Array.isArray(s.methods)?{methods:Go(s.methods)}:{},...Array.isArray(s.approve)?{approve:Go(s.approve)}:{},...Array.isArray(s.deny)?{deny:Go(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 bm=e=>{const t=_n(e);if(!t)return null;const n={};for(const[s,o]of Object.entries(t))typeof o=="string"&&(n[s]=o);return n};function xm(e){const t=_n(e),n=bm(t==null?void 0:t.approve),s=bm(t==null?void 0:t.deny);if(!t||typeof t.version!="number"||typeof t.revision!="number"||typeof t.session_id!="string"||!n||!s||!Array.isArray(t.ask))throw new Error("The gateway answered without a chat tool policy (policy.version, revision, session_id, approve, deny, ask).");const o=Array.isArray(t.clamped)?t.clamped.map(_n).filter(u=>!!u).map(u=>({selector:String(u.selector??""),name:String(u.name??""),reason:String(u.reason??"")})):void 0,l=_n(t.set_by);return{version:t.version,session_id:t.session_id,revision:t.revision,approve:n,deny:s,ask:Go(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 Su(e){const t=_n(e);if(!t)return;const n={};return typeof t.approve=="string"&&t.approve.trim()&&(n.approve=t.approve),typeof t.deny=="string"&&t.deny.trim()&&(n.deny=t.deny),n.approve||n.deny?n:void 0}function q1(e){const t=_n(e)??(e instanceof Error?e:void 0);if(!t)return null;const n=_n(t.body),s=_n(t.detail)??_n(n==null?void 0:n.detail)??n,o=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 W1(ar(s==null?void 0:s.message),typeof l=="number"?l:void 0)}function H1(e,t,n,s={}){const o=String(t??"");if(!Bg.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=ut(Lb(o));let d,f;const m=x=>f?{...x,scope:f}:x,g=async(x,j,b="")=>{if(!l)throw new U1;if(n!=null&&n.methods&&!n.methods.includes(x))throw new Error(`${Dv} with ${x} (the gateway advertises ${n.methods.join(", ")}).`);try{return _n(await e(`${u}${b}`,j===void 0?{method:x}:{method:x,body:j}))}catch(k){throw q1(k)??k}},v=x=>s.client&&x.client===void 0?{...x,client:s.client}:x,w=x=>{const j=xm(x==null?void 0:x.policy);return d=j.revision,f=Su(x==null?void 0:x.scope),m(j)};return{supported:l,sessionId:o,get revision(){return d},get scope(){return f},async get(){const x=await g("GET");if(!x||!("policy"in x))throw new Error("The gateway answered without `policy` for this chat.");const j=x.policy===null?null:xm(x.policy);return d=typeof x.revision=="number"?x.revision:j?j.revision:void 0,f=Su(x.scope),j?m(j):null},replace:async x=>w(await g("PUT",v(x))),merge:async x=>w(await g("POST",v(x))),async reset(x){if(x!==void 0&&!Number.isInteger(x))throw new Error(`reset(ifRevision) takes an integer revision, got ${JSON.stringify(x)}.`);const j=await g("DELETE",void 0,x===void 0?"":`?if_revision=${x}`);return d=typeof(j==null?void 0:j.revision)=="number"?j.revision:void 0,f=Su(j==null?void 0:j.scope),{...d===void 0?{}:{revision:d},...f?{scope:f}:{}}}}}function G1(e){return((e==null?void 0:e.clamped)||[]).map(t=>`Not covered: ${t.name}${t.selector&&t.selector!=="tools"?` (${t.selector})`:""} (${t.reason})`)}const K1={off:"Off",ask:"Ask",auto:"Auto",on:"On"},J1={app:"Use the gateway's",session:"Use my defaults"},Y1="Off = denied for every run of this chat, automations included",Q1="The gateway did not say where this policy applies",km={app:"this app",session:"this chat"},Nu=`Auto for a whole group reaches the tools that read or make changes (risk ${Vd} or lower) and whose destination the assistant does not choose. Set the others to Auto one at a time.`;function X1(e){const t=e.split("_");return t.map((n,s)=>s<t.length-1?a.jsxs(it.Fragment,{children:[n,"_",a.jsx("wbr",{})]},s):a.jsx(it.Fragment,{children:n},s))}function jm(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=wl(e.set_at);return!t&&!s?"":`Set${t?` by ${t}`:""}${n?` (${n})`:""}${s?` on ${s}`:""}`}function Z1(e){var M,W,Y,oe,de,me;const t={...K1,...e.labels||{}},n=e.disabled===!0,s=e.compact===!0,[o,l]=p.useState(!1),[u,d]=p.useState({}),f=e.allowListOnly===!0,m=e.value||{},g=it.useId(),[v,w]=p.useState(""),[x,j]=p.useState(!1),b=ee=>{var ce;return ee.offered?((ce=e.inherited)==null?void 0:ce[ee.name])??ee.gatewayDefault:"off"},k=ee=>{if(!ee.offered)return"off";const ce=m[ee.name];return ce==="off"||ce==="ask"||ce==="auto"?ce:b(ee)},$=p.useMemo(()=>{const ee={};for(const ce of e.catalog)ee[ce.name]=b(ce);return ee},[e.catalog,e.inherited]),S=p.useMemo(()=>{const ee=v.trim().toLowerCase(),ce=new Map;for(const ye of e.catalog){if(ee&&![ye.name,ye.description||"",ye.toolset].some(ze=>ze.toLowerCase().includes(ee)))continue;const Ce=ce.get(ye.toolset)||[];Ce.push(ye),ce.set(ye.toolset,Ce)}return[...ce.entries()].sort(([ye],[Ce])=>ye==="other"?1:Ce==="other"?-1:ye.localeCompare(Ce)).map(([ye,Ce])=>({toolset:ye,items:[...Ce].sort((ze,Ve)=>ze.offered===Ve.offered?ze.name.localeCompare(Ve.name):ze.offered?-1:1)}))},[e.catalog,v]),N=ee=>{n||e.onChange(ee)},C=ee=>{const ce=b(ee);return ce!=="off"?ce:ee.gatewayDefault!=="off"?ee.gatewayDefault:"ask"},R=(ee,ce)=>N(hd(m,ee,ce,b(ee))),E=(ee,ce)=>{if(ce==="on"){let ye=m;for(const Ce of ee)Ce.offered&&k(Ce)==="off"&&(ye=hd(ye,Ce,C(Ce),b(Ce)));N(ye);return}N(O1(m,ee,ce,$).layer)},I=e.catalog.filter(ee=>ee.offered),L={auto:0,ask:0};for(const ee of I){const ce=k(ee);ce==="auto"?L.auto+=1:ce==="ask"&&(L.ask+=1)}const D=L.auto+L.ask,P=ee=>{if(!ee.offered||!Object.prototype.hasOwnProperty.call(m,ee.name))return!1;const ce=m[ee.name];return(ce==="off"||ce==="ask"||ce==="auto")&&ce!==b(ee)},K=e.catalog.filter(P).map(ee=>ee.name),se=sx(e.toolMode,e.toolModeLabel,e.toolModeDetail),Q=e.scope??((M=e.policy)==null?void 0:M.scope)??null,z=f?["off","on"]:["off","ask","auto"],T=ee=>t[ee],q=a.jsxs("div",{className:`af-tool-modes${s?" af-tool-modes--compact":""}${e.className?` ${e.className}`:""}`,"data-layer":e.layer,"data-allowlist":f?"true":void 0,children:[se?a.jsxs("div",{className:`af-tool-policy__mode is-${se.tone}`,children:[a.jsx("div",{className:"af-tool-policy__mode-badge",children:"Tool mode"}),a.jsx("div",{className:"af-tool-policy__mode-value",children:se.label}),a.jsx("div",{className:"af-tool-policy__mode-detail",children:se.detail})]}):null,e.note&&!s?a.jsx("div",{className:"af-tool-policy__note",children:e.note}):null,(W=e.warnings)!=null&&W.length?a.jsx("div",{className:"af-tool-modes__warnings",role:"status","data-catalog-warnings":"",children:e.warnings.map((ee,ce)=>a.jsxs("div",{children:["Gateway warning: ",ee]},ce))}):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:v,onChange:ee=>{w(ee.target.value),d({})}}),s?a.jsx(za,{content:[e.note,e.savedWhere,(Y=e.storage)==null?void 0:Y.where].filter(Boolean).join(" "),children:a.jsx("button",{type:"button",className:"af-settings-help","aria-label":"About tool permissions",children:a.jsx(be,{name:"info",size:16})})}):null,a.jsx("span",{className:"af-tool-modes__count","data-tool-count":"",children:f?`${D} of ${I.length} tools on`:`${D} of ${I.length} tools on · ${L.auto} run without asking · ${L.ask} ask first`}),e.onReset&&Object.keys(m).length?a.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","data-action":"reset-layer",disabled:n,onClick:e.onReset,children:J1[e.layer]}):null,!s&&e.storage?a.jsx("span",{className:"af-tool-modes__saved","data-storage":e.storage.kind,children:e.storage.where}):!s&&e.savedWhere?a.jsx("span",{className:"af-tool-modes__saved",children:e.savedWhere}):null]}),(oe=e.storage)!=null&&oe.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"&&((de=e.storage)==null?void 0:de.kind)==="gateway"?a.jsx("div",{className:"af-tool-modes__policy","data-session-off-help":"",children:Y1}):null,((me=e.storage)==null?void 0:me.kind)==="gateway"||e.policy?a.jsx("div",{className:"af-tool-modes__policy","data-policy-scope":Q?"served":"unsaid",children:Q?a.jsxs(a.Fragment,{children:[Q.approve?a.jsxs("div",{children:["Approve applies to: ",Q.approve]}):null,Q.deny?a.jsxs("div",{children:["Deny applies to: ",Q.deny]}):null]}):Q1}):null,e.policy?a.jsxs("div",{className:"af-tool-modes__policy","data-session-policy":e.policy.revision,children:[jm(e.policy)?a.jsx("div",{"data-policy-set":"",children:jm(e.policy)}):null,G1(e.policy).map((ee,ce)=>a.jsx("div",{"data-policy-clamped":"",children:ee},ce))]}):null,e.catalog.length?null:a.jsx("div",{className:"af-tool-policy__empty",children:"The gateway offers no tools."}),e.catalog.length&&!S.length?a.jsx("div",{className:"af-tool-policy__empty",children:"No tools match the search."}):null,S.map(ee=>{const ce=s?e.catalog.filter(ne=>ne.toolset===ee.toolset):ee.items,ye=ce.filter(ne=>ne.offered),Ce=new Set(ye.map(ne=>f?k(ne)==="off"?"off":"on":k(ne))),ze=Ce.size===1?[...Ce][0]:void 0,Ve=f?[]:ye.filter(ne=>!Pv(ne)),Ee=!s||(u[ee.toolset]??!!v.trim()),je=`${g}-${encodeURIComponent(ee.toolset)}`,Ue=a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"af-tool-modes__group-name",children:s?ee.toolset.replace(/[_-]/g," "):ee.toolset}),s?a.jsx("span",{className:"af-tool-modes__group-count",children:ye.length}):null]});return a.jsxs("section",{className:"af-tool-modes__group","data-toolset":ee.toolset,hidden:s&&!v.trim()&&!o&&!ye.length,children:[a.jsxs("div",{className:"af-tool-modes__group-head",children:[s?a.jsxs("button",{type:"button",className:"af-tool-modes__toggle","aria-label":`${Ee?"Hide":"Show"} ${ee.toolset} tools`,"aria-expanded":Ee,"aria-controls":je,onClick:()=>d(ne=>({...ne,[ee.toolset]:!Ee})),children:[a.jsx(be,{name:Ee?"chevronDown":"chevronRight",size:14}),Ue]}):Ue,ye.length?a.jsx("span",{className:"af-tool-modes__group-state","data-group-state":ze??"mixed",children:ze?T(ze):"Mixed"}):null,a.jsx("div",{className:"af-tool-modes__seg",role:"group","aria-label":`All ${ee.toolset} tools`,children:z.map(ne=>a.jsx("button",{type:"button",className:`af-tool-modes__seg-btn${ze===ne?" is-active":""}`,"aria-pressed":ze===ne,"data-group-mode":`${ee.toolset}:${ne}`,disabled:n||!ye.length||ne==="auto"&&Ve.length===ye.length,title:!s&&ne==="auto"&&Ve.length?Nu:void 0,onClick:()=>E(ce,ne),children:T(ne)},ne))}),s&&Ve.length?a.jsx(za,{content:Nu,children:a.jsx("button",{type:"button",className:"af-settings-help","aria-label":`About Auto for ${ee.toolset}`,children:a.jsx(be,{name:"info",size:15})})}):null]}),a.jsxs("div",{id:je,hidden:!Ee,className:"af-tool-modes__items",children:[!s&&Ve.length?a.jsxs("div",{className:"af-tool-modes__cap","data-bulk-cap":ee.toolset,children:[Nu," ",Ve.length===1?"1 tool here stays":`${Ve.length} tools here stay`," as it is: ",Ve.map(ne=>ne.name).join(", "),"."]}):null,ee.items.map(ne=>{var fe;const $e=k(ne),Pe=f&&$e!=="off"?"on":$e,Ge=P(ne),G=b(ne);return a.jsxs("div",{className:`af-tool-mode-row${ne.offered?"":" is-unavailable"}`,"data-tool":ne.name,"data-mode":$e,"data-overridden":Ge?"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:X1(ne.name)}),ne.riskTier?a.jsx("span",{className:"af-tool-row__badge","data-risk":ne.riskRank??"",title:ne.riskRank!==void 0?`Risk ${ne.riskRank}`:void 0,children:ne.riskTier}):null,Ge?a.jsxs("span",{className:"af-tool-mode-row__default","data-default-chip":ne.name,title:e.layer==="app"||G===ne.gatewayDefault?"The gateway's default":"Your default for this app",children:["Default: ",f?G==="off"?t.off:t.on:T(G)]}):null]}),ne.state?a.jsx("div",{className:"af-tool-row__state-line",children:a.jsx(za,{content:ne.state.tooltip||"",children:a.jsx("span",{className:`af-tool-row__state${ne.state.tone?` is-${ne.state.tone}`:""}`,"data-tool-state":ne.name,tabIndex:ne.state.tooltip?0:void 0,"aria-label":ne.state.tooltip?`${ne.state.label}. ${ne.state.tooltip}`:void 0,children:ne.state.label})})}):null,!s&&ne.description?a.jsx("div",{className:"af-tool-row__desc",children:ne.description}):null,!s&&ne.whenToUse?a.jsx("div",{className:"af-tool-row__hint",children:ne.whenToUse}):null,!s&&ne.offered&&ne.defaultUnserved?a.jsx("div",{className:"af-tool-mode-row__why","data-default-unserved":ne.name,children:"The gateway did not say whether this tool asks first; Ask is assumed."}):null,!s&&!ne.offered?a.jsx("div",{className:"af-tool-mode-row__why","data-why-disabled":ne.name,children:ne.whyDisabled?`Not offered by the gateway: ${ne.whyDisabled}`:"Not offered by the gateway."}):null]}),s?a.jsx(za,{content:{title:ne.name,description:[ne.description,ne.whenToUse,(fe=ne.state)==null?void 0:fe.tooltip,ne.offered?"":ne.whyDisabled||"Not offered by the gateway.",ne.riskTier?`Risk: ${ne.riskTier}.`:""].filter(Boolean).join(" ")},children:a.jsx("button",{type:"button",className:"af-settings-help","aria-label":`About ${ne.name}`,children:a.jsx(be,{name:"info",size:16})})}):null,a.jsx("div",{className:"af-tool-modes__seg",role:"group","aria-label":`Mode for ${ne.name}`,children:z.map(te=>a.jsx("button",{type:"button",className:`af-tool-modes__seg-btn${Pe===te?" is-active":""}`,"aria-pressed":Pe===te,"data-tool-mode":`${ne.name}:${te}`,disabled:n||!ne.offered,onClick:()=>R(ne,te==="on"?C(ne):te),children:T(te)},te))})]},ne.name)})]})]},ee.toolset)}),s&&!v.trim()&&S.some(ee=>!ee.items.some(ce=>ce.offered))?a.jsx("button",{type:"button",className:"af-setting-btn af-setting-btn--quiet","aria-expanded":o,onClick:()=>l(ee=>!ee),children:o?"Hide unavailable tools":"Unavailable tools"}):null]});if(e.rowLabel===void 0)return q;const J=e.layer==="session"&&I.some(ee=>b(ee)!==ee.gatewayDefault),B=K.length?`${K.length} tool${K.length===1?"":"s"} changed`:J?"Your defaults":"",O=K.length?km[e.layer]:km.app,Z=e.open??x;return a.jsx(fd,{label:e.rowLabel,help:e.rowHelp,defaultSummary:f?`${D} of ${I.length} tools on`:`${D} tools on, ${L.auto} without asking`,overrideSummary:B,overrideOwner:O,open:Z,onToggle:e.onToggle??(()=>j(ee=>!ee)),disabled:n,setting:`tools-${e.layer}`,children:q})}function Fv(e){const{brand:t,leading:n,...s}=e.topBar,o=Fg(Dg.md),[l,u]=p.useState(!1),d=e.nav,f=(d==null?void 0:d.open)??l,m=x=>{var j;(j=d==null?void 0:d.onOpenChange)==null||j.call(d,x),(d==null?void 0:d.open)===void 0&&u(x)},g=(d==null?void 0:d.width)??280,v=t?t.href?a.jsxs("a",{className:"af-shell__brand",href:t.href,children:[t.mark,a.jsx("span",{className:"af-shell__brand-name",children:t.name})]}):a.jsxs("span",{className:"af-shell__brand",children:[t.mark,a.jsx("span",{className:"af-shell__brand-name",children:t.name})]}):null,w=a.jsx("main",{className:"af-shell__main",children:e.children});return a.jsxs("div",{className:`af-shell${e.className?` ${e.className}`:""}`,children:[a.jsxs("header",{className:"af-shell__top","data-af-topbar":"",children:[d&&o?a.jsx("button",{type:"button",className:"af-topbar__btn af-shell__nav-toggle","aria-label":`Open ${d.label}`,"data-af-tip":d.label,"aria-expanded":f,onClick:()=>m(!f),children:a.jsx(be,{name:"list",size:16})}):null,v,a.jsx("div",{className:"af-shell__leading",children:n}),a.jsx(Kx,{...s})]}),a.jsxs("div",{className:"af-shell__body",children:[d&&!o?a.jsx("nav",{className:"af-shell__nav","aria-label":d.label,style:{width:g},children:d.content}):null,e.drawers?a.jsx(e1,{...e.drawers,topOffset:e.drawers.topOffset??"auto",children:w}):w]}),d&&o?a.jsx(gx,{open:f,onClose:()=>m(!1),label:d.label,side:"left",backdrop:!0,topOffset:"auto",width:g,children:d.content}):null]})}var ej=it.forwardRef(function(e,t){let n=e.variant!=="legacy",s=typeof e.rows=="number"&&Number.isFinite(e.rows)?Math.max(1,Math.trunc(e.rows)):n?2:3,o=!!e.disabled,l=!!e.busy,u=!o&&!l&&(e.canSubmit??!!String(e.value||"").trim()),d=l?e.busyLabel||"Thinking…":e.sendLabel||"Send",f=p.useRef(null),m=p.useRef(!1),g=p.useCallback(w=>{f.current=w,typeof t=="function"?t(w):t&&(t.current=w)},[t]),v=p.useCallback(()=>{let w=f.current;if(!w||!m.current)return;w.style.height="0px";let x=parseFloat(getComputedStyle(w).maxHeight);w.style.height=`${Math.min(w.scrollHeight,Number.isFinite(x)?x:1/0)}px`},[]);return p.useEffect(()=>{var b;let w=f.current;if(!n||!w||typeof CSS<"u"&&((b=CSS.supports)!=null&&b.call(CSS,"field-sizing","content")))return;m.current=!0,v(),window.addEventListener("resize",v);let x=w.clientWidth,j=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{w.clientWidth!==x&&(x=w.clientWidth,v())});return j==null||j.observe(w),()=>{m.current=!1,j==null||j.disconnect(),window.removeEventListener("resize",v),w.style.removeProperty("height")}},[n,v]),p.useEffect(()=>{v()},[e.value,s,v]),a.jsxs("div",{className:["pc-composer",n?"pc-composer--compact":"",e.className].filter(Boolean).join(" "),children:[e.leading,a.jsx("textarea",{id:e.textareaId,ref:g,className:["pc-composer__textarea",e.textareaClassName].filter(Boolean).join(" "),value:e.value,onChange:w=>e.onChange(w.target.value),rows:s,style:{"--pc-composer-rows":String(s)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:e.placeholder||"","aria-label":e.ariaLabel||e.placeholder||"Message","aria-describedby":e.ariaDescribedBy,disabled:o,autoFocus:!!e.autoFocus,onPaste:e.onPaste,onKeyDown:w=>{w.key!=="Enter"||w.shiftKey||e.submitKey==="mod-enter"&&!w.ctrlKey&&!w.metaKey||w.nativeEvent.isComposing||w.keyCode===229||(w.preventDefault(),u&&e.onSubmit())}}),a.jsxs("div",{className:"pc-composer__row",children:[a.jsxs("div",{className:"pc-composer__actions",children:[e.onAttach?a.jsxs("button",{type:"button",className:n?"pc-composer__icon-action":"pc-composer__icon-action pc-workflow-chat__icon-button","aria-label":e.attachLabel||"Attach files","data-af-tip":e.attachLabel||"Attach files","aria-busy":e.attachPending||void 0,disabled:o||e.attachDisabled||e.attachPending,onClick:e.onAttach,children:[a.jsx(be,{name:e.attachPending?"loader":n?"plus":"paperclip",size:16}),a.jsx("span",{className:n?"pc-sr-only":void 0,children:e.attachPending?"Attaching…":e.attachLabel||"Attach"})]}):null,e.actions]}),e.trailingActions?a.jsx("div",{className:"pc-composer__trailing",children:e.trailingActions}):null,a.jsx("button",{type:"button",className:[e.sendButtonClassName||"pc-btn",n?"pc-composer__send--compact":""].filter(Boolean).join(" "),"aria-label":n?d:void 0,"data-af-tip":n?d:void 0,"aria-busy":n?l:void 0,disabled:!u,onClick:()=>e.onSubmit(),children:n?a.jsx(be,{name:l?"loader":"send",size:17}):d})]}),e.overlay]})});function tj(e){let t=String(e??"").trim();if(!t||!(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))return null;try{return JSON.parse(t)}catch{return null}}async function bl(e){var n;let 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{let s=document.createElement("textarea");s.value=t,s.style.position="fixed",s.style.left="-9999px",document.body.appendChild(s),s.select();let o=document.execCommand("copy")===!0;return document.body.removeChild(s),o}catch{return!1}}function qd(e){let t=[],n=/(?:https?:\/\/|www\.)[^\s<>"'`\\]+/gi,s=0;for(let o of e.matchAll(n)){let l=o.index;if(l>0&&/[\w@]/.test(e[l-1]))continue;let u=o[0].replace(/[.,;:!?]+$/,"");for(let[f,m]of[["(",")"],["[","]"],["{","}"]])for(;u.endsWith(m)&&u.split(m).length>u.split(f).length;)u=u.slice(0,-1);let d=/^www\./i.test(u)?`https://${u}`:u;try{let f=new URL(d);if(!["http:","https:"].includes(f.protocol)||!f.hostname||/[\u0000-\u001f\u007f]/.test(d))continue}catch{continue}l>s&&t.push({text:e.slice(s,l)}),t.push({text:u,href:d}),s=l+u.length}return s<e.length&&t.push({text:e.slice(s)}),t}function os(e){return qd(e).map((t,n)=>t.href?a.jsx("a",{className:"pc-md_link",href:t.href,target:"_blank",rel:"noopener noreferrer",children:t.text},n):t.text)}function To({text:e}){return a.jsx(a.Fragment,{children:os(String(e??""))})}function Cu({text:e}){return a.jsxs(a.Fragment,{children:['"',qd(e).map((t,n)=>t.href?a.jsx("a",{className:"pc-md_link",href:t.href,target:"_blank",rel:"noopener noreferrer",children:t.text},n):JSON.stringify(t.text).slice(1,-1)),'"']})}function nj({code:e,lang:t}){let[n,s]=p.useState("idle"),o=p.useRef(null);p.useEffect(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let l=zd(e,yl(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()=>{let u=await bl(e);s(u?"copied":"failed"),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>s("idle"),900)},children:a.jsx(be,{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(it.Fragment,{children:u.text},d):a.jsx("span",{className:`af-code__${u.kind}`,children:u.text},d))})})]})}function Lr(e,t,n=!0){let s=String(e??"");if(n)return qd(s).map((d,f)=>d.href?a.jsx("a",{className:"pc-md_link",href:d.href,target:"_blank",rel:"noopener noreferrer",children:Lr(d.text,t,!1)},f):a.jsx(it.Fragment,{children:Lr(d.text,t,!1)},f));if(!t||!t.needles.length)return n?os(s):[s];let o=[],l=s.toLowerCase(),u=0;for(;u<s.length;){let d=-1,f="";for(let v=0;v<t.needlesLower.length;v++){let w=t.needlesLower[v];if(!w)continue;let x=l.indexOf(w,u);if(x===-1)continue;let j=t.needles[v]||"";j&&(d===-1||x<d||x===d&&j.length>f.length)&&(d=x,f=j)}if(d===-1||!f){o.push(...n?os(s.slice(u)):[s.slice(u)]);break}d>u&&o.push(...n?os(s.slice(u,d)):[s.slice(u,d)]);let m=t.hits===0&&t.id?t.id:void 0,g=s.slice(d,d+f.length);o.push(a.jsx("span",{id:m,className:t.className,children:g},`hl:${t.hits}`)),t.hits+=1,u=d+f.length}return o}function Bv(e){let t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}var pd="http://same-origin.invalid/";function rj(e){try{let t=new URL(e,pd);return t.protocol==="http:"&&t.origin===new URL(pd).origin}catch{return!1}}function zv(e){let t=String(e||"").trim();return Bv(t)??(t&&rj(t)?t:void 0)}var ls=null;function sj(e){let t=String(e||"").trim();if(!t)return!1;let n=typeof document<"u"&&document.baseURI?document.baseURI:null;if(n===null&&/^[a-z][a-z0-9+.-]*:/i.test(t))return!1;let s=n??pd,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 Uv(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 Sm(e){return!!e&&/[\p{L}\p{N}]/u.test(e)}function Ir(e,t){let n=[],s=String(e??""),o=0,l="",u=()=>{if(l){for(let d of Lr(l,t))n.push(d);l=""}};for(;o<s.length;){let d=s[o];if(d==="!"&&s[o+1]==="["){let f=s.indexOf("]",o+2);if(f!==-1&&s[f+1]==="("){let m=s.indexOf(")",f+2);if(m!==-1){let g=s.slice(o+2,f),v=zv(s.slice(f+2,m));if(v&&ls&&!ls(v)){u(),n.push(Uv(`img:${o}`,v,g)),o=m+1;continue}if(v){u(),n.push(a.jsxs("span",{className:"pc-md_image_inline",children:[a.jsx("img",{className:"pc-md_img",src:v,alt:g,loading:"lazy"}),g?a.jsx("span",{className:"pc-md_img_caption",children:t?Lr(g,t):g}):null]},`img:${o}`)),o=m+1;continue}}}}if(d==="["){let f=s.indexOf("]",o+1);if(f!==-1&&s[f+1]==="("){let m=s.indexOf(")",f+2);if(m!==-1){let g=s.slice(o+1,f),v=Bv(s.slice(f+2,m));if(v){u(),n.push(a.jsx("a",{className:"pc-md_link",href:v,target:v.startsWith("#")?void 0:"_blank",rel:"noopener noreferrer",children:t?Lr(g,t,!1):g},`link:${o}`)),o=m+1;continue}}}}if(d==="`"){let f=s.indexOf("`",o+1);if(f!==-1){u();let m=s.slice(o+1,f);n.push(a.jsx("code",{children:t?Lr(m,t):os(m)},`code:${o}`)),o=f+1;continue}}if(d==="_"&&!Sm(s[o-1])){let f=s[o+1]==="_"?"__":"_",m=f.length;if(s[o+m]&&!/\s/.test(s[o+m])&&s[o+m]!=="_"){let g=s.indexOf(f,o+m);for(;g!==-1&&(/\s/.test(s[g-1]||" ")||Sm(s[g+m])||m===1&&s[g+1]==="_");)g=s.indexOf(f,g+1);if(g!==-1&&g>o+m){u();let v=s.slice(o+m,g),w=Ir(v,t);n.push(m===2?a.jsx("strong",{children:w},`ubold:${o}`):a.jsx("em",{children:w},`uem:${o}`)),o=g+m;continue}}}if(d==="*"&&s[o+1]==="*"){let f=s.indexOf("**",o+2);if(f!==-1){u();let m=s.slice(o+2,f);n.push(a.jsx("strong",{children:t?Lr(m,t):os(m)},`bold:${o}`)),o=f+2;continue}}if(d==="*"&&s[o+1]!=="*"){let f=s.indexOf("*",o+1);if(f!==-1){u();let m=s.slice(o+1,f);n.push(a.jsx("em",{children:t?Lr(m,t):os(m)},`em:${o}`)),o=f+1;continue}}l+=d,o+=1}return u(),n}function aj(e){return String(e??"").replace(/\r\n/g,`
50
+ `).replace(/\r/g,`
51
+ `).split(`
52
+ `)}function Ko(e){let t=String(e??"").match(/^([ \t]*)(?:([-*+])|(\d{1,9})[.)])\s+(.*)$/);return t?{indent:t[1].replace(/\t/g," ").length,ordered:!!t[3],start:t[3]?Math.max(1,parseInt(t[3],10)||1):1,content:t[4]??""}:null}function ij(e){let t=[];for(let o of e){let l=Ko(o);l?t.push(l):t.length>0&&o.trim()&&(t[t.length-1].content+=` ${o.trim()}`)}let n=[],s=[];for(let 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){let u=l.node.items,d=u[u.length-1];if(d){let 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();let u=s.length>0?s[s.length-1]:null,d={ordered:o.ordered,start:o.start,items:[]};if(u){let 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){let 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 Wv(e,t,n){let s=e.items.map((o,l)=>a.jsxs("li",{children:[Ir(o.content,t),o.children.map((u,d)=>Wv(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 oj(e,t,n){return ij(e).map((s,o)=>Wv(s,t,`${n}:${o}`))}function Nm(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 Cm(e){let t=String(e??"").trim();if(!t)return!1;t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));let n=t.split("|").map(s=>String(s??"").trim());return n.length<2?!1:n.every(s=>/^:?-{3,}:?$/.test(s))}var Em=/^(#{1,5})\s+(.*)$/;function Tm(e){return e.trim().startsWith("```")}function Am(e){return e.trimStart().startsWith(">")}function Vv(e){let t=ls;ls=e.images==="link"?e.inlineImage||sj:null;try{return lj(e)}finally{ls=t}}function lj({text:e,className:t,highlight:n,highlights:s,highlightClassName:o,highlightId:l}){let u=aj(e),d=[],f=[];Array.isArray(s)&&f.push(...s),typeof n=="string"&&n.trim()&&f.push(n);let m=Array.from(new Set(f.map(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),g=m.length?{needles:m,needlesLower:m.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null,v=0;for(;v<u.length;){let x=String(u[v]??"");if(!x.trim()){v+=1;continue}let j=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(j)){d.push(a.jsx("hr",{className:"pc-md_hr"},`hr:${v}`)),v+=1;continue}let b=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){let S=zv(b[2]||"");if(S&&ls&&!ls(S)){d.push(a.jsx("p",{className:"pc-md_p",children:Uv(`img:${v}`,S,b[1]||"")},`p:${v}`)),v+=1;continue}if(S){let N=b[1]||"";d.push(a.jsxs("figure",{className:"pc-md_figure",children:[a.jsx("img",{className:"pc-md_img",src:S,alt:N,loading:"lazy"}),N?a.jsx("figcaption",{children:Ir(N,g)}):null]},`figure:${v}`)),v+=1;continue}}if(Tm(x)){let S=x.trim().replace(/```/g,"").trim(),N=[];for(v+=1;v<u.length&&!String(u[v]??"").trim().startsWith("```");)N.push(String(u[v]??"")),v+=1;v<u.length&&(v+=1);let C=N.join(`
53
+ `);d.push(a.jsx(nj,{code:C,lang:S},`pre:${v}`));continue}let k=x.match(Em);if(k){let S=k[1].length,N=k[2]||"",C=Ir(N,g);S===1?d.push(a.jsx("h1",{children:C},`h1:${v}`)):S===2?d.push(a.jsx("h2",{children:C},`h2:${v}`)):S===3?d.push(a.jsx("h3",{children:C},`h3:${v}`)):S===4?d.push(a.jsx("h4",{children:C},`h4:${v}`)):d.push(a.jsx("h5",{children:C},`h5:${v}`)),v+=1;continue}if(Am(x)){let S=[];for(;v<u.length&&String(u[v]??"").trimStart().startsWith(">");){let N=String(u[v]??"").trimStart();S.push(N.replace(/^>\s?/,"")),v+=1}d.push(a.jsx("blockquote",{className:"pc-md_quote",children:S.map((N,C)=>a.jsxs(it.Fragment,{children:[Ir(N,g),C<S.length-1?a.jsx("br",{}):null]},`q:${v}:${C}`))},`quote:${v}`));continue}if(x.includes("|")&&v+1<u.length&&Cm(String(u[v+1]??""))){let S=Nm(x),N=Math.max(1,S.length),C=[];for(v+=2;v<u.length;){let R=String(u[v]??"");if(!R.trim()||!R.includes("|"))break;let E=Nm(R),I=[];for(let L=0;L<N;L++)I.push(E[L]??"");C.push(I),v+=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:S.slice(0,N).map((R,E)=>a.jsx("th",{children:Ir(R,g)},`th:${v}:${E}`))})}),a.jsx("tbody",{children:C.map((R,E)=>a.jsx("tr",{children:R.map((I,L)=>a.jsx("td",{children:Ir(I,g)},`td:${v}:${E}:${L}`))},`tr:${v}:${E}`))})]})},`table:${v}`));continue}if(Ko(x)){let S=[];for(;v<u.length;){let N=String(u[v]??"");if(!N.trim()||N.trimStart().startsWith("```"))break;if(Ko(N)||/^\s{2,}\S/.test(N)){S.push(N),v+=1;continue}break}d.push(a.jsx(it.Fragment,{children:oj(S,g,`list:${v}`)},`list:${v}`));continue}let $=[];for(;v<u.length&&String(u[v]??"").trim()&&!($.length>0&&Ko(String(u[v]??"")));){let S=String(u[v]??"");if($.length>0&&(Em.test(S)||Tm(S)||Am(S))||$.length>0&&S.includes("|")&&v+1<u.length&&Cm(String(u[v+1]??"")))break;$.push(S),v+=1}d.push(a.jsx("p",{className:"pc-md_p",children:$.map((S,N)=>a.jsxs(it.Fragment,{children:[Ir(S,g),N<$.length-1?a.jsx("br",{}):null]},`pl:${v}:${N}`))},`p:${v}`))}let w=["pc-md",t].filter(Boolean).join(" ");return a.jsx("div",{className:w,children:d})}var Eu=1024*1024,cj="1 MiB",uj=25*1024*1024;function qv(e){let t=e.headers.get("content-range"),n=t?Number(t.split("/")[1]):NaN;if(Number.isFinite(n))return n;let s=Number(e.headers.get("content-length"));return e.status===200&&Number.isFinite(s)&&e.headers.has("content-length")?s:void 0}async function $m(e,t,n){var m;let s=new TextDecoder,o="",l=0,u=(m=e.body)==null?void 0:m.getReader();if(u){for(;l<t;){let{done:g,value:v}=await u.read();if(g)break;let w=v.subarray(0,t-l);l+=w.length,o+=s.decode(w,{stream:!0})}await u.cancel().catch(()=>{})}else o=(await e.text()).slice(0,t),l=o.length;let d=qv(e)??n,f=d!==void 0?d>l:l>=t;return{text:o,received:l,total:d,partial:f}}function Rm(e){return`Showing the first ${cj} of ${e!==void 0?di(e):"a file of unknown size"}; download for the rest.`}function Hv(e){let{markdownImages:t,inlineImage:n,renderMarkdown:s,...o}=e;return a.jsx(Nv,{...o,nowMs:e.nowMs??Date.now(),renderMarkdown:s||(l=>a.jsx(Vv,{text:l,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}async function Ur(e,t){let n="";try{let s=await e.text();try{let 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 dj(e,t,n){let s=e,o=URL.createObjectURL(s);{let l=document.createElement("a");l.href=o,l.download=t,document.body.appendChild(l),l.click(),l.remove()}window.setTimeout(()=>URL.revokeObjectURL(o),6e4)}var md={};function fj(){return typeof navigator>"u"||navigator.mediaDevices&&typeof navigator.mediaDevices.getUserMedia=="function"?null:"The microphone needs a secure (https) page or this computer."}function hj(e,t=md){var n;return!!(t.model||t.provider||(n=e==null?void 0:e.tts)!=null&&n.configured)}async function pj(e,t,n,s){var m;if(!t.runId)throw new Error("This reply has no run available for speech.");let o=encodeURIComponent(t.runId),l=await e(ut(`runs/${o}/voice/tts`),{method:"POST",signal:s,headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t.content,...Wd(n)})});if(!l.ok)throw await Ur(l,"The reply could not be spoken");let u=(m=await l.json())==null?void 0:m.audio_artifact,d=String((u==null?void 0:u.$artifact)||(u==null?void 0:u.artifact_id)||(u==null?void 0:u.id)||"");if(!d)throw new Error("The speech service returned no audio.");let f=await e(ut(`runs/${o}/artifacts/${encodeURIComponent(d)}/content`),{signal:s});if(!f.ok)throw await Ur(f,"The speech audio could not be read");return f.arrayBuffer()}function mj(e){var v;let t=p.useRef(e);t.current=e;let n=p.useRef(null),[s,o]=p.useState(null);p.useEffect(()=>{if(o(null),!e.connected)return;let w=new AbortController;return t.current.fetchGateway(ut("voice/defaults"),{signal:w.signal}).then(async x=>x.ok?x.json():null).then(x=>{w.signal.aborted||o(x)}).catch(()=>{}),()=>w.abort()},[e.connected,e.scope.split(":")[0]]);let l=e.preferences||md,u=e.connected&&hj(s,l),d=o0({...Tv(l),tts_stream:u?async function*(w,x){let j=n.current;if(!j)throw new Error("Choose a reply to read aloud.");yield await pj(t.current.fetchGateway,{runId:j.runId,content:w},t.current.preferences||md,x)}:void 0,on_error:w=>t.current.onError(w)});p.useEffect(()=>{d.stop_tts()},[e.scope,e.connected,e.visible,d.stop_tts]);let f=u?w=>{n.current=w,d.toggle_tts(w.id||w.runId||"",w.content)}:void 0,m=w=>d.tts_playback.key===(w.id||w.runId||"")?d.tts_playback.status:"idle",g=e.connected&&((v=s==null?void 0:s.stt)==null?void 0:v.configured)===!0;return{onSpeakToggle:f,getSpeakState:m,stop:d.stop_tts,voice:d,dictationAvailable:g,captureMode:hs(l.capture_mode),routeText:Jx(l,s),microphoneReason:fj()}}async function gj(e,t=uj){var u,d;let n=qv(e);if(n!==void 0&&n>t)throw await((u=e.body)==null?void 0:u.cancel()),Error("This file is too large to preview. Use Download.");let s=(d=e.body)==null?void 0:d.getReader();if(!s)return new Blob([],{type:e.headers.get("content-type")||""});let o=[],l=0;try{for(;;){let f=await s.read();if(f.done)break;if(l+=f.value.byteLength,l>t)throw Error("This file is too large to preview. Use Download.");o.push(f.value)}}finally{await s.cancel().catch(()=>{})}return new Blob(o,{type:e.headers.get("content-type")||""})}function Mm(e,t){let n=t.split(";",1)[0].trim().toLowerCase();if(n.includes("html")||n.includes("xml")||n==="image/svg+xml")return"text";let s=gs("",n),o=gs(e,"");return s==="text"?["code","json","markdown"].includes(o)?o:"text":s!=="binary"?s:o}function vj(e){let[t,n]=p.useState({status:"loading",kind:"binary"}),[s,o]=p.useState(0),[l,u]=p.useState(null),[d,f]=p.useState(!1),[m,g]=p.useState(""),v=p.useRef(null),w=p.useRef(null),x=p.useRef(!0);p.useEffect(()=>(x.current=!0,()=>{var b;x.current=!1,(b=w.current)==null||b.abort()}),[]),p.useEffect(()=>{let b=new AbortController;v.current=b;let k="";return n({status:"loading",kind:"binary"}),(async()=>{var $,S;try{let N=await e.fetchGateway(`${e.path}/content`,{signal:b.signal,headers:{Range:`bytes=0-${Eu-1}`}});if(!N.ok)throw await Ur(N,"Attachment preview failed");let C=N.headers.get("content-type")||"",R=Mm(e.name,C);if(Zs(R)){let E=await $m(N,Eu);if(b.signal.aborted)return;n({status:"ready",kind:R,contentType:C,text:E.text,...E.partial?{partialNote:Rm(E.total)}:{}})}else if(["image","audio","video","pdf"].includes(R)){let E=N,I=/^bytes 0-(\d+)\/(\d+)$/.exec(N.headers.get("content-range")||"");if(N.status===206&&(!I||Number(I[1])+1<Number(I[2]))&&(await(($=N.body)==null?void 0:$.cancel()),E=await e.fetchGateway(`${e.path}/content`,{signal:b.signal}),!E.ok))throw await Ur(E,"Attachment preview failed");let L=E.headers.get("content-type")||C,D=Mm(e.name,L);if(Zs(D)){let K=await $m(E,Eu);b.signal.aborted||n({status:"ready",kind:D,contentType:L,text:K.text,...K.partial?{partialNote:Rm(K.total)}:{}});return}let P=await gj(E);if(b.signal.aborted)return;k=URL.createObjectURL(D==="pdf"?new Blob([P],{type:"application/pdf"}):P),n({status:"ready",kind:D,contentType:L,url:k})}else await((S=N.body)==null?void 0:S.cancel()),b.signal.aborted||n({status:"ready",kind:"binary",contentType:C})}catch(N){b.signal.aborted||n({status:"error",kind:"binary",error:N instanceof Error?N.message:String(N)})}})(),()=>{b.abort(),k&&URL.revokeObjectURL(k)}},[e.fetchGateway,e.path,e.name,s]);let j=async()=>{if(d)return;let b=new AbortController;w.current=b,f(!0),g("");try{let k=await e.fetchGateway(`${e.path}/content`,{signal:b.signal});if(!k.ok)throw await Ur(k,"Attachment download failed");let $=await k.blob();!b.signal.aborted&&x.current&&dj($,e.name,"download")}catch(k){!b.signal.aborted&&x.current&&g(k instanceof Error?k.message:String(k))}finally{!b.signal.aborted&&x.current&&f(!1)}};return a.jsx(Gg,{open:!0,title:e.name,onClose:()=>{var b,k;x.current=!1,(b=v.current)==null||b.abort(),(k=w.current)==null||k.abort(),e.onClose()},className:`pc-artifact-preview pc-artifact-preview--${t.kind}`,footerNote:d?"Downloading…":m||void 0,footer:t.status==="error"?a.jsx("button",{type:"button",className:"pc-artifact-preview__retry",onClick:()=>o(b=>b+1),children:"Retry preview"}):void 0,children:a.jsx("div",{className:"pc-artifact-preview__content",style:l&&l.url===t.url?{"--pc-media-width":`${l.width}px`,"--pc-media-aspect":l.width/l.height}:void 0,onLoadCapture:b=>{let k=b.target;k instanceof HTMLImageElement&&k.naturalWidth&&k.naturalHeight&&k.src===t.url&&u({url:k.src,width:k.naturalWidth,height:k.naturalHeight})},onLoadedMetadataCapture:b=>{let k=b.target;k instanceof HTMLVideoElement&&k.videoWidth&&k.videoHeight&&k.src===t.url&&u({url:k.src,width:k.videoWidth,height:k.videoHeight})},children:a.jsx(Hv,{name:e.name,onDownload:()=>void j(),status:t.status,kind:t.kind,contentType:t.contentType,text:t.text,url:t.url,error:t.error,partialNote:t.partialNote,markdownImages:"link",inlineImage:()=>!1})})})}function yj(e){let t=e.tags&&typeof e.tags=="object"?e.tags:{},n=e.artifact_envelope_v1&&typeof e.artifact_envelope_v1=="object"?e.artifact_envelope_v1:{};return["node_trace_offload","run_output_offload","run_input_offload","conversation_offload","session_offload","state_offload"].includes(String(t.source||e.source||""))||["internal","bookkeeping"].includes(String(t.role||n.role||e.role||""))}var Tu=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},wj=p.createContext(void 0);function _j({artifact:e}){let t=p.useContext(wj),[n,s]=p.useState(e.name||"Attached file"),[o,l]=p.useState(""),[u,d]=p.useState(!1),[f,m]=p.useState(!1),[g,v]=p.useState("loading"),[w,x]=p.useState(0),j=ut(`runs/${encodeURIComponent(e.runId)}/artifacts/${encodeURIComponent(e.id)}`);return p.useEffect(()=>{let b=new AbortController;return s(e.name||"Attached file"),l(""),m(!1),v("loading"),t&&t(j,{signal:b.signal}).then(async k=>{if(!k.ok)throw await Ur(k,"Attachment unavailable");let $=await k.json(),S=Tu($.tags),N=Tu($.descriptor),C=Tu($.artifact_envelope_v1),R=yj($);b.signal.aborted||(m(R),v("ready"));let E=$.filename||$.name||S.filename||N.name||C.name;!b.signal.aborted&&typeof E=="string"&&s(E)}).catch(k=>{b.signal.aborted||(v("error"),l(k instanceof Error?k.message:String(k)))}),()=>{b.abort()}},[t,j,w]),p.useEffect(()=>{e.name&&s(e.name)},[e.name]),f?a.jsx(a.Fragment,{}):a.jsxs("span",{className:"pc-message-artifact",children:[a.jsxs("button",{type:"button",className:"pc-chat-attachment-chip","aria-haspopup":"dialog",disabled:!t||g!=="ready",onClick:()=>d(!0),children:[a.jsx(be,{name:"paperclip",size:14}),a.jsx("span",{className:"pc-chat-attachment-name",children:n})]}),o&&a.jsxs("span",{role:"status",className:"pc-message-artifact__error",children:[o," ",a.jsxs("button",{type:"button",onClick:()=>x(b=>b+1),children:["Retry ",n]})]}),u&&t&&a.jsx(vj,{name:n,path:j,fetchGateway:t,onClose:()=>d(!1)})]})}var bj=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),xj=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 Gv(e){let t=String(e??"");if(!t.trim())return!1;try{let 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 kj(e,t){let n=String(t||"").split("/").pop()||"",s=n.lastIndexOf(".");if(s>0&&bj.has(n.slice(s+1).toLowerCase()))return!1;let o=String(e||"").split(";",1)[0].trim().toLowerCase();return!o||o==="text/html"||o.includes("xml")?!1:xj.has(o)}function jj(e){let t=n=>!!n&&(!Gv(n)||kj(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}var Sj=3,Nj=Number.MAX_SAFE_INTEGER;function Kv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Jv(e){return Array.isArray(e)}function Cj(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function qa({kind:e,children:t}){return a.jsx("span",{className:`pc-json-token ${e}`,children:t})}function Ej(e){let t=JSON.stringify(e.value),n=!/^https?:\/\/[^\s]+$/i.test(e.value)&&(t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t")),[s,o]=p.useState(!n||e.expansionMode==="unfolded");return p.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:a.jsx(Cu,{text:e.value})}):a.jsxs("span",{className:"pc-json-string__preview",children:[a.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:a.jsx(Cu,{text:e.value})}),a.jsx("button",{type:"button",className:"pc-json-string__suffix",onClick:()=>o(!0),"aria-label":"Expand string value",children:"(...)"})]})]}):a.jsx("span",{className:"pc-json-token string",children:a.jsx(Cu,{text:e.value})})}function Tj(e,t,n){return e===null?a.jsx(qa,{kind:"null",children:"null"}):typeof e=="string"?a.jsx(Ej,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?a.jsx(qa,{kind:"number",children:String(e)}):typeof e=="boolean"?a.jsx(qa,{kind:"boolean",children:e?"true":"false"}):a.jsx(qa,{kind:"string",children:JSON.stringify(String(e))})}function Aj(e){return Jv(e)?e.length===1?"1 item":`${e.length} items`:Kv(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Yv(e){let{label:t,value:n,depth:s,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:d}=e,f=s*14,m=Kv(n),g=Jv(n),v=m||g,w=s<o,[x,j]=p.useState(w);p.useEffect(()=>{j(w)},[w,u]);let b=t?a.jsxs(a.Fragment,{children:[a.jsx(qa,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!v)return a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,Tj(n,l,u),d?",":""]});let k=g?"[":"{",$=g?"]":"}",S=Aj(n),N=x?`${k}`:`${k}…${$}${S?` (${S})`:""}`,C=g?n.map((R,E)=>({key:String(E),label:void 0,value:R})):Object.entries(n).map(([R,E])=>({key:R,label:R,value:E}));return a.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:R=>j(R.currentTarget.open),children:[a.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[b,a.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),a.jsx("span",{className:"pc-json-viewer__punct",children:N}),!x&&d?a.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?a.jsx("div",{className:"pc-json-viewer__children",children:C.length===0?a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[a.jsx("span",{className:"pc-json-viewer__punct",children:$}),d?",":""]}):a.jsxs(a.Fragment,{children:[C.map((R,E)=>{let I=E===C.length-1;return a.jsx(Yv,{label:R.label,value:R.value,depth:s+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!I},`${s}:${t||"root"}:${R.key}`)}),a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[a.jsx("span",{className:"pc-json-viewer__punct",children:$}),d?",":""]})]})}):null]})}function $j(e){let 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 Jo(e){let{value:t,className:n,showCopy:s=!0}=e,[o,l]=p.useState({mode:"folded",version:0}),[u,d]=p.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):Sj,m=o.mode==="unfolded"?Nj:f,g=p.useMemo(()=>typeof t=="string"?$j(t):t,[t]),v=p.useMemo(()=>Cj(t),[t]),w=["pc-json-viewer",n].filter(Boolean).join(" ");return p.useEffect(()=>{l(x=>({mode:"folded",version:x.version+1}))},[g]),a.jsxs("div",{className:w,children:[a.jsxs("div",{className:"pc-json-viewer__toolbar",children:[a.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:()=>{l(x=>({mode:x.mode==="unfolded"?"folded":"unfolded",version:x.version+1}))},"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 bl(v).then(x=>{d(x?"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(Yv,{value:g,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function Rj(e){let t=String(e.text??""),n=p.useMemo(()=>tj(t),[t]),s=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?a.jsx("div",{className:s,children:a.jsx(Jo,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?a.jsx("div",{className:s,children:e.renderMarkdown(t)}):a.jsx("div",{className:s,children:a.jsx(Vv,{text:t,images:e.images,inlineImage:e.inlineImage})})}function Mj({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}function Lm(e){if(e.decision==="denied")return"Denied by this chat's policy";let t=e.setAt?wl(e.setAt):"",n=[e.setBy?`set by ${e.setBy}`:"",t?`at ${t}`:""].filter(Boolean).join(" ");return`Allowed by this chat's policy${n?` (${n})`:""}`}var Ft="not reported",Xt=e=>e===void 0?Ft:Math.round(e).toLocaleString(),Kt=e=>{if(e===void 0)return Ft;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.round(e/1e3);return`${Math.floor(t/60)}m ${String(t%60).padStart(2,"0")}s`},Qv=e=>e===void 0?Ft:`${Math.round(e).toLocaleString()} tok/s`,Lj=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",lr=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,Ij=e=>{let t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function Pj(e){let t=new Map;for(let n of e)n&&t.set(n,(t.get(n)||0)+1);return[...t].map(([n,s])=>s>1?`${n} ×${s}`:n).join(" · ")}function ol(e){let t=[],n=(e.models||[]).map(Ij),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 Oj(e){let t=e.modelCalls||[],n=[],s=[{label:"Input",value:Xt(e.inputTokens)},{label:"Output",value:Xt(e.outputTokens)}];if(e.reasoningTokens!==void 0&&s.push({label:"Reasoning",value:Xt(e.reasoningTokens),hint:"part of output"}),s.push({label:"Total",value:Xt(e.totalTokens)}),n.push({heading:`Usage · ${lr(e.llmCalls,"model call")}`,rows:s}),e.measuredCacheCalls){let l=e.cachedTokens||0,u=e.fedTokens||0,d=[{label:"Reused from cache",value:`${Xt(l)}${l+u?` (${Lj(l,l+u)})`:""}`},{label:"Newly processed",value:Xt(e.fedTokens)},{label:"Outcome",value:Pj(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Ft},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Ft}];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:Ft}]});let o=t.filter(l=>l.inputTokens!==void 0);return o.length===1&&t.length===1?n.push({heading:"Context",rows:[{label:"Prompt size",value:`${Xt(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Xt(o[0].inputTokens)} → ${Xt(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),Xt(l.inputTokens),l.cachedTokens===void 0?"—":Xt(l.cachedTokens),l.fedTokens===void 0?"—":Xt(l.fedTokens),Xt(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Ft:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:ol(e)}}function Ao(e,t,n,s){if(e===void 0)return Ft;let o=[Kt(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${s}${n!==void 0?` at ${Qv(n)}`:""}`),o.join(" · ")}function Dj(e){var m,g,v;let t=e.modelCalls||[],n=[],s=e.durationMs,o=[{label:"Wall clock",value:Kt(s)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Ft:`${Kt(e.genTimeMs)} · ${lr(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Kt(e.toolTimeMs)} · ${lr(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Ft:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),s!==void 0&&e.genTimeMs!==void 0){let w=s-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:w>=0?Kt(w):"overlaps (parallel runs)",hint:"wall − model − tools: routing, hand-offs, model load"})}n.push({heading:"Turn",rows:o});let l=[],u=e.ttftCalls||0,d=e.promptPhaseCalls||0;e.promptPhaseMs!==void 0?l.push({label:u&&u===d?"Prefill (TTFT)":"Prefill",value:Ao(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:Ao(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Kt(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Qv(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Ft}),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?Ao(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Ao(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});let f=e.speculation;if(f){let w=(f.draftKinds||[]).map(j=>j.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(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?Ft:`${Math.round(f.acceptanceRate*100)}% · ${Xt(f.acceptedTokens)} of ${Xt(f.draftedTokens)} drafted`}];((g=f.draftLengths)!=null&&g.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(v=f.draftLengths)!=null&&v.length?`${f.draftLengths.join("/")} tok/round`:Ft}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:x})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${Kt(e.toolTimeMs)} · ${lr(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Kt(e.slowestToolBatch.ms)} · ${Xv(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((w,x)=>[String(x+1),w.promptMs===void 0?"—":`${Kt(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Kt(w.generationMs),w.generationTokensPerSecond===void 0?"—":Math.round(w.generationTokensPerSecond).toLocaleString(),w.cacheOutcome||"—"])},note:t.some(w=>w.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:s===void 0?Ft:`${Kt(s)} wall clock`,sections:n,footer:ol(e)}}function Xv(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${lr(e.calls,"call")} (${e.tools.join(", ")})`}function Fj(e){let 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:ol(e)};let 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});let 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?`${Kt(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Ft])},note:o.some(([,d])=>d.sharedBatches)?"A batch that mixed tools ran them together; its time is not split between them.":void 0});let 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,g)=>g[1]-m[1]).map(([m,g])=>g>1?`${m} ×${g}`:m).join(" · ")}))});let u=[{label:"Tool time",value:e.toolTimeMs===void 0?Ft:`${Kt(e.toolTimeMs)} · ${lr(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Kt(e.slowestToolBatch.ms)} · ${Xv(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:`${lr(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:ol(e)}}var Au=30;function Bj(e){let t=e.changedFiles||[],n=t.slice(0,Au).map(s=>{let o=s.replace(/[\\/]+$/,""),l=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\"));return{label:l>=0&&o.slice(l+1)||o,value:l>0?o.slice(0,l):l===0?"/":"workspace folder"}});return{kind:"files",title:"Files changed",headline:lr(t.length,"file"),sections:[{heading:"Written by this turn's tools",rows:n,note:t.length>Au?`and ${lr(t.length-Au,"more file")}`:void 0}],footer:["From the run ledger: the paths of this turn's completed file-writing tool calls."]}}function $o(e,t){return e==="tokens"?Oj(t):e==="time"?Dj(t):e==="files"?Bj(t):Fj(t)}function zj(e){let 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,l)=>a.jsxs(it.Fragment,{children:[a.jsx("dt",{children:o.label}),a.jsxs("dd",{children:[a.jsx("span",{className:o.value===Ft?"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}:${l}`))}):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))})]})}var nr=8;function Uj(e){let[t,n]=p.useState(!!e.defaultOpen),[s,o]=p.useState(null),l=p.useRef(null),u=p.useRef(null),d=p.useRef(null),f=`pc-stat-${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=p.useCallback(()=>{d.current!==null&&window.clearTimeout(d.current),d.current=null},[]),g=p.useCallback(()=>{m(),n(!0)},[m]),v=p.useCallback(()=>{m(),d.current=window.setTimeout(()=>n(!1),120)},[m]);p.useEffect(()=>m,[m]),p.useLayoutEffect(()=>{if(!t){o(null);return}let b=()=>{let k=l.current,$=u.current;if(!k||!$)return;let S=k.getBoundingClientRect(),N=$.offsetWidth,C=$.offsetHeight,R=window.innerWidth,E=window.innerHeight,I=S.top-nr-C,L=S.bottom+nr,D=I>=nr?I:L+C<=E-nr?L:Math.max(nr,E-nr-C),P=Math.min(Math.max(nr,S.left),Math.max(nr,R-nr-N));o({top:D,left:P})};return b(),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[t]),p.useEffect(()=>{if(!t)return;let b=k=>{k.key==="Escape"&&n(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);let w=typeof e.onClick=="function",x=w?"button":"span",j=t?a.jsx(zj,{detail:e.detail,id:f,panelRef:u,onMouseEnter:m,onMouseLeave:v,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(x,{ref:l,...w?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",w?"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:g,onMouseLeave:v,onFocus:g,onBlur:()=>n(!1),onKeyDown:b=>{b.key==="Escape"&&n(!1)},onClick:w?()=>{var b;return(b=e.onClick)==null?void 0:b.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})]}),j&&typeof document<"u"?oi.createPortal(j,document.body):j]})}function gd(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function Wj(e){let t=gd(e);if(!t||typeof t!="object"||Array.isArray(t))return{label:"input",value:t==null?"":String(t)};let n=Object.entries(t),s=["command","query","url","file_path","path","pattern","name"].map(o=>n.find(([l])=>l===o)).find(Boolean)||n[0];return s?{label:s[0].replace(/_/g," "),value:typeof s[1]=="string"?s[1]:JSON.stringify(s[1])??""}:{label:"",value:""}}function Zv({tool:e,showCopy:t=!0}){let[n,s]=p.useState(!1),o=gd(e.arguments),l=Wj(e.arguments),u=gd(e.output),d=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,f=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,m={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},g=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,v=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(be,{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}),a.jsx(To,{text:d})]}):"No parameters"}),a.jsx("span",{className:"pc-tool-activity__status",children:m[e.status]}),e.policy?a.jsx("span",{className:"pc-tool-activity__policy","data-policy":e.policy.decision,title:Lm(e.policy),children:e.policy.decision==="denied"?"Denied by this chat's policy":"Allowed by this chat's policy"}):null,Number.isFinite(g)&&g>=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:[Kt(g),e.approvalWait?" incl. approval wait":""]}):null,a.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:a.jsx(be,{name:"chevronRight",size:13})}),e.error?a.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:f}):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:[Lm(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,a.jsx(Mj,{sandbox:e.sandbox}),e.error?a.jsxs(a.Fragment,{children:[a.jsx("h4",{children:"Error"}),a.jsx("pre",{className:"pc-tool-activity__output",children:a.jsx(To,{text: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 bl(JSON.stringify(e,null,2))),children:[a.jsx(be,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),v?a.jsx("dl",{className:"pc-tool-activity__parameters",children:v.map(([w,x])=>a.jsxs(it.Fragment,{children:[a.jsx("dt",{children:w}),a.jsx("dd",{children:x&&typeof x=="object"?a.jsx(Jo,{value:x}):a.jsx("code",{children:typeof x=="string"?a.jsx(To,{text:x}):JSON.stringify(x)})})]},w))}):e.arguments===void 0?a.jsx("p",{children:"Arguments are unavailable in this ledger."}):a.jsx(Jo,{value:o}),e.output!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("h4",{children:"Result"}),typeof u=="string"?a.jsx("pre",{className:"pc-tool-activity__output",children:a.jsx(To,{text:u})}):a.jsx("div",{className:"pc-tool-activity__output",children:a.jsx(Jo,{value:u})})]}):null]})]})}function Vj({tools:e,showCopy:t}){let 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(be,{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(Zv,{tool:s,showCopy:t},s.id))]})}var $u=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),ey=/^(\d{4})-(\d{2})-(\d{2})$/,Hd=e=>typeof e=="string"&&ey.test(e.trim());function Gd(e){if(e==null||typeof e=="string"&&!e.trim())return null;if(typeof e=="string"){let n=ey.exec(e.trim());if(n)return new Date(Number(n[1]),Number(n[2])-1,Number(n[3]))}let t=e instanceof Date?new Date(e.getTime()):new Date(typeof e=="string"?e.trim():e);return Number.isFinite(t.getTime())?t:null}function qj(e,t=new Date,n){let s=Gd(e);if(!s)return"";let o=Hd(e)?"":s.toLocaleTimeString(n,{hour:"2-digit",minute:"2-digit"}),l=$u(s),u=$u(t);if(l===u)return o||"Today";let d=$u(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1));if(l===d)return o?`Yesterday · ${o}`:"Yesterday";let f=s.getFullYear()===t.getFullYear(),m=s.toLocaleDateString(n,f?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"});return o?`${m} · ${o}`:m}function Hj(e,t){let n=Gd(e);return n?Hd(e)?n.toLocaleDateString(t,{weekday:"long",year:"numeric",month:"long",day:"numeric"}):n.toLocaleString(t,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"}):""}function Gj(e){if(Hd(e))return e.trim();let t=Gd(e);return t?t.toISOString():""}function Ru(e=new Date){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}var ni=new Set,ir=null;function ty(){var n;if(ir!==null||!ni.size||typeof setTimeout!="function")return;let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1,0,0,1);ir=setTimeout(()=>{ir=null;for(let s of[...ni])s();ty()},Math.min(Math.max(1e3,t.getTime()-e.getTime()),36e5)),(n=ir.unref)==null||n.call(ir)}function Kj(e){return ni.add(e),ty(),()=>{ni.delete(e),!ni.size&&ir!==null&&(clearTimeout(ir),ir=null)}}function Jj(){let[e,t]=p.useState(()=>Ru());return p.useEffect(()=>(t(Ru()),Kj(()=>t(Ru()))),[]),e}function Yj(e){let t=e.totalTokens!==void 0?$o("tokens",e):null,n=$o("tools",e),s=e.durationMs!==void 0?$o("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`,detail:$o("files",e)}]:[],...s?[{label:Kt(e.durationMs),detail:s}]:[]]}function Qj(e){let 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"}}var Xj=new Set(["blob:","data:","http:","https:"]);function ll(e){let t=String(e||"").trim();if(t)try{let n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return Xj.has(new URL(t,n).protocol)?t:void 0}catch{return}}function ny(e,t){return Gv(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function Zj({item:e,onOpen:t,markdown:n}){let[s,o]=p.useState(!1),l=ll(e.src),u=String(e.name||e.label||"").trim()||"File",d=jj({href:e.href?ll(e.href):void 0,src:l,contentType:e.contentType,name:e.name||e.label}),f=gs(u,e.contentType),m=Zs(f),g=typeof e.text=="string";if(!l&&!d&&!g)return null;let v=di(e.size),w=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(be,{name:"file",size:14}),a.jsx("span",{className:"pc-chat-media__file-name",title:u,children:w}),v?a.jsx("span",{className:"pc-chat-media__file-size",children:v}):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(x=>!x),children:s?"Close":"Open"}),d?a.jsx("a",{className:"pc-chat-media__link",...ny(d,String(e.name||"").trim()||w),children:"Raw file"}):null]}),s&&!t?a.jsx(Hv,{className:"pc-chat-media__viewer",name:u,kind:f,contentType:e.contentType,sizeBytes:e.size,status:m&&!g?"error":"ready",error:m&&!g?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}:{},...g?{text:e.text}:{},...l&&!m?{url:l}:{},onClose:()=>o(!1)}):null]})}function eS({item:e,onOpenFile:t,markdown:n}){let[s,o]=p.useState(!1);if(e.kind==="file")return a.jsx(Zj,{item:e,onOpen:t,markdown:n||{}});let l=ll(e.src),u=e.href?ll(e.href):void 0,d=e.kind==="image"||e.kind==="audio"||e.kind==="video"?e.kind:null;if(!d||!l&&!u)return null;let f=d==="image"?"Image":d==="video"?"Video":"Audio",m=String(e.label||"").trim()||`Generated ${f.toLowerCase()}`,g=()=>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:g}):null,l&&d==="video"?a.jsx("video",{className:"pc-chat-media__video",src:l,controls:!0,playsInline:!0,preload:"metadata","aria-label":m,onError:g}):null,l&&d==="audio"?a.jsx(Bd,{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",...ny(u,String(e.name||"").trim()||m),children:m})}):null]})}function tS(e){return e==="loading"?{icon:"loader",title:"Generating audio…",spinning:!0}:e==="playing"?{icon:"pause",title:"Pause",spinning:!1}:e==="paused"?{icon:"play",title:"Resume",spinning:!1}:{icon:"speaker",title:"Speak (TTS)",spinning:!1}}function nS(e){var se,Q,z;let t=e.message,n=p.useMemo(()=>Qj(t),[t.kind,t.level,t.role,t.title]),s=t.ts,o=Jj(),l=p.useMemo(()=>qj(s),[s,o]),u=p.useMemo(()=>Hj(s),[s]),d=p.useMemo(()=>Gj(s),[s]),[f,m]=p.useState("idle"),g=p.useRef(null);p.useEffect(()=>()=>{g.current!==null&&window.clearTimeout(g.current)},[]);let v=t.live,w=typeof e.onSpeakToggle=="function"&&n.variant==="assistant",x=w?v?"Read aloud when the reply is finished":String(t.content||"").trim()?"":"No text to read aloud":"",j=w&&!x,b=j&&((se=e.getSpeakState)==null?void 0:se.call(e,t))||"idle",k=tS(b),$=e.showCopy!==!1,S=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],N=t.statistics,C=t.stats,R=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(C)?C:N?Yj(N):[],[e.stats,C,N]),E=Array.isArray(t.media)?t.media:[],I=String(v?v.reasoning||"":t.reasoning||""),L=!!String(t.content||"").trim();if(t.toolActivity)return a.jsx(Zv,{tool:t.toolActivity,showCopy:e.showCopy});let D=(Q=e.variant)==null?void 0:Q.call(e,t),P=D==="caption",K=e.renderFooter&&!P?e.renderFooter(t):null;if(D==="hint"||t.kind==="tool_policy_decision"){let T=String(t.level||"").trim().toLowerCase();return a.jsxs("div",{className:["pc-chat-hint",T==="warn"||T==="error"?`pc-chat-hint--${T}`:"",e.className].filter(Boolean).join(" "),role:"note","data-variant":"hint",children:[a.jsx("span",{className:"pc-chat-hint__text",children:String(t.content||"")}),K!=null&&K!==!1?a.jsx("div",{className:"pc-chat-footer",children:K}):null]})}return a.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,P?"pc-chat-item--caption":"",v?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...v?{"aria-busy":!0}:{},...P?{"data-variant":"caption"}:{},children:[P?null:a.jsxs("div",{className:"pc-chat-header",children:[a.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:a.jsx(be,{name:n.icon,size:14})}),a.jsx("span",{className:"pc-chat-role",children:n.label}),v?a.jsxs("span",{className:"pc-chat-live-indicator",title:v.label?`Pending: ${v.label}`:"The reply is still being written",children:[a.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),v.label||"streaming"]}):null,v!=null&&v.caption?a.jsx("span",{className:"pc-chat-live-caption",children:v.caption}):null,a.jsx("span",{className:"pc-chat-header-spacer"}),l?a.jsx("time",{className:"pc-chat-time",dateTime:d||void 0,title:u||void 0,children:l}):null,a.jsxs("div",{className:"pc-chat-header-actions",children:[w?a.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":x||k.title,title:x||k.title,"data-speak-state":x?"unavailable":b,...x?{"aria-disabled":!0}:{},onClick:j?()=>{var T;return(T=e.onSpeakToggle)==null?void 0:T.call(e,t)}:void 0,children:a.jsx(be,{name:k.icon,size:22,className:k.spinning?"pc-chat-speak-spinner":void 0},k.icon)}):null,$?a.jsx("button",{className:`pc-chat-icon-btn ${f!=="idle"?`pc-chat-icon-btn--${f}`:""}`.trim(),type:"button","aria-label":"Copy message",title:f==="idle"?"Copy":f==="copied"?"Copied":"Copy failed",onClick:async()=>{let T=await bl(String(t.content||""));m(T?"copied":"failed"),g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>m("idle"),900)},children:a.jsx(be,{name:"copy",size:22})}):null]})]}),I.trim()&&!P?a.jsxs("details",{className:"pc-chat-thinking",children:[a.jsx("summary",{children:"Thinking"}),a.jsx("div",{className:"pc-chat-thinking-body",children:I})]}):null,L||!v&&!E.length?a.jsx("div",{className:"pc-chat-body",children:a.jsx(Rj,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,E.length?a.jsx("div",{className:"pc-chat-media",children:E.map((T,q)=>a.jsx(eS,{item:T,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},T.id||`${T.kind}:${T.src}:${q}`))}):null,(z=t.artifactRefs)!=null&&z.length?a.jsx("div",{className:"pc-chat-attachments","aria-label":"Attached files",children:t.artifactRefs.map(T=>a.jsx(_j,{artifact:T},`${T.runId}:${T.id}`))}):null,S.length?a.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:S.map((T,q)=>{let J=String(T.label||"").trim()||"attachment",B=String(T.target||"").trim(),O=String(T.title||"").trim(),Z=!!T.disabled||typeof T.onClick!="function";return a.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:O||J,onClick:Z?void 0:T.onClick,disabled:Z,children:[a.jsx(be,{name:"paperclip",size:14}),B?a.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${B}`,children:B}):null,a.jsx("span",{className:"pc-chat-attachment-name",children:J})]},T.id||`${J}:${q}`)})}):null,R.length&&!P?a.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:R.slice(0,12).map((T,q)=>{let J=String(T.label||"").trim();if(!J)return null;if(T.detail)return a.jsx(Uj,{label:J,detail:T.detail,icon:T.icon,onClick:T.onClick},T.id||`${J}:${q}`);let B=String(T.title||"").trim(),O=typeof T.onClick=="function";return a.jsxs(O?"button":"span",{...O?{type:"button"}:{},className:["pc-chat-stat",O?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:B||void 0,onClick:O?()=>{var Z;return(Z=T.onClick)==null?void 0:Z.call(T)}:void 0,children:[T.icon?a.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:T.icon}):null,a.jsx("span",{className:"pc-chat-stat-label",children:J})]},T.id||`${J}:${q}`)})}):null,K!=null&&K!==!1?a.jsx("div",{className:"pc-chat-footer",children:K}):null]})}function rS(e,t){let n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function sS(e){let t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,s=p.useRef(null),o=p.useRef(null),[l,u]=p.useState(!0),d=p.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=p.useMemo(()=>{var v;let g=[];for(let w of d){let x=g[g.length-1];w.toolActivity&&((v=x==null?void 0:x[0])!=null&&v.toolActivity)&&x[0].runId===w.runId?x.push(w):g.push([w])}return g},[d]);p.useEffect(()=>{if(!n)return;let g=s.current;if(!g)return;let v=()=>{u(rS(g,t))};return g.addEventListener("scroll",v,{passive:!0}),v(),()=>g.removeEventListener("scroll",v)},[n,t]);let m=p.useMemo(()=>{var v,w,x;let g=0;for(let j of d){g+=String(j.content??"").length;for(let b of j.artifactRefs||[])g+=b.id.length+(((v=b.name)==null?void 0:v.length)||0)+1;if(g+=(((w=j.artifactIds)==null?void 0:w.length)||0)+(((x=j.attachments)==null?void 0:x.length)||0),Array.isArray(j.media))for(let b of j.media)g+=String((b==null?void 0:b.src)??"").length+1}return`${d.length}:${g}:${String(e.afterKey??"")}`},[d,e.afterKey]);return p.useEffect(()=>{if(!n||!l)return;let g=s.current;g&&(g.scrollTop=g.scrollHeight)},[n,l,m]),p.useEffect(()=>{if(!n)return;let g=s.current;if(!g)return;let v=()=>{l&&(g.scrollTop=g.scrollHeight)};return g.addEventListener("load",v,!0),g.addEventListener("loadedmetadata",v,!0),()=>{g.removeEventListener("load",v,!0),g.removeEventListener("loadedmetadata",v,!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((g,v)=>{var j;let w=g[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+v;return w.toolActivity?a.jsx(Vj,{tools:g.map(b=>b.toolActivity),showCopy:(j=e.messageProps)==null?void 0:j.showCopy},x):a.jsx(nS,{message:w,...e.messageProps||{}},x)}),e.after,a.jsx("div",{ref:o})]})}function aS(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function ry(e){let t=[],n=[],s=e==null?void 0:e.items;if(s&&s.length){for(let l=0;l<s.length;l+=1){let u=s[l];if(!u||u.kind!=="file")continue;let 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}}let 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 iS(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.`:""}var oS={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Pa(e){return String(e).padStart(2,"0")}function lS(e,t,n){let s=String(e||"").trim();if(s&&!/^image\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i.test(s))return s;let o=oS[String(t||"").toLowerCase()]||s.split(".").pop()||"bin",l=`${n.getFullYear()}-${Pa(n.getMonth()+1)}-${Pa(n.getDate())} at ${Pa(n.getHours())}.${Pa(n.getMinutes())}.${Pa(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!s?"Pasted image":"Pasted file"} ${l}.${o}`}function cS(e,t=new Date){if(!e)return[];let n=e.types?Array.from(e.types):[];if(n.includes("text/plain")&&n.includes("text/html"))return[];let{files:s}=ry(e);return s.map(o=>{let l=lS(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}var Ha="llm.delta",qs="llm.delta_end";function uS(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ns(e){return typeof e=="string"&&e.trim()!==""}function dS(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function fS(e){return"reason"in e}function hS(e,t){let n=uS(e),s=n==null?void 0:n.kind,o=t||(typeof s=="string"&&s?s:n&&"reason"in n?qs:Ha),l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(t!==void 0&&t!==Ha&&t!==qs&&l(`unknown event name ${JSON.stringify(t)}`),!n)return l("the payload is not an object");s!==void 0&&s!==Ha&&s!==qs&&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`),ns(n.run_id)||l("run_id is missing"),ns(n.call_id)||l("call_id is missing"),dS(n.seq)||l("seq is not a non-negative integer");let u=t||s?(t||s)===qs:"reason"in n;n.root_run_id!==void 0&&!ns(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ns(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");let d={run_id:n.run_id,...ns(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ns(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:qs,...d,reason:n.reason,...ns(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:Ha,...d,text:n.text,channel:n.channel,snapshot:n.snapshot})}function pS(e,t){if(e!==Ha&&e!==qs)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 hS(n,e)}var mS={registry_scope:"tenant_catalog",bundle_id:"docs-qa",bundle_version:"0.1.1",flow_id:"docsqa001"},sy="docs";function gS(e){return ut(`docs/corpus?${new URLSearchParams({app:String(e||"")})}`)}function Mu(e){return`${String(e||"app")}-docs-assistant:${Ys()}`}function vS(e){let t={prompt:e.question,docs:e.docs,app:e.appName,use_session_history:!0};return e.attachments&&e.attachments.length&&(t.context={attachments:e.attachments}),{...mS,session_id:e.sessionId,kind:sy,input_data:t}}function ay(e){let t=e==null?void 0:e.output;if(typeof t=="string")return t.trim();let n=t==null?void 0:t.response;return typeof n=="string"?n.trim():""}function yS(e){let 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"";let 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*wS(e,t){let n=e.getReader(),s=new TextDecoder,o="",l=()=>{n.cancel().catch(()=>{})};t==null||t.addEventListener("abort",l,{once:!0});try{for(;;){let{value:u,done:d}=await n.read();if(d)break;o+=s.decode(u,{stream:!0}).replace(/\r\n/g,`
54
+ `);let f=o.indexOf(`
55
+
56
+ `);for(;f>=0;){let m=o.slice(0,f);o=o.slice(f+2);let g="message",v=[];for(let w of m.split(`
57
+ `))w.startsWith("event:")?g=w.slice(6).trim():w.startsWith("data:")&&v.push(w.slice(5).replace(/^ /,""));v.length&&(yield{event:g,data:v.join(`
58
+ `)}),f=o.indexOf(`
59
+
60
+ `)}}}finally{t==null||t.removeEventListener("abort",l)}}function _S(e,t){return new Promise((n,s)=>{if(t.aborted)return s(new DOMException("Aborted","AbortError"));let o=setTimeout(()=>{t.removeEventListener("abort",l),n()},e),l=()=>{clearTimeout(o),s(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",l,{once:!0})})}async function Br(e,t){if(!e.ok)throw await Ur(e,t);return e.json()}function bS(e){let t=e.pollMs??1e3,n=e.timeoutMs??18e4,s=null;return async(o,l)=>{var j,b,k;let{fetchGateway:u,source:d}=e;if(s===null){let $=await u(gS(d.app),{signal:l.signal,headers:{Accept:"application/json"}}),S=await Br($,`The ${d.name} documentation could not be read, so nothing was asked`),N=typeof(S==null?void 0:S.text)=="string"?S.text:"";if(!N.trim())throw new Error(`The gateway returned an empty ${d.name} documentation corpus, so nothing was asked.`);s=N}let f=String(s),m=[];for(let $ of l.files||[]){let S=new FormData;S.append("session_id",l.sessionId),S.append("file",$,$.name||"upload.bin"),S.append("filename",$.name||"upload.bin"),$.type&&S.append("content_type",$.type);let N=(j=await Br(await u(ut("attachments/upload"),{method:"POST",body:S,signal:l.signal}),`"${$.name}" could not be attached`))==null?void 0:j.attachment;if(!N||typeof N.$artifact!="string"||!N.$artifact)throw new Error(`"${$.name}" could not be attached: the gateway returned no attachment reference.`);m.push(N)}let g=await Br(await u(ut("runs/start"),{method:"POST",signal:l.signal,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(vS({question:o,docs:f,appName:d.name,sessionId:l.sessionId,attachments:m}))}),"The docs-qa workflow could not start"),v=String((g==null?void 0:g.run_id)||"");if(!v)throw new Error("The gateway did not return a run id for the docs-qa workflow.");(b=l.onRun)==null||b.call(l,v);let w=new AbortController,x=()=>w.abort();l.signal.addEventListener("abort",x,{once:!0}),l.onText&&(async()=>{var $;try{let S=await u(ut(`runs/${encodeURIComponent(v)}/ledger/stream?after=0`),{signal:w.signal,headers:{Accept:"text/event-stream"}});if(!S.ok||!S.body)return;let N="",C="";for await(let R of wS(S.body,w.signal)){let E=pS(R.event,R.data);!E||fS(E)||E.channel!=="content"||E.run_id!==v||(E.call_id!==N&&(N=E.call_id,C=""),C=E.snapshot?E.text:C+E.text,($=l.onText)==null||$.call(l,C))}}catch{}})();try{let $=Date.now()+n;for(;;){await _S(t,l.signal);let S=await Br(await u(ut(`runs/${encodeURIComponent(v)}`),{signal:l.signal}),"The docs-qa run could not be read"),N=String((S==null?void 0:S.status)||"").toLowerCase();if(N==="completed"){(k=l.onHistory)==null||k.call(l,(S==null?void 0:S.session_history)??null);let C=ay(S);if(!C)throw new Error(`The docs-qa run ${v} completed without an answer.`);return C}if(N==="failed"||N==="cancelled"){let C=S==null?void 0:S.error,R=typeof C=="string"?C:typeof(C==null?void 0:C.message)=="string"?C.message:"";throw new Error(`The docs-qa run ${N}${R?`: ${R}`:""}.`)}if(N==="waiting")throw new Error(`The docs-qa run ${v} is waiting for input it should never need. Inspect it in Observer.`);if(Date.now()>=$)throw new Error(`The docs-qa run ${v} is still running after ${Math.round(n/1e3)} s. It stays in the gateway's history.`)}}finally{l.signal.removeEventListener("abort",x),w.abort()}}}async function xS(e,t,n={}){let s=new URLSearchParams({root_only:"true",kind:sy,limit:"500",include_ledger_len:"false"}),o=await Br(await e(ut(`runs?${s}`),{signal:n.signal}),"The docs assistant history could not be read"),l=`${String(t||"app")}-docs-assistant:`,u=new Map;for(let f of Array.isArray(o==null?void 0:o.items)?o.items:[]){let m=String((f==null?void 0:f.session_id)||"");if(!m.startsWith(l)||!(f!=null&&f.run_id))continue;let g=u.get(m)||{runs:[],updatedAt:""};g.runs.push({id:String(f.run_id),created:String(f.created_at||"")});let v=String(f.updated_at||f.created_at||"");v>g.updatedAt&&(g.updatedAt=v),u.set(m,g)}let 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 w;let g=m.runs.sort((x,j)=>x.created<j.created?-1:1).map(x=>x.id),v="";try{let x=await Br(await e(ut(`runs/${encodeURIComponent(g[0])}/input_data`),{signal:n.signal}),"");v=String(((w=x==null?void 0:x.input_data)==null?void 0:w.prompt)||"").trim()}catch{v=""}return{sessionId:f,title:v||"Untitled question",updatedAt:m.updatedAt,runIds:g}}))}async function kS(e,t,n,s){var l;let o=[];for(let u of t.runIds){let[d,f]=await Promise.all([Br(await e(ut(`runs/${encodeURIComponent(u)}/input_data`),{signal:s}),"A past question could not be read"),Br(await e(ut(`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});let g=ay(f),v=String((f==null?void 0:f.status)||"").toLowerCase();o.push(g?{id:`a-${u}`,runId:u,role:"assistant",title:n,content:g,ts:String((f==null?void 0:f.updated_at)||"")||void 0}:{id:`a-${u}`,role:"assistant",title:n,level:"warn",content:v==="completed"?"This answer was empty.":`No answer: the run is ${v||"unknown"}.`})}return o}function jS(e){let[t,n]=p.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:[Sv(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(be,{name:"archive",size:16})})]})},s.sessionId))}):a.jsx("div",{className:"pc-docs-history__note",children:"No past conversations yet."})}var SS=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml)$/i;function NS(e){let t=p.useRef(null),[n,s]=p.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 g;return(g=e.onSuggestion)==null?void 0:g.call(e,m)},children:m},m))}):null]});return a.jsxs("div",{className:`pc-docs-assistant${n?" is-dragging":""}`,onDragOver:m=>{var g;!d||!aS((g=m.dataTransfer)==null?void 0:g.types)||(m.preventDefault(),s(!0))},onDragLeave:()=>s(!1),onDrop:m=>{var v,w;if(!d)return;m.preventDefault(),s(!1);let g=ry(m.dataTransfer);g.files.length&&((v=e.onAddFiles)==null||v.call(e,g.files)),g.folders.length&&((w=e.onNotice)==null||w.call(e,iS(g.folders)))},children:[a.jsx(sS,{className:"pc-docs-assistant__thread",messages:e.messages,autoScroll:!0,empty:f,messageProps:{showCopy:!0,onSpeakToggle:e.onSpeakToggle,getSpeakState:e.getSpeakState}}),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(ej,{variant:e.composerVariant,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,onAttach:d?()=>{var m;return(m=t.current)==null?void 0:m.click()}:void 0,attachDisabled:l,sendLabel:"Send",busyLabel:"Answering…",onPaste:m=>{var v;if(!d)return;let g=cS(m.clipboardData);g.length&&(m.preventDefault(),(v=e.onAddFiles)==null||v.call(e,g))},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(be,{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 g;return(g=e.onRemoveFile)==null?void 0:g.call(e,m.id)},children:a.jsx(be,{name:"x",size:12})}):null]},m.id))}):null,actions:a.jsx(a.Fragment,{children:d?a.jsx(a.Fragment,{children:a.jsx("input",{ref:t,type:"file",multiple:!0,hidden:!0,"aria-hidden":"true",tabIndex:-1,onChange:m=>{var v;let g=Array.from(m.currentTarget.files||[]);m.currentTarget.value="",g.length&&((v=e.onAddFiles)==null||v.call(e,g))}})}):null}),trailingActions:e.composerTrailingActions||l&&e.onStop?a.jsxs(a.Fragment,{children:[e.composerTrailingActions,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(be,{name:"stop",size:14})}):null]}):void 0})}),a.jsxs("div",{className:"pc-docs-assistant__footer",children:["Powered by ",e.source.name,"’s documentation."]})]})}function Ro(){return new Date().toISOString()}function CS(e,t=e.visible!==!1){ci();let{source:n}=e,s=p.useRef(e.fetchGateway);s.current=e.fetchGateway;let o=p.useMemo(()=>e.ask||bS({fetchGateway:(T,q)=>s.current(T,q),source:n}),[e.ask,n.app,n.name]),l=p.useRef(Mu(n.app)),[u,d]=p.useState([]),f=p.useRef(u);f.current=u;let[m,g]=p.useState(""),[v,w]=p.useState([]),[x,j]=p.useState(!1),[b,k]=p.useState(""),$=mj({fetchGateway:e.fetchGateway,connected:e.connected,visible:t,scope:l.current,preferences:e.voicePreferences,onError:k}),S=p.useRef(null),[N,C]=p.useState(!1),[R,E]=p.useState({state:"loading",items:[]});p.useEffect(()=>()=>{var T;return(T=S.current)==null?void 0:T.abort()},[]);let I=p.useCallback(async()=>{E(T=>({...T,state:"loading"}));try{let T=await xS((q,J)=>s.current(q,J),n.app);E({state:"ready",items:T})}catch(T){E({state:"error",items:[],error:String((T==null?void 0:T.message)||T)})}},[n.app]),L=p.useCallback(async T=>{var q;(q=S.current)==null||q.abort(),$.stop(),E(J=>({...J,state:"loading"}));try{let J=await kS((B,O)=>s.current(B,O),T,n.name);l.current=T.sessionId,d(J),k(""),C(!1),E(B=>({...B,state:"ready"}))}catch(J){E(B=>({...B,state:"error",error:String((J==null?void 0:J.message)||J)}))}},[n.name]),D=p.useCallback(async T=>{try{let q=await s.current(ut(`sessions/${encodeURIComponent(T.sessionId)}/archive`),{method:"POST"});if(!q.ok)throw await Ur(q,"The conversation could not be archived");l.current===T.sessionId&&(l.current=Mu(n.app),d([])),E(J=>({...J,items:J.items.filter(B=>B.sessionId!==T.sessionId)}))}catch(q){E(J=>({...J,state:"error",error:String((q==null?void 0:q.message)||q)}))}},[n.app]);p.useEffect(()=>{var T;e.connected||((T=S.current)==null||T.abort())},[e.connected]),p.useEffect(()=>()=>{for(let T of v)T.preview&&URL.revokeObjectURL(T.preview)},[]);let P=p.useCallback(T=>{k(""),w(q=>[...q,...T.map(J=>({id:Ys(),file:J,preview:SS.test(J.type)&&typeof URL<"u"&&typeof URL.createObjectURL=="function"?URL.createObjectURL(J):void 0}))])},[]),K=p.useCallback(async T=>{let q=String(T||"").trim();if(!q||x||!e.connected)return;let J=v;g(""),w([]),k("");let B=J.filter(me=>me.preview).map(me=>({kind:"image",src:me.preview,label:me.file.name})),O=J.map(me=>({id:me.id,label:me.file.name,title:me.file.name,disabled:!0})),Z={id:`u-${Ys()}`,role:"user",content:q,ts:Ro(),...B.length?{media:B}:{},...O.length?{attachments:O}:{}},M=`a-${Ys()}`,W=[...f.current,Z],Y={id:M,role:"assistant",title:n.name,content:"",ts:Ro(),live:{callId:M,reasoning:"",label:"answering"}};d([...W,Y]),j(!0);let oe=new AbortController;S.current=oe;let de=me=>d([...W,me]);try{let me=await o(q,{signal:oe.signal,sessionId:l.current,files:J.map(ee=>ee.file),onRun:ee=>{Y={...Y,runId:ee},oe.signal.aborted||de(Y)},onText:ee=>{oe.signal.aborted||de({...Y,content:ee,live:{callId:M,reasoning:"",label:"streaming"}})},onHistory:ee=>k(yS(ee))});oe.signal.aborted||de({id:M,runId:Y.runId,role:"assistant",title:n.name,content:me,ts:Ro()})}catch(me){let ee=oe.signal.aborted;de({id:M,role:"assistant",title:n.name,level:ee?"warn":"error",content:ee?"Stopped. Nothing more will be shown for this question.":String((me==null?void 0:me.message)||me||"The docs assistant failed."),ts:Ro()})}finally{S.current===oe&&(S.current=null),j(!1)}},[o,x,v,e.connected,n.name]),se=()=>{var T;$.stop(),(T=S.current)==null||T.abort(),l.current=Mu(n.app),d([]),w([]),g(""),k("")},Q=a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:`pc-docs-assistant__icon-btn${N?" is-active":""}`,"aria-label":"Past conversations","data-af-tip":"Past conversations","aria-pressed":N,disabled:!e.connected||x,onClick:()=>{let T=!N;C(T),T&&I()},children:a.jsx(be,{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:!u.length&&!m&&!v.length&&!N,onClick:()=>{se(),C(!1)},children:a.jsx(be,{name:"compose",size:16})})]}),z=a.jsxs(a.Fragment,{children:[N?a.jsx("div",{className:"pc-docs-assistant pc-docs-assistant--history",children:a.jsx(jS,{items:R.items,state:R.state,error:R.error,nowMs:Date.now(),activeSessionId:l.current,onOpen:T=>void L(T),onArchive:T=>void D(T)})}):null,a.jsx("div",{hidden:N,style:{display:N?"none":"contents"},children:a.jsx(NS,{composerVariant:e.composerVariant,composerTrailingActions:$.dictationAvailable?a.jsx(al,{voice:$.voice,mode:$.captureMode,routeText:$.routeText,showStatus:!1,unavailableReason:$.microphoneReason,onTranscript:T=>g(q=>q.trim()?`${q.trim()} ${T.trim()}`:T.trim())}):void 0,source:n,messages:u,onSpeakToggle:$.onSpeakToggle,getSpeakState:$.getSpeakState,draft:m,onDraftChange:g,onSend:()=>void K(m),onStop:()=>{var T;return(T=S.current)==null?void 0:T.abort()},busy:x,blockedNotice:e.connected?void 0:"Connect to the gateway to use the docs assistant.",files:v.map(T=>({id:T.id,name:T.file.name})),onAddFiles:P,onNotice:k,onRemoveFile:T=>w(q=>{let J=q.find(B=>B.id===T);return J!=null&&J.preview&&URL.revokeObjectURL(J.preview),q.filter(B=>B.id!==T)}),notice:b,suggestions:e.suggestions,onSuggestion:T=>void K(T),placeholder:e.placeholder})})]});return{headerActions:Q,body:z}}function ES(e){let{headerActions:t,body:n}=CS(e);return a.jsxs("div",{className:"pc-docs-assistant-panel",children:[a.jsx(Yk,{children:t}),n]})}function TS(e,t,n){let{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",fill:!0,defaultWidth:d??420,content:a.jsx(ES,{source:e,fetchGateway:t,...f})}}var AS=new Set(["board","inbox","server","agent","playCircle","list","gear"]);function $S(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"about":return a.jsxs(a.Fragment,{children:[a.jsx("circle",{cx:"12",cy:"12",r:"9"}),a.jsx("circle",{cx:"12",cy:"7.5",r:"1.5",fill:"currentColor",stroke:"none"}),a.jsx("path",{d:"M12 11v6"})]});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"wrench":return a.jsx("path",{d:"M14.5 6.5 18 3a6 6 0 0 0-7.6 7.6L3 18a2.1 2.1 0 0 0 3 3l7.4-7.4A6 6 0 0 0 21 6l-3.5 3.5-3-3Z"});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 cs({name:e,size:t=16,className:n,title:s,...o}){const l=s?void 0:!0,u=AS.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,$S(e)]})}var iy=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Ga=6e4,Ka=60*Ga,Mo=24*Ka;function xl(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)?xl(Number(t)):Date.parse(t)}function Im(e){return e<10?`0${e}`:String(e)}function Pm(e,t){const n=xl(e);if(!Number.isFinite(n))return"";const s=new Date(n),o=s.getFullYear()===new Date(t).getFullYear();return`${iy[s.getMonth()]} ${s.getDate()}${o?"":`, ${s.getFullYear()}`}`}function RS(e){const t=xl(e);if(!Number.isFinite(t))return"";const n=new Date(t);return`${iy[n.getMonth()]} ${n.getDate()}, ${n.getFullYear()}, ${Im(n.getHours())}:${Im(n.getMinutes())}`}function MS(e,t){const n=xl(e);if(!Number.isFinite(n)||!Number.isFinite(t))return"";const s=t-n;if(s<0){const l=-s;if(l<Ga)return"due now";if(l<Ka)return`in ${Math.round(l/Ga)} min`;if(l<Mo)return`in ${Math.round(l/Ka)} h`;const u=Math.round(l/Mo);return u<7?`in ${u} ${u===1?"day":"days"}`:Pm(n,t)}if(s<Ga)return"just now";if(s<Ka)return`${Math.floor(s/Ga)} min ago`;if(s<Mo)return`${Math.floor(s/Ka)} h ago`;const o=Math.floor(s/Mo);return o===1?"yesterday":o<7?`${o} days ago`:Pm(n,t)}function oy(e){const t=e.needsAttention?"attention":e.working?"working":e.failed?"failed":e.unread?"unread":"";return a.jsxs("div",{className:`af-session-card${e.className?` ${e.className}`:""}`,"data-selected":e.selected||void 0,"data-unread":e.unread||void 0,"data-attention":e.needsAttention||void 0,"data-working":e.working||void 0,"data-failed":e.failed||void 0,children:[a.jsxs("button",{type:"button",className:"af-session-card__open",...e.openAttributes,disabled:e.disabled,"aria-current":e.selected?"page":void 0,"aria-label":`${e.title}${e.description?`. ${e.description}`:""}`,onClick:e.onOpen,children:[a.jsxs("span",{className:"af-session-card__heading",children:[t&&a.jsx("span",{className:`af-session-card__marker is-${t}`,"aria-hidden":"true"}),a.jsx("span",{className:"af-session-card__title",title:e.title,children:e.title})]}),a.jsx("span",{className:"af-session-card__meta",children:e.metadata})]}),e.onArchive&&a.jsx("button",{type:"button",className:"af-session-card__archive","aria-label":`Archive ${e.title}`,title:e.archiveTitle||"Archive conversation",disabled:e.disabled||e.archiveDisabled,onClick:e.onArchive,children:a.jsx(cs,{name:"archive",size:14})})]})}function LS(e){const t=[e.needsAttention?"Needs you":"",e.unread?"New messages":"",e.working?"Working":""].filter(Boolean).join(". "),n=d=>typeof d=="number"&&Number.isSafeInteger(d)&&d>=0,s=MS(e.updatedAt,e.nowMs),o=d=>`${e.countsPartial?"≥":""}${d}`,l=(d,f)=>`${e.countsPartial?"At least ":""}${d} ${f}${d===1?"":"s"}`,u=[t,n(e.turnCount)?l(e.turnCount,"turn"):"",n(e.toolCount)&&e.toolCount>0?l(e.toolCount,"tool call"):"",s].filter(Boolean).join(". ");return a.jsx(oy,{...e,description:u,openAttributes:{"data-session-id":e.sessionId},metadata:a.jsxs(a.Fragment,{children:[n(e.turnCount)&&a.jsxs("span",{"aria-label":l(e.turnCount,"turn"),title:l(e.turnCount,"turn"),children:[a.jsx(cs,{name:"chat",size:14}),a.jsx("span",{"aria-hidden":"true",children:o(e.turnCount)})]}),n(e.toolCount)&&e.toolCount>0&&a.jsxs("span",{"aria-label":l(e.toolCount,"tool call"),title:l(e.toolCount,"tool call"),children:[a.jsx(cs,{name:"wrench",size:14}),a.jsx("span",{"aria-hidden":"true",children:o(e.toolCount)})]}),e.needsAttention?a.jsx("span",{className:"af-session-card__attention",children:"Needs you"}):s&&a.jsxs("span",{className:"af-session-card__time",title:RS(e.updatedAt),children:[a.jsx(cs,{name:"clock",size:14}),a.jsx("span",{children:s})]})]})})}function ly(e){const t=e.trigger.config;if(typeof t.every=="string"){const n=/^([1-9][0-9]*)([smhd])$/.exec(t.every);if(n){const s=Number(n[1])*({s:1,m:60,h:3600,d:86400}[n[2]]||1);if(Number.isSafeInteger(s)){for(const[o,l]of[[86400,"d"],[3600,"h"],[60,"m"],[1,"s"]])if(s%o===0)return`${s/o}${l}`}}}return e.trigger.source_id==="schedule"?{daily:"Daily",weekly:"Weekly",monthly:"Monthly",once:"Once"}[String(t.kind)]||(e.trigger.source_version===1&&!t.every?"Once":e.schedule_rule_text||"Schedule"):e.trigger.source_id.startsWith("email")?"Email":e.trigger.source_id==="manual"?"Manual":e.trigger_text||e.schedule_rule_text||"Event"}function cy(e,t){const n=e?Date.parse(e):NaN;if(!Number.isFinite(n)||!Number.isFinite(t))return"";const s=Math.floor((n-t)/1e3);return s<=30?"now":s<3600?`${Math.max(1,Math.floor(s/60))}m`:s<172800?`${Math.floor(s/3600)}h`:`${Math.floor(s/86400)}d`}function IS(e){var x;const t=e.summary,n=t.attention.pending_waits>0,s=Math.max(0,t.attention.unseen_count),o=!!t.current_occurrence&&!n,l=((x=t.last_occurrence)==null?void 0:x.status)==="failed"||t.status==="failed",u=ly(t),d=t.next_run_at,f=t.status==="active"?cy(d,e.nowMs):"",m=t.status==="paused"?"Paused":t.status==="archived"?"Archived":t.status==="failed"?"Failed":t.status==="completed"?"Ended":"",g=Number.isSafeInteger(t.occurrence_count)&&t.occurrence_count>=0?t.occurrence_count:null,v=t.trigger_text||t.schedule_rule_text||u,w=[n?"Needs you":o?"Running":"",l?"Last run failed":"",s?`${s} new results`:"",g!==null?`Ran ${g} ${g===1?"time":"times"}`:"",m||v,f?`Next run ${f==="now"?"due now":`in ${f}`}`:""].filter(Boolean).join(". ");return a.jsx(oy,{title:t.title||"Automation",description:w,selected:e.selected,className:`af-automation-card${e.className?` ${e.className}`:""}`,unread:s>0||t.attention.unread,needsAttention:n,working:o,failed:l,openAttributes:{"data-automation-id":t.automation_id,"data-status":t.status},disabled:e.disabled,onOpen:e.onOpen,onArchive:e.onArchive,archiveDisabled:e.archiveDisabled,archiveTitle:e.archiveTitle||"Archive automation",metadata:a.jsxs(a.Fragment,{children:[g!==null&&a.jsxs("span",{"data-field":"runs",title:`Ran ${g} times`,"aria-label":`${g} runs`,children:[a.jsx(cs,{name:"loop",size:14}),a.jsx("span",{"aria-hidden":"true",children:g})]}),a.jsxs("span",{className:"af-automation-card__schedule","data-field":"cadence",title:v,"aria-label":m||v,children:[a.jsx(cs,{name:t.status==="paused"?"pause":m?"stop":"clock",size:14}),a.jsx("span",{"aria-hidden":"true",children:m||u})]}),f&&a.jsxs("span",{"data-field":"next",title:`Next run: ${d}`,"aria-label":`Next run ${f==="now"?"due now":`in ${f}`}`,children:[a.jsx(cs,{name:"playCircle",size:14}),a.jsx("span",{"aria-hidden":"true",children:f})]}),n&&a.jsx("span",{className:"af-session-card__attention",children:"Needs you"}),s>0&&a.jsx("span",{className:"af-automation-card__unseen","aria-label":`${s} new results`,title:`${s} new results`,children:s})]})})}function vd(e,t){return JSON.stringify([e,["completed","failed","cancelled"].includes(t.toLowerCase())?t.toLowerCase():"request"])}function uy(e){const t=e.waiting&&typeof e.waiting=="object"?e.waiting:{};return e.status==="waiting"&&(t.reason==="user"||e.wait_reason==="user")}function dy(e){const t=e.session_kind??e.sessionKind;return t&&t!=="chat"&&t!=="discussion"||e.role==="controller"?!1:e.role==="occurrence"||!String(e.parent_run_id??e.parentRunId??"").trim()}function PS(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(e)?e:Array.isArray(t.items)?t.items:Array.isArray(t.runs)?t.runs:[],s=new Map;for(const u of n){if(!u||typeof u!="object"||!dy(u)||typeof u.session_id!="string"||typeof u.run_id!="string")continue;const d=s.get(u.session_id)??[];d.push(u),s.set(u.session_id,d)}const o=Object.create(null),l=u=>Date.parse(String(u.created_at||u.updated_at||""))||0;for(const[u,d]of s){d.sort((g,v)=>l(v)-l(g));const f=d[0],m=d.map(g=>g.tool_calls);o[u]={revision:vd(String(f.run_id),String(f.status||"")),updatedAt:String(f.updated_at||f.created_at||""),content:d.map(g=>({sessionId:u,runId:String(g.run_id),status:String(g.status||""),revision:vd(String(g.run_id),String(g.status||"")),updatedAt:String(g.updated_at||g.created_at||"")})),needsAttention:d.some(uy),working:d.some(g=>["running","queued","pending"].includes(String(g.status))),...m.every(g=>typeof g=="number"&&Number.isSafeInteger(g)&&g>=0)?{toolCount:m.reduce((g,v)=>g+v,0)}:{}}}return o}function fy(e){var s,o,l,u,d,f;const t=(o=(s=e==null?void 0:e.gateway)==null?void 0:s.principal)==null?void 0:o.user_id;if(!t||!(e!=null&&e.gateway_url))return"";let n;try{const m=new URL(e.gateway_url);m.username="",m.password="",m.search="",m.hash="",n=m.href.replace(/\/+$/,"")}catch{return""}return JSON.stringify([n,((u=(l=e.gateway)==null?void 0:l.principal)==null?void 0:u.tenant_id)||"",t,((f=(d=e.gateway)==null?void 0:d.principal)==null?void 0:f.runtime_id)||""])}var Om=class{constructor(e,t,n=Date.now()){this.storage=t,this.error="",this.memory=new Set,this.prefix=`af.session-read.v1:${encodeURIComponent(e)}:`;let s=n;e&&!t&&(this.error="Read markers could not be saved in this browser.");try{const o=t==null?void 0:t.getItem(this.prefix+"since"),l=Number(o);o&&Number.isFinite(l)&&l>0&&l<=n?s=l:t==null||t.setItem(this.prefix+"since",String(n))}catch{this.error="Read markers could not be saved in this browser."}this.since=s}key(e){return this.prefix+encodeURIComponent(JSON.stringify(e.sessionId))+":"+encodeURIComponent(JSON.stringify(e.revision))}observe(e){Date.parse(e.updatedAt)<this.since&&this.markRead(e)}isUnread(e){var n;if(!e.sessionId||!e.revision||!Number.isFinite(Date.parse(e.updatedAt))||Date.parse(e.updatedAt)<this.since)return!1;const t=this.key(e);if(this.memory.has(t))return!1;try{return!((n=this.storage)!=null&&n.getItem(t))}catch{return!0}}markRead(e){var n,s,o,l;if(!e.sessionId||!e.revision)return;const t=this.key(e);if(!this.memory.has(t)){this.memory.add(t);try{if((n=this.storage)!=null&&n.getItem(t))return;(s=this.storage)==null||s.setItem(t,String(Date.now()));const u=[];for(let d=0;d<(((o=this.storage)==null?void 0:o.length)||0);d++){const f=this.storage.key(d);f!=null&&f.startsWith(this.prefix)&&f!==this.prefix+"since"&&u.push([f,Number(this.storage.getItem(f))||0])}u.sort((d,f)=>f[1]-d[1]);for(const[d]of u.slice(4096))d!==t&&((l=this.storage)==null||l.removeItem(d))}catch{this.error="Read markers could not be saved in this browser."}this.memory.size>4096&&this.memory.delete(this.memory.values().next().value)}}};function hy(e,t,n){const s=n==="failed"?"Request failed.":n==="cancelled"?"Request cancelled.":void 0,o=n==="completed"?"assistant":"user",l=e.filter(u=>u.runId===t&&!u.live&&!u.toolActivity&&u.role===o);return{message:l[l.length-1],...s?{outcome:s}:{}}}function OS(e,t,n){return!(t!=null&&t.length)||t[0].runId!==n?[]:t.filter(s=>!!hy(e,s.runId,s.status).message)}function ri(e){const t=JSON.parse(e.revision);if(!Array.isArray(t)||t.length!==2||!e.sessionId)throw Error("Invalid session read revision");const[n,s]=t;if(typeof n!="string"||!n||!["request","completed","failed","cancelled"].includes(s))throw Error("Invalid session read revision");return{session_id:e.sessionId,run_id:n,status:s}}function yd(e){if(!e||!Number.isSafeInteger(e.sequence)||e.sequence<1||typeof e.event_id!="string"||!e.event_id||typeof e.session_id!="string"||!e.session_id||typeof e.run_id!="string"||!e.run_id||typeof e.at!="string"||!Number.isFinite(Date.parse(e.at))||!["request","completed","failed","cancelled"].includes(e.status))throw Error("Invalid shared read receipt");return{sessionId:e.session_id,revision:JSON.stringify([e.run_id,e.status]),updatedAt:e.at}}var $r=e=>JSON.stringify([e.sessionId,e.revision]);function DS(e){async function t(n,s){var u;const o=await e(`api/gateway/me/session-reads${n}`,s);if(!o.ok){const d=Object.assign(new Error(`Shared read state unavailable (HTTP ${o.status}).`),{status:o.status});throw await((u=o.body)==null?void 0:u.cancel()),d}const l=await o.json();if(!l||!Array.isArray(l.items)||l.more)throw Error("Shared read state returned an incomplete page.");for(const d of l.items)yd(d);return l.items}return{async load(n,s){const o=[...new Set(n.map(u=>ri(u).run_id))].sort(),l=[];for(let u=0;u<o.length;u+=100){const d=new URLSearchParams({limit:"1000"});for(const f of o.slice(u,u+100))d.append("run_id",f);l.push(...await t(`?${d}`,{signal:s}))}return l},async mark(n,s){const o=[];for(let l=0;l<n.length;l+=100)o.push(...await t("",{method:"POST",signal:s,headers:{"Content-Type":"application/json"},body:JSON.stringify({receipts:n.slice(l,l+100).map(ri)})}));return o}}}function FS(e,t,n){const[,s]=p.useState(0),o=p.useRef(t);o.current=t;const l=p.useMemo(()=>({keys:new Map,pending:new Map,controllers:new Set,active:!1,generation:0,loaded:!1,writing:!1,queued:!1,readError:"",writeError:""}),[e,n]),u=p.useCallback(v=>{const w=new Set(o.current.map(x=>ri(x).run_id));for(const[x,j]of l.keys)!w.has(j)&&!l.pending.has(x)&&l.keys.delete(x);for(const x of v)w.has(x.run_id)&&l.keys.set($r(yd(x)),x.run_id);s(x=>x+1)},[l]),d=p.useCallback(async()=>{if(!n||!e||!l.active||l.writing)return;l.writing=!0;const v=l.generation;try{for(;l.active&&l.generation===v&&l.pending.size;){const w=new AbortController,x=[...l.pending.values()].slice(0,100);l.controllers.add(w);try{const j=await n.mark(x,w.signal);if(!l.active||l.generation!==v)return;const b=new Set(j.map(k=>$r(yd(k))));if(x.some(k=>!b.has($r(k))))throw Error("The gateway did not confirm every read receipt. Please retry.");for(const k of x)l.pending.delete($r(k));l.writeError="",u(j)}catch(j){if(!w.signal.aborted&&l.active&&l.generation===v){l.writeError=j instanceof Error?j.message:String(j);const b=j==null?void 0:j.status;if(b&&b>=400&&b<500&&b!==408&&b!==429)for(const k of x)l.pending.delete($r(k));s(k=>k+1)}break}finally{l.controllers.delete(w)}}}finally{l.generation===v&&(l.writing=!1)}},[n,e,l,u]),f=p.useCallback(async()=>{if(!n||!e||!l.active)return;const v=new AbortController,w=l.generation;l.controllers.add(v);try{const x=await n.load([...o.current],v.signal);if(!l.active||l.generation!==w)return;l.loaded=!0,l.readError="",u(x)}catch(x){!v.signal.aborted&&l.active&&l.generation===w&&(l.readError=x instanceof Error?x.message:String(x),s(j=>j+1))}finally{l.controllers.delete(v)}await d()},[n,e,l,u,d]),m=[...new Set(t.map(v=>ri(v).run_id))].sort().join("\0");return p.useEffect(()=>{if(!n||!e)return;l.active=!0,l.generation++,l.writing=!1;const v=()=>{document.hidden||f()},w=window.setInterval(v,1e4);return window.addEventListener("focus",v),window.addEventListener("online",v),document.addEventListener("visibilitychange",v),()=>{l.active=!1,l.queued=!1;for(const x of l.controllers)x.abort();l.controllers.clear(),window.clearInterval(w),window.removeEventListener("focus",v),window.removeEventListener("online",v),document.removeEventListener("visibilitychange",v)}},[n,e,l,f]),p.useEffect(()=>{f()},[m,f]),{markRead:p.useCallback(v=>{!e||!n||!l.active||l.keys.has($r(v))||(ri(v),l.pending.set($r(v),v),!l.queued&&(l.queued=!0,queueMicrotask(()=>{l.queued=!1,d()})))},[n,e,l,d]),refresh:f,isUnread:v=>!!(e&&l.loaded&&!l.keys.has($r(v))),error:l.writeError||l.readError,loading:!l.loaded}}function BS(e){const t=p.useRef(null),n=p.useRef(e.onConsume);return n.current=e.onConsume,p.useEffect(()=>{const s=t.current;if(!s||!e.enabled)return;const o=n.current;let l,u=!1;const d=()=>{if(document.hidden||!document.hasFocus()||!s.isConnected)return!1;const g=s.getBoundingClientRect();if(g.width<=0||g.height<=0||g.top<0||g.bottom>window.innerHeight)return!1;const v=document.elementFromPoint(g.left+g.width/2,g.top+g.height/2);return v===s||!!(v&&s.contains(v))},f=()=>{u||(clearTimeout(l),d()&&(l=setTimeout(()=>{d()&&(u=!0,o())},250)))},m=new IntersectionObserver(f,{threshold:1});m.observe(s);for(const g of["focus","blur","resize","pointerup","keyup","scroll"])window.addEventListener(g,f,!0);return document.addEventListener("visibilitychange",f),f(),()=>{clearTimeout(l),m.disconnect();for(const g of["focus","blur","resize","pointerup","keyup","scroll"])window.removeEventListener(g,f,!0);document.removeEventListener("visibilitychange",f)}},[e.enabled,e.ownerKey,e.contentKey]),a.jsx("span",{ref:t,"aria-hidden":"true",className:"af-session-read-marker",style:{display:"block",width:"100%",height:1}})}function zS(e,t=[],n){const s=FS(e,n?t:[],n),[,o]=p.useState(0),l=p.useMemo(()=>{if(n)return new Om("",null);let d=null;try{d=window.localStorage}catch{}return new Om(e,e?d:null)},[e,n]);p.useEffect(()=>{if(e&&!n)for(const d of t)l.observe(d)},[e,l,t,n]),p.useEffect(()=>{if(n)return;const d=f=>{(!f.key||f.key.startsWith(l.prefix))&&o(m=>m+1)};return window.addEventListener("storage",d),()=>window.removeEventListener("storage",d)},[l,n]);const u=p.useCallback(d=>{e&&(l.markRead(d),o(f=>f+1),window.dispatchEvent(new StorageEvent("storage",{key:l.prefix})))},[e,l]);return n?s:{refresh:async()=>{},loading:!1,isUnread:d=>!!e&&l.isUnread(d),markRead:u,error:l.error}}function US(e){return a.jsx(BS,{ownerKey:e.ownerKey,contentKey:`${e.receipt.sessionId}:${e.receipt.revision}:${e.receipt.updatedAt||""}`,enabled:e.enabled,onConsume:()=>{const t=new Set;for(const n of[...e.relatedReceipts||[],e.receipt])n.sessionId!==e.receipt.sessionId||t.has(n.revision)||(t.add(n.revision),e.onRead(n))}})}const WS="0.1.0";function Dm(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]}`}const VS=3;function Fm(e){return`${Math.round(e).toLocaleString("en-US")} bytes`}function qS(e,t){if(!t||!(t>0)||e.size<=t)return null;let n=Dm(e.size),s=Dm(t);return n===s&&(n=Fm(e.size),s=Fm(t)),`${e.name||"This file"} is ${n}; the gateway accepts files up to ${s}.`}function HS(e){return`Upload failed: ${String(e||"").replace(/^[a-z_]*upload failed:?\s*/i,"").trim()||"the gateway did not say why"}`}async function GS(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 cl=e=>`${e} ${e===1?"file":"files"}`;function Bm(e,t){const n=[];return e&&n.push(`${cl(e)} attached`),t&&n.push(`${cl(t)} could not be attached`),n.join(", ")}function KS(e){const t=e.filter(o=>o.state==="queued"||o.state==="uploading").length;if(t)return`Wait for ${cl(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.`:`${cl(n.length)} were not attached. ${s?"Retry or remove":"Remove"} them before sending.`}function JS(e){const[t,n]=p.useState([]),[s,o]=p.useState(""),l=p.useRef(e);l.current=e;const u=p.useRef(new Set),d=p.useRef(0),f=p.useRef(!0);p.useEffect(()=>(f.current=!0,()=>{f.current=!1,d.current+=1}),[]);const m=($,S)=>n(N=>N.map(C=>C.id===$?{...C,...S}:C)),g=async $=>{const S=d.current,N=E=>!f.current||d.current!==S||u.current.has(E);let C=0,R=0;await GS($,l.current.concurrency??VS,async E=>{if(!(N(E.id)||!E.file)){m(E.id,{state:"uploading",error:void 0});try{const I=await l.current.upload(E.file);if(N(E.id))return;m(E.id,{state:"attached",ref:I,error:void 0}),C+=1}catch(I){if(N(E.id))return;m(E.id,{state:"failed",error:HS(I instanceof Error?I.message:String(I??""))}),R+=1}}}),f.current&&d.current===S&&(C||R)&&o(Bm(C,R))},v=$=>{if(!$.length)return[];const{maxBytes:S,thumbnail:N}=l.current,C=$.map(E=>{const I=qS(E,S),L=N==null?void 0:N(E);return{id:Ys(),file:E,name:E.name||"Untitled file",size:E.size,state:I?"refused":"queued",...I?{error:I}:{},...L?{thumbnailUrl:L}:{}}});n(E=>[...E,...C]);const R=C.filter(E=>E.state==="refused").length;return R&&o(Bm(0,R)),g(C.filter(E=>E.state==="queued")),C.map(E=>E.id)},w=$=>{const S=t.find(C=>C.id===$);if(!S||S.state!=="failed")return;const N={...S,state:"queued",error:void 0};n(C=>C.map(R=>R.id===$?N:R)),g([N])},x=$=>{u.current.add($),n(S=>S.filter(N=>N.id!==$))},j=()=>{d.current+=1,n([])},b=p.useMemo(()=>t.map(({id:$,name:S,size:N,state:C,thumbnailUrl:R,error:E})=>({id:$,name:S,size:N,state:C,...R?{thumbnailUrl:R}:{},...E?{error:E}:{}})),[t]),k=p.useMemo(()=>t.filter($=>$.state==="attached").map($=>$.ref),[t]);return{items:b,attached:k,add:v,remove:x,retry:w,clear:j,sendBlock:KS(b),announcement:s}}const Ja="llm.delta",Hs="llm.delta_end";function YS(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function rs(e){return typeof e=="string"&&e.trim()!==""}function QS(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function XS(e,t){const n=YS(e),s=n==null?void 0:n.kind,o=t||(typeof s=="string"&&s?s:n&&"reason"in n?Hs:Ja),l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(t!==void 0&&t!==Ja&&t!==Hs&&l(`unknown event name ${JSON.stringify(t)}`),!n)return l("the payload is not an object");s!==void 0&&s!==Ja&&s!==Hs&&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`),rs(n.run_id)||l("run_id is missing"),rs(n.call_id)||l("call_id is missing"),QS(n.seq)||l("seq is not a non-negative integer");const u=t||s?(t||s)===Hs:"reason"in n;n.root_run_id!==void 0&&!rs(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!rs(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const d={run_id:n.run_id,...rs(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...rs(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:Hs,...d,reason:n.reason,...rs(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:Ja,...d,text:n.text,channel:n.channel,snapshot:n.snapshot})}function ZS(e,t){if(e!==Ja&&e!==Hs)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 XS(n,e)}async function*eN(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,`
61
+ `);let f=o.indexOf(`
62
+
63
+ `);for(;f>=0;){const m=o.slice(0,f);o=o.slice(f+2);let g="message";const v=[];for(const w of m.split(`
64
+ `))w.startsWith("event:")?g=w.slice(6).trim():w.startsWith("data:")&&v.push(w.slice(5).replace(/^ /,""));v.length&&(yield{event:g,data:v.join(`
65
+ `)}),f=o.indexOf(`
66
+
67
+ `)}}}finally{t==null||t.removeEventListener("abort",l)}}const zm="replay_view_v1";class tN{constructor(){this.lastEventId="",this.buffer="",this.event="",this.data=[],this.pendingCr=!1}push(t){const n=[];let s=t;for(this.pendingCr&&s.startsWith(`
68
+ `)&&(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(`
69
+ `),...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 nN 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 rN=200;async function Lu(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 nN(e.status,t.trim());const n=new Error(t||`Gateway answered ${e.status}`);return n.status=e.status,n.detail=t,n}const Um=e=>`runs/${encodeURIComponent(e)}/view`;function sN(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(`${Um(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 Lu(u);const f=new Uint8Array(await u.arrayBuffer()),m=JSON.parse(new TextDecoder().decode(f));if((m==null?void 0:m.version)!==zm)throw new Error(`Unsupported replay view version ${JSON.stringify(m==null?void 0:m.version)} (this client reads ${zm}).`);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=${rN+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 Lu(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,g=[];for(const v of f){const w=typeof(v==null?void 0:v.run_id)=="string"?v.run_id:"";!w||m.has(w)||(m.add(w),g.push({run_id:w,...typeof v.created_at=="string"?{created_at:v.created_at}:{}}))}return g},async streamView(n,s){var g;const o={Accept:"text/event-stream"};s.lastEventId&&(o["Last-Event-ID"]=s.lastEventId);const l=await t(`${Um(n)}/stream`,{method:"GET",headers:o,signal:s.signal});if(!l.ok)throw await Lu(l);if(!l.body)throw new Error("The replay view stream has no body.");(g=s.onOpen)==null||g.call(s);const u=new tN,d=new TextDecoder,f=l.body.getReader();let m=0;try{for(;;){const{done:v,value:w}=await f.read();if(v)break;m+=w.byteLength;for(const x of u.push(d.decode(w,{stream:!0})))if(s.onFrame(x),x.event==="done")return{bytes:m}}for(const v of u.push(d.decode()))s.onFrame(v)}finally{try{await f.cancel()}catch{}}return{bytes:m}}}}function aN(e){return e.source==="replay_view"?"Live view from the gateway (replay view)":e.source==="ledger_fold"?`Rebuilt in this client from the run ledger${e.sourceReason?`: ${e.sourceReason}`:""}`:""}function iN(e){return e.toolApprovalGranted?null:e.interaction}class py extends Error{constructor(n,s,o=""){super(n);Bs(this,"status");Bs(this,"reasonCode");this.name="GatewayHttpError",this.status=s,this.reasonCode=o}}function En(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function Iu(e,t){let n="",s="";try{const o=await e.text();try{const l=JSON.parse(o),u=En(l)?l.detail:void 0;typeof u=="string"?n=u:En(u)?(n=String(u.message||u.detail||JSON.stringify(u)),s=String(u.reason_code||"")):En(l)&&typeof l.message=="string"&&(n=l.message),!s&&En(l)&&typeof l.reason_code=="string"&&(s=l.reason_code),n||(n=o)}catch{n=o}}catch{n=""}return new py(`${t}: ${n||`HTTP ${e.status}`}`,e.status,s)}class oN{constructor(t){Bs(this,"fetchGateway",(t,n={})=>{const s=String(n.method||"GET").toUpperCase(),o=s!=="GET"&&s!=="HEAD";try{const l={...n.headers,...this.host.auth.headers(o)};return fetch(t,{...n,headers:l,credentials:this.host.auth.credentials})}catch(l){return Promise.reject(l)}});Bs(this,"replayFetch",(t,n={})=>{try{const s={...n.headers,...this.host.auth.headers(!1)};return fetch(this.host.gatewayUrl(t),{...n,headers:s,credentials:this.host.auth.credentials})}catch(s){return Promise.reject(s)}});Bs(this,"policyRequest",async(t,n)=>{const s=await this.fetchGateway(t,{method:n.method,headers:{Accept:"application/json",...n.body===void 0?{}:{"Content-Type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}}),o=await s.text();let l=null;try{l=o?JSON.parse(o):null}catch{l=o}if(!s.ok)throw Object.assign(new py(`The chat's tool policy: HTTP ${s.status}`,s.status),{body:l});return l});this.host=t}async request(t,n,s,o){const l=t!=="GET"&&t!=="HEAD",u={Accept:"application/json",...this.host.auth.headers(l)};s!==void 0&&(u["Content-Type"]="application/json");const d=await fetch(this.host.gatewayUrl(n),{method:t,headers:u,credentials:this.host.auth.credentials,body:s===void 0?void 0:JSON.stringify(s)});if(!d.ok)throw await Iu(d,o||`${t} ${n}`);const f=await d.json();if(!En(f))throw new Error(`${o||n}: the gateway did not answer with a JSON object`);return f}me(){return this.request("GET","me",void 0,"Who am I")}capabilities(){return this.request("GET","discovery/capabilities",void 0,"Gateway capabilities")}listSessionRuns(t,n=0){const s=`runs?limit=${Math.max(1,Math.trunc(t))}&offset=${Math.max(0,Math.trunc(n))}&root_only=true&include_ledger_len=false&include_metrics=true&session_kind=chat,discussion`;return this.request("GET",s,void 0,"Conversations")}listWaitingRuns(){return this.request("GET","runs?status=waiting&root_only=false&limit=200&include_ledger_len=false",void 0,"Pending questions and approvals")}archiveSession(t){return this.request("POST",`sessions/${encodeURIComponent(t)}/archive`,{},"The conversation could not be archived")}executableBundles(t){return this.request("GET",`bundles?executable_for=${encodeURIComponent(t)}`,void 0,"Workflows")}discoveryTools(){return this.request("GET","discovery/tools",void 0,"Tools")}accountPreferences(){return this.request("GET","accounts/me/preferences",void 0,"Your preferences")}async startRun(t){if(t.flow_id==="@default"&&!t.interface)throw new Error("startRun: '@default' needs an interface");if(!t.session_id)throw new Error("startRun: a session_id is required");const n=await this.request("POST","runs/start",t,"The message could not be sent"),s=typeof n.run_id=="string"?n.run_id.trim():"";if(!s)throw new Error("The gateway accepted the message but returned no run id.");return{run_id:s,resolved_workflow:En(n.resolved_workflow)?n.resolved_workflow:null}}inputData(t){return this.request("GET",`runs/${encodeURIComponent(t)}/input_data`,void 0,"Run input")}meEvents(t,n){return this.request("GET",`me/events?after=${Math.max(0,t)}&limit=${Math.max(1,Math.trunc(n))}`,void 0,"Your events")}getRun(t){return this.request("GET",`runs/${encodeURIComponent(t)}`,void 0,"Run")}historyBundle(t){const n=`runs/${encodeURIComponent(t)}/history_bundle?include_subruns=true&include_session=true&session_turn_limit=200&ledger_mode=tail&ledger_max_items=2000&detail=replay`;return this.request("GET",n,void 0,"Conversation history")}submitCommand(t){return this.request("POST","commands",t,"The answer could not be sent")}cancelRun(t){return this.submitCommand({command_id:`cancel_${Date.now()}_${Math.random().toString(36).slice(2,10)}`,run_id:t,type:"cancel",payload:{reason:"Stopped by the user"},client_id:"abstractassistant-web"})}async uploadAttachment(t,n,s,o={}){const l=new FormData;l.set("session_id",t);for(const[m,g]of Object.entries(o))l.set(m,g);l.set("file",n,s);const u=await fetch(this.host.gatewayUrl("attachments/upload"),{method:"POST",headers:{Accept:"application/json",...this.host.auth.headers(!0)},credentials:this.host.auth.credentials,body:l});if(!u.ok)throw await Iu(u,`${s} could not be attached`);const d=await u.json(),f=En(d)?d.attachment??d.artifact:void 0;if(!En(f)||typeof f.$artifact!="string"||!f.$artifact)throw new Error(`${s}: the gateway stored the file but returned no artifact reference.`);return{ref:f,ownerRunId:String(En(d)&&d.run_id||f.run_id||"")}}async transcribe(t,n,s={}){const o=await this.request("POST",`runs/${encodeURIComponent(t)}/audio/transcribe`,{audio_artifact:{$artifact:n},...s},"Dictation failed");if(typeof o.text!="string")throw new Error("Dictation: the gateway returned no text.");return o.text.trim()}voiceCatalog(t,n){const s=new URLSearchParams({compact:"true"});return t&&s.set("provider",t),n&&s.set("model",n),this.request("GET",`voice/voices?${s.toString()}`,void 0,"Voices")}voiceDefaults(){return this.request("GET","voice/defaults",void 0,"Voice defaults")}async streamLedger(t,n,s,o){const l=await this.sse(`runs/${encodeURIComponent(t)}/ledger/stream?after=${Math.max(0,n)}`,o,u=>{if(u.event==="step"){const d=JSON.parse(u.data);if(!En(d)||typeof d.cursor!="number"||!En(d.record))throw new Error(`Live updates: a ledger step of run ${t} had no cursor or record.`);return n=d.cursor,s.onStep({cursor:d.cursor,record:d.record}),!1}return(u.event==="llm.delta"||u.event==="llm.delta_end")&&s.onDelta?(s.onDelta(u.event,u.data),!1):u.event==="done"},s.onOpen);return{cursor:n,done:l}}async ledgerPage(t,n,s=500){const o=await this.request("GET",`runs/${encodeURIComponent(t)}/ledger?after=${Math.max(0,n)}&limit=${s}`,void 0,"Run ledger");if(!Array.isArray(o.items)||typeof o.next_after!="number")throw new Error(`Run ledger of ${t}: no items or next_after in the answer.`);return{items:o.items.filter(En),next_after:o.next_after}}followMeEvents(t,n,s){return this.sse(`me/events/stream?after=${Math.max(0,t)}&heartbeat_s=15`,s,o=>(o.data&&n(JSON.parse(o.data)),!1)).then(()=>{})}async sse(t,n,s,o){const l=await fetch(this.host.gatewayUrl(t),{headers:{Accept:"text/event-stream",...this.host.auth.headers(!1)},credentials:this.host.auth.credentials,signal:n});if(!l.ok)throw await Iu(l,"Live updates");if(!l.body)throw new Error("Live updates: the gateway sent no stream.");o==null||o();const u=new AbortController,d=()=>u.abort();n.addEventListener("abort",d,{once:!0});try{for await(const f of eN(l.body,u.signal))if(s(f))return u.abort(),!0;return!1}finally{n.removeEventListener("abort",d)}}}function lN(e){var t;return((t=xb(e))==null?void 0:t.group)==="light"?"light":"dark"}function cN(e){const[t,n]=p.useState(""),[s,o]=p.useState(""),[l,u]=p.useState(!1),[d,f]=p.useState(""),m=Date.now(),g=new Date().setHours(0,0,0,0),v=new Date(g);v.setDate(v.getDate()-1);const w=e.rows.filter(b=>(e.titles[b.session_id]||"Untitled conversation").toLowerCase().includes(t.toLowerCase())),x=b=>{var k,$;return(k=e.activity[b.session_id])!=null&&k.needsAttention?"Needs you":($=e.activity[b.session_id])!=null&&$.working?"In progress":Date.parse(b.updated_at)>=g?"Today":Date.parse(b.updated_at)>=v.getTime()?"Yesterday":"Earlier"},j=["Needs you","In progress","Today","Yesterday","Earlier"].map(b=>({name:b,rows:w.filter(k=>x(k)===b)})).filter(b=>b.rows.length);return a.jsxs("div",{className:"aa-sidebar",children:[a.jsxs("div",{className:"aa-sidebar__top",children:[e.heading??a.jsx("span",{className:"aa-sidebar__heading",children:"Conversations"}),a.jsxs("button",{type:"button",className:"aa-button aa-button--primary",onClick:e.onNew,children:[a.jsx(be,{name:"plus",size:16})," New"]})]}),a.jsxs("label",{className:"aa-search",children:[a.jsx(be,{name:"chat",size:15}),a.jsx("input",{"aria-label":"Search conversations",placeholder:"Find a conversation",value:t,onChange:b=>n(b.target.value)})]}),e.error?a.jsxs("p",{className:"aa-sidebar__error",role:"alert",children:[e.error," ",a.jsx("button",{type:"button",className:"aa-link",onClick:e.onRefresh,children:"Try again"})]}):null,e.notice?a.jsx("p",{className:"aa-sidebar__more",role:"status",children:e.notice}):null,a.jsxs("div",{className:"aa-sidebar__list",children:[j.map(({name:b,rows:k})=>a.jsxs("section",{className:"aa-session-group","aria-label":b,children:[a.jsx("h2",{children:b}),a.jsx("ul",{className:"aa-sessions",children:k.map($=>{const S=e.titles[$.session_id]||"Untitled conversation",N=e.activity[$.session_id];return a.jsxs("li",{children:[a.jsx(LS,{className:"aa-session",sessionId:$.session_id,title:S,selected:$.session_id===e.activeId,unread:e.isUnread($),needsAttention:N==null?void 0:N.needsAttention,working:N==null?void 0:N.working,turnCount:$.turns,toolCount:N==null?void 0:N.toolCount,countsPartial:e.truncated,updatedAt:$.updated_at,nowMs:m,onOpen:()=>e.onOpen($),onArchive:()=>{o($.session_id),f("")},archiveDisabled:$.state==="waiting"||(N==null?void 0:N.working)||l}),s===$.session_id&&a.jsxs("div",{className:"aa-archive-confirm",children:[a.jsx("p",{children:"Archive this conversation? It can be restored later."}),a.jsx("button",{type:"button",disabled:l,onClick:async()=>{u(!0);try{await e.onArchive($),o("")}catch(C){f(C instanceof Error?C.message:String(C))}finally{u(!1)}},children:"Archive"}),a.jsx("button",{type:"button",disabled:l,onClick:()=>o(""),children:"Cancel"}),d&&a.jsx("p",{role:"alert",children:d})]})]},$.session_id)})})]},b)),!w.length&&a.jsx("p",{className:"aa-sidebar__more",children:t?"No conversations match.":"Your conversations will appear here."}),e.truncated?a.jsx("p",{className:"aa-sidebar__more",children:"Older conversations are not listed yet."}):null]}),a.jsxs("div",{className:"aa-sidebar__footer",children:[a.jsxs("button",{type:"button",onClick:e.onSettings,children:[a.jsx(be,{name:"settings",size:16})," Settings"]}),a.jsx("button",{type:"button",onClick:e.onRefresh,"aria-label":"Refresh conversations",title:"Refresh conversations",children:a.jsx(be,{name:"refresh",size:16})})]})]})}const wd="abstractcode.agent.v1",my=["30s","1m","5m","15m","30m","1h","2h","4h","6h","8h","12h","24h","48h","7d"],gy=10,Pu=e=>e.section,Ou=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):null;function uN(e){const t=((e==null?void 0:e.items)??[]).filter(o=>o.status!=="archived"),n=Ou(e==null?void 0:e.archived_automations_count)??Ou(e==null?void 0:e.archived_automations)??0;if(!t.some(o=>typeof Pu(o)=="string"))return{main:t,paused:[],pausedCount:0,archivedCount:n};const s=t.filter(o=>Pu(o)==="paused");return{main:t.filter(o=>Pu(o)!=="paused"),paused:s,pausedCount:s.length?Ou(e==null?void 0:e.paused_automations_count)??s.length:0,archivedCount:n}}function Wm(e){const t=/^([1-9][0-9]*)([smhd])$/.exec(e);return t?Number(t[1])*{s:1,m:60,h:3600,d:86400}[t[2]]:null}function vy(e){const t=z0(e);return t.charAt(0).toUpperCase()+t.slice(1)}function dN(e){const t=Wm(e),n=[...my];return!e||n.some(s=>Wm(s)===t)?n:[e,...n]}function Du(e){var n,s;const t=(s=(n=e.trigger)==null?void 0:n.config)==null?void 0:s.every;return typeof t=="string"?t:""}function fN(e){const t=/^([01][0-9]|2[0-3]):([0-5][0-9])$/.exec(e.trim());return t?`${t[1]}:${t[2]}`:""}function hN(e){const t=(e.trim().split(`
70
+ `)[0]??"").trim();return t.length<=120?t:`${t.slice(0,119)}…`}function pN(e,t,n){return t===void 0||n===void 0?null:t===n||t.length===120&&n.startsWith(t)?e.slice(0,120):null}function mN(e){const t=e.task.trim(),n=e.workflow?{...e.workflow.input_data}:{prompt:t},s=n._runtime&&typeof n._runtime=="object"&&!Array.isArray(n._runtime)?n._runtime:{},o={...n,tools:[...e.tools.tools],_runtime:{...s,allowed_tools:[...e.tools.allowed_tools]}},l=e.workflow?{bundle_ref:e.workflow.bundle_ref,flow_id:e.workflow.flow_id,input_data:o}:{flow_id:"@default",interface:wd,input_data:o},u={mode:e.buildsOnEarlierRuns?"growing":"independent"};e.buildsOnEarlierRuns&&e.growingMaxTokens&&e.growingMaxTokens>0&&(u.growing={max_tokens:e.growingMaxTokens});const d=e.tools.tool_policy,m={tool_approval:((d==null?void 0:d.require_approval_tools.length)??0)>0?"ask":"auto"};return d&&(m.tool_policy={auto_approve_tools:[...d.auto_approve_tools],require_approval_tools:[...d.require_approval_tools]}),{request_id:e.requestId,title:hN(t),target:l,trigger:{source_id:"schedule",source_version:2,config:e.when.kind==="every"?{kind:"every",every:e.when.every}:{kind:"daily",at:e.when.at}},context:u,policy:m}}function yy(e){const t=e.replace(/[\s,.'’]/g,"");if(!/^[0-9]+$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}function gN(e){var s;const t=Dd(e).slice(-gy),n=[];for(const o of t){const l=o.row;l.user_turn.trim()&&n.push({id:`run:${l.run_id}:asked`,role:"user",title:"Task",content:l.user_turn,ts:l.fired_at,runId:l.run_id});const u=o.tone==="failed",d=u?`It failed${(s=l.failure)!=null&&s.message?`: ${l.failure.message}`:"."}`:o.tone==="waiting"?"Waiting for you.":o.tone==="running"?"Working…":l.status==="cancelled"?"Stopped.":l.answer.trim()||"It finished without a written answer.";n.push({id:`run:${l.run_id}`,role:"assistant",title:"Assistant",content:d,ts:l.finished_at||l.fired_at,runId:l.run_id,...u?{level:"error"}:{}})}return n}function Vm(e){const t=Dd(e).filter(n=>n.canDiscuss).map(n=>n.row.index);return t.length?Math.max(...t):null}function vN(e){const t=Dd(e).filter(n=>n.tone==="waiting");return t.length?t[t.length-1].row:null}const Ya=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):null,Rr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function wy(e,t){var m,g,v,w;const n=Rr((g=Rr((m=Rr(t))==null?void 0:m.target))==null?void 0:g.input_data)??{},s=Rr(n._runtime)??{},o=Rr((w=Rr((v=Rr(t))==null?void 0:v.policy))==null?void 0:w.tool_policy)??Rr(s.tool_policy)??{},l=new Set(Ya(o.auto_approve_tools)??[]),u=new Set(Ya(o.require_approval_tools)??[]),d=Ya(s.allowed_tools)??Ya(n.tools),f={};for(const x of e)f[x.name]=l.has(x.name)?"auto":u.has(x.name)?"ask":d&&!d.includes(x.name)?"off":x.gatewayDefault;return f}function yN(e,t,n){return n.length>0&&n.every(s=>t.includes(s)&&e[s]!==void 0&&e[s]!=="off")}const _y="abstractassistant.automationTrust";function Kd(e){try{const t=localStorage.getItem(`${_y}:${e}`),n=t?JSON.parse(t):null;return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}catch{return{}}}function by(e,t){return Ya(Kd(e)[t])??[]}function qm(e,t,n){const s=Kd(e);n.length?s[t]=[...n].sort():delete s[t];try{localStorage.setItem(`${_y}:${e}`,JSON.stringify(s))}catch{}}function wN(e){return Object.keys(Kd(e))}const _N=6e4;function Bn(e){if(Xs(e)){const n=nk(e);return n.detail?`${n.title} ${n.detail}`:n.title}const t=e==null?void 0:e.error;return Xs(t)?Bn(t):e instanceof Error?e.message:String(e)}function bN(e){return T0({fetch:e.fetchGateway,baseUrl:""})}async function xy(e,t,n){await e.submitCommand({command_id:crypto.randomUUID(),run_id:t.run_id,type:"resume",payload:{wait_key:t.wait_key,payload:{approved:n}}})}function xN(e){const t=p.useRef(null);return p.useCallback(async()=>{if(t.current&&Date.now()-t.current.at<6e5)return t.current.items;const n=Lv(await e.discoveryTools());return t.current={at:Date.now(),items:n},n},[e])}function kN(e,t){const n=p.useMemo(()=>bN(e),[e]),s=xN(e),o=p.useRef(new Set),l=p.useCallback(async j=>{var N;const b=new Set(wN(t)),k=j.filter(C=>b.has(C.automation_id)&&C.attention.waits.some(R=>R.kind==="tool_approval"));if(!k.length)return!1;let $=!1;const S=await s();for(const C of k){const R=wy(S,(await n.getAutomation(C.automation_id)).definition),E=by(t,C.automation_id);for(const I of C.attention.waits){const L=`${I.run_id}|${I.wait_key}`,D=((N=dd(I))==null?void 0:N.map(P=>P.name))??[];o.current.has(L)||!yN(R,E,D)||(o.current.add(L),await xy(e,I,!0),$=!0)}}return $},[n,s,e,t]),[u,d]=p.useState({page:null,error:"",loading:!0,archived:null,archivedError:""}),f=p.useRef(!1),m=p.useRef(0),g=p.useCallback(async()=>{f.current=!0;try{const j=await n.listAutomations({status:"archived",limit:200});d(b=>({...b,archived:j.items,archivedError:""}))}catch(j){d(b=>({...b,archivedError:Bn(j)}))}},[n]),v=p.useCallback(async()=>{const j=++m.current;d(b=>({...b,loading:!0}));try{let b=await n.listAutomations({limit:50});if(j!==m.current||(await l(b.items).catch(()=>!1)&&(b=await n.listAutomations({limit:50})),j!==m.current))return;d(k=>({...k,page:b,error:"",loading:!1})),f.current&&g()}catch(b){if(j!==m.current)return;d(k=>({...k,error:Bn(b),loading:!1}))}},[n,g,l]);p.useEffect(()=>{v();const j=setInterval(()=>{(typeof document>"u"||document.visibilityState!=="hidden")&&v()},_N);return()=>clearInterval(j)},[v]);const w=p.useCallback(async(j,b)=>{await n.sendAutomationCommand(j,{type:b}),await v()},[n,v]),x=p.useCallback(j=>{d(b=>b.page?{...b,page:{...b.page,items:b.page.items.map(k=>k.automation_id===j.automation_id?j:k)}}:b)},[]);return{api:n,client:e,catalog:s,trustScope:t,approveTrusted:l,state:u,refresh:v,loadArchived:g,command:w,replace:x}}function jN(e){const{state:t,command:n,loadArchived:s,refresh:o}=e.automations,[l,u]=p.useState(""),[d,f]=p.useState(""),[m,g]=p.useState(""),[v,w]=p.useState(""),[x,j]=p.useState(!1),[b,k]=p.useState(!1),$=Date.now(),S=uN(t.page),N=l.trim().toLowerCase().split(/\s+/).filter(Boolean),C=P=>N.every(K=>(P.title||"").toLowerCase().includes(K)),R=N.length>0,E=S.main.filter(C),I=S.paused.filter(C),L=async(P,K)=>{g(P),w("");try{await K()}catch(se){w(Bn(se))}finally{g("")}},D=P=>a.jsxs("li",{children:[a.jsx(IS,{className:"aa-automation",summary:P,selected:P.automation_id===e.activeId,nowMs:$,onOpen:()=>e.onOpen(P),onArchive:()=>{f(P.automation_id),w("")},archiveDisabled:m===P.automation_id}),d===P.automation_id&&a.jsxs("div",{className:"aa-archive-confirm",children:[a.jsx("p",{children:"Archive this automation? It stops running. Its history is kept and it can be restored."}),a.jsx("button",{type:"button",disabled:m===P.automation_id,onClick:()=>void L(P.automation_id,async()=>{await n(P.automation_id,"automation.archive"),f("")}),children:"Archive"}),a.jsx("button",{type:"button",disabled:m===P.automation_id,onClick:()=>f(""),children:"Cancel"})]})]},P.automation_id);return a.jsxs("div",{className:"aa-sidebar","data-list":"automations",children:[a.jsxs("div",{className:"aa-sidebar__top",children:[e.heading,a.jsxs("button",{type:"button",className:"aa-button aa-button--primary",onClick:e.onNew,children:[a.jsx(be,{name:"plus",size:16})," New"]})]}),a.jsxs("label",{className:"aa-search",children:[a.jsx(be,{name:"chat",size:15}),a.jsx("input",{"aria-label":"Search automations",placeholder:"Find an automation",value:l,onChange:P=>u(P.target.value)})]}),t.error?a.jsxs("p",{className:"aa-sidebar__error",role:"alert",children:[t.error," ",a.jsx("button",{type:"button",className:"aa-link",onClick:()=>void o(),children:"Try again"})]}):null,v?a.jsx("p",{className:"aa-sidebar__error",role:"alert",children:v}):null,a.jsxs("div",{className:"aa-sidebar__list",children:[!t.page&&t.loading?a.jsx("p",{className:"aa-sidebar__more",role:"status",children:"Loading automations…"}):null,a.jsx("ul",{className:"aa-sessions",children:E.map(D)}),S.pausedCount>0&&a.jsxs("section",{className:"aa-fold","data-section":"paused",children:[a.jsxs("button",{type:"button",className:"aa-fold__toggle","aria-expanded":x||R&&I.length>0,onClick:()=>j(P=>!P),children:[a.jsx(be,{name:"pause",size:14})," Paused · ",S.pausedCount]}),(x||R&&I.length>0)&&a.jsx("ul",{className:"aa-sessions",children:I.map(D)})]}),S.archivedCount>0&&a.jsxs("section",{className:"aa-fold","data-section":"archived",children:[a.jsxs("button",{type:"button",className:"aa-fold__toggle","aria-expanded":b,onClick:()=>{const P=!b;k(P),P&&t.archived===null&&s()},children:[a.jsx(be,{name:"archive",size:14})," Archived · ",S.archivedCount]}),b&&a.jsxs("ul",{className:"aa-archived",children:[t.archived===null&&!t.archivedError?a.jsx("li",{className:"aa-sidebar__more",role:"status",children:"Loading…"}):null,t.archivedError?a.jsx("li",{className:"aa-sidebar__error",role:"alert",children:t.archivedError}):null,(t.archived??[]).map(P=>a.jsxs("li",{className:"aa-archived__row",children:[a.jsx("span",{className:"aa-archived__title",title:P.title,children:P.title||"Automation"}),a.jsx("button",{type:"button",disabled:m===P.automation_id,onClick:()=>void L(P.automation_id,async()=>{await n(P.automation_id,"automation.unarchive"),await s()}),children:m===P.automation_id?"Restoring…":"Restore"})]},P.automation_id))]})]}),t.page&&!E.length&&(R?!I.length:!S.pausedCount)?a.jsx("p",{className:"aa-sidebar__more",children:R?"No automation holds these words.":"No automations yet."}):null]}),a.jsxs("div",{className:"aa-sidebar__footer",children:[a.jsxs("button",{type:"button",onClick:e.onSettings,children:[a.jsx(be,{name:"settings",size:16})," Settings"]}),a.jsx("button",{type:"button",onClick:()=>void o(),"aria-label":"Refresh automations",title:"Refresh automations",children:a.jsx(be,{name:"refresh",size:16})})]})]})}function ky(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 SN(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function NN(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 CN(e){return e.endsWith(`
71
+ `)?e:`${e}
72
+ `}function EN(e){return String(e||"").trimStart().startsWith("```")}function TN(e,t){const s=[`# ${String((t==null?void 0:t.heading)||"Chat").trim()||"Chat"}`,""];for(const o of e){const l=NN(o);s.push(`## ${l}`,"");const u=String(o.content||""),d=ky(u);d!==null&&!EN(u)?s.push("```json",SN(d).trimEnd(),"```",""):s.push(CN(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(`
73
+ `).trimEnd()}
74
+ `}async function fi(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 AN(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)}function Jd(e){const t=[],n=/(?:https?:\/\/|www\.)[^\s<>"'`\\]+/gi;let s=0;for(const o of e.matchAll(n)){const l=o.index;if(l>0&&/[\w@]/.test(e[l-1]))continue;let u=o[0].replace(/[.,;:!?]+$/,"");for(const[f,m]of[["(",")"],["[","]"],["{","}"]])for(;u.endsWith(m)&&u.split(m).length>u.split(f).length;)u=u.slice(0,-1);const d=/^www\./i.test(u)?`https://${u}`:u;try{const f=new URL(d);if(!["http:","https:"].includes(f.protocol)||!f.hostname||/[\u0000-\u001f\u007f]/.test(d))continue}catch{continue}l>s&&t.push({text:e.slice(s,l)}),t.push({text:u,href:d}),s=l+u.length}return s<e.length&&t.push({text:e.slice(s)}),t}function us(e){return Jd(e).map((t,n)=>t.href?a.jsx("a",{className:"pc-md_link",href:t.href,target:"_blank",rel:"noopener noreferrer",children:t.text},n):t.text)}function Qa({text:e}){return a.jsx(a.Fragment,{children:us(String(e??""))})}function Fu({text:e}){return a.jsxs(a.Fragment,{children:['"',Jd(e).map((t,n)=>t.href?a.jsx("a",{className:"pc-md_link",href:t.href,target:"_blank",rel:"noopener noreferrer",children:t.text},n):JSON.stringify(t.text).slice(1,-1)),'"']})}function $N({code:e,lang:t}){const[n,s]=p.useState("idle"),o=p.useRef(null);p.useEffect(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);const l=zd(e,yl(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 fi(e);s(u?"copied":"failed"),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>s("idle"),900)},children:a.jsx(be,{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(it.Fragment,{children:u.text},d):a.jsx("span",{className:`af-code__${u.kind}`,children:u.text},d))})})]})}function Pr(e,t,n=!0){const s=String(e??"");if(n)return Jd(s).map((d,f)=>d.href?a.jsx("a",{className:"pc-md_link",href:d.href,target:"_blank",rel:"noopener noreferrer",children:Pr(d.text,t,!1)},f):a.jsx(it.Fragment,{children:Pr(d.text,t,!1)},f));if(!t||!t.needles.length)return n?us(s):[s];const o=[],l=s.toLowerCase();let u=0;for(;u<s.length;){let d=-1,f="";for(let v=0;v<t.needlesLower.length;v++){const w=t.needlesLower[v];if(!w)continue;const x=l.indexOf(w,u);if(x===-1)continue;const j=t.needles[v]||"";j&&(d===-1||x<d||x===d&&j.length>f.length)&&(d=x,f=j)}if(d===-1||!f){o.push(...n?us(s.slice(u)):[s.slice(u)]);break}d>u&&o.push(...n?us(s.slice(u,d)):[s.slice(u,d)]);const m=t.hits===0&&t.id?t.id:void 0,g=s.slice(d,d+f.length);o.push(a.jsx("span",{id:m,className:t.className,children:g},`hl:${t.hits}`)),t.hits+=1,u=d+f.length}return o}function jy(e){const t=String(e||"").trim();if(t&&/^(https?:|mailto:|tel:|#|\/)/i.test(t))return t}var _d="http://same-origin.invalid/";function RN(e){try{const t=new URL(e,_d);return t.protocol==="http:"&&t.origin===new URL(_d).origin}catch{return!1}}function Sy(e){const t=String(e||"").trim();return jy(t)??(t&&RN(t)?t:void 0)}var ds=null;function MN(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??_d;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 Ny(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 Hm(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 Pr(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 g=s.slice(o+2,f),v=Sy(s.slice(f+2,m));if(v&&ds&&!ds(v)){u(),n.push(Ny(`img:${o}`,v,g)),o=m+1;continue}if(v){u(),n.push(a.jsxs("span",{className:"pc-md_image_inline",children:[a.jsx("img",{className:"pc-md_img",src:v,alt:g,loading:"lazy"}),g?a.jsx("span",{className:"pc-md_img_caption",children:t?Pr(g,t):g}):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 g=s.slice(o+1,f),v=jy(s.slice(f+2,m));if(v){u(),n.push(a.jsx("a",{className:"pc-md_link",href:v,target:v.startsWith("#")?void 0:"_blank",rel:"noopener noreferrer",children:t?Pr(g,t,!1):g},`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?Pr(m,t):us(m)},`code:${o}`)),o=f+1;continue}}if(d==="_"&&!Hm(s[o-1])){const f=s[o+1]==="_"?"__":"_",m=f.length;if(s[o+m]&&!/\s/.test(s[o+m])&&s[o+m]!=="_"){let g=s.indexOf(f,o+m);for(;g!==-1&&(/\s/.test(s[g-1]||" ")||Hm(s[g+m])||m===1&&s[g+1]==="_");)g=s.indexOf(f,g+1);if(g!==-1&&g>o+m){u();const v=s.slice(o+m,g),w=Or(v,t);n.push(m===2?a.jsx("strong",{children:w},`ubold:${o}`):a.jsx("em",{children:w},`uem:${o}`)),o=g+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?Pr(m,t):us(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?Pr(m,t):us(m)},`em:${o}`)),o=f+1;continue}}l+=d,o+=1}return u(),n}function LN(e){return String(e??"").replace(/\r\n/g,`
75
+ `).replace(/\r/g,`
76
+ `).split(`
77
+ `)}function Yo(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 IN(e){const t=[];for(const o of e){const l=Yo(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 Cy(e,t,n){const s=e.items.map((o,l)=>a.jsxs("li",{children:[Or(o.content,t),o.children.map((u,d)=>Cy(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 PN(e,t,n){return IN(e).map((s,o)=>Cy(s,t,`${n}:${o}`))}function Gm(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 Km(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))}var Jm=/^(#{1,5})\s+(.*)$/;function Ym(e){return e.trim().startsWith("```")}function Qm(e){return e.trimStart().startsWith(">")}function Ey(e){const t=ds;ds=e.images==="link"?e.inlineImage||MN:null;try{return ON(e)}finally{ds=t}}function ON({text:e,className:t,highlight:n,highlights:s,highlightClassName:o,highlightId:l}){const u=LN(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(x=>String(x??"").trim()).filter(Boolean))).filter(x=>x.length>=4),g=m.length?{needles:m,needlesLower:m.map(x=>x.toLowerCase()),className:o||"pc-md_hl",id:l,hits:0}:null;let v=0;for(;v<u.length;){const x=String(u[v]??"");if(!x.trim()){v+=1;continue}const j=x.trim();if(/^([-_*])(\s*\1){2,}$/.test(j)){d.push(a.jsx("hr",{className:"pc-md_hr"},`hr:${v}`)),v+=1;continue}const b=x.match(/^\s*!\[([^\]]*)\]\(([^)]+)\)\s*$/);if(b){const S=Sy(b[2]||"");if(S&&ds&&!ds(S)){d.push(a.jsx("p",{className:"pc-md_p",children:Ny(`img:${v}`,S,b[1]||"")},`p:${v}`)),v+=1;continue}if(S){const N=b[1]||"";d.push(a.jsxs("figure",{className:"pc-md_figure",children:[a.jsx("img",{className:"pc-md_img",src:S,alt:N,loading:"lazy"}),N?a.jsx("figcaption",{children:Or(N,g)}):null]},`figure:${v}`)),v+=1;continue}}if(Ym(x)){const N=x.trim().replace(/```/g,"").trim(),C=[];for(v+=1;v<u.length&&!String(u[v]??"").trim().startsWith("```");)C.push(String(u[v]??"")),v+=1;v<u.length&&(v+=1);const R=C.join(`
78
+ `);d.push(a.jsx($N,{code:R,lang:N},`pre:${v}`));continue}const k=x.match(Jm);if(k){const S=k[1].length,N=k[2]||"",C=Or(N,g);S===1?d.push(a.jsx("h1",{children:C},`h1:${v}`)):S===2?d.push(a.jsx("h2",{children:C},`h2:${v}`)):S===3?d.push(a.jsx("h3",{children:C},`h3:${v}`)):S===4?d.push(a.jsx("h4",{children:C},`h4:${v}`)):d.push(a.jsx("h5",{children:C},`h5:${v}`)),v+=1;continue}if(Qm(x)){const S=[];for(;v<u.length&&String(u[v]??"").trimStart().startsWith(">");){const C=String(u[v]??"").trimStart();S.push(C.replace(/^>\s?/,"")),v+=1}d.push(a.jsx("blockquote",{className:"pc-md_quote",children:S.map((N,C)=>a.jsxs(it.Fragment,{children:[Or(N,g),C<S.length-1?a.jsx("br",{}):null]},`q:${v}:${C}`))},`quote:${v}`));continue}if(x.includes("|")&&v+1<u.length&&Km(String(u[v+1]??""))){const S=Gm(x),N=Math.max(1,S.length),C=[];for(v+=2;v<u.length;){const R=String(u[v]??"");if(!R.trim()||!R.includes("|"))break;const E=Gm(R),I=[];for(let L=0;L<N;L++)I.push(E[L]??"");C.push(I),v+=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:S.slice(0,N).map((R,E)=>a.jsx("th",{children:Or(R,g)},`th:${v}:${E}`))})}),a.jsx("tbody",{children:C.map((R,E)=>a.jsx("tr",{children:R.map((I,L)=>a.jsx("td",{children:Or(I,g)},`td:${v}:${E}:${L}`))},`tr:${v}:${E}`))})]})},`table:${v}`));continue}if(Yo(x)){const S=[];for(;v<u.length;){const N=String(u[v]??"");if(!N.trim()||N.trimStart().startsWith("```"))break;if(Yo(N)||/^\s{2,}\S/.test(N)){S.push(N),v+=1;continue}break}d.push(a.jsx(it.Fragment,{children:PN(S,g,`list:${v}`)},`list:${v}`));continue}const $=[];for(;v<u.length&&String(u[v]??"").trim()&&!($.length>0&&Yo(String(u[v]??"")));){const S=String(u[v]??"");if($.length>0&&(Jm.test(S)||Ym(S)||Qm(S))||$.length>0&&S.includes("|")&&v+1<u.length&&Km(String(u[v+1]??"")))break;$.push(S),v+=1}d.push(a.jsx("p",{className:"pc-md_p",children:$.map((S,N)=>a.jsxs(it.Fragment,{children:[Or(S,g),N<$.length-1?a.jsx("br",{}):null]},`pl:${v}:${N}`))},`p:${v}`))}const w=["pc-md",t].filter(Boolean).join(" ");return a.jsx("div",{className:w,children:d})}var Bu=1024*1024,DN="1 MiB",FN=25*1024*1024;function Ty(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 Xm(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:g,value:v}=await u.read();if(g)break;const w=v.subarray(0,t-l);l+=w.length,o+=s.decode(w,{stream:!0})}await u.cancel().catch(()=>{})}else o=(await e.text()).slice(0,t),l=o.length;const d=Ty(e)??n,f=d!==void 0?d>l:l>=t;return{text:o,received:l,total:d,partial:f}}function Zm(e){return`Showing the first ${DN} of ${e!==void 0?di(e):"a file of unknown size"}; download for the rest.`}function Ay(e){const{markdownImages:t,inlineImage:n,renderMarkdown:s,...o}=e;return a.jsx(Nv,{...o,nowMs:e.nowMs??Date.now(),renderMarkdown:s||(l=>a.jsx(Ey,{text:l,...t?{images:t}:{},...n?{inlineImage:n}:{}}))})}async function Qs(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 BN(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 zN(e,t,n){const s={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 UN(e,t=FN){var u,d;const n=Ty(e);if(n!==void 0&&n>t)throw await((u=e.body)==null?void 0:u.cancel()),Error("This file is too large to preview. Use Download.");const s=(d=e.body)==null?void 0:d.getReader();if(!s)return new Blob([],{type:e.headers.get("content-type")||""});const o=[];let l=0;try{for(;;){const f=await s.read();if(f.done)break;if(l+=f.value.byteLength,l>t)throw Error("This file is too large to preview. Use Download.");o.push(f.value)}}finally{await s.cancel().catch(()=>{})}return new Blob(o,{type:e.headers.get("content-type")||""})}function eg(e,t){const n=t.split(";",1)[0].trim().toLowerCase();if(n.includes("html")||n.includes("xml")||n==="image/svg+xml")return"text";const s=gs("",n),o=gs(e,"");return s==="text"?["code","json","markdown"].includes(o)?o:"text":s!=="binary"?s:o}function WN(e){const[t,n]=p.useState({status:"loading",kind:"binary"}),[s,o]=p.useState(0),[l,u]=p.useState(null),[d,f]=p.useState(!1),[m,g]=p.useState(""),v=p.useRef(null),w=p.useRef(null),x=p.useRef(!0);p.useEffect(()=>(x.current=!0,()=>{var b;x.current=!1,(b=w.current)==null||b.abort()}),[]),p.useEffect(()=>{const b=new AbortController;v.current=b;let k="";return n({status:"loading",kind:"binary"}),(async()=>{var $,S;try{const N=await e.fetchGateway(`${e.path}/content`,{signal:b.signal,headers:{Range:`bytes=0-${Bu-1}`}});if(!N.ok)throw await Qs(N,"Attachment preview failed");const C=N.headers.get("content-type")||"",R=eg(e.name,C);if(Zs(R)){const E=await Xm(N,Bu);if(b.signal.aborted)return;n({status:"ready",kind:R,contentType:C,text:E.text,...E.partial?{partialNote:Zm(E.total)}:{}})}else if(["image","audio","video","pdf"].includes(R)){let E=N;const I=/^bytes 0-(\d+)\/(\d+)$/.exec(N.headers.get("content-range")||"");if(N.status===206&&(!I||Number(I[1])+1<Number(I[2]))&&(await(($=N.body)==null?void 0:$.cancel()),E=await e.fetchGateway(`${e.path}/content`,{signal:b.signal}),!E.ok))throw await Qs(E,"Attachment preview failed");const L=E.headers.get("content-type")||C,D=eg(e.name,L);if(Zs(D)){const K=await Xm(E,Bu);b.signal.aborted||n({status:"ready",kind:D,contentType:L,text:K.text,...K.partial?{partialNote:Zm(K.total)}:{}});return}const P=await UN(E);if(b.signal.aborted)return;k=URL.createObjectURL(D==="pdf"?new Blob([P],{type:"application/pdf"}):P),n({status:"ready",kind:D,contentType:L,url:k})}else await((S=N.body)==null?void 0:S.cancel()),b.signal.aborted||n({status:"ready",kind:"binary",contentType:C})}catch(N){b.signal.aborted||n({status:"error",kind:"binary",error:N instanceof Error?N.message:String(N)})}})(),()=>{b.abort(),k&&URL.revokeObjectURL(k)}},[e.fetchGateway,e.path,e.name,s]);const j=async()=>{if(d)return;const b=new AbortController;w.current=b,f(!0),g("");try{const k=await e.fetchGateway(`${e.path}/content`,{signal:b.signal});if(!k.ok)throw await Qs(k,"Attachment download failed");const $=await k.blob();!b.signal.aborted&&x.current&&zN($,e.name,"download")}catch(k){!b.signal.aborted&&x.current&&g(k instanceof Error?k.message:String(k))}finally{!b.signal.aborted&&x.current&&f(!1)}};return a.jsx(Gg,{open:!0,title:e.name,onClose:()=>{var b,k;x.current=!1,(b=v.current)==null||b.abort(),(k=w.current)==null||k.abort(),e.onClose()},className:`pc-artifact-preview pc-artifact-preview--${t.kind}`,footerNote:d?"Downloading…":m||void 0,footer:t.status==="error"?a.jsx("button",{type:"button",className:"pc-artifact-preview__retry",onClick:()=>o(b=>b+1),children:"Retry preview"}):void 0,children:a.jsx("div",{className:"pc-artifact-preview__content",style:l&&l.url===t.url?{"--pc-media-width":`${l.width}px`,"--pc-media-aspect":l.width/l.height}:void 0,onLoadCapture:b=>{const k=b.target;k instanceof HTMLImageElement&&k.naturalWidth&&k.naturalHeight&&k.src===t.url&&u({url:k.src,width:k.naturalWidth,height:k.naturalHeight})},onLoadedMetadataCapture:b=>{const k=b.target;k instanceof HTMLVideoElement&&k.videoWidth&&k.videoHeight&&k.src===t.url&&u({url:k.src,width:k.videoWidth,height:k.videoHeight})},children:a.jsx(Ay,{name:e.name,onDownload:()=>void j(),status:t.status,kind:t.kind,contentType:t.contentType,text:t.text,url:t.url,error:t.error,partialNote:t.partialNote,markdownImages:"link",inlineImage:()=>!1})})})}async function tg(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)}var ng=e=>`${e} ${e===1?"file":"files"}`;function VN(e){const t=e.filter(o=>o.state==="queued"||o.state==="uploading").length;if(t)return`Wait for ${ng(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.`:`${ng(n.length)} were not attached. ${s?"Retry or remove":"Remove"} them before sending.`}var qN=new Set(["scratchpad","node_traces","node_trace","trace","traces","bookkeeping"]);function $y(e){return e.startsWith("_")||qN.has(e)}function HN(e){const t=String(e||"").split(/[.\[\]]/).filter(Boolean);if(t.some($y))return!1;const n=t.findIndex(s=>["attachments","files","artifacts","media","artifact","artifact_ref","image_artifact","audio_artifact","video_artifact","music_artifact"].includes(s));return n<0?!1:!t.slice(0,n).some(s=>["session","sessions","history","conversation","transcript","messages","context"].includes(s))}function GN(e,t){const n=t;let s=!1;const o=[];for(const l of e.artifact_ids||[]){const u=n.get(l);if(!u){s=!0;continue}HN(String(u.path||""))&&o.push({id:l,runId:typeof u.run_id=="string"&&u.run_id?u.run_id:e.run_id})}return{refs:o,unresolved:s}}function KN(e){const t=e.tags&&typeof e.tags=="object"?e.tags:{},n=e.artifact_envelope_v1&&typeof e.artifact_envelope_v1=="object"?e.artifact_envelope_v1:{};return["node_trace_offload","run_output_offload","run_input_offload","conversation_offload","session_offload","state_offload"].includes(String(t.source||e.source||""))||["internal","bookkeeping"].includes(String(t.role||n.role||e.role||""))}var Tn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};function Ry(e,t){const n=[],s=new Set,o=(l,u=0)=>{if(u>8)return;if(Array.isArray(l)){l.forEach(m=>o(m,u+1));return}const d=Tn(l),f=d.$artifact||d.artifact_id;if(typeof f=="string"&&f){const m=typeof d.run_id=="string"?d.run_id:typeof d.artifact_run_id=="string"?d.artifact_run_id:t,g=JSON.stringify([m,f]);s.has(g)||(s.add(g),n.push({id:f,runId:m,...typeof(d.filename||d.name)=="string"?{name:String(d.filename||d.name)}:{}}));return}Object.entries(d).forEach(([m,g])=>{$y(m)||g&&typeof g=="object"&&o(g,u+1)})};return o(e),n}function JN(e,t){const n=Tn(e),s=Tn(n.input_data||e),o=Tn(s.context);return Ry([s.attachments,o.attachments,s.image_artifact,o.image_artifact],t)}function zu(e,t){const n=Tn(e),s=Tn(n.result),o=["attachments","artifacts","files","media","artifact","artifact_ref","image_artifact","audio_artifact","video_artifact","music_artifact"];return Ry([n,Tn(n.meta),s,Tn(s.meta)].flatMap(l=>o.map(u=>l[u])),t)}function YN(e,t,n,s){const[o,l]=p.useState(0),u=p.useRef({owner:n,refs:new Map,outputs:new Map});u.current.owner!==n&&(u.current={owner:n,refs:new Map,outputs:new Map});const d=JSON.stringify([...new Set(e.filter(j=>j.role==="user"&&j.runId).map(j=>j.runId))]),[f,m]=p.useState({owner:n,refs:{},error:""});p.useEffect(()=>{const j=new AbortController,b=JSON.parse(d).filter($=>!u.current.refs.has($)),k=new Set(JSON.parse(d));for(const $ of u.current.refs.keys())k.has($)||u.current.refs.delete($);for(const $ of u.current.outputs.keys())k.has($)||u.current.outputs.delete($);return m({owner:n,refs:Object.fromEntries(u.current.refs),error:""}),t?(tg(b,4,async $=>{try{const S=await t(ut(`runs/${encodeURIComponent($)}/input_data`),{signal:j.signal});if(!S.ok)throw await Qs(S,"Message attachments could not be checked");const N=JN(await S.json(),$);!j.signal.aborted&&u.current.owner===n&&(u.current.refs.set($,N),m(C=>({...C,refs:{...C.refs,[$]:N}})))}catch(S){!j.signal.aborted&&u.current.owner===n&&m(N=>({...N,error:S instanceof Error?S.message:String(S)}))}}),()=>j.abort()):()=>j.abort()},[t,n,d,o]);const g=JSON.stringify(JSON.parse(d).filter(j=>!e.some(b=>b.runId===j&&b.role==="assistant")||e.some(b=>b.runId===j&&b.artifactReferencesUnresolved))),[v,w]=p.useState({owner:n,files:{},error:""});return p.useEffect(()=>{const j=new AbortController;return w(b=>b.owner===n?{...b,error:""}:{owner:n,files:{},error:""}),t&&tg(JSON.parse(g).filter(b=>!u.current.outputs.has(b)),4,async b=>{if(!(b===(s==null?void 0:s.runId)&&zu(s.output,b).length))try{const k=await t(ut(`runs/${encodeURIComponent(b)}`),{signal:j.signal});if(!k.ok)throw await Qs(k,"Attached reply could not be checked");const $=Tn(await k.json()),S=$.status==="completed"?zu($.output,b):[];!j.signal.aborted&&u.current.owner===n&&(["completed","failed","cancelled"].includes(String($.status))&&u.current.outputs.set(b,S),w(N=>N.owner===n?{...N,files:{...N.files,[b]:S}}:N))}catch(k){j.signal.aborted||w($=>$.owner===n?{...$,error:k instanceof Error?k.message:String(k)}:$)}}),()=>j.abort()},[t,n,g,s==null?void 0:s.runId,s==null?void 0:s.output,o]),{messages:p.useMemo(()=>{const j=new Set,b=e.map(S=>{const N=S.role==="user"&&!!S.runId&&!j.has(S.runId);N&&j.add(S.runId);const C=N&&f.owner===n?f.refs[S.runId||""]||[]:[],R=[...S.artifactRefs||[],...C],E=[...new Map(R.filter(I=>I.id&&I.runId).map(I=>[I.id,I])).values()];return E.length?{...S,artifactRefs:E}:S}),k=new Set(e.map(S=>S.runId)),$=[...v.owner===n?Object.entries(v.files).filter(([S])=>k.has(S)):[],...s?[[s.runId,zu(s.output,s.runId)]]:[]];for(const[S,N]of $)if(N.length){let C=-1;for(let R=b.length-1;R>=0;R--)if(b[R].role==="assistant"&&b[R].runId===S&&!b[R].live){C=R;break}if(C<0){const R=b.reduce((E,I,L)=>I.runId===S?L:E,-1);b.splice(R+1,0,{id:`attachments:${S}`,kind:"attachments",role:"assistant",runId:S,content:"",artifactRefs:N})}else b[C]={...b[C],artifactRefs:[...new Map([...N,...b[C].artifactRefs||[]].map(R=>[R.id,R])).values()]}}return b},[e,f,v,n,s==null?void 0:s.runId,s==null?void 0:s.output]),error:[f.owner===n?f.error:"",v.owner===n?v.error:""].filter(Boolean).join(" "),retry:()=>l(j=>j+1)}}var My=p.createContext(void 0);function QN({artifact:e}){const t=p.useContext(My),[n,s]=p.useState(e.name||"Attached file"),[o,l]=p.useState(""),[u,d]=p.useState(!1),[f,m]=p.useState(!1),[g,v]=p.useState("loading"),[w,x]=p.useState(0),j=ut(`runs/${encodeURIComponent(e.runId)}/artifacts/${encodeURIComponent(e.id)}`);return p.useEffect(()=>{const b=new AbortController;return s(e.name||"Attached file"),l(""),m(!1),v("loading"),t&&t(j,{signal:b.signal}).then(async k=>{if(!k.ok)throw await Qs(k,"Attachment unavailable");const $=await k.json(),S=Tn($.tags),N=Tn($.descriptor),C=Tn($.artifact_envelope_v1),R=KN($);b.signal.aborted||(m(R),v("ready"));const E=$.filename||$.name||S.filename||N.name||C.name;!b.signal.aborted&&typeof E=="string"&&s(E)}).catch(k=>{b.signal.aborted||(v("error"),l(k instanceof Error?k.message:String(k)))}),()=>{b.abort()}},[t,j,w]),p.useEffect(()=>{e.name&&s(e.name)},[e.name]),f?a.jsx(a.Fragment,{}):a.jsxs("span",{className:"pc-message-artifact",children:[a.jsxs("button",{type:"button",className:"pc-chat-attachment-chip","aria-haspopup":"dialog",disabled:!t||g!=="ready",onClick:()=>d(!0),children:[a.jsx(be,{name:"paperclip",size:14}),a.jsx("span",{className:"pc-chat-attachment-name",children:n})]}),o&&a.jsxs("span",{role:"status",className:"pc-message-artifact__error",children:[o," ",a.jsxs("button",{type:"button",onClick:()=>x(b=>b+1),children:["Retry ",n]})]}),u&&t&&a.jsx(WN,{name:n,path:j,fetchGateway:t,onClose:()=>d(!1)})]})}function XN(e){let t=0;const n=[],s=()=>{for(;t<4&&n.length;)n.shift()()};return(o,l={})=>new Promise((u,d)=>{const f=l.signal;let m=!0;const g=()=>{m&&(m=!1,d(new DOMException("Aborted","AbortError")))};f==null||f.addEventListener("abort",g,{once:!0}),f!=null&&f.aborted&&g(),n.push(()=>{f==null||f.removeEventListener("abort",g),m&&(m=!1,t++,Promise.resolve().then(()=>e(o,l)).then(u,d).finally(()=>{t--,s()}))}),s()})}var ZN=it.forwardRef(function(t,n){const s=t.variant!=="legacy",o=typeof t.rows=="number"&&Number.isFinite(t.rows)?Math.max(1,Math.trunc(t.rows)):s?2:3,l=!!t.disabled,u=!!t.busy,d=!l&&!u&&(t.canSubmit??!!String(t.value||"").trim()),f=u?t.busyLabel||"Thinking…":t.sendLabel||"Send",m=p.useRef(null),g=p.useRef(!1),v=p.useCallback(x=>{m.current=x,typeof n=="function"?n(x):n&&(n.current=x)},[n]),w=p.useCallback(()=>{const x=m.current;if(!x||!g.current)return;x.style.height="0px";const j=parseFloat(getComputedStyle(x).maxHeight);x.style.height=`${Math.min(x.scrollHeight,Number.isFinite(j)?j:1/0)}px`},[]);return p.useEffect(()=>{var k;const x=m.current;if(!s||!x||typeof CSS<"u"&&((k=CSS.supports)!=null&&k.call(CSS,"field-sizing","content")))return;g.current=!0,w(),window.addEventListener("resize",w);let j=x.clientWidth;const b=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{x.clientWidth!==j&&(j=x.clientWidth,w())});return b==null||b.observe(x),()=>{g.current=!1,b==null||b.disconnect(),window.removeEventListener("resize",w),x.style.removeProperty("height")}},[s,w]),p.useEffect(()=>{w()},[t.value,o,w]),a.jsxs("div",{className:["pc-composer",s?"pc-composer--compact":"",t.className].filter(Boolean).join(" "),children:[t.leading,a.jsx("textarea",{id:t.textareaId,ref:v,className:["pc-composer__textarea",t.textareaClassName].filter(Boolean).join(" "),value:t.value,onChange:x=>t.onChange(x.target.value),rows:o,style:{"--pc-composer-rows":String(o)},spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",autoComplete:"off",placeholder:t.placeholder||"","aria-label":t.ariaLabel||t.placeholder||"Message","aria-describedby":t.ariaDescribedBy,disabled:l,autoFocus:!!t.autoFocus,onPaste:t.onPaste,onKeyDown:x=>{x.key!=="Enter"||x.shiftKey||t.submitKey==="mod-enter"&&!x.ctrlKey&&!x.metaKey||x.nativeEvent.isComposing||x.keyCode===229||(x.preventDefault(),d&&t.onSubmit())}}),a.jsxs("div",{className:"pc-composer__row",children:[a.jsxs("div",{className:"pc-composer__actions",children:[t.onAttach?a.jsxs("button",{type:"button",className:s?"pc-composer__icon-action":"pc-composer__icon-action pc-workflow-chat__icon-button","aria-label":t.attachLabel||"Attach files","data-af-tip":t.attachLabel||"Attach files","aria-busy":t.attachPending||void 0,disabled:l||t.attachDisabled||t.attachPending,onClick:t.onAttach,children:[a.jsx(be,{name:t.attachPending?"loader":s?"plus":"paperclip",size:16}),a.jsx("span",{className:s?"pc-sr-only":void 0,children:t.attachPending?"Attaching…":t.attachLabel||"Attach"})]}):null,t.actions]}),t.trailingActions?a.jsx("div",{className:"pc-composer__trailing",children:t.trailingActions}):null,a.jsx("button",{type:"button",className:[t.sendButtonClassName||"pc-btn",s?"pc-composer__send--compact":""].filter(Boolean).join(" "),"aria-label":s?f:void 0,"data-af-tip":s?f:void 0,"aria-busy":s?u:void 0,disabled:!d,onClick:()=>t.onSubmit(),children:s?a.jsx(be,{name:u?"loader":"send",size:17}):f})]}),t.overlay]})}),e2=new Set("html htm xhtml xht shtml svg svgz xml xsl xslt mht mhtml".split(" ")),t2=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 Ly(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 n2(e,t){const n=String(t||"").split("/").pop()||"",s=n.lastIndexOf(".");if(s>0&&e2.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:t2.has(o)}function r2(e){const t=n=>!!n&&(!Ly(n)||n2(e.contentType,e.name));if(t(e.href))return e.href;if(t(e.src))return e.src}var s2=3,a2=Number.MAX_SAFE_INTEGER;function Iy(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Py(e){return Array.isArray(e)}function i2(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Xa({kind:e,children:t}){return a.jsx("span",{className:`pc-json-token ${e}`,children:t})}function o2(e){const t=JSON.stringify(e.value),s=!/^https?:\/\/[^\s]+$/i.test(e.value)&&(t.length>96||t.includes("\\n")||t.includes("\\r")||t.includes("\\t")),[o,l]=p.useState(!s||e.expansionMode==="unfolded");return p.useEffect(()=>{s&&l(e.expansionMode==="unfolded")},[s,e.expansionMode,e.expansionVersion]),s?a.jsxs("span",{className:`pc-json-string ${o?"open":"collapsed"}`,children:[a.jsx("button",{type:"button",className:"pc-json-string__toggle",onClick:()=>l(u=>!u),"aria-label":o?"Collapse string value":"Expand string value","aria-expanded":o,children:o?"▾":"▸"}),o?a.jsx("span",{className:"pc-json-token string pc-json-string__value",children:a.jsx(Fu,{text:e.value})}):a.jsxs("span",{className:"pc-json-string__preview",children:[a.jsx("span",{className:"pc-json-token string pc-json-string__preview_text",children:a.jsx(Fu,{text:e.value})}),a.jsx("button",{type:"button",className:"pc-json-string__suffix",onClick:()=>l(!0),"aria-label":"Expand string value",children:"(...)"})]})]}):a.jsx("span",{className:"pc-json-token string",children:a.jsx(Fu,{text:e.value})})}function l2(e,t,n){return e===null?a.jsx(Xa,{kind:"null",children:"null"}):typeof e=="string"?a.jsx(o2,{value:e,expansionMode:t,expansionVersion:n}):typeof e=="number"?a.jsx(Xa,{kind:"number",children:String(e)}):typeof e=="boolean"?a.jsx(Xa,{kind:"boolean",children:e?"true":"false"}):a.jsx(Xa,{kind:"string",children:JSON.stringify(String(e))})}function c2(e){return Py(e)?e.length===1?"1 item":`${e.length} items`:Iy(e)?Object.keys(e).length===1?"1 key":`${Object.keys(e).length} keys`:""}function Oy(e){const{label:t,value:n,depth:s,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:d}=e,f=s*14,m=Iy(n),g=Py(n),v=m||g,w=s<o,[x,j]=p.useState(w);p.useEffect(()=>{j(w)},[w,u]);const b=t?a.jsxs(a.Fragment,{children:[a.jsx(Xa,{kind:"key",children:JSON.stringify(t)}),": "]}):null;if(!v)return a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[b,l2(n,l,u),d?",":""]});const k=g?"[":"{",$=g?"]":"}",S=c2(n),N=x?`${k}`:`${k}…${$}${S?` (${S})`:""}`,C=g?n.map((R,E)=>({key:String(E),label:void 0,value:R})):Object.entries(n).map(([R,E])=>({key:R,label:R,value:E}));return a.jsxs("details",{className:"pc-json-viewer__details",open:x,onToggle:R=>j(R.currentTarget.open),children:[a.jsxs("summary",{className:"pc-json-viewer__summary",style:{paddingLeft:f},children:[b,a.jsx("span",{className:"pc-json-viewer__caret","aria-hidden":"true",children:x?"▾":"▸"}),a.jsx("span",{className:"pc-json-viewer__punct",children:N}),!x&&d?a.jsx("span",{className:"pc-json-viewer__punct",children:","}):null]}),x?a.jsx("div",{className:"pc-json-viewer__children",children:C.length===0?a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[a.jsx("span",{className:"pc-json-viewer__punct",children:$}),d?",":""]}):a.jsxs(a.Fragment,{children:[C.map((R,E)=>{const I=E===C.length-1;return a.jsx(Oy,{label:R.label,value:R.value,depth:s+1,collapseAfterDepth:o,expansionMode:l,expansionVersion:u,trailingComma:!I},`${s}:${t||"root"}:${R.key}`)}),a.jsxs("div",{className:"pc-json-viewer__line",style:{paddingLeft:f},children:[a.jsx("span",{className:"pc-json-viewer__punct",children:$}),d?",":""]})]})}):null]})}function u2(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 si(e){const{value:t,className:n,showCopy:s=!0}=e,[o,l]=p.useState({mode:"folded",version:0}),[u,d]=p.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):s2,m=o.mode==="unfolded"?a2:f,g=p.useMemo(()=>typeof t=="string"?u2(t):t,[t]),v=p.useMemo(()=>i2(t),[t]),w=["pc-json-viewer",n].filter(Boolean).join(" ");p.useEffect(()=>{l(j=>({mode:"folded",version:j.version+1}))},[g]);const x=()=>{l(j=>({mode:j.mode==="unfolded"?"folded":"unfolded",version:j.version+1}))};return a.jsxs("div",{className:w,children:[a.jsxs("div",{className:"pc-json-viewer__toolbar",children:[a.jsx("button",{type:"button",className:"pc-btn pc-json-viewer__toggle-all",onClick:x,"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 fi(v).then(j=>{d(j?"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(Oy,{value:g,depth:0,collapseAfterDepth:m,expansionMode:o.mode,expansionVersion:o.version,trailingComma:!1})})]})}function d2(e){const t=String(e.text??""),n=p.useMemo(()=>ky(t),[t]),s=["pc-chat-content",e.className].filter(Boolean).join(" ");return n!==null?a.jsx("div",{className:s,children:a.jsx(si,{value:n,collapseAfterDepth:e.jsonCollapseAfterDepth})}):e.renderMarkdown?a.jsx("div",{className:s,children:e.renderMarkdown(t)}):a.jsx("div",{className:s,children:a.jsx(Ey,{text:t,images:e.images,inlineImage:e.inlineImage})})}function Za(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Dr(e){return typeof e=="string"?e.trim():""}function f2(e){var o;const t=Za(e);if(!t)return null;const n=Za(t.sandbox);if(n&&Dr(n.kind))return n;const s=Za((o=Za(t.output))==null?void 0:o.sandbox);return s&&Dr(s.kind)?s:null}function rg(e){const t=f2(e);if(!t)return null;const n=Dr(t.kind),s=Dr(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=Dr(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=Za(f),g=Dr(m==null?void 0:m.path);g&&l.push({path:g,mode:Dr(m==null?void 0:m.mode)==="ro"?"Read-only":"Read & write"})}for(const f of Array.isArray(t.refused)?t.refused:[]){const m=Dr(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 h2({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}var Uu=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,dn=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"";function p2(e){const t=dn(e==null?void 0:e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=Uu(e==null?void 0:e.policy),s=Uu(n==null?void 0:n.set_by),o=dn(s==null?void 0:s.user_id)||dn(s==null?void 0:s.client),l=typeof(n==null?void 0:n.revision)=="number"?n.revision:void 0,u={decision:t,...dn(e==null?void 0:e.source)?{source:dn(e==null?void 0:e.source)}:{},...l!==void 0?{revision:l}:{},...o?{setBy:o}:{},...dn(n==null?void 0:n.set_at)?{setAt:dn(n==null?void 0:n.set_at)}:{}},d=(Array.isArray(e==null?void 0:e.tool_calls)?e.tool_calls:[]).map(f=>Uu(f)).filter(f=>!!(f&&dn(f.call_id))).map(f=>({callId:dn(f.call_id),name:dn(f.name),...dn(f.matched)?{matched:dn(f.matched)}:{}}));return d.length?{provenance:u,calls:d}:null}function ul(e){if(e.decision==="denied")return"Denied by this chat's policy";const t=e.setAt?wl(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 sg(e){const t=new Map;for(const n of e||[]){const s=dn(n==null?void 0:n.name);if(!s)continue;const o=dn(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("; ")}`:""}var Bt="not reported",Zt=e=>e===void 0?Bt:Math.round(e).toLocaleString(),Jt=e=>{if(e===void 0)return Bt;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`},Dy=e=>e===void 0?Bt:`${Math.round(e).toLocaleString()} tok/s`,m2=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"",cr=(e,t,n=`${t}s`)=>`${e.toLocaleString()} ${e===1?t:n}`,g2=e=>{const t=e.split("#")[0].replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||e};function v2(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 dl(e){const t=[],n=(e.models||[]).map(g2),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 y2(e){const t=e.modelCalls||[],n=[],s=[{label:"Input",value:Zt(e.inputTokens)},{label:"Output",value:Zt(e.outputTokens)}];if(e.reasoningTokens!==void 0&&s.push({label:"Reasoning",value:Zt(e.reasoningTokens),hint:"part of output"}),s.push({label:"Total",value:Zt(e.totalTokens)}),n.push({heading:`Usage · ${cr(e.llmCalls,"model call")}`,rows:s}),e.measuredCacheCalls){const l=e.cachedTokens||0,u=e.fedTokens||0,d=[{label:"Reused from cache",value:`${Zt(l)}${l+u?` (${m2(l,l+u)})`:""}`},{label:"Newly processed",value:Zt(e.fedTokens)},{label:"Outcome",value:v2(t.map(f=>f.cacheOutcome))||(e.cacheOutcomes||[]).join(" · ")||Bt},{label:"Backend",value:(e.cacheBackends||[]).join(", ")||Bt}];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:Bt}]});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:`${Zt(o[0].inputTokens)} tokens`}]}):o.length>1&&n.push({heading:"Context",rows:[{label:"First → last call",value:`${Zt(o[0].inputTokens)} → ${Zt(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),Zt(l.inputTokens),l.cachedTokens===void 0?"—":Zt(l.cachedTokens),l.fedTokens===void 0?"—":Zt(l.fedTokens),Zt(l.outputTokens),l.cacheOutcome||"—"])}}),{kind:"tokens",title:"Tokens",headline:e.totalTokens===void 0?Bt:`${e.totalTokens.toLocaleString()} total`,sections:n,footer:dl(e)}}function Lo(e,t,n,s){if(e===void 0)return Bt;const o=[Jt(e)];return t!==void 0&&o.push(`${t.toLocaleString()} ${s}${n!==void 0?` at ${Dy(n)}`:""}`),o.join(" · ")}function w2(e){var m,g,v;const t=e.modelCalls||[],n=[],s=e.durationMs,o=[{label:"Wall clock",value:Jt(s)}];if(o.push({label:"Model",value:e.genTimeMs===void 0?Bt:`${Jt(e.genTimeMs)} · ${cr(e.timedCalls||0,"call")}${e.timedCalls!==e.llmCalls?` (of ${e.llmCalls})`:""}`}),o.push({label:"Tools",value:e.toolTimeMs!==void 0?`${Jt(e.toolTimeMs)} · ${cr(e.toolBatches||0,"batch","batches")}`:e.toolCalls?Bt:"none",hint:e.toolTimeIncludesApproval?"includes approval wait":void 0}),s!==void 0&&e.genTimeMs!==void 0){const w=s-e.genTimeMs-(e.toolTimeMs||0);o.push({label:"Orchestration",value:w>=0?Jt(w):"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:Lo(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:Lo(e.prefillMs,e.prefillNewTokens,e.prefillNewTokensPerSecond,"new tok"),hint:"derived: prompt ÷ provider rate"}):e.prefillMs!==void 0?l.push({label:"Prefill",value:`${Jt(e.prefillMs)}${e.promptTokensPerSecond!==void 0?` at ${Dy(e.promptTokensPerSecond)}`:""}`,hint:"provider rate over all prompt tokens, restored included"}):l.push({label:"Prefill",value:Bt}),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?Lo(e.generationPhaseMs,e.generationPhaseTokens,e.generationPhaseTokensPerSecond,"tok"):Lo(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 w=(f.draftKinds||[]).map(j=>j.toUpperCase()).join(", "),x=[{label:"Mode",value:`${f.used?"on":"off"}${w?` · ${w}`:""}${(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?Bt:`${Math.round(f.acceptanceRate*100)}% · ${Zt(f.acceptedTokens)} of ${Zt(f.draftedTokens)} drafted`}];((g=f.draftLengths)!=null&&g.length||f.rounds!==void 0)&&x.push({label:"Draft length",value:`${(v=f.draftLengths)!=null&&v.length?`${f.draftLengths.join("/")} tok/round`:Bt}${f.rounds!==void 0?` · ${f.rounds.toLocaleString()} rounds`:""}`}),n.push({heading:"Speculation",rows:x})}return e.slowestToolBatch&&n.push({heading:"Tools",rows:[{label:"Total",value:`${Jt(e.toolTimeMs)} · ${cr(e.toolBatches||0,"batch","batches")}`},{label:"Slowest",value:`${Jt(e.slowestToolBatch.ms)} · ${Fy(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((w,x)=>[String(x+1),w.promptMs===void 0?"—":`${Jt(w.promptMs)}${w.promptSource==="rate"?"*":""}`,w.promptNewTokensPerSecond===void 0?"—":Math.round(w.promptNewTokensPerSecond).toLocaleString(),w.generationMs===void 0?"—":Jt(w.generationMs),w.generationTokensPerSecond===void 0?"—":Math.round(w.generationTokensPerSecond).toLocaleString(),w.cacheOutcome||"—"])},note:t.some(w=>w.promptSource==="rate")?"* derived from the provider's prompt rate (no TTFT event).":void 0}),{kind:"time",title:"Time",headline:s===void 0?Bt:`${Jt(s)} wall clock`,sections:n,footer:dl(e)}}function Fy(e){return e.tools.length===1?`${e.tools[0]} ×${e.calls}`:`${cr(e.calls,"call")} (${e.tools.join(", ")})`}function _2(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:dl(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?`${Jt(f.ms)}${f.sharedBatches?" +shared":""}`:f.sharedBatches?"shared":Bt])},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,g)=>g[1]-m[1]).map(([m,g])=>g>1?`${m} ×${g}`:m).join(" · ")}))});const u=[{label:"Tool time",value:e.toolTimeMs===void 0?Bt:`${Jt(e.toolTimeMs)} · ${cr(e.toolBatches||0,"batch","batches")}`}];return e.slowestToolBatch&&u.push({label:"Slowest batch",value:`${Jt(e.slowestToolBatch.ms)} · ${Fy(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:`${cr(e.toolCalls,"call")}${e.toolsFailed?` · ${e.toolsFailed} failed`:""}`,sections:t,footer:dl(e)}}var Wu=30;function b2(e){const t=e.changedFiles||[],n=t.slice(0,Wu).map(s=>{const o=s.replace(/[\\/]+$/,""),l=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\"));return{label:l>=0&&o.slice(l+1)||o,value:l>0?o.slice(0,l):l===0?"/":"workspace folder"}});return{kind:"files",title:"Files changed",headline:cr(t.length,"file"),sections:[{heading:"Written by this turn's tools",rows:n,note:t.length>Wu?`and ${cr(t.length-Wu,"more file")}`:void 0}],footer:["From the run ledger: the paths of this turn's completed file-writing tool calls."]}}function Io(e,t){return e==="tokens"?y2(t):e==="time"?w2(t):e==="files"?b2(t):_2(t)}function x2(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,l)=>a.jsxs(it.Fragment,{children:[a.jsx("dt",{children:o.label}),a.jsxs("dd",{children:[a.jsx("span",{className:o.value===Bt?"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}:${l}`))}):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))})]})}var rr=8;function k2(e){const[t,n]=p.useState(!!e.defaultOpen),[s,o]=p.useState(null),l=p.useRef(null),u=p.useRef(null),d=p.useRef(null),f=`pc-stat-${p.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,m=p.useCallback(()=>{d.current!==null&&window.clearTimeout(d.current),d.current=null},[]),g=p.useCallback(()=>{m(),n(!0)},[m]),v=p.useCallback(()=>{m(),d.current=window.setTimeout(()=>n(!1),120)},[m]);p.useEffect(()=>m,[m]),p.useLayoutEffect(()=>{if(!t){o(null);return}const b=()=>{const k=l.current,$=u.current;if(!k||!$)return;const S=k.getBoundingClientRect(),N=$.offsetWidth,C=$.offsetHeight,R=window.innerWidth,E=window.innerHeight,I=S.top-rr-C,L=S.bottom+rr,D=I>=rr?I:L+C<=E-rr?L:Math.max(rr,E-rr-C),P=Math.min(Math.max(rr,S.left),Math.max(rr,R-rr-N));o({top:D,left:P})};return b(),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[t]),p.useEffect(()=>{if(!t)return;const b=k=>{k.key==="Escape"&&n(!1)};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const w=typeof e.onClick=="function",x=w?"button":"span",j=t?a.jsx(x2,{detail:e.detail,id:f,panelRef:u,onMouseEnter:m,onMouseLeave:v,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(x,{ref:l,...w?{type:"button"}:{tabIndex:0},className:["pc-chat-stat","pc-chat-stat--detail",w?"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:g,onMouseLeave:v,onFocus:g,onBlur:()=>n(!1),onKeyDown:b=>{b.key==="Escape"&&n(!1)},onClick:w?()=>{var b;return(b=e.onClick)==null?void 0:b.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})]}),j&&typeof document<"u"?oi.createPortal(j,document.body):j]})}function fl(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function j2(e){const t=fl(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 By({tool:e,showCopy:t=!0}){const[n,s]=p.useState(!1),o=fl(e.arguments),l=j2(e.arguments),u=fl(e.output),d=["file path","path"].includes(l.label)&&l.value.length>60?`${l.value.split(/[\\/]/).pop()} · ${l.value.slice(0,24)}…`:l.value,f=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,m={running:"Running",waiting:"Approval needed",completed:"Done",failed:"Failed"},g=e.startedAt&&e.endedAt?Date.parse(e.endedAt)-Date.parse(e.startedAt):NaN,v=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(be,{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}),a.jsx(Qa,{text:d})]}):"No parameters"}),a.jsx("span",{className:"pc-tool-activity__status",children:m[e.status]}),e.policy?a.jsx("span",{className:"pc-tool-activity__policy","data-policy":e.policy.decision,title:ul(e.policy),children:e.policy.decision==="denied"?"Denied by this chat's policy":"Allowed by this chat's policy"}):null,Number.isFinite(g)&&g>=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:[Jt(g),e.approvalWait?" incl. approval wait":""]}):null,a.jsx("span",{className:"pc-tool-activity__chevron","aria-hidden":"true",children:a.jsx(be,{name:"chevronRight",size:13})}),e.error?a.jsx("span",{className:"pc-tool-activity__error",title:e.error,children:f}):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:[ul(e.policy),e.policy.matched?` · matched ${e.policy.matched}`:""]}):null,a.jsx(h2,{sandbox:e.sandbox}),e.error?a.jsxs(a.Fragment,{children:[a.jsx("h4",{children:"Error"}),a.jsx("pre",{className:"pc-tool-activity__output",children:a.jsx(Qa,{text: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 fi(JSON.stringify(e,null,2))),children:[a.jsx(be,{name:"copy",size:13}),n?"Copied":"Copy details"]}):null]}),v?a.jsx("dl",{className:"pc-tool-activity__parameters",children:v.map(([w,x])=>a.jsxs(it.Fragment,{children:[a.jsx("dt",{children:w}),a.jsx("dd",{children:x&&typeof x=="object"?a.jsx(si,{value:x}):a.jsx("code",{children:typeof x=="string"?a.jsx(Qa,{text:x}):JSON.stringify(x)})})]},w))}):e.arguments===void 0?a.jsx("p",{children:"Arguments are unavailable in this ledger."}):a.jsx(si,{value:o}),e.output!==void 0?a.jsxs(a.Fragment,{children:[a.jsx("h4",{children:"Result"}),typeof u=="string"?a.jsx("pre",{className:"pc-tool-activity__output",children:a.jsx(Qa,{text:u})}):a.jsx("div",{className:"pc-tool-activity__output",children:a.jsx(si,{value:u})})]}):null]})]})}function S2({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(be,{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(By,{tool:s,showCopy:t},s.id))]})}var Vu=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),zy=/^(\d{4})-(\d{2})-(\d{2})$/,Yd=e=>typeof e=="string"&&zy.test(e.trim());function Qd(e){if(e==null||typeof e=="string"&&!e.trim())return null;if(typeof e=="string"){const n=zy.exec(e.trim());if(n)return new Date(Number(n[1]),Number(n[2])-1,Number(n[3]))}const t=e instanceof Date?new Date(e.getTime()):new Date(typeof e=="string"?e.trim():e);return Number.isFinite(t.getTime())?t:null}function N2(e,t=new Date,n){const s=Qd(e);if(!s)return"";const o=Yd(e)?"":s.toLocaleTimeString(n,{hour:"2-digit",minute:"2-digit"}),l=Vu(s),u=Vu(t);if(l===u)return o||"Today";const d=Vu(new Date(t.getFullYear(),t.getMonth(),t.getDate()-1));if(l===d)return o?`Yesterday · ${o}`:"Yesterday";const f=s.getFullYear()===t.getFullYear(),m=s.toLocaleDateString(n,f?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"});return o?`${m} · ${o}`:m}function C2(e,t){const n=Qd(e);return n?Yd(e)?n.toLocaleDateString(t,{weekday:"long",year:"numeric",month:"long",day:"numeric"}):n.toLocaleString(t,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"}):""}function E2(e){if(Yd(e))return e.trim();const t=Qd(e);return t?t.toISOString():""}function qu(e=new Date){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}var ai=new Set,or=null;function Uy(){var n;if(or!==null||!ai.size||typeof setTimeout!="function")return;const e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1,0,0,1);or=setTimeout(()=>{or=null;for(const s of[...ai])s();Uy()},Math.min(Math.max(1e3,t.getTime()-e.getTime()),36e5)),(n=or.unref)==null||n.call(or)}function T2(e){return ai.add(e),Uy(),()=>{ai.delete(e),!ai.size&&or!==null&&(clearTimeout(or),or=null)}}function A2(){const[e,t]=p.useState(()=>qu());return p.useEffect(()=>(t(qu()),T2(()=>t(qu()))),[]),e}function $2(e){const t=e.totalTokens!==void 0?Io("tokens",e):null,n=Io("tools",e),s=e.durationMs!==void 0?Io("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`,detail:Io("files",e)}]:[],...s?[{label:Jt(e.durationMs),detail:s}]:[]]}function R2(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"}}var M2=new Set(["blob:","data:","http:","https:"]);function hl(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return M2.has(new URL(t,n).protocol)?t:void 0}catch{return}}function Wy(e,t){return Ly(e)?{href:e,download:t||"file"}:{href:e,target:"_blank",rel:"noopener noreferrer"}}function L2({item:e,onOpen:t,markdown:n}){const[s,o]=p.useState(!1),l=hl(e.src),u=String(e.name||e.label||"").trim()||"File",d=r2({href:e.href?hl(e.href):void 0,src:l,contentType:e.contentType,name:e.name||e.label}),f=gs(u,e.contentType),m=Zs(f),g=typeof e.text=="string";if(!l&&!d&&!g)return null;const v=di(e.size),w=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(be,{name:"file",size:14}),a.jsx("span",{className:"pc-chat-media__file-name",title:u,children:w}),v?a.jsx("span",{className:"pc-chat-media__file-size",children:v}):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(x=>!x),children:s?"Close":"Open"}),d?a.jsx("a",{className:"pc-chat-media__link",...Wy(d,String(e.name||"").trim()||w),children:"Raw file"}):null]}),s&&!t?a.jsx(Ay,{className:"pc-chat-media__viewer",name:u,kind:f,contentType:e.contentType,sizeBytes:e.size,status:m&&!g?"error":"ready",error:m&&!g?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}:{},...g?{text:e.text}:{},...l&&!m?{url:l}:{},onClose:()=>o(!1)}):null]})}function I2({item:e,onOpenFile:t,markdown:n}){const[s,o]=p.useState(!1);if(e.kind==="file")return a.jsx(L2,{item:e,onOpen:t,markdown:n||{}});const l=hl(e.src),u=e.href?hl(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()}`,g=()=>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:g}):null,l&&d==="video"?a.jsx("video",{className:"pc-chat-media__video",src:l,controls:!0,playsInline:!0,preload:"metadata","aria-label":m,onError:g}):null,l&&d==="audio"?a.jsx(Bd,{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",...Wy(u,String(e.name||"").trim()||m),children:m})}):null]})}function P2(e){return e==="loading"?{icon:"loader",title:"Generating audio…",spinning:!0}:e==="playing"?{icon:"pause",title:"Pause",spinning:!1}:e==="paused"?{icon:"play",title:"Resume",spinning:!1}:{icon:"speaker",title:"Speak (TTS)",spinning:!1}}function Xd(e){var se,Q,z;const t=e.message,n=p.useMemo(()=>R2(t),[t.kind,t.level,t.role,t.title]),s=t.ts,o=A2(),l=p.useMemo(()=>N2(s),[s,o]),u=p.useMemo(()=>C2(s),[s]),d=p.useMemo(()=>E2(s),[s]),[f,m]=p.useState("idle"),g=p.useRef(null);p.useEffect(()=>()=>{g.current!==null&&window.clearTimeout(g.current)},[]);const v=t.live,w=typeof e.onSpeakToggle=="function"&&n.variant==="assistant",x=w?v?"Read aloud when the reply is finished":String(t.content||"").trim()?"":"No text to read aloud":"",j=w&&!x,b=j&&((se=e.getSpeakState)==null?void 0:se.call(e,t))||"idle",k=P2(b),$=e.showCopy!==!1,S=Array.isArray(e.attachments)?e.attachments:Array.isArray(t.attachments)?t.attachments:[],N=t.statistics,C=t.stats,R=p.useMemo(()=>Array.isArray(e.stats)?e.stats:Array.isArray(C)?C:N?$2(N):[],[e.stats,C,N]),E=Array.isArray(t.media)?t.media:[],I=String(v?v.reasoning||"":t.reasoning||""),L=!!String(t.content||"").trim();if(t.toolActivity)return a.jsx(By,{tool:t.toolActivity,showCopy:e.showCopy});const D=(Q=e.variant)==null?void 0:Q.call(e,t),P=D==="caption",K=e.renderFooter&&!P?e.renderFooter(t):null;if(D==="hint"||t.kind==="tool_policy_decision"){const T=String(t.level||"").trim().toLowerCase();return a.jsxs("div",{className:["pc-chat-hint",T==="warn"||T==="error"?`pc-chat-hint--${T}`:"",e.className].filter(Boolean).join(" "),role:"note","data-variant":"hint",children:[a.jsx("span",{className:"pc-chat-hint__text",children:String(t.content||"")}),K!=null&&K!==!1?a.jsx("div",{className:"pc-chat-footer",children:K}):null]})}return a.jsxs("div",{className:["pc-chat-item",`pc-chat-item--${n.variant}`,P?"pc-chat-item--caption":"",v?"pc-chat-item--live":"",e.className].filter(Boolean).join(" "),...v?{"aria-busy":!0}:{},...P?{"data-variant":"caption"}:{},children:[P?null:a.jsxs("div",{className:"pc-chat-header",children:[a.jsx("div",{className:"pc-chat-avatar","aria-hidden":"true",children:a.jsx(be,{name:n.icon,size:14})}),a.jsx("span",{className:"pc-chat-role",children:n.label}),v?a.jsxs("span",{className:"pc-chat-live-indicator",title:v.label?`Pending: ${v.label}`:"The reply is still being written",children:[a.jsx("span",{className:"pc-chat-live-dot","aria-hidden":"true"}),v.label||"streaming"]}):null,v!=null&&v.caption?a.jsx("span",{className:"pc-chat-live-caption",children:v.caption}):null,a.jsx("span",{className:"pc-chat-header-spacer"}),l?a.jsx("time",{className:"pc-chat-time",dateTime:d||void 0,title:u||void 0,children:l}):null,a.jsxs("div",{className:"pc-chat-header-actions",children:[w?a.jsx("button",{className:"pc-chat-icon-btn",type:"button","aria-label":x||k.title,title:x||k.title,"data-speak-state":x?"unavailable":b,...x?{"aria-disabled":!0}:{},onClick:j?()=>{var T;return(T=e.onSpeakToggle)==null?void 0:T.call(e,t)}:void 0,children:a.jsx(be,{name:k.icon,size:22,className:k.spinning?"pc-chat-speak-spinner":void 0},k.icon)}):null,$?a.jsx("button",{className:`pc-chat-icon-btn ${f!=="idle"?`pc-chat-icon-btn--${f}`:""}`.trim(),type:"button","aria-label":"Copy message",title:f==="idle"?"Copy":f==="copied"?"Copied":"Copy failed",onClick:async()=>{const T=await fi(String(t.content||""));m(T?"copied":"failed"),g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>m("idle"),900)},children:a.jsx(be,{name:"copy",size:22})}):null]})]}),I.trim()&&!P?a.jsxs("details",{className:"pc-chat-thinking",children:[a.jsx("summary",{children:"Thinking"}),a.jsx("div",{className:"pc-chat-thinking-body",children:I})]}):null,L||!v&&!E.length?a.jsx("div",{className:"pc-chat-body",children:a.jsx(d2,{text:String(t.content||""),renderMarkdown:e.renderMarkdown,jsonCollapseAfterDepth:e.jsonCollapseAfterDepth,images:e.images||(n.variant==="user"?"inline":"link"),inlineImage:e.inlineImage})}):null,E.length?a.jsx("div",{className:"pc-chat-media",children:E.map((T,q)=>a.jsx(I2,{item:T,onOpenFile:e.onOpenMedia,markdown:{renderMarkdown:e.renderMarkdown,images:e.images,inlineImage:e.inlineImage}},T.id||`${T.kind}:${T.src}:${q}`))}):null,(z=t.artifactRefs)!=null&&z.length?a.jsx("div",{className:"pc-chat-attachments","aria-label":"Attached files",children:t.artifactRefs.map(T=>a.jsx(QN,{artifact:T},`${T.runId}:${T.id}`))}):null,S.length?a.jsx("div",{className:"pc-chat-attachments","aria-label":"Attachments",children:S.map((T,q)=>{const J=String(T.label||"").trim()||"attachment",B=String(T.target||"").trim(),O=String(T.title||"").trim(),Z=!!T.disabled||typeof T.onClick!="function";return a.jsxs("button",{type:"button",className:"pc-chat-attachment-chip",title:O||J,onClick:Z?void 0:T.onClick,disabled:Z,children:[a.jsx(be,{name:"paperclip",size:14}),B?a.jsx("span",{className:`pc-chat-attachment-target pc-chat-attachment-target--${B}`,children:B}):null,a.jsx("span",{className:"pc-chat-attachment-name",children:J})]},T.id||`${J}:${q}`)})}):null,R.length&&!P?a.jsx("div",{className:"pc-chat-stats","aria-label":"Stats",children:R.slice(0,12).map((T,q)=>{const J=String(T.label||"").trim();if(!J)return null;if(T.detail)return a.jsx(k2,{label:J,detail:T.detail,icon:T.icon,onClick:T.onClick},T.id||`${J}:${q}`);const B=String(T.title||"").trim(),O=typeof T.onClick=="function",Z=O?"button":"span";return a.jsxs(Z,{...O?{type:"button"}:{},className:["pc-chat-stat",O?"pc-chat-stat--clickable":""].filter(Boolean).join(" "),title:B||void 0,onClick:O?()=>{var M;return(M=T.onClick)==null?void 0:M.call(T)}:void 0,children:[T.icon?a.jsx("span",{className:"pc-chat-stat-icon","aria-hidden":"true",children:T.icon}):null,a.jsx("span",{className:"pc-chat-stat-label",children:J})]},T.id||`${J}:${q}`)})}):null,K!=null&&K!==!1?a.jsx("div",{className:"pc-chat-footer",children:K}):null]})}function O2(e,t){const n=Math.max(0,Math.trunc(t));return e.scrollHeight-e.scrollTop-e.clientHeight<=n}function D2(e){const t=typeof e.autoScrollThresholdPx=="number"&&Number.isFinite(e.autoScrollThresholdPx)?e.autoScrollThresholdPx:120,n=e.autoScroll!==!1,s=p.useRef(null),o=p.useRef(null),[l,u]=p.useState(!0),d=p.useMemo(()=>Array.isArray(e.messages)?e.messages:[],[e.messages]),f=p.useMemo(()=>{var v;const g=[];for(const w of d){const x=g[g.length-1];w.toolActivity&&((v=x==null?void 0:x[0])!=null&&v.toolActivity)&&x[0].runId===w.runId?x.push(w):g.push([w])}return g},[d]);p.useEffect(()=>{if(!n)return;const g=s.current;if(!g)return;const v=()=>{u(O2(g,t))};return g.addEventListener("scroll",v,{passive:!0}),v(),()=>g.removeEventListener("scroll",v)},[n,t]);const m=p.useMemo(()=>{var v,w,x;let g=0;for(const j of d){g+=String(j.content??"").length;for(const b of j.artifactRefs||[])g+=b.id.length+(((v=b.name)==null?void 0:v.length)||0)+1;if(g+=(((w=j.artifactIds)==null?void 0:w.length)||0)+(((x=j.attachments)==null?void 0:x.length)||0),Array.isArray(j.media))for(const b of j.media)g+=String((b==null?void 0:b.src)??"").length+1}return`${d.length}:${g}:${String(e.afterKey??"")}`},[d,e.afterKey]);return p.useEffect(()=>{if(!n||!l)return;const g=s.current;g&&(g.scrollTop=g.scrollHeight)},[n,l,m]),p.useEffect(()=>{if(!n)return;const g=s.current;if(!g)return;const v=()=>{l&&(g.scrollTop=g.scrollHeight)};return g.addEventListener("load",v,!0),g.addEventListener("loadedmetadata",v,!0),()=>{g.removeEventListener("load",v,!0),g.removeEventListener("loadedmetadata",v,!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((g,v)=>{var j;const w=g[0],x=String(w.id||"")||String(w.ts||"")+":"+String(w.role||"")+":"+v;return w.toolActivity?a.jsx(S2,{tools:g.map(b=>b.toolActivity),showCopy:(j=e.messageProps)==null?void 0:j.showCopy},x):a.jsx(Xd,{message:w,...e.messageProps||{}},x)}),e.after,a.jsx("div",{ref:o})]})}var F2=new Set(["blob:","data:","http:","https:"]);function B2(e){const t=String(e||"").trim();if(t)try{const n=typeof window<"u"&&window.location?window.location.href:"http://same-origin.invalid/";return F2.has(new URL(t,n).protocol)?t:void 0}catch{return}}function z2(e){const t=typeof e.size=="number"?BN(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 U2(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}=z2(n),u=B2(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(be,{name:"paperclip",size:13}):a.jsx(be,{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(be,{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(be,{name:"x",size:12})}):null]},n.id)})}):null}function Po(e){if(!e)return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="Files")return!0;return!1}function ag(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 ig(e){return e===1?"Drop file to attach":typeof e=="number"&&e>1?`Drop ${e} files to attach`:"Drop files to attach"}function Vy(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 W2(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.`:""}var V2={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic","image/tiff":"tiff","image/bmp":"bmp"};function Oa(e){return String(e).padStart(2,"0")}function q2(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=V2[String(t||"").toLowerCase()]||s.split(".").pop()||"bin",l=`${n.getFullYear()}-${Oa(n.getMonth()+1)}-${Oa(n.getDate())} at ${Oa(n.getHours())}.${Oa(n.getMinutes())}.${Oa(n.getSeconds())}`;return`${String(t||"").startsWith("image/")||!s?"Pasted image":"Pasted file"} ${l}.${o}`}function H2(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}=Vy(e);return s.map(o=>{const l=q2(o.name,o.type,t);return l===o.name?o:new File([o],l,{type:o.type,lastModified:o.lastModified})})}var G2=class{constructor(e=1200){this.staleMs=e,this.depth=0,this.lastSeen=0}enter(e){this.depth+=1,this.lastSeen=e}over(e){this.depth===0&&(this.depth=1),this.lastSeen=e}leave(e){return this.depth=Math.max(0,this.depth-1),this.lastSeen=e,this.depth>0}reset(){this.depth=0}active(e){return this.depth>0&&e-this.lastSeen<this.staleMs}};function K2(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")}var Gs={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 og(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function J2(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"})]})}var cn=Gs;function lg(e){var Q,z,T,q,J;const t=e.interaction,n=e.variant==="card",s=e.variant==="conversation",[o,l]=p.useState(""),[u,d]=p.useState(()=>t.kind==="event-wait"&&t.initialPayload||""),[f,m]=p.useState(null),[g,v]=p.useState(!1),[w,x]=p.useState(""),[j,b]=p.useState(null),k=`${t.kind}:${t.id}`,$=p.useRef(k),S=p.useRef(!1),N=p.useRef(!1),C=p.useRef(!0),R=p.useRef(0);$.current!==k&&($.current=k,S.current=!1,N.current=!1,R.current+=1);const E=!!e.disabled||f!==null||g||S.current||N.current,I=async(B,O)=>{var W;if(e.disabled||S.current||N.current)return;const Z=k,M=++R.current;S.current=!0,b(null),x(""),m(B);try{const Y=await O();if(!C.current||$.current!==Z||R.current!==M)return;N.current=!0,v(!0);const oe=Y&&typeof Y=="object"&&typeof Y.outcomeNote=="string"?String(Y.outcomeNote):"";x(s?`Your choice was sent. I’m waiting for work to continue.${oe?" Some actions may still be blocked by your saved permissions; review the details if needed.":""}`:`Response sent. Waiting for the workflow to continue.${oe?` ${oe}`:""}`)}catch(Y){if(!C.current||$.current!==Z||R.current!==M)return;b({submission:B,message:og(Y)}),x("The action failed. You can try again."),(W=e.onError)==null||W.call(e,Y)}finally{if(!C.current||$.current!==Z||R.current!==M)return;S.current=!1,m(null)}},L=async B=>{var Z;if(e.disabled||S.current||N.current)return;const O=k;try{if(await B(),!C.current||$.current!==O)return;b(null),x(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(M){if(!C.current||$.current!==O)return;x(`Could not leave this for later: ${og(M)}`),(Z=e.onError)==null||Z.call(e,M)}};p.useEffect(()=>{l(""),d(t.kind==="event-wait"&&t.initialPayload||""),b(null),m(null),v(!1),x("")},[k]),p.useEffect(()=>(C.current=!0,()=>{C.current=!1,R.current+=1,S.current=!1}),[]);const D=()=>{j&&I(j.submission,()=>K2(t,j.submission))},P=s&&t.kind==="tool-approval"?((Q=t.publicRequest)==null?void 0:Q.question)||"May I take this next step?":t.title||(t.kind==="tool-approval"?"Tool approval required":"Input required"),K=(B,O)=>B?a.jsx("button",{type:"button",className:"pc-workflow-interaction__defer","data-decision":"defer",disabled:E,onClick:()=>void L(B),children:O}):null;let se;if(t.kind==="ask-user")se=a.jsxs("div",{className:"pc-workflow-interaction__body",children:[a.jsx("div",{className:"pc-workflow-interaction__prompt",children:t.prompt}),(z=t.choices)!=null&&z.length?a.jsx("div",{className:"pc-workflow-interaction__choices","aria-label":"Choices",children:t.choices.map(B=>a.jsxs("button",{type:"button",className:"pc-workflow-interaction__choice","data-decision":"choice",disabled:E||B.disabled,onClick:()=>void I({kind:"choice",answer:B.id},()=>t.onSubmit(B.id)),children:[a.jsx("span",{children:B.label}),B.description?a.jsx("small",{children:B.description}):null]},B.id))}):null,t.allowFreeText!==!1?a.jsxs("div",{className:"pc-workflow-interaction__entry",children:[a.jsx("textarea",{"aria-label":"Response",value:o,onChange:B=>l(B.target.value),placeholder:t.freeTextPlaceholder||"Type a response",rows:n?1:2,disabled:E,onKeyDown:B=>{B.key!=="Enter"||B.shiftKey||B.nativeEvent.isComposing||B.keyCode===229||(B.preventDefault(),o.trim()&&I({kind:"free-text",answer:o},()=>t.onSubmit(o)))}},`${k}:text`),a.jsx("button",{type:"button",className:"pc-btn","data-decision":"submit",disabled:E||!o.trim(),onClick:()=>void I({kind:"free-text",answer:o},()=>t.onSubmit(o)),children:(f==null?void 0:f.kind)==="free-text"?"Sending…":t.submitLabel||cn.submit})]}):null,t.onSkip||t.onDefer?a.jsxs("div",{className:"pc-workflow-interaction__buttons pc-workflow-interaction__buttons--secondary",children:[K(t.onDefer,t.deferLabel||cn.keepWaiting),t.onSkip?a.jsx("button",{type:"button",className:"pc-workflow-interaction__skip","data-decision":"skip",disabled:E,onClick:()=>void I({kind:"skip"},t.onSkip),children:(f==null?void 0:f.kind)==="skip"?"Continuing…":t.skipLabel||cn.skip}):null]}):null]});else if(t.kind==="tool-approval"&&s){const B=t.publicRequest,O=!B||B.reviewRequired;se=a.jsxs("div",{className:"pc-workflow-interaction__body pc-public-approval",children:[a.jsxs("div",{className:"pc-public-approval__context",children:[a.jsxs("div",{className:"pc-public-approval__reason",children:[a.jsx("p",{className:"pc-public-approval__reason-label",children:"Why I’m asking"}),a.jsx("p",{children:((T=B==null?void 0:B.explanation)==null?void 0:T.text)||"The reason for this request isn’t available here."})]}),B!=null&&B.actions.length?a.jsx("ul",{className:"pc-public-approval__targets","aria-label":"What this will do","data-uniform":B.actions.every(Z=>Z.kind===B.actions[0].kind)&&!["write","edit","unknown"].includes(B.actions[0].kind)||void 0,children:B.actions.map((Z,M)=>a.jsxs("li",{children:[a.jsx(be,{name:Z.kind==="page"||Z.kind==="search"?"book":Z.kind==="write"||Z.kind==="edit"?"edit":Z.kind==="folder"?"folder":Z.kind==="unknown"?"info":"file",size:20}),a.jsxs("span",{children:[a.jsx("span",{className:"pc-public-approval__action",children:Z.label}),Z.target?a.jsx("span",{className:"pc-public-approval__target",children:Z.target}):null]})]},M))}):null,O?a.jsx("p",{className:"pc-public-approval__note",children:"I can’t describe this request clearly here. Review the details before allowing it."}):a.jsx("p",{className:"pc-public-approval__note",children:"Allow once covers only what is shown here. I’ll ask again for later requests."})]},k),a.jsxs("div",{className:"pc-workflow-interaction__buttons pc-public-approval__buttons",children:[K(t.onDefer,t.deferLabel||cn.decideLater),a.jsxs("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:E,onClick:()=>void I({kind:"deny"},t.onDeny),children:[a.jsx(be,{name:"x",size:18}),(f==null?void 0:f.kind)==="deny"?"Declining…":t.denyLabel||cn.deny]}),O?null:a.jsxs("button",{type:"button",className:"pc-btn","data-decision":"approve",disabled:E,onClick:()=>void I({kind:"approve"},t.onApprove),children:[a.jsx(be,{name:"check",size:18}),(f==null?void 0:f.kind)==="approve"?"Allowing…":t.approveLabel||cn.allowOnce]}),e.onReviewTechnical?a.jsxs("button",{type:"button",className:"pc-public-approval__review",disabled:E,onClick:e.onReviewTechnical,children:[a.jsx(be,{name:"list",size:18}),"Review details"]}):null]}),O&&!e.onReviewTechnical?a.jsx("p",{className:"pc-public-approval__note",children:"Switch to the conversation’s detailed view to review this request."}):null,t.deniedNote?a.jsx("p",{className:"pc-public-approval__note",role:"note",children:"Some of these actions are blocked by your saved permissions. Allow once cannot override that choice. Review details to see what is blocked."}):null]})}else if(t.kind==="tool-approval"){const B=String(t.disabledReason||"").trim(),O=E||!!B,Z=[!B&&t.onApproveForSession&&t.approveForSessionDescription?t.approveForSessionDescription:"",!B&&t.onApproveAll&&t.approveAllDescription?t.approveAllDescription:""].filter(Boolean),M=Z.length?String(t.broadScopeSummary||"").trim():"";se=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:[K(t.onDefer,t.deferLabel||cn.decideLater),a.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny",disabled:E,onClick:()=>void I({kind:"deny"},t.onDeny),children:(f==null?void 0:f.kind)==="deny"?"Denying…":t.denyLabel||cn.deny}),a.jsx("button",{type:"button",className:"pc-btn","data-decision":"approve",disabled:E,onClick:()=>void I({kind:"approve"},t.onApprove),children:(f==null?void 0:f.kind)==="approve"?"Allowing…":t.approveLabel||cn.allowOnce}),t.onApproveForSession?a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session","data-decision":"approve-session",disabled:O,title:B||t.approveForSessionDescription||void 0,onClick:()=>void I({kind:"approve-session"},t.onApproveForSession),children:(f==null?void 0:f.kind)==="approve-session"?"Allowing…":t.approveForSessionLabel||cn.allowForChat}):null,(t.approveKinds||[]).map(W=>a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-session pc-workflow-interaction__allow-kind","data-decision":"approve-kind","data-kind":W.kind,disabled:O,title:B||t.approveForSessionDescription||void 0,onClick:()=>void I({kind:"approve-kind",toolset:W.kind},W.onApprove),children:(f==null?void 0:f.kind)==="approve-kind"&&f.toolset===W.kind?"Allowing…":W.label||cn.allowKindForChat(W.kind)},W.kind)),t.onApproveAll?a.jsx("button",{type:"button",className:"pc-workflow-interaction__allow-all","data-decision":"approve-all",disabled:O,title:B||t.approveAllDescription||void 0,onClick:()=>void I({kind:"approve-all"},t.onApproveAll),children:(f==null?void 0:f.kind)==="approve-all"?"Allowing…":t.approveAllLabel||cn.allowAll}):null]}),M?a.jsx("p",{className:"pc-workflow-interaction__scope","data-scope-summary":"",children:M}):null,t.remember?a.jsxs("label",{className:"pc-workflow-interaction__remember",children:[a.jsx("input",{type:"checkbox",checked:t.remember.checked,disabled:E,onChange:W=>t.remember.onChange(W.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,(q=t.denyOptions)!=null&&q.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:cn.denyForChatNote}),a.jsx("div",{className:"pc-workflow-interaction__buttons",children:t.denyOptions.map(W=>a.jsx("button",{type:"button",className:"pc-workflow-interaction__deny","data-decision":"deny-chat","data-key":W.key,disabled:E,onClick:()=>void I({kind:"deny-chat",key:W.key},W.onDeny),children:(f==null?void 0:f.kind)==="deny-chat"&&f.key===W.key?"Denying…":W.label},W.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,B&&(t.onApproveAll||t.onApproveForSession||(J=t.approveKinds)!=null&&J.length)?a.jsx("p",{className:"pc-workflow-interaction__unavailable",role:"note",children:B}):null,M&&Z.length?a.jsxs("details",{className:"pc-workflow-interaction__scope-details","data-scope-details":"",children:[a.jsx("summary",{children:"What the broader choices allow"}),Z.map(W=>a.jsx("p",{className:"pc-workflow-interaction__scope",children:W},W))]}):Z.map(W=>a.jsx("p",{className:"pc-workflow-interaction__scope",children:W},W))]})}else se=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:u,onChange:B=>d(B.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},`${k}: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 I({kind:"event",payload:u},()=>t.onSend(u)),children:(f==null?void 0:f.kind)==="event"?"Sending…":t.sendLabel||cn.sendEvent})})]});return a.jsxs("section",{className:["pc-workflow-interaction",n?"pc-workflow-interaction--card":"",s?"pc-workflow-interaction--conversation":""].filter(Boolean).join(" "),"data-variant":e.variant||"panel","aria-labelledby":`pc-workflow-interaction-${k}`,children:[a.jsxs("div",{className:"pc-workflow-interaction__heading",children:[a.jsx(be,{name:t.kind==="tool-approval"?s?"lock":"warning":t.kind==="event-wait"?"history":"info",size:n?14:16}),a.jsxs("div",{children:[a.jsx("h3",{className:s&&t.kind==="tool-approval"?"pc-workflow-interaction__prompt":void 0,tabIndex:-1,id:`pc-workflow-interaction-${k}`,children:P}),t.description&&!(s&&t.kind==="tool-approval")?a.jsx("div",{className:"pc-workflow-interaction__description",children:t.description}):null]})]}),se,j?a.jsx(J2,{message:s?"Your choice could not be sent.":j.message,onRetry:D,disabled:E}):null,a.jsx("div",{className:"pc-workflow-interaction__outcome","aria-live":"polite",children:w})]})}var bd={approval:{visual:!0,audio:!0,haptic:!1},question:{visual:!0,audio:!0,haptic:!1},completion:{visual:!0,audio:!0,haptic:!1}},Qo=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null;function qy(e,t){const n=Qo(e);return!n||typeof n.id!="string"||!n.id.trim()||typeof n.text!="string"||!n.text.trim()||n.text.length>4e3||n.run_id!==void 0&&n.run_id!==t||!Array.isArray(n.source_call_ids)||n.source_call_ids.some(s=>typeof s!="string"||!s.trim())?null:{id:n.id,text:n.text,runId:t,sourceCallIds:[...new Set(n.source_call_ids)],kind:n.kind==="finding"?"finding":"progress",...typeof n.session_id=="string"?{sessionId:n.session_id}:{},...typeof n.iteration=="number"?{iteration:n.iteration}:{}}}var Zd=e=>{var t;return`${e.runId||""}:${((t=e.publicUpdate)==null?void 0:t.id)||e.id||`${e.kind}:${e.content}`}`};function kl(e){const t=new Set;return e.filter(n=>{var u,d,f;const s=!!((u=n.attachments)!=null&&u.length||(d=n.artifactRefs)!=null&&d.length||(f=n.media)!=null&&f.length);if(n.live||n.toolActivity||!n.content.trim()&&!s||!(n.role==="user"||n.role==="assistant"&&["public_update","answer","final","question","attachments"].includes(n.kind||"")||n.role==="system"&&n.kind==="question_outcome"&&n.source==="emit_event")||n.kind==="public_update"&&!n.publicUpdate)return!1;const l=Zd(n);return t.has(l)?!1:(t.add(l),!0)})}function Y2(e,t,n,s=[]){if(!t||t.kind!=="public_update"||!t.publicUpdate)return e;if(!n||t.publicUpdate.runId!==t.runId||t.runId!==n&&!s.includes(t.publicUpdate.runId))throw new Error("The update you chose to reply to is from an earlier exchange. Choose Latest, then send your message again.");return`The person is replying to this quoted public update (context only):
79
+ ${JSON.stringify({message_id:t.id||t.publicUpdate.id,run_id:t.publicUpdate.runId,root_run_id:n,text:t.content})}
80
+
81
+ The person's message:
82
+ ${e}`}var cg=new WeakMap;function xd(e){let t=cg.get(e);return t||cg.set(e,t={...e,reasoning:void 0,live:void 0,toolActivity:void 0,statistics:void 0,stats:void 0}),t}function Q2(e,t={}){const n=kl(e);let s=0,o="";for(let f=n.length-1;f>=0;f--)if(n[f].role==="user"&&(o||(o=Zd(n[f])),n[f].kind!=="guidance")){s=f+1;break}let l=-1,u=-1;const d=[];for(let f=s;f<n.length;f++){const m=n[f];m.role!=="user"&&(m.kind==="public_update"||m.kind==="question_outcome"||m.kind==="question"&&!t.pinnedRequest?l=f:m.kind!=="question"&&(u=f,d.push(xd(m))))}return{line:l>u?xd(n[l]):null,answers:d,personKey:o}}function X2(e){const t=new Map;for(const n of e){const s=n.toolActivity;s!=null&&s.callId&&t.set(`${s.runId}:${s.callId}`,s)}return kl(e).filter(n=>{var s;return((s=n.publicUpdate)==null?void 0:s.kind)==="finding"}).map(n=>{const s=n.publicUpdate;return{key:Zd(n),message:xd(n),sources:s.sourceCallIds.map(o=>t.get(`${s.runId}:${o}`)).filter(o=>!!o)}})}function Z2(e){var t,n;return e.status==="completed"||e.status==="failed"?e.listening?"listening":e.speaking?"speaking":e.status:e.connection==="disconnected"?"disconnected":e.connection==="connecting"||e.connection==="reconnecting"?"connecting":e.status==="paused"?"paused":((t=e.attention)==null?void 0:t.kind)==="approval"?"approval":((n=e.attention)==null?void 0:n.kind)==="question"?"question":e.listening?"listening":e.speaking?"speaking":e.status||"idle"}function eC(e){var f,m;const t=e.toolApprovalGranted?null:e.interaction,n=Qo(t==null?void 0:t.wait),s=Qo(n==null?void 0:n.details),o=Qo(s==null?void 0:s.question),l=(t==null?void 0:t.kind)==="tool_approval"||(s==null?void 0:s.kind)==="tool_approval"||(s==null?void 0:s.mode)==="approval_required"||(n==null?void 0:n.reason)==="tool_approval";let u=null;return t&&(l||t.kind==="ask_user"||(n==null?void 0:n.reason)==="user"||(n==null?void 0:n.reason)==="ask_user")?u={id:`${t.runId}:${String((o==null?void 0:o.id)||(n==null?void 0:n.wait_key)||t.stepId||"")}`,kind:l?"approval":"question",...(o==null?void 0:o.importance)==="essential"||(o==null?void 0:o.importance)==="clarification"?{importance:o.importance}:{},...typeof(o==null?void 0:o.deadline)=="string"?{deadline:o.deadline}:{},...typeof(o==null?void 0:o.fallback)=="string"?{fallback:o.fallback}:{}}:e.status==="completed"&&(u={id:`${String(((f=e.run)==null?void 0:f.run_id)||"")}:completed`,kind:"completion"}),{status:e.status==="completed"?"completed":["failed","cancelled"].includes(e.status)?"failed":((m=e.run)==null?void 0:m.paused)===!0||e.status==="paused"?"paused":["running","waiting","queued"].includes(e.status)?"working":"idle",connection:e.connection,attention:u,replaying:!!(e.loading||e.historyLoading)}}function tC(e,t){var f,m;const n=t.attention?`${t.attention.kind}:${t.attention.id}`:"",s=!e||e.sessionKey!==t.sessionKey,o=new Set(s?[]:e.seen),l=!!(n&&!o.has(n));n&&o.add(n);const u=((f=t.attention)==null?void 0:f.kind)==="question"||((m=t.attention)==null?void 0:m.kind)==="approval",d=!s&&e.connected&&t.connected&&(!t.attended||u)&&l&&t.attention;return{cursor:{sessionKey:t.sessionKey,connected:t.connected,seen:[...o]},cue:d?{...t.attention,channels:{...t.preferences[t.attention.kind]}}:null}}function nC(e,t){const n=kl(t.messages),s=n.filter(g=>g.kind==="public_update"),o=!e||e.sessionKey!==t.sessionKey,l=new Set(o?[]:e.seen),u=g=>`${g.runId||""}:${g.publicUpdate.id}`,d=n[n.length-1],f=(d==null?void 0:d.kind)==="public_update"&&!l.has(u(d));for(const g of s)l.add(u(g));const m=!o&&e.connected&&t.connected&&t.enabled&&!t.attended&&!t.listening&&f;return{cursor:{sessionKey:t.sessionKey,connected:t.connected,seen:[...l]},message:m?d:null}}var rC={idle:"Ready",working:"Working",paused:"Paused — work resumes only when you continue",listening:"Listening — your words have not been submitted",speaking:"Speaking",question:"A question for you",approval:"Permission required",completed:"Completed",failed:"Work stopped",connecting:"Connecting…",disconnected:"Connection interrupted"};function sC(e){return a.jsx(fC,{...e},e.sessionKey)}var aC=()=>"caption",Hy=it.memo(function(t){return a.jsx(Xd,{...t,showCopy:!1,variant:aC})}),iC=e=>({renderMarkdown:e==null?void 0:e.renderMarkdown,images:e==null?void 0:e.images,inlineImage:e==null?void 0:e.inlineImage,onOpenMedia:e==null?void 0:e.onOpenMedia,jsonCollapseAfterDepth:e==null?void 0:e.jsonCollapseAfterDepth}),oC=e=>{var t,n;return!((n=(t=e.target).closest)!=null&&n.call(t,"a, button, input, textarea, select, summary, video, audio"))},lC=["url","file_path","path","query"];function cC(e){const t=e.arguments&&typeof e.arguments=="object"&&!Array.isArray(e.arguments)?e.arguments:{},n=lC.map(s=>t[s]).find(s=>typeof s=="string"&&s.trim());return typeof n=="string"?n.trim():""}function Gy(e){const{className:t,open:n,onOpen:s,openerRef:o,children:l,...u}=e,d=p.useId();return a.jsxs("div",{...u,className:`${t} pc-avatar-conversation__expandable`,"data-open":n||void 0,children:[a.jsx("div",{id:d,children:l}),n?null:a.jsx("button",{ref:o,type:"button",className:"pc-avatar-conversation__opener","aria-expanded":!1,"aria-labelledby":d,onClick:s})]})}var uC=it.memo(function(t){const[n,s]=p.useState(!1),o=p.useRef(null),l=p.useRef(null),u=p.useRef(!1),{finding:d,onOpen:f,...m}=t;p.useEffect(()=>{var w,x;n?(w=l.current)==null||w.focus():u.current&&(u.current=!1,(x=o.current)==null||x.focus())},[n]);const g=()=>{u.current=!0,s(!1)},v=d.sources.map(w=>({id:w.id,text:cC(w)})).filter(w=>w.text);return a.jsxs("div",{ref:l,className:"pc-avatar-conversation__finding","data-open":n||void 0,tabIndex:n?-1:void 0,onClick:w=>{n&&oC(w)&&g()},onKeyDown:w=>{n&&w.key==="Escape"&&(w.stopPropagation(),g())},children:[a.jsx(Gy,{className:"pc-avatar-conversation__finding-text",open:n,openerRef:o,onOpen:()=>{f(),s(!0)},children:a.jsx(Hy,{...m,message:d.message})}),n&&v.length?a.jsx("ul",{className:"pc-avatar-conversation__sources","aria-label":"Sources",children:v.map(w=>a.jsx("li",{children:a.jsx(Qa,{text:w.text})},w.id))}):null]})},(e,t)=>e.finding.message===t.finding.message&&e.finding.sources.length===t.finding.sources.length&&e.finding.sources.every((n,s)=>n===t.finding.sources[s])&&e.onOpen===t.onOpen&&e.renderMarkdown===t.renderMarkdown&&e.images===t.images&&e.inlineImage===t.inlineImage&&e.onOpenMedia===t.onOpenMedia&&e.jsonCollapseAfterDepth===t.jsonCollapseAfterDepth),dC=720;function fC(e){const[t,n]=p.useState(null),[s,o]=p.useState(!1),[l,u]=p.useState(!1),d=e.preferences||bd,f=p.useMemo(()=>kl(e.messages),[e.messages]),m=!!e.interaction&&(e.interactionId===void 0||!!e.interactionId),g=p.useMemo(()=>Q2(e.messages,{pinnedRequest:m}),[e.messages,m]),v=p.useMemo(()=>X2(e.messages),[e.messages]),w=!!(e.attended||t||l&&v.length);p.useEffect(()=>{var O;return(O=e.onAttendedChange)==null||O.call(e,w),()=>{var Z;return(Z=e.onAttendedChange)==null?void 0:Z.call(e,!1)}},[w,e.onAttendedChange]);const x=Z2(e),j=p.useRef(null),b=p.useRef(null),k=p.useRef(e);k.current=e,p.useEffect(()=>()=>{var O,Z,M,W;(Z=(O=k.current).onInterruptSpeech)==null||Z.call(O),(W=(M=k.current).onReplyContext)==null||W.call(M,null)},[]),p.useEffect(()=>{var O,Z;e.listening&&((Z=(O=k.current).onInterruptSpeech)==null||Z.call(O))},[e.listening]);const $=p.useRef(g.personKey);p.useEffect(()=>{$.current!==g.personKey&&($.current=g.personKey,n(null),o(O=>{var Z,M;return O&&((M=(Z=k.current).onReplyContext)==null||M.call(Z,null)),!1}))},[g.personKey]),p.useEffect(()=>{var M;const O=!e.replaying&&(!e.connection||e.connection==="connected"||e.status==="completed"||e.status==="failed")&&(typeof document>"u"||document.visibilityState!=="hidden"),Z=tC(j.current,{sessionKey:e.sessionKey,connected:O,attended:w,attention:e.attention,preferences:d});j.current=Z.cursor,Z.cue&&((M=e.onCue)==null||M.call(e,Z.cue))},[e.sessionKey,e.connection,e.status,e.replaying,e.attention,e.onCue,w,d]),p.useEffect(()=>{var M,W;const O=!e.replaying&&(!e.connection||e.connection==="connected"||e.status==="completed"||e.status==="failed")&&(typeof document>"u"||document.visibilityState!=="hidden"),Z=nC(b.current,{sessionKey:e.sessionKey,connected:O,attended:w,enabled:!!e.narrate&&e.status!=="paused",listening:e.listening,messages:f});b.current=Z.cursor,Z.message&&((M=e.onInterruptSpeech)==null||M.call(e),(W=e.onNarrate)==null||W.call(e,Z.message))},[f,e.sessionKey,e.connection,e.replaying,e.status,e.narrate,e.listening,e.onNarrate,e.onInterruptSpeech,w]);const S=p.useCallback(()=>{var O,Z;return(Z=(O=k.current).onInterruptSpeech)==null?void 0:Z.call(O)},[]),N=t||g.line,C=p.useRef(null),R=p.useRef(null),E=p.useRef(null),I=p.useRef(null),L=p.useRef(null),D=p.useRef(!1);p.useEffect(()=>{var O,Z,M,W;t?(Z=(O=E.current)==null?void 0:O.querySelector("button"))==null||Z.focus():D.current&&((W=((M=R.current)==null?void 0:M.querySelector(".pc-avatar-conversation__opener"))||R.current)==null||W.focus()),D.current=!1},[t]);const P=()=>{N&&(S(),n(N))},K=()=>{var O;t&&(S(),o(!0),(O=e.onReplyContext)==null||O.call(e,t))},se=()=>{var O;D.current=!0,n(null),s&&(o(!1),(O=e.onReplyContext)==null||O.call(e,null))};p.useEffect(()=>{var O;l&&((O=L.current)==null||O.focus())},[l]);const Q=()=>{S(),u(!0)},z=()=>{var O;u(!1),(O=I.current)==null||O.focus()};p.useEffect(()=>{const O=C.current;if(!l||!O||typeof ResizeObserver>"u")return;const Z=new ResizeObserver(([M])=>{M.contentRect.width>=dC&&u(!1)});return Z.observe(O),()=>Z.disconnect()},[l]);const T=e.attention&&d[e.attention.kind].visual?e.attention:null,q=iC(e.messageProps),{renderFooter:J,...B}=e.messageProps||{};return a.jsxs("section",{ref:C,className:"pc-avatar-conversation","aria-label":"Avatar conversation","data-state":x,"data-has-request":m||void 0,"data-compact":m||void 0,"data-has-findings":v.length?"":void 0,"data-findings-open":v.length&&l?"":void 0,onKeyDown:O=>{O.key==="Escape"&&l&&v.length&&z()},children:[a.jsxs("div",{className:"pc-avatar-conversation__presence",children:[a.jsx("div",{className:"pc-avatar-conversation__scene",children:e.avatar}),a.jsx("p",{className:"pc-avatar-conversation__status",role:"status",children:rC[x]})]}),v.length?a.jsxs("aside",{className:"pc-avatar-conversation__findings","aria-label":"Findings",children:[a.jsxs("div",{className:"pc-avatar-conversation__findings-head",children:[a.jsx("h2",{children:"Findings"}),a.jsx("button",{ref:L,type:"button",className:"pc-avatar-conversation__findings-close",onClick:z,children:"Close"})]}),a.jsx("ol",{children:v.map(O=>a.jsx("li",{children:a.jsx(uC,{...q,finding:O,onOpen:S})},O.key))})]}):null,T&&T.kind!=="completion"&&!m?a.jsxs("p",{className:"pc-avatar-conversation__attention","data-kind":T.kind,children:[T.kind==="approval"?"An explicit decision is required. Waiting never grants permission.":T.importance==="essential"?"Your answer is required. I will keep waiting.":"Your input is welcome.",T.kind==="question"&&T.importance==="clarification"?a.jsxs(a.Fragment,{children:[" ",T.deadline&&Number.isFinite(Date.parse(T.deadline))?a.jsxs(a.Fragment,{children:["Answer by ",a.jsx("time",{dateTime:T.deadline,children:new Date(T.deadline).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}),". "]}):null,T.fallback?`Without an answer: ${T.fallback}`:""]}):null]}):null,m?a.jsx("div",{className:"pc-avatar-conversation__request",children:e.interaction}):null,a.jsxs("div",{ref:R,className:"pc-avatar-conversation__live","aria-live":w?"off":"polite",tabIndex:-1,children:[N?a.jsx(Gy,{className:"pc-avatar-conversation__line",open:!!t,onOpen:P,children:a.jsx(Hy,{...q,message:N})},N.id||N.content):null,t?a.jsxs("div",{ref:E,className:"pc-avatar-conversation__line-actions",children:[t.kind==="public_update"?a.jsx("button",{type:"button","aria-pressed":s,onClick:K,children:"Reply to this"}):null,a.jsx("button",{type:"button",onClick:se,children:"Latest"})]}):null]}),g.answers.length?a.jsx("div",{className:"pc-avatar-conversation__answer","aria-live":w?"off":"polite","data-attention":(T==null?void 0:T.kind)==="completion"?"completion":void 0,children:g.answers.map(O=>a.jsx(Xd,{...B,message:O},O.id||O.content))}):null,m?null:e.interaction,a.jsxs("div",{className:"pc-avatar-conversation__actions",children:[v.length?a.jsx("button",{ref:I,type:"button",className:"pc-avatar-conversation__findings-toggle","aria-expanded":l,onClick:()=>l?z():Q(),children:"Findings"}):null,e.voiceControl?a.jsx("span",{onPointerDownCapture:S,onKeyDownCapture:O=>{(O.key==="Enter"||O.key===" ")&&S()},children:e.voiceControl}):null,e.playbackControl]})]})}function Us(e){return(e instanceof Error?e.message:String(e||"Unknown error")).trim()||"Unknown error"}function Ky(e){var Ze,Ye,rt;ci();const t=p.useMemo(()=>e.artifactFetch?XN(e.artifactFetch):void 0,[e.artifactFetch,e.attachmentScope]),n=YN(e.messages,t,e.attachmentScope||"",e.attachmentRun),[s,o]=p.useState(!1),[l,u]=p.useState(!1),[d,f]=p.useState(!1),[m,g]=p.useState(null),[v,w]=p.useState(()=>{var V,he;return((he=(V=e.steer)==null?void 0:V.modes)==null?void 0:he[0])||"guide"}),[x,j]=p.useState(null),[b,k]=p.useState("idle"),$=p.useRef(null),S=p.useRef(!0),N=p.useRef(!1),C=p.useRef(!1),R=p.useRef(!1),E=p.useRef(0),I=p.useRef(0),L=p.useRef(0);p.useEffect(()=>(S.current=!0,()=>{var V;S.current=!1,E.current+=1,I.current+=1,L.current+=1,N.current=!1,C.current=!1,R.current=!1,(V=$.current)==null||V.abort(),$.current=null}),[]);const D=!!e.blockedNotice,P=!!e.disabled||D,K=!!e.busy||s,se=s||!!e.busy&&!e.sendWhileBusy,Q=e.stopState||null,z=(Q==null?void 0:Q.phase)==="stopping",T=e.steer&&typeof e.steer.onSteer=="function"?e.steer:null,q=T?(Ze=T.modes)!=null&&Ze.length?T.modes:["guide"]:[],J=q.includes(v)?v:q[0]||"guide",B=!!T&&!!e.busy,O=Array.isArray(e.attachmentItems)?e.attachmentItems:[];p.useEffect(()=>{j(null)},[!!e.busy]);const Z=typeof e.onFiles=="function",M=p.useRef(null),[W,Y]=p.useState(null),[oe,de]=p.useState(""),me=p.useRef(e.onFiles);me.current=e.onFiles;const ee=p.useRef(P);ee.current=P;const ce=async(V,he)=>{const Je=me.current;if(Je){if(ee.current){g({action:"attach",message:"attachments are unavailable right now."});return}if(he.length)g({action:"attach",message:W2(he)});else if(V.length)g(null);else{g({action:"attach",message:"the drop contained no files."});return}if(V.length){de(`Attaching ${V.length} ${V.length===1?"file":"files"}…`);try{await Je(V)}catch(Oe){S.current&&g({action:"attach",message:Us(Oe)})}}}},ye=p.useRef(ce);ye.current=ce,p.useEffect(()=>{if(!Z||typeof window>"u")return;const V=new G2;let he=0;const Je=U=>!!(M.current&&U instanceof Node&&M.current.contains(U)),Oe=()=>{V.reset(),he&&window.clearInterval(he),he=0,Y(null)},_t=()=>{he||(he=window.setInterval(()=>{V.active(Date.now())||Oe()},250))},Nt=U=>{var we;if(!Po((we=U.dataTransfer)==null?void 0:we.types))return;V.enter(Date.now());const ie=Je(U.target),ue=ag(U.dataTransfer);Y(Ne=>Ne&&Ne.over===ie&&Ne.count===(ue??Ne.count)?Ne:{count:ue??(Ne==null?void 0:Ne.count)??null,over:ie}),_t()},zt=U=>{var ue;if(!Po((ue=U.dataTransfer)==null?void 0:ue.types))return;U.preventDefault(),V.over(Date.now());const ie=Je(U.target);U.dataTransfer&&(U.dataTransfer.dropEffect=ie&&!ee.current?"copy":"none"),Y(we=>we&&we.over===ie?we:{count:(we==null?void 0:we.count)??ag(U.dataTransfer),over:ie}),_t()},An=U=>{var ie;Po((ie=U.dataTransfer)==null?void 0:ie.types)&&(V.leave(Date.now())||Oe())},ht=U=>{var Te;if(!Po((Te=U.dataTransfer)==null?void 0:Te.types))return;const ie=Je(U.target),ue=U.defaultPrevented&&!ie;if(U.preventDefault(),Oe(),ue)return;if(!ie){g({action:"attach",message:"drop files on the conversation to attach them."});return}const{files:we,folders:Ne}=Vy(U.dataTransfer);ye.current(we,Ne)},Tt=U=>{U.key==="Escape"&&V.depth>0&&Oe()};return window.addEventListener("dragenter",Nt),window.addEventListener("dragover",zt),window.addEventListener("dragleave",An),window.addEventListener("drop",ht),window.addEventListener("dragend",Oe),window.addEventListener("blur",Oe),window.addEventListener("keydown",Tt),()=>{window.removeEventListener("dragenter",Nt),window.removeEventListener("dragover",zt),window.removeEventListener("dragleave",An),window.removeEventListener("drop",ht),window.removeEventListener("dragend",Oe),window.removeEventListener("blur",Oe),window.removeEventListener("keydown",Tt),he&&window.clearInterval(he)}},[Z]);const Ce=V=>{if(!Z||P)return;const he=H2(V.clipboardData);he.length&&(V.preventDefault(),ce(he,[]))},ze=W?a.jsxs("div",{className:["pc-workflow-chat__dropzone",W.over?"is-over":"",P?"is-disabled":""].filter(Boolean).join(" "),"aria-hidden":"true",children:[a.jsx("span",{className:"pc-workflow-chat__dropzone-icon",children:a.jsx(be,{name:"paperclip",size:18})}),a.jsxs("span",{className:"pc-workflow-chat__dropzone-text",children:[a.jsx("strong",{children:P?"Attachments are unavailable right now":ig(W.count)}),P?null:a.jsx("span",{children:W.over?"Release to upload to this conversation":"Drop anywhere on the conversation"})]})]}):null,Ve=W?P?"Attachments are unavailable right now":ig(W.count):oe,Ee=async V=>{if(!T)return;const he=J,Je=++E.current;N.current=!0,g(null),j(null),o(!0);try{const Oe=await T.onSteer(V,he);if(!S.current||E.current!==Je)return;if(!(Oe!=null&&Oe.accepted)&&!(Oe!=null&&Oe.duplicate)){g({action:"steer",message:"the gateway did not accept this message (accepted=false)."});return}j({mode:he,...typeof Oe.seq=="number"?{seq:Oe.seq}:{},duplicate:!!Oe.duplicate}),e.onDraftChange("")}catch(Oe){S.current&&E.current===Je&&g({action:"steer",message:Us(Oe)})}finally{S.current&&E.current===Je&&(N.current=!1,o(!1))}},je=async()=>{const V=String(e.draft||"");if(P||N.current||!V.trim())return;if(B)return void Ee(V);if(!e.sendWhileBusy&&e.busy)return;const he=O.length?VN(O):null;if(he){g({action:"send",message:he});return}const Je=++E.current,Oe=new AbortController;$.current=Oe,N.current=!0,g(null),j(null),o(!0);try{await e.onSend(V,{signal:Oe.signal})}catch(_t){S.current&&E.current===Je&&!Oe.signal.aborted&&g({action:"send",message:Us(_t)})}finally{$.current===Oe&&($.current=null),S.current&&E.current===Je&&(N.current=!1,o(!1))}},Ue=async()=>{if(P||C.current||!e.onCancel)return;const V=++I.current;C.current=!0,g(null),u(!0);const Je=$.current||new AbortController;Je.abort(new DOMException("Stopped by the user","AbortError"));try{await e.onCancel(Je.signal)}catch(Oe){S.current&&I.current===V&&g({action:"cancel",message:Us(Oe)})}finally{S.current&&I.current===V&&(C.current=!1,u(!1))}},ne=async()=>{if(P||R.current||!e.onAttach)return;const V=++L.current;R.current=!0,g(null),f(!0);try{await e.onAttach()}catch(he){S.current&&L.current===V&&g({action:"attach",message:Us(he)})}finally{S.current&&L.current===V&&(R.current=!1,f(!1))}},$e=()=>{m&&((m.action==="send"||m.action==="steer")&&je(),m.action==="cancel"&&Ue(),m.action==="attach"&&ne())},Pe=e.toolbar||null,Ge=V=>TN((Array.isArray(e.messages)?e.messages:[]).filter(he=>!he.toolActivity&&!he.live&&String(he.content||"").trim()),V?{heading:V}:void 0),G=async V=>{if(!P){g(null);try{await V()}catch(he){S.current&&g({action:"toolbar",message:Us(he)})}}},fe=async()=>{const V=await fi(Ge());S.current&&(k(V?"copied":"failed"),typeof window<"u"&&window.setTimeout(()=>S.current&&k("idle"),1200))},te=Pe?a.jsxs("div",{className:"pc-workflow-chat__toolbar",role:"toolbar","aria-label":"Conversation actions",children:[Pe.onNewSession?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"new",disabled:P,onClick:()=>void G(Pe.onNewSession),children:[a.jsx(be,{name:"plus",size:14}),a.jsx("span",{children:"New chat"})]}):null,Pe.onClear?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"clear",disabled:P,onClick:()=>void G(Pe.onClear),children:[a.jsx(be,{name:"trash",size:14}),a.jsx("span",{children:"Clear"})]}):null,Pe.copyTranscript?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"copy",onClick:()=>void fe(),children:[a.jsx(be,{name:b==="copied"?"check":"copy",size:14}),a.jsx("span",{children:b==="copied"?"Copied":b==="failed"?"Copy failed":"Copy"})]}):null,Pe.exportTranscript?a.jsxs("button",{type:"button",className:"pc-workflow-chat__icon-button","data-toolbar":"export",onClick:()=>{const V=Pe.exportTranscript;AN({filename:V.filename,text:Ge(V.heading),mime:"text/markdown;charset=utf-8"})},children:[a.jsx(be,{name:"download",size:14}),a.jsx("span",{children:"Export"})]}):null]}):null,pe=e.avatarConversation?"Send":J==="queue"?"Queue":"Steer",Se=x?e.avatarConversation?"Sent. Your message is available to the assistant.":x.mode==="queue"?`Queued for the next turn${typeof x.seq=="number"?` (seq ${x.seq})`:""}.`:`${x.duplicate?"Already queued":"Queued"}${typeof x.seq=="number"?` (seq ${x.seq})`:""}. ${T!=null&&T.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:M,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||te?a.jsxs("header",{className:["pc-workflow-chat__header",te?"pc-workflow-chat__header--toolbar":""].filter(Boolean).join(" "),children:[e.header?a.jsx("div",{className:"pc-workflow-chat__header-main",children:e.header}):null,te]}):null,a.jsx("div",{className:"pc-workflow-chat__transcript",children:a.jsxs(My.Provider,{value:t,children:[n.error&&a.jsxs("p",{role:"status",className:"pc-workflow-chat__error",children:[n.error," ",a.jsx("button",{type:"button",onClick:n.retry,children:"Retry attachment check"})]}),e.avatarConversation?a.jsx(sC,{...e.avatarConversation,messages:n.messages,messageProps:{...e.messageProps,...(Ye=e.messageProps)!=null&&Ye.renderFooter?{renderFooter:V=>e.messageProps.renderFooter(e.messages.find(he=>he===V||he.id&&he.id===V.id)||V)}:{},...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},attended:!!e.draft.trim(),interactionId:e.interaction?`${e.interaction.kind}:${e.interaction.id}`:"",interaction:a.jsxs(a.Fragment,{children:[e.interaction?a.jsx(lg,{interaction:e.interaction,disabled:P,variant:"conversation",onReviewTechnical:e.avatarConversation.onTechnicalView}):null,D?a.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]})}):a.jsx(D2,{messages:n.messages,empty:e.emptyState,autoScroll:!0,messageProps:{...e.messageProps,...(rt=e.messageProps)!=null&&rt.renderFooter?{renderFooter:V=>e.messageProps.renderFooter(e.messages.find(he=>he===V||he.id&&he.id===V.id)||V)}:{},...e.renderMarkdown?{renderMarkdown:e.renderMarkdown}:{}},after:a.jsxs(a.Fragment,{children:[e.interaction?a.jsx(lg,{interaction:e.interaction,disabled:P}):null,D?a.jsx("div",{className:"pc-workflow-chat__blocked",role:"status",children:e.blockedNotice}):null]}),afterKey:`${e.interaction?`${e.interaction.kind}:${e.interaction.id}`:""}:${D?"blocked":""}`})]},e.attachmentScope)}),m?a.jsxs("div",{className:"pc-workflow-chat__error",role:"alert",children:[a.jsxs("span",{children:["Could not"," ",m.action==="send"?"send this message":m.action==="steer"?e.avatarConversation?"send this message":J==="queue"?"queue this message":"steer the run":m.action==="attach"?"attach a file":m.action==="toolbar"?"complete that action":"stop the run",": ",m.message]}),m.action!=="toolbar"?a.jsx("button",{type:"button",onClick:$e,disabled:P,children:"Try again"}):null]}):null,a.jsxs("div",{className:"pc-workflow-chat__composer",children:[a.jsx(ZN,{variant:e.composerVariant,value:e.draft,onChange:V=>{var he,Je;e.avatarConversation&&((Je=(he=e.avatarConversation).onInterruptSpeech)==null||Je.call(he)),e.onDraftChange(V)},onSubmit:()=>void je(),placeholder:e.placeholder||"Send a message",ariaLabel:"Message",disabled:P,busy:B?s:se,sendLabel:B?pe:e.sendLabel,busyLabel:B?e.avatarConversation?"Sending…":J==="queue"?"Queueing…":"Steering…":e.busyLabel,rows:2,onAttach:e.onAttach?()=>void ne():void 0,attachLabel:"Attach file",attachPending:d,leading:e.attachments||O.length?a.jsxs("div",{className:"pc-workflow-chat__attachments",children:[O.length?a.jsx(U2,{items:O,onRemove:e.onRemoveAttachment,onRetry:e.onRetryAttachment,disabled:P}):null,e.attachments]}):null,overlay:ze,onPaste:Z?Ce:void 0,actions:a.jsxs(a.Fragment,{children:[e.composerExtras,B&&q.length>1?a.jsx("span",{className:"pc-workflow-chat__steer-modes",role:"group","aria-label":"While the run is busy",children:q.map(V=>a.jsx("button",{type:"button",className:"pc-workflow-chat__steer-mode","data-steer-mode":V,"aria-pressed":J===V,disabled:P||s,onClick:()=>w(V),children:V==="queue"?"Queue next turn":"Guide this run"},V))}):null]}),trailingActions:e.composerTrailingActions||K&&e.onCancel||Q?a.jsxs(a.Fragment,{children:[e.composerTrailingActions,K&&e.onCancel?a.jsxs("button",{type:"button",className:"pc-workflow-chat__stop",disabled:P||l||z,onClick:()=>void Ue(),children:[a.jsx(be,{name:"x",size:14}),a.jsx("span",{children:l||z?"Stopping…":"Stop"})]}):Q?a.jsx("span",{className:`pc-workflow-chat__stop-state pc-workflow-chat__stop-state--${Q.phase}`,role:"status","aria-live":"polite",children:Q.label}):null]}):void 0}),T?a.jsx("div",{className:"pc-workflow-chat__steer-status",role:"status","aria-live":"polite",children:Se}):null,Z?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]})}var ct=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Xo=e=>Array.isArray(e)?e.map(ct):[],nt=e=>typeof e=="string"?e:"",Da=e=>nt(e.runtime_call_id||e.call_uid),sr=e=>nt(e.call_id||e.id);function hC(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 Jy(e,t){const n=t.record,s=ct(n.effect);if(s.type!=="tool_calls")return[];const o=ct(n.result),l=Xo(ct(s.payload).tool_calls),u=l.length||n.status!=="waiting"?l:Xo(ct(ct(o.wait).details).tool_calls),d=Xo(o.results),f=u.length?u:d,m=[];return f.forEach((g,v)=>{let w=Da(g)?d.filter(E=>Da(E)===Da(g)):[];!w.length&&sr(g)&&u.filter(E=>sr(E)===sr(g)).length===1&&(w=d.filter(E=>sr(E)===sr(g)));const x=u.length?w.length===1?w[0]:u.length===d.length?d[v]:{}:g,j=Da(g)||Da(x)||`${nt(n.idempotency_key)||nt(n.step_id)||t.cursor}:${v}`,b=`${t.runId}:${j}`,k=e.get(b),$=nt(g.name||x.name)||(k==null?void 0:k.name);if(!$)return;const S=n.status==="completed"||n.status==="failed",N=n.status==="failed"||x.success===!1||!!x.error,C=g.arguments??x.arguments??(k==null?void 0:k.arguments),R={...k,id:b,runId:t.runId,name:$,arguments:C,status:S?N?"failed":"completed":n.status==="waiting"?"waiting":"running",...typeof x.success=="boolean"?{success:x.success}:{},...x.output!==void 0||x.result!==void 0?{output:x.output??x.result}:{},...x.error?{error:String(x.error)}:{},...rg(x)?{sandbox:rg(x)}:{},...sr(g)||sr(x)?{callId:sr(g)||sr(x)}:{},...k!=null&&k.approvalWait||hC(n)?{approvalWait:!0}:{},startedAt:(k==null?void 0:k.startedAt)||nt(n.started_at)||void 0,endedAt:S&&nt(n.ended_at)||(k==null?void 0:k.endedAt)};k&&["completed","failed"].includes(k.status)&&!S||(e.set(b,R),m.push(R))}),m}function Ks(e){if(e==null||e===""||typeof e=="boolean")return;const t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}function Gn(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 Yy(e){if(typeof e=="string")try{return ct(JSON.parse(e))}catch{return{}}return ct(e)}function Ws(e,t){if(t===void 0||t==="")return e;const n=e||[];return n.includes(t)||n.push(t),n}function pC(e){return Gn(e,["reasoning_tokens","thinking_tokens"])??Gn(ct(e.completion_tokens_details),["reasoning_tokens"])??Gn(ct(e.output_tokens_details),["reasoning_tokens"])}function mC(e){const t=ct(typeof e=="string"&&e.trim().startsWith("{")?Yy(e):e);return nt(t.error_class)}function gC(e){const t=new Map;for(const n of e){const s=n.record;if(ct(s.effect).type!=="emit_event")continue;const o=ct(s.result);if(nt(o.name)!=="abstract.progress")continue;const l=ct(o.payload);if(nt(l.kind)!=="llm"||!nt(l.step_id))continue;const u=`${nt(l.run_id)||n.runId}:${nt(l.step_id)}`,d=t.get(u)||{},f=Ks(l.ttft_s);f!==void 0&&(d.ttftS=f),d.provider=d.provider||nt(l.provider)||void 0,d.model=d.model||nt(l.model)||void 0,t.set(u,d)}return t}function Hu(e){var b,k,$,S;const t=new Map,n=new Set,s=new Set,o={llmCalls:0,toolCalls:0,changedFiles:[]};let l=1/0,u=-1/0,d=!1,f=0,m=0,g=0;const v=gC(e),w=[],x=new Set;for(const N of e){const C=N.record,R=`${N.runId}:${C.step_id||N.cursor}:${C.status}`;if(n.has(R))continue;n.add(R);for(const ce of[C.started_at,C.ended_at]){const ye=Date.parse(nt(ce));Number.isFinite(ye)&&(l=Math.min(l,ye),u=Math.max(u,ye))}for(const ce of Jy(t,N))ce.status==="waiting"&&x.add(ce.id);if(ct(C.effect).type!=="llm_call"||C.status!=="completed")continue;o.llmCalls+=1;const E=ct(C.result),I=ct(E.output),L=ct(E.usage||E.token_usage||E.tokens||I.usage||I.token_usage||I.tokens),D=Gn(L,["input_tokens","prompt_tokens","prompt","input","in"]),P=Gn(L,["output_tokens","completion_tokens","completion","output","out"]),K=Gn(L,["total_tokens","total"])??(D!==void 0||P!==void 0?(D||0)+(P||0):void 0);K!==void 0&&(D===void 0||P===void 0||D+P!==K)&&(d=!0),D!==void 0&&(o.inputTokens=(o.inputTokens||0)+D),P!==void 0&&(o.outputTokens=(o.outputTokens||0)+P),K!==void 0&&(o.totalTokens=(o.totalTokens||0)+K);const se=Ks(E.gen_time??I.gen_time);se!==void 0&&(o.genTimeMs=(o.genTimeMs||0)+se,o.timedCalls=(o.timedCalls||0)+1);const Q=ct(E.metadata||I.metadata),z=ct(Q.performance),T=Ks(z.prompt_tokens_per_second),q=Ks(z.generation_tokens_per_second),J=ct(Q.prompt_cache),B=Ks(J.cached_tokens),O=Ks(J.fed_tokens);if(T!==void 0||q!==void 0){if(o.measuredSpeedCalls=(o.measuredSpeedCalls||0)+1,T!==void 0&&T>0&&(o.promptTokensPerSecond=(o.promptTokensPerSecond||0)+T,D!==void 0)){const ce=D/T*1e3;o.prefillMs=(o.prefillMs||0)+ce,O!==void 0&&(f+=O,m+=ce)}q!==void 0&&q>0&&(o.generationTokensPerSecond=(o.generationTokensPerSecond||0)+q,P!==void 0&&(o.decodeMs=(o.decodeMs||0)+P/q*1e3))}if(B!==void 0||O!==void 0){o.measuredCacheCalls=(o.measuredCacheCalls||0)+1,o.cachedTokens=(o.cachedTokens||0)+(B||0),o.fedTokens=(o.fedTokens||0)+(O||0);const ce=nt(J.outcome);if(ce){const ye=o.cacheOutcomes||[];ye.includes(ce)||ye.push(ce),o.cacheOutcomes=ye}}const Z=nt(C.step_id)||void 0,M=Z&&v.get(`${N.runId}:${Z}`)||{},W=ct(E.route),Y={runId:N.runId};Z&&(Y.stepId=Z),nt(C.started_at)&&(Y.startedAt=nt(C.started_at));const oe=nt(E.model||I.model)||nt(W.model)||M.model,de=nt(W.provider)||nt(ct(Q._provider_request).provider)||M.provider||nt(E.provider);oe&&(Y.model=oe),de&&(Y.provider=de),oe&&(o.models=Ws(o.models,oe)),de&&(o.providers=Ws(o.providers,de)),(K===void 0||D!==void 0&&P!==void 0&&D+P===K)&&(D!==void 0&&(Y.inputTokens=D),P!==void 0&&(Y.outputTokens=P)),K!==void 0&&(Y.totalTokens=K);const me=pC(L);me!==void 0&&(Y.reasoningTokens=me,o.reasoningTokens=(o.reasoningTokens||0)+me),B!==void 0&&(Y.cachedTokens=B),O!==void 0&&(Y.fedTokens=O),nt(J.outcome)&&(Y.cacheOutcome=nt(J.outcome)),nt(J.backend)&&(Y.cacheBackend=nt(J.backend),o.cacheBackends=Ws(o.cacheBackends,Y.cacheBackend)),se!==void 0&&(Y.genTimeMs=se),T!==void 0&&T>0&&(Y.promptTokensPerSecond=T),q!==void 0&&q>0&&(Y.generationTokensPerSecond=q),M.ttftS!==void 0?(Y.ttftMs=M.ttftS*1e3,Y.promptMs=Y.ttftMs,Y.promptSource="ttft",o.ttftMs=(o.ttftMs||0)+Y.ttftMs,o.ttftCalls=(o.ttftCalls||0)+1):Y.promptTokensPerSecond!==void 0&&D!==void 0&&(Y.promptMs=D/Y.promptTokensPerSecond*1e3,Y.promptSource="rate"),Y.promptMs!==void 0&&(o.promptPhaseMs=(o.promptPhaseMs||0)+Y.promptMs,o.promptPhaseCalls=(o.promptPhaseCalls||0)+1,O!==void 0&&Y.promptMs>0&&(Y.promptNewTokensPerSecond=O/(Y.promptMs/1e3),o.promptPhaseNewTokens=(o.promptPhaseNewTokens||0)+O,g+=Y.promptMs)),Y.ttftMs!==void 0&&se!==void 0&&se>=Y.ttftMs?Y.generationMs=se-Y.ttftMs:Y.generationTokensPerSecond!==void 0&&P!==void 0&&(Y.generationMs=P/Y.generationTokensPerSecond*1e3),Y.generationMs!==void 0&&P!==void 0&&(o.generationPhaseMs=(o.generationPhaseMs||0)+Y.generationMs,o.generationPhaseTokens=(o.generationPhaseTokens||0)+P);const ee=ct(Q.speculation);if(Object.keys(ee).length){const ce={};nt(ee.mode)&&(ce.mode=nt(ee.mode)),typeof ee.used=="boolean"&&(ce.used=ee.used),nt(ee.draft_kind)&&(ce.draftKind=nt(ee.draft_kind));const ye=Gn(ee,["accepted_tokens"]),Ce=Gn(ee,["drafted_tokens"]),ze=Gn(ee,["rounds"]),Ve=Gn(ee,["num_draft_tokens"]);ye!==void 0&&(ce.acceptedTokens=ye),Ce!==void 0&&(ce.draftedTokens=Ce),ye!==void 0&&Ce&&(ce.acceptanceRate=ye/Ce),ze!==void 0&&(ce.rounds=ze),Ve!==void 0&&(ce.draftLength=Ve),Y.speculation=ce;const Ee=o.speculation||(o.speculation={calls:0,used:0});Ee.calls+=1,ce.used&&(Ee.used+=1),ce.mode&&(Ee.modes=Ws(Ee.modes,ce.mode)),ce.draftKind&&(Ee.draftKinds=Ws(Ee.draftKinds,ce.draftKind)),ye!==void 0&&Ce!==void 0&&(Ee.acceptedTokens=(Ee.acceptedTokens||0)+ye,Ee.draftedTokens=(Ee.draftedTokens||0)+Ce),ze!==void 0&&(Ee.rounds=(Ee.rounds||0)+ze),Ve!==void 0&&(Ee.draftLengths=Ws(Ee.draftLengths,Ve))}w.push(Y)}w.length&&(w.every(N=>N.startedAt)&&w.sort((N,C)=>Date.parse(N.startedAt)-Date.parse(C.startedAt)),o.modelCalls=w),g>0&&o.promptPhaseNewTokens!==void 0&&(o.promptPhaseTokensPerSecond=o.promptPhaseNewTokens/(g/1e3)),o.generationPhaseMs&&o.generationPhaseTokens!==void 0&&(o.generationPhaseTokensPerSecond=o.generationPhaseTokens/(o.generationPhaseMs/1e3)),(b=o.speculation)!=null&&b.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 j=new Map;for(const N of t.values()){if(N.status==="waiting"){o.toolsWaiting=(o.toolsWaiting||0)+1;continue}if(N.status==="running"){o.toolsRunning=(o.toolsRunning||0)+1;continue}if(!["completed","failed"].includes(N.status))continue;o.toolCalls+=1;const C=N.status==="failed";C&&(o.toolsFailed=(o.toolsFailed||0)+1);const R=o.toolBreakdown||(o.toolBreakdown={}),E=R[N.name]||(R[N.name]={calls:0,failed:0});if(E.calls+=1,C){E.failed+=1;const K=mC(N.output);K&&((E.errors||(E.errors={}))[K]=(((k=E.errors)==null?void 0:k[K])||0)+1)}const I=Date.parse(nt(N.startedAt)),L=Date.parse(nt(N.endedAt));if(Number.isFinite(I)&&Number.isFinite(L)&&L>=I){const K=`${N.runId}|${N.startedAt}|${N.endedAt}`,se=j.get(K)||{ms:L-I,calls:0,names:new Map,waited:!1};se.calls+=1,se.names.set(N.name,(se.names.get(N.name)||0)+1),x.has(N.id)&&(se.waited=!0),j.set(K,se)}if(N.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(N.name))continue;const D=Yy(N.arguments),P=nt(D.destination||D.destination_path||D.file_path||D.path||D.filename);P&&s.add(P)}for(const N of j.values()){o.toolBatches=(o.toolBatches||0)+1,o.toolTimeMs=(o.toolTimeMs||0)+N.ms,N.waited&&(o.toolTimeIncludesApproval=!0);const C=[...N.names.keys()].sort();(!o.slowestToolBatch||N.ms>o.slowestToolBatch.ms)&&(o.slowestToolBatch={ms:N.ms,calls:N.calls,tools:C});const R=($=o.toolBreakdown)==null?void 0:$[C[0]];if(C.length===1&&R)R.ms=(R.ms||0)+N.ms;else for(const E of C){const I=(S=o.toolBreakdown)==null?void 0:S[E];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 vC(e){const t=ct(ct(e).ledgers);return Object.entries(t).flatMap(([n,s])=>Xo(ct(s).items).map((o,l)=>({runId:n,cursor:Number(o.cursor)||l+1,record:Object.keys(ct(o.record)).length?ct(o.record):o})))}var Gu="llm.delta",Oo="llm.delta_end";function yC(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ss(e){return typeof e=="string"&&e.trim()!==""}function wC(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function _C(e){return"reason"in e}function bC(e,t){const n=yC(e),s=n==null?void 0:n.kind,o=typeof s=="string"&&s?s:n&&"reason"in n?Oo:Gu,l=f=>{throw new Error(`Malformed ${o} event from the gateway: ${f}`)};if(!n)return l("the payload is not an object");s!==void 0&&s!==Gu&&s!==Oo&&l(`unknown kind ${JSON.stringify(s)}`),ss(n.run_id)||l("run_id is missing"),ss(n.call_id)||l("call_id is missing"),wC(n.seq)||l("seq is not a non-negative integer");const u=s?s===Oo:"reason"in n;n.root_run_id!==void 0&&!ss(n.root_run_id)&&l("root_run_id is not a run id"),n.parent_run_id!==void 0&&n.parent_run_id!==null&&!ss(n.parent_run_id)&&l("parent_run_id is neither a run id nor null");const d={run_id:n.run_id,...ss(n.root_run_id)?{root_run_id:n.root_run_id}:{},...n.parent_run_id!==void 0?{parent_run_id:n.parent_run_id}:{},...ss(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:Oo,...d,reason:n.reason,...ss(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:Gu,...d,text:n.text,channel:n.channel,snapshot:n.snapshot})}var xC={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 kC(e){return`This reply is not streamed: ${e?xC[e]||`the gateway reported "${e}"`:"the gateway gave no reason"}. It appears when it is complete.`}var jC=["version","root_run_id","workflow","session_id","status","display_status","cursor","interaction","open_waits","usage","warnings"],ug=["runs","messages","activities","artifacts"],Qy=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Xy(e){return e==null?"None":e===!0?"True":e===!1?"False":String(e)}function SC(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 Xy(e)}function dg(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 kd(e,t){return Xy(e==="runs"?t.run_id:t.id)}function jd(e,t){return[(Array.isArray(t.order)&&t.order.length?t.order:[]).map(SC),kd(e,t)]}function Zy(e,t){const n=Math.min(e[0].length,t[0].length);for(let s=0;s<n;s+=1){const o=dg(e[0][s],t[0][s]);if(o)return o}return e[0].length!==t[0].length?e[0].length-t[0].length:dg(e[1],t[1])}function NC(e,t){return Zy(jd("messages",e),jd("messages",t))}function Sd(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)=>Sd(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=>Qy(t,o)&&Sd(e[o],t[o]))}return!1}function CC(e,t){const n=e&&Object.keys(e).length?{...e}:Object.fromEntries(ug.map(s=>[s,[]]));for(const s of jC)Qy(t,s)&&(n[s]=t[s]);for(const s of ug){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,g)=>[kd(s,m),g]));let f=!1;for(const m of o){const g=kd(s,m),v=d.get(g);v===void 0?(d.set(g,u.length),u.push(m),f=!0):(Sd(u[v].order??null,m.order??null)||(f=!0),u[v]=m)}if(f){const m=u.map(g=>({it:g,key:jd(s,g)}));m.sort((g,v)=>Zy(g.key,v.key)),n[s]=m.map(g=>g.it)}else n[s]=u}return n}var EC=class{constructor(){this.view=null,this.lastEventId=null,this.terminal=!1}adopt(e,t){var n,s,o;return this.view&&fg((n=e.cursor)==null?void 0:n.runs,(s=this.view.cursor)==null?void 0:s.runs)?!1:(this.view=e,this.lastEventId=TC(t)||((o=e.cursor)==null?void 0:o.token)||null,!0)}apply(e){var s,o,l,u;if(e.event==="done")return this.terminal=!0,"done";if(e.event!=="view"&&e.event!=="delta")return"ignored";const t=JSON.parse(e.data);if(e.event==="view")return this.view=t,this.lastEventId=e.id||((s=this.view.cursor)==null?void 0:s.token)||null,"view";if(!this.view)throw new Error("replay view: a delta arrived before any view (reconnect without Last-Event-ID).");const n=e.id||((o=t.cursor)==null?void 0:o.token)||null;return n&&n===this.lastEventId?"duplicate":fg((l=t.cursor)==null?void 0:l.runs,(u=this.view.cursor)==null?void 0:u.runs)?"stale":(this.view=CC(this.view,t),this.lastEventId=n,"delta")}};function TC(e){return String(e||"").trim().replace(/^W\//,"").replace(/^"|"$/g,"")}function fg(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}var Ku=200,Xe=e=>typeof e=="string"?e.trim():typeof e=="number"?String(e):"",vs=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,hg=new Set(["completed","failed","cancelled"]),AC=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 ew(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 $C(e,t){const n=Xe(e.status||t.status).toLowerCase();return n==="completed"?"completed":n==="waiting"?"waiting":n==="running"||n==="started"||n==="pending"?"running":"failed"}function RC(e){const t=vs(e.policy_decision),n=Xe(t==null?void 0:t.decision);if(n!=="auto_approved"&&n!=="denied")return;const s=vs(t==null?void 0:t.set_by),o=Xe(s==null?void 0:s.user_id)||Xe(s==null?void 0:s.client);return{decision:n,...Xe(e.decided_by)?{source:Xe(e.decided_by)}:{},...Xe(e.matched)?{matched:Xe(e.matched)}:{},...typeof(t==null?void 0:t.revision)=="number"?{revision:t.revision}:{},...o?{setBy:o}:{},...Xe(t==null?void 0:t.set_at)?{setAt:Xe(t==null?void 0:t.set_at)}:{}}}function MC(e,t){if(typeof e.error=="string"&&e.error.trim())return e.error.trim();const n=vs(e.error);if(n)return Xe(n.message)||Xe(n.detail)||JSON.stringify(n);if(t==="denied")return"Denied";if(t==="cancelled")return"Cancelled"}function LC(e){return(Array.isArray(e.tool_calls)?e.tool_calls:[]).map((n,s)=>{var f;const o=$C(n,e),l=Xe(n.status||e.status).toLowerCase(),u=RC(n),d=o==="failed"?MC(n,l):void 0;return{id:`${e.id}:${Xe(n.id)||s}`,runId:e.run_id,name:Xe(n.name)||"tool",...n.arguments!==void 0?{arguments:n.arguments}:{},...n.output!==void 0?{output:n.output}:{},status:o,...o==="completed"?{success:!0}:o==="failed"?{success:!1}:{},...d?{error:d}:{},...Xe(e.started_at)?{startedAt:Xe(e.started_at)}:{},...Xe(e.ended_at)?{endedAt:Xe(e.ended_at)}:{},...((f=e.wait)==null?void 0:f.kind)==="tool_approval"&&e.wait.outcome?{approvalWait:!0}:{},...Xe(n.call_id)||Xe(n.id)?{callId:Xe(n.call_id)||Xe(n.id)}:{},...u?{policy:u}:{}}})}function tw(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 IC(e){const t=Xe(e.decision);if(t!=="auto_approved"&&t!=="denied")return null;const n=vs(e.policy),s=vs(n==null?void 0:n.set_by),o=Xe(s==null?void 0:s.user_id)||Xe(s==null?void 0:s.client),l={decision:t,...Xe(e.source)?{source:Xe(e.source)}:{},...typeof(n==null?void 0:n.revision)=="number"?{revision:n.revision}:{},...o?{setBy:o}:{},...Xe(n==null?void 0:n.set_at)?{setAt:Xe(n==null?void 0:n.set_at)}:{}};return{id:`policy:${e.id}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",runId:e.run_id,content:ul(l),ts:Xe(e.started_at)||void 0}}function PC(e){const t=vs(e.usage)||{},n=new Set;let s=0,o=0,l=1/0,u=-1/0;for(const m of e.activities||[]){const g=Date.parse(Xe(m.started_at)),v=Date.parse(Xe(m.ended_at));if(Number.isFinite(g)&&(l=Math.min(l,g)),Number.isFinite(v)&&(u=Math.max(u,v)),m.kind==="llm"&&(o+=1),m.kind==="tool")for(const w of m.tool_calls||[]){if(s+=1,Xe(w.status)!=="completed"||!AC.has(Xe(w.name)))continue;const x=vs(w.arguments)||{},j=Xe(x.destination)||Xe(x.destination_path)||Xe(x.file_path)||Xe(x.path)||Xe(x.filename);j&&n.add(j)}}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 OC(e,t,n){const s=Array.isArray(e.order)&&typeof e.order[0]=="string"&&e.order[0]?e.order[0]:void 0,o=Xe(e.level).toLowerCase(),l=GN(e,n);return{id:e.id,role:e.role,kind:e.kind,content:e.text,runId:e.run_id,...e.source?{source:e.source}:{},...e.kind==="public_update"?{publicUpdate:qy({id:e.public_update_id||e.id,text:e.text,run_id:e.run_id,session_id:e.session_id,iteration:e.iteration,source_call_ids:e.source_call_ids,kind:e.update_kind},e.run_id)||void 0}:{},...s?{ts:s}:{},...e.role==="system"?{title:"Workflow",level:o==="error"?"error":o==="warn"||o==="warning"?"warn":"info"}:{},...Array.isArray(e.artifact_ids)&&e.artifact_ids.length?{artifactIds:[...e.artifact_ids]}:{},artifactRefs:l.refs,artifactReferencesUnresolved:l.unresolved,...t?{statistics:t}:{}}}function pg(e){const t=e.root_run_id,n=PC(e),s=e.interaction?ew(e.interaction):null,o=e.interaction?`${e.interaction.run_id}:${e.interaction.step_id||""}:question`:"",l=(e.messages||[]).find(b=>b.id===`${t}:final`),u=l?l.repeats||l.id:"",d=[],f=new Map((e.artifacts||[]).map(b=>[String(b.id||""),b])),m=new Map;for(const b of e.messages||[])b.repeats&&m.set(b.repeats,[...m.get(b.repeats)||[],...b.artifact_ids||[]]);for(const b of e.messages||[])b.kind==="final"&&b.repeats||b.kind==="question"&&b.id===o||d.push({order:b.order,id:b.id,message:OC({...b,artifact_ids:[...new Set([...b.artifact_ids||[],...m.get(b.id)||[]])]},b.id===u?n:void 0,f)});const g=[],v=[],w=[];for(const b of e.activities||[])if(b.kind==="tool"){const k=LC(b);g.push(...k),k.forEach(($,S)=>d.push({order:[...b.order||[],S],id:`${b.id}:${S}`,message:tw($)}))}else if(b.kind==="tool_policy"){const k=IC(b);k&&d.push({order:b.order,id:b.id,message:k})}else if(b.kind==="llm")for(const k of b.step_ids||[])(hg.has(b.status)?w:v).push(`${b.run_id}:${k}`);d.sort((b,k)=>NC(b,k));const x=new Map((e.runs||[]).map(b=>[b.run_id,Xe(b.status).toLowerCase()])),j=Xe(e.status).toLowerCase()||"unknown";return{messages:d.map(b=>b.message),tools:g,interaction:hg.has(j)?null:s,status:j,displayStatus:Xe(e.display_status),openLlmCalls:v,endedLlmCalls:w,runStatus:x,statistics:n}}var Ju={messages:[],records:[],run:null,interaction:null,status:"idle",displayStatus:"",loading:!1,historyLoading:!1,error:null,connection:"idle",toolApprovalGranted:!1,stop:null};function We(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Me(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function ei(e){return Array.isArray(e)?e:[]}function DC(e){const t=We(e);return!!(t&&(t.code==="revision_conflict"||t.reason_code==="revision_conflict"||t.status===409||t.name==="SessionToolPolicyConflict"))}function un(e){return Me(e==null?void 0:e.status).toLowerCase()||"unknown"}function dt(e){return["completed","failed","cancelled"].includes(e.toLowerCase())}function Cn(e){const t=We(e),n=Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode));return n===401||n===403}function FC(e){const t=We(e);return Number((t==null?void 0:t.status)??(t==null?void 0:t.statusCode))}function Yu(e){const t=n=>{if(Array.isArray(n))return n.map(t);const s=We(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 Nd(e){if(typeof e=="string")return e.trim();const t=We(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 Vs(e){const t=Nd(e);if(t)return t;if(!We(e)&&!Array.isArray(e))return"";try{return JSON.stringify(e,null,2)}catch{return""}}function mg(e){if(!e)return"";for(const s of["prompt","request","task","message","query","input"]){const o=Me(e[s]);if(o)return o}const t=We(e.context);for(const s of["task","message"]){const o=Me(t==null?void 0:t[s]);if(o)return o}const n=ei(t==null?void 0:t.messages);for(let s=n.length-1;s>=0;s-=1){const o=We(n[s]);if(Me(o==null?void 0:o.role).toLowerCase()!=="user")continue;const l=Me(o==null?void 0:o.content);if(l)return l}return""}function nw(e){const t=We(e.result);return We(t==null?void 0:t.wait)}function Qu(e){return e?Me(e.reason)==="subworkflow"||Me(e.wait_key).startsWith("subworkflow:"):!1}function gg(e,t){return!!(e&&e.runId===t.runId&&Me(e.wait.wait_key)===Me(t.wait.wait_key))}function Cd(e){return We(e.effect)||{}}function BC(e,t){return Me(e.run_id)||t}function vg(e){return Me(e.ended_at)||Me(e.started_at)||void 0}function yg(e){const t=new Set,n=m=>{const g=Me(m);g&&t.add(g)},s=We(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=Cd(e),l=We(o.payload);Me(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=nw(e),d=We(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=Me(u==null?void 0:u.wait_key);return f.startsWith("subworkflow:")&&n(f.slice(12)),[...t]}var Xu=new WeakMap,zC=/^(live|live-end|stream-unavailable):/;function UC(e){return!!(e&&typeof e=="object"&&e.name==="ReplayViewUnavailableError")}function wg(e){const t=String(e||""),n=t.indexOf("~");return n<0?"":t.slice(n+1)}var Fa=()=>({sessionId:"",transport:null,order:[],created:new Map,turns:new Map}),WC=class{constructor(e,t={}){this.transport=e,this.options=t,this.snapshot={...Ju},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=Fa();const n=t.liveRenderIntervalMs??60;if(typeof n!="number"||!Number.isFinite(n)||n<0)throw new Error(`liveRenderIntervalMs must be a non-negative number of milliseconds, got ${JSON.stringify(t.liveRenderIntervalMs)}`);this.liveRenderIntervalMs=n,this.sessionToolPolicy=t.sessionToolPolicy||null,this.sessionToolPolicy||(this.sessionPolicyUnavailableReason=Me(t.sessionToolPolicyUnavailableReason)),this.snapshot=this.withSessionPolicy({...Ju})}sessionPolicyMode(){var e;return((e=this.sessionToolPolicy)==null?void 0:e.supported)===!0?"gateway":!this.sessionToolPolicy&&this.sessionPolicyUnavailableReason?"unavailable":"local-fallback"}sessionPolicyStatus(){const e=this.sessionPolicyMode();return{mode:e,...e==="unavailable"?{reason:this.sessionPolicyUnavailableReason}:{},clamped:this.sessionPolicyClamped,policy:this.sessionPolicyState}}setSessionToolPolicyClient(e,t={}){const n=e?"":Me(t.reason);if(e===this.sessionToolPolicy&&n===this.sessionPolicyUnavailableReason)return;const s=!!(e&&this.sessionToolPolicy&&e.sessionId===this.sessionToolPolicy.sessionId);this.sessionToolPolicy=e,this.sessionPolicyUnavailableReason=n,s||(this.sessionPolicyState=null,this.sessionPolicyClamped=[]),this.set({...this.snapshot})}gatewayPolicy(){const e=this.sessionToolPolicy;if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);if(!e||e.supported!==!0)throw new Error("This gateway cannot store chat tool policies (session_tool_policy is not supported).");return e}adoptSessionPolicy(e){var t,n;this.sessionPolicyState=e,this.sessionPolicyClamped=Array.isArray(e==null?void 0:e.clamped)?e.clamped.filter(s=>s&&typeof s=="object"):[],this.set({...this.snapshot}),(n=(t=this.options).onSessionPolicy)==null||n.call(t,e,this.sessionPolicyClamped)}async loadSessionPolicy(){const e=await this.gatewayPolicy().get();return this.adoptSessionPolicy(e),e}requireRootSession(e){var n,s;const t=Me((n=this.snapshot.run)==null?void 0:n.session_id)||Me((s=this.runStates.get(this.rootRunId))==null?void 0:s.session_id);if(!t)throw new Error("This chat's session is not known yet: the policy is written to the root run's session.");if(t!==e.sessionId)throw new Error(`The tool policy client is bound to session ${e.sessionId}, but this chat's root run belongs to session ${t}: the policy is written to the root run's session.`)}async currentRevision(e){var s;if(typeof((s=this.sessionPolicyState)==null?void 0:s.revision)=="number")return this.sessionPolicyState.revision;const t=await this.loadSessionPolicy();if(typeof(t==null?void 0:t.revision)=="number")return t.revision;const n=e.revision;return typeof n=="number"?n:void 0}async policyWriteError(e){if(DC(e))return await this.loadSessionPolicy().catch(()=>null),new Error("Someone changed this chat's policy; re-read it before deciding again (it was refreshed).");const t=e instanceof Error?e.message:String(e);return new Error(`This chat's policy was not changed: ${t}`)}requireTarget(e){const t=this.requireInteraction();if(dt(this.snapshot.status))throw new Error("This run has already ended.");if(t.runId!==e.runId||Me(t.wait.wait_key)!==e.waitKey||e.stepId!==void 0&&t.stepId!==e.stepId)throw new Error("This approval request has changed. Review the current request before deciding.");if(!this.isToolApproval(t))throw new Error("This is not a tool approval request.");return t}async writeThenAnswer(e,t,n,s=[]){this.requireTarget(e);const o=this.gatewayPolicy();this.requireRootSession(o);const l=[...new Set(s.map(f=>Me(f)).filter(Boolean))];let u={};if(t.deny){const f=await this.currentRevision(o);if(typeof f!="number")throw new Error("This chat's policy was not changed: the gateway did not return a policy revision to guard the deny with.");u={if_revision:f}}let d;try{d=await o.merge({...t,...l.length?{ask:l}:{},...u,client:t.client||"panel-chat"})}catch(f){throw await this.policyWriteError(f)}this.sessionToolPolicy===o&&this.adoptSessionPolicy(d);try{await this.approve(n,e)}catch(f){const m=f instanceof Error?f.message:String(f);throw new Error(`This chat's tool policy was saved, but this request was not answered: ${m} The policy does not answer requests that were already waiting.`)}return d}async approveAllForSession(e,t={}){const n=this.sessionPolicyMode();if(n==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason} Allow once still works.`);return n!=="gateway"?(await this.allowAllToolsForRun(e),null):this.writeThenAnswer(e,{approve:{all:!0,...typeof t.maxRiskRank=="number"?{max_risk_rank:t.maxRiskRank}:{}}},!0,t.ask)}approveKindForSession(e,t,n={}){return this.writeThenAnswer(e,{approve:{kinds:[t]}},!0,n.ask)}denyKindForSession(e,t,n={}){return this.writeThenAnswer(e,{deny:{kinds:[t]}},!1,n.ask)}denyToolForSession(e,t,n={}){return this.writeThenAnswer(e,{deny:{tools:[t]}},!1,n.ask)}async resetSessionPolicy(){if(this.sessionPolicyMode()==="unavailable")throw new Error(`${this.sessionPolicyUnavailableReason}`);if(this.sessionPolicyMode()!=="gateway"){this.revokeToolApproval();return}const e=this.gatewayPolicy();this.requireRootSession(e);const t=await this.currentRevision(e);if(typeof t!="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 e.reset(t)}catch(n){throw await this.policyWriteError(n)}this.adoptSessionPolicy(null)}withSessionPolicy(e){const t=this.sessionPolicyMode(),{sessionPolicyReason:n,...s}=e;return{...s,sessionPolicyMode:t,...t==="unavailable"?{sessionPolicyReason:this.sessionPolicyUnavailableReason}:{},sessionPolicy:this.sessionPolicyState,sessionPolicyClamped:this.sessionPolicyClamped}}withSource(e){const{source:t,sourceReason:n,...s}=e;return this.source?{...s,source:this.source.source,...this.source.reason?{sourceReason:this.source.reason}:{}}:s}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}getSnapshot(){return this.snapshot}reset(){var e;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,(e=this.controller)==null||e.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({...Ju})}dispose(){this.reset(),this.viewTurnCache=Fa(),this.subscribers.clear()}async load(e){const t=Me(e);if(this.reset(),!t)return;const n=++this.generation,s=new AbortController;this.controller=s,this.rootRunId=t,this.set({...this.snapshot,loading:!0,historyLoading:!0,status:"loading",error:null,connection:"connecting"});try{if(await this.loadView(t,n,s.signal)||!this.live(n))return;this.set({...this.snapshot});const[o,l]=await Promise.all([this.transport.getRun(t,s.signal),this.transport.getHistory(t,s.signal)]);if(!this.live(n))return;const u=We(o),d=We(u==null?void 0:u.waiting),f=un(u);if(await this.ingestHistory(l,t,n),!this.live(n))return;if(this.set({...this.snapshot,run:u,status:f,loading:!1,historyLoading:!1,...d&&!dt(f)?{interaction:this.interactionWith({runId:t,wait:d})}:{}}),u&&this.updateRunState(t,u),d)for(const m of yg({result:{wait:d}}))m!==t&&this.catchUpAndWatch(m,n);await this.catchUpAndWatch(t,n),this.pollRootLifecycle(t,n)}catch(o){!s.signal.aborted&&this.live(n)&&this.fail(o)}}async sendCommand(e,t={}){var m,g;e==="cancel"&&(this.toolApprovalStopped=!0,this.revokeToolApproval(),this.stopRequested=!0,this.recomputeStop());const n=Me(t.wait_key),s=e==="resume"?n?this.interactionRunId()||this.rootRunId:this.rootRunId:e==="emit_event"?this.interactionRunId()||this.rootRunId:this.rootRunId;if(!s)throw new Error("No workflow run is loaded");const o=e==="resume"&&n&&((m=this.snapshot.interaction)==null?void 0:m.stepId)||"",l=`${s}\0${e}\0${o}\0${Yu(t)}`;let u=this.commandIds.get(l);u||(u=this.newCommandId(),this.commandIds.set(l,u));const d=this.generation,f=(g=this.controller)==null?void 0:g.signal;try{const v=await this.transport.submitCommand({command_id:u,run_id:s,type:e,payload:t,...this.options.clientId?{client_id:this.options.clientId}:{}},f);if(!this.live(d))return v;const w=We(v);if(w&&w.accepted===!1)throw e==="cancel"&&(this.stopRequested=!1,this.recomputeStop()),new Error(Me(w.detail)||"Gateway did not accept the command");return this.commandIds.delete(l),this.viewFold?["pause","resume","cancel"].includes(e)&&this.refreshViewRun(d):s===this.rootRunId&&["pause","resume","cancel"].includes(e)&&this.refreshRunState(s,d),v}catch(v){throw this.live(d)&&this.fail(v,!1),v}}resume(e,t){const n=this.requireInteraction();if(t&&(n.runId!==t.runId||Me(n.wait.wait_key)!==t.waitKey||t.stepId!==void 0&&n.stepId!==t.stepId))throw new Error("This question has changed. Review the current question before answering.");return this.sendCommand("resume",{wait_key:Me(n.wait.wait_key),payload:{response:e}})}answerEvent(e,t){const n=this.requireInteraction();if(t&&(n.runId!==t.runId||Me(n.wait.wait_key)!==t.waitKey||t.stepId!==void 0&&n.stepId!==t.stepId))throw new Error("This wait has changed. Review the current one before answering.");if(!n.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:Me(n.wait.wait_key),payload:e})}approve(e,t){const n=this.requireInteraction();if(dt(this.snapshot.status))throw new Error("This run has already ended.");if(t&&(n.runId!==t.runId||Me(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(e&&this.toolApprovalPolicy&&!this.toolCallsMatch(n,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 s=this.generation;return this.sendCommand("resume",{wait_key:Me(n.wait.wait_key),payload:{approved:!!e}}).then(o=>{if(!this.live(s))return o;const l=this.occurrenceKey(n);return this.approvedWaits.add(l),e&&this.isToolApproval(n)&&!this.grantedToolWaits.has(l)&&(this.grantedToolWaits.add(l),this.set({...this.snapshot})),o})}async approveWithPolicyChange(e,t){const n=this.generation,s=this.approvalEpoch;if(!this.isToolApproval(this.requireInteraction()))throw new Error("This is not a tool approval request.");await this.approve(!0,e),!(!this.live(n)||s!==this.approvalEpoch||this.toolApprovalStopped||dt(this.snapshot.status))&&t()}async allowAllToolsForRun(e){const t=this.generation,n=this.approvalEpoch,s=this.requireInteraction();if(!this.isToolApproval(s))throw new Error("This is not a tool approval request.");await this.approve(!0,e),!(!this.live(t)||n!==this.approvalEpoch||dt(this.snapshot.status))&&(this.approvedWaits.add(`${e.runId}:${e.waitKey}${s.stepId?`:${s.stepId}`:""}`),this.set({...this.snapshot,autoApproveTools:!0}))}revokeToolApproval(){this.approvalEpoch+=1,this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1})}setToolApprovalPolicy(e){Yu(e)!==Yu(this.toolApprovalPolicy)&&(this.approvalEpoch+=1,this.toolApprovalSuspended=!1,this.toolApprovalPolicy=e?{enabledTools:[...e.enabledTools],autoApproveTools:[...e.autoApproveTools]}:null,this.set({...this.snapshot}))}occurrenceKey(e){return`${e.runId}:${Me(e.wait.wait_key)}${e.stepId?`:${e.stepId}`:""}`}interactionWith(e){const t=this.snapshot.interaction;return t&&Qu(e.wait)&&!Qu(t.wait)?t:t&&gg(t,e)&&e.stepId===void 0&&t.stepId!==void 0?{...e,stepId:t.stepId}:e}adoptDurableWait(e,t){const n=We(t.waiting);if(!n||un(t)!=="waiting"||Qu(n)||dt(this.snapshot.status)||this.resolvedWaits.has(`${e}:${Me(n.wait_key)}`))return;const s=this.interactionWith({runId:e,wait:n}),o=this.snapshot.interaction;o&&gg(o,s)&&o.stepId===s.stepId||this.set({...this.snapshot,interaction:s})}coveredByStandingPermission(e,t){var n;return e.loading||this.toolApprovalStopped||this.toolApprovalSuspended||!this.toolApprovalPolicy&&!e.autoApproveTools||dt(e.status)||((n=e.run)==null?void 0:n.paused)===!0||e.status==="paused"||!t||!this.isToolApproval(t)||this.toolApprovalPolicy&&(!this.toolCallsMatch(t,this.toolApprovalPolicy.enabledTools)||!this.toolCallsMatch(t,this.toolApprovalPolicy.autoApproveTools))?!1:!!Me(t.wait.wait_key)}present(e){const t=e.interaction,n=t?this.occurrenceKey(t):"",s=!!(t&&this.isToolApproval(t)&&(this.grantedToolWaits.has(n)||!this.approvedWaits.has(n)&&this.coveredByStandingPermission({...e,loading:!1},t)));if(!s&&!this.snapshot.toolApprovalGranted&&!e.toolApprovalGranted)return e.toolApprovalGranted===!1?e:{...e,toolApprovalGranted:!1};let o=!1;const l=e.messages.map(u=>{var m;const d=u.toolActivity;if(!d||((m=this.toolActivities.get(d.id))==null?void 0:m.status)!=="waiting")return u;const f=s&&d.runId===(t==null?void 0:t.runId)?"running":"waiting";return d.status===f?u:(o=!0,this.toolMessage({...d,status:f}))});return{...e,toolApprovalGranted:s,...o?{messages:l}:{}}}toolCallsMatch(e,t){var s;const n=ei((s=We(e.wait.details))==null?void 0:s.tool_calls);return n.length>0&&n.every(o=>{var u;const l=Me((u=We(o))==null?void 0:u.name);return!!l&&t.includes(l)})}isToolApproval(e){const t=We(e.wait.details);return(t==null?void 0:t.mode)==="approval_required"||(t==null?void 0:t.kind)==="tool_approval"}autoApproveCurrentWait(){const e=this.snapshot.interaction;if(!this.coveredByStandingPermission(this.snapshot,e))return;const t={runId:e.runId,waitKey:Me(e.wait.wait_key),stepId:e.stepId},n=this.occurrenceKey(e);if(this.approvedWaits.has(n))return;this.approvedWaits.add(n),this.grantedToolWaits.add(n);const s=this.generation,o=this.approvalEpoch;this.approve(!0,t).catch(l=>{if(this.live(s)){if(this.grantedToolWaits.delete(n),o!==this.approvalEpoch){this.set({...this.snapshot});return}this.toolApprovalSuspended=!0,this.set({...this.snapshot,autoApproveTools:!1}),this.fail(l,!1)}})}emitEvent(e){return this.sendCommand("emit_event",e)}cancel(){return this.sendCommand("cancel",{})}requireInteraction(){if(!this.snapshot.interaction)throw new Error("This workflow is not waiting for input");if(!Me(this.snapshot.interaction.wait.wait_key))throw new Error("The workflow wait has no wait_key");return this.snapshot.interaction}interactionRunId(){var e;return((e=this.snapshot.interaction)==null?void 0:e.runId)||""}live(e){var t;return e===this.generation&&!((t=this.controller)!=null&&t.signal.aborted)}set(e){this.snapshot=this.present(this.withSource(this.withSessionPolicy(e)));for(const t of this.subscribers)t();this.autoApproveCurrentWait()}async loadView(e,t,n){const s=this.transport.replayView,o=m=>(this.live(t)&&(this.source={source:"ledger_fold",reason:m}),!1);if(!s)return o("this app's transport does not read the replay view");if(s.advertised===!1)return o("the gateway does not advertise the replay view");const l=Xu.get(s);if(typeof l=="string")return o(l);let u,d;try{[u,d]=await Promise.all([s.getView(e,{signal:n}),this.transport.getRun(e,n)])}catch(m){if(!UC(m))throw m;const g=m instanceof Error?m.message:"the gateway does not serve the replay view";return Xu.set(s,g),o(g)}if(Xu.set(s,!0),!this.live(t))return!0;if(u.notModified)throw new Error("The gateway answered 304 to a replay view read without If-None-Match.");this.source={source:"replay_view"},this.viewRun=We(d);const f=new EC;return f.adopt(u.view,u.etag),this.viewFold=f,this.viewDigest=wg(f.lastEventId),this.adoptView(),this.followView(e,t),this.followLiveReplies(e,t),await this.loadEarlierTurns(e,Me(u.view.session_id),t,n),this.live(t)&&this.set({...this.snapshot,historyLoading:!1}),!0}async loadEarlierTurns(e,t,n,s){var k;const o=this.transport.replayView;if(!o||!t)return;const l=($,S)=>({id:$,role:"system",level:"warn",title:"History",content:S});if(!o.listSessionTurns){this.viewEarlier={messages:[l(`history:${t}: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 u=this.viewTurnCache.sessionId===t&&this.viewTurnCache.transport===o?this.viewTurnCache:{...Fa(),sessionId:t,transport:o};this.viewTurnCache=u;const d=($,S=new Map,N=[])=>{const C=$.map(R=>u.turns.get(R)||S.get(R)).filter(R=>!!R);this.viewEarlier={messages:[...N,...C.flatMap(R=>R.messages)],tools:C.flatMap(R=>R.tools)}},f=u.order.indexOf(e);let m,g=!1;if(f>=0&&u.order.slice(0,f).every($=>u.turns.has($)))m=u.order.slice(0,f);else{const $=Me((k=this.viewRun)==null?void 0:k.created_at),S=$?u.order.filter(R=>u.turns.has(R)&&u.created.has(R)&&u.created.get(R)<$):[];S.length&&(d(S),this.adoptView());let N;try{N=await o.listSessionTurns(e,{signal:s})}catch(R){if(!this.live(n))return;if(Cn(R))throw this.viewTurnCache=Fa(),R;d(S,new Map,[l(`history:${t}:unlisted`,`Earlier turns of this conversation could not be listed: ${R instanceof Error?R.message:String(R)}`)]),this.adoptView();return}if(!this.live(n))return;g=N.length>Ku,g&&(N=N.slice(N.length-Ku));for(const R of N)R.created_at&&u.created.set(R.run_id,R.created_at);u.order=N.map(R=>R.run_id);const C=u.order.indexOf(e);m=C>=0?u.order.slice(0,C):u.order.filter(R=>R!==e)}const v=new Map,w=m.filter($=>!u.turns.has($));let x=0;const j=async()=>{for(;this.live(n);){const $=w[x++];if(!$)return;try{const S=await o.getView($,{signal:s});if(S.notModified||!S.view)throw new Error("the gateway answered without a view");const N=pg(S.view);dt(N.status)?u.turns.set($,{messages:N.messages,tools:N.tools}):v.set($,{messages:[...N.messages,l(`history:${$}:open`,`This earlier turn is still ${N.status||"running"}; open it to follow or answer it.`)],tools:N.tools})}catch(S){if(!this.live(n))return;if(Cn(S))throw this.viewTurnCache=Fa(),S;v.set($,{messages:[l(`history:${$}:unavailable`,`An earlier turn could not be restored (${$.slice(0,8)}): ${S instanceof Error?S.message:String(S)}`)],tools:[]})}}};if(await Promise.all(Array.from({length:Math.min(4,w.length)},()=>j())),!this.live(n))return;const b=g?[l(`history:${t}:limit`,`Only the last ${Ku} turns of this conversation are shown.`)]:[];d(m,v,b),this.adoptView()}adoptView(){var f,m,g;const e=(f=this.viewFold)==null?void 0:f.view;if(!e)return;const t=pg(e);dt(t.status)&&e.session_id&&this.viewTurnCache.sessionId===e.session_id&&this.viewTurnCache.turns.set(e.root_run_id,{messages:t.messages,tools:t.tools}),this.toolActivities=new Map([...this.viewEarlier.tools,...t.tools].map(v=>[v.id,v]));for(const v of t.endedLlmCalls)this.closedLiveCalls.has(v)||this.closeLiveReply(v);for(const v of e.messages||[])v.role!=="assistant"||this.viewAssistantIds.has(v.id)||(this.viewAssistantIds.add(v.id),this.closeLiveRepliesOfRun(v.run_id));for(const[v,w]of t.runStatus)!dt(w)||this.viewTerminalRuns.has(v)||(this.viewTerminalRuns.add(v),this.endLiveRepliesOfRun(v,w));this.openLlmSteps=new Set(t.openLlmCalls);const n=dt(t.status),s=this.snapshot.messages.filter(v=>zC.test(String(v.id||""))),o={...this.viewRun||{},run_id:e.root_run_id,status:t.status,...e.session_id?{session_id:e.session_id}:{}};let l=t.interaction;const u=this.snapshot.interaction;if(l&&u&&u.runId===l.runId&&Me(u.wait.wait_key)===Me(l.wait.wait_key)&&u.stepId!==l.stepId&&(u.stepId===void 0||l.stepId===void 0)){const{stepId:v,...w}=l;l=u.stepId===void 0?w:{...w,stepId:u.stepId}}this.set({...this.snapshot,view:e,run:o,status:t.status,displayStatus:n?"":t.displayStatus,messages:[...this.viewEarlier.messages,...t.messages,...s],interaction:l,loading:!1,...n?{autoApproveTools:!1}:{}}),(this.stopRequested||this.forcedStop)&&this.recomputeStop();const d=wg((m=this.viewFold)==null?void 0:m.lastEventId);d!==this.viewDigest&&Object.keys(((g=e.cursor)==null?void 0:g.runs)||{}).length<=32&&(this.viewDigest=d,this.refreshViewRun(this.generation))}async followView(e,t){const n=this.transport.replayView,s=this.viewFold;if(!n||!s)return;let o=0;for(;this.live(t)&&this.viewFold===s&&!s.terminal;){this.set({...this.snapshot,connection:o?"reconnecting":"connecting"});try{if(await n.streamView(e,{lastEventId:s.lastEventId,signal:this.controller.signal,onOpen:()=>{this.live(t)&&this.set({...this.snapshot,connection:"connected",error:null})},onFrame:l=>{if(!this.live(t)||this.viewFold!==s)return;o=0;const u=s.apply(l);(u==="view"||u==="delta")&&this.adoptView()}}),!this.live(t))return;if(s.terminal)break;o+=1}catch(l){if(!this.live(t))return;if(o+=1,this.fail(l,!1),Cn(l)){this.set({...this.snapshot,connection:"disconnected"});return}}if(o>=5||!this.live(t))break;await this.waitForRetry(Math.min(2e3,150*2**(o-1)))}if(this.viewStreamEnded=!0,!(!this.live(t)||this.viewFold!==s)){if(s.terminal||dt(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(e,t){var s,o,l;let n=0;try{for(;this.live(t)&&this.viewFold&&!this.viewStreamEnded&&!dt(this.snapshot.status);){const u=Number((l=(o=(s=this.viewFold.view)==null?void 0:s.cursor)==null?void 0:o.runs)==null?void 0:l[e])||0;this.dropLiveRepliesVia(e);try{if(await this.transport.streamLedger(e,u,()=>{},this.controller.signal,void 0,d=>{this.live(t)&&(n=0,this.ingestDelta(e,d))}),!this.live(t))return;n+=1}catch(d){if(!this.live(t))return;if(n+=1,Cn(d)){this.fail(d);return}}if(n>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(n-1)))}}finally{this.live(t)&&this.closeLiveRepliesVia(e)}}async refreshView(e){var o;const t=this.transport.replayView,n=this.viewFold;if(!t||!n)return;const s=await t.getView(this.rootRunId,{ifNoneMatch:n.lastEventId?`"${n.lastEventId}"`:null,signal:(o=this.controller)==null?void 0:o.signal});!this.live(e)||this.viewFold!==n||s.notModified||n.adopt(s.view,s.etag)&&this.adoptView()}async refreshViewRun(e){var t;try{const n=We(await this.transport.getRun(this.rootRunId,(t=this.controller)==null?void 0:t.signal));if(!n||!this.live(e)||!this.viewFold)return;this.viewRun=n,this.adoptView()}catch(n){this.live(e)&&this.fail(n,!1)}}async catchUpAndWatch(e,t){var n;if(!(!this.live(t)||this.watchedRuns.has(e))){this.watchedRuns.add(e);try{if(e!==this.rootRunId)try{const s=We(await this.transport.getRun(e,(n=this.controller)==null?void 0:n.signal));if(!this.live(t))return;s&&this.updateRunState(e,s)}catch(s){if(!this.live(t))return;if(Cn(s))throw s;this.fail(s,!1)}if(await this.catchUp(e,t),!this.live(t)||dt(un(this.runStates.get(e)||null)))return;this.childCatchUpAttempts.delete(e),this.watch(e,t)}catch(s){if(!this.live(t))return;if(this.watchedRuns.delete(e),e===this.rootRunId)throw s;if(Cn(s)){this.fail(s);return}const o=(this.childCatchUpAttempts.get(e)||0)+1;if(this.childCatchUpAttempts.set(e,o),this.fail(s,!1),o>=5)return;await this.waitForRetry(Math.min(2e3,150*2**(o-1))),this.live(t)&&this.catchUpAndWatch(e,t)}}}async catchUp(e,t){var n;for(let s=0;s<100&&this.live(t);s+=1){const o=this.cursors.get(e)||0,l=await this.transport.getLedger(e,o,(n=this.controller)==null?void 0:n.signal);if(!this.live(t))return;const u=We(l),d=Array.isArray(l)?l:ei(u==null?void 0:u.items);for(const m of d)this.ingestItem(e,m);const f=Number(u==null?void 0:u.next_after);if(!d.length||!Number.isFinite(f)||f<=o)break;this.cursors.set(e,f)}}async watch(e,t){try{await this.followStream(e,t)}finally{this.live(t)&&this.closeLiveRepliesVia(e)}}async followStream(e,t){var s;let n=0;for(;this.live(t)&&!dt(un(this.runStates.get(e)||null));){const o=this.cursors.get(e)||0;this.set({...this.snapshot,connection:n?"reconnecting":"connecting"});try{let l=!1;const u=()=>{!this.live(t)||l||(l=!0,this.set({...this.snapshot,connection:"connected",error:null}))};if(this.dropLiveRepliesVia(e),await this.transport.streamLedger(e,o,f=>{this.live(t)&&(u(),this.ingestItem(e,f))},this.controller.signal,u,f=>{this.live(t)&&(u(),this.ingestDelta(e,f))}),!this.live(t)||(await this.catchUp(e,t),!this.live(t)))return;const d=We(await this.transport.getRun(e,(s=this.controller)==null?void 0:s.signal));if(!this.live(t))return;d&&this.updateRunState(e,d),n+=1}catch(l){if(!this.live(t))return;if(n+=1,this.fail(l,!1),Cn(l)){this.set({...this.snapshot,connection:"disconnected"});return}}if(n>=5||!this.live(t))break;await this.waitForRetry(Math.min(2e3,150*2**(n-1)))}if(this.live(t)){if(dt(un(this.runStates.get(e)||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(e,t,n){const s=We(e);if(!s)return;const o=We(s.session),l=ei(o==null?void 0:o.turns).map(We).filter(f=>!!f);if(await this.hydrateHistoricalSessionRuns(l,t,n),!this.live(n))return;for(const f of l){const m=Me(f==null?void 0:f.run_id)||t;this.ingestSessionTurn(f,t,m!==t&&this.historicalRuns.get(m)||null)}const u=`turn:${t}:user`;if(!this.seenMessages.has(u)){const f=mg(We(s.input_data));f&&this.addMessage({id:u,role:"user",content:f})}const d=We(s.ledgers);if(d)for(const[f,m]of Object.entries(d)){const g=We(m);for(const v of ei(g==null?void 0:g.items))this.ingestItem(f,v)}}ingestSessionTurn(e,t,n){if(!e)return;const s=Me(e.run_id)||t,o=We(e.input_data)||We(e.input)||{},l=Me(e.prompt)||mg(o);l&&this.addMessage({id:`turn:${s}:user`,role:"user",content:l,ts:Me(e.created_at)||void 0});const u=this.historicalRunFailures.get(s);if(u){const g=Me(e.answer)||Nd(e.output),v=u.missing?"is unavailable because the run no longer exists":"could not be restored",w=g?` Saved reply (not verified as the final result): ${g}`:"";this.addMessage({id:`history:${s}:unavailable`,role:"system",level:"warn",title:"History",content:`The final output for an earlier turn ${v}.${w}`});return}const f=(n&&dt(un(n))?Vs(n.output):"")||(n?Me(e.answer)||Nd(e.output):""),m=this.historicalEvidence.get(s);for(const g of(m==null?void 0:m.tools)||[])this.upsertTool(g);f&&this.addRunAssistantMessage(s,{id:`final:${s}`,role:"assistant",content:f,runId:s,statistics:m==null?void 0:m.statistics,ts:Me(e.updated_at)||void 0})}async hydrateHistoricalSessionRuns(e,t,n){const s=[...new Set(e.map(d=>Me(d.run_id)).filter(d=>d&&d!==t&&!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)))];if(!s.length||!this.live(n))return;let o=0,l=!1;const u=async()=>{var d,f,m;for(;!l&&this.live(n);){const g=s[o++];if(!g)return;try{const v=We(await this.transport.getRun(g,(d=this.controller)==null?void 0:d.signal));if(!this.live(n))return;if(v){this.historicalRuns.set(g,v);try{const w=await this.transport.getHistory(g,(f=this.controller)==null?void 0:f.signal);if(!this.live(n))return;this.historicalEvidence.set(g,Hu(vC(w)))}catch(w){if(!this.live(n))return;if(Cn(w))throw w;this.fail(new Error(`Earlier turn activity could not be restored: ${w instanceof Error?w.message:String(w)}`),!1)}}else this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:!1,detail:"gateway returned an invalid historical run snapshot"})}catch(v){if(!this.live(n))return;const w=FC(v)===404;this.historicalRuns.set(g,null),this.historicalRunFailures.set(g,{missing:w,detail:v instanceof Error?v.message:Me((m=We(v))==null?void 0:m.detail)||"request failed"}),Cn(v)&&(l=!0,this.fail(v))}}};if(await Promise.all(Array.from({length:Math.min(4,s.length)},()=>u())),l&&this.live(n))for(const d of s)!this.historicalRuns.has(d)&&!this.historicalRunFailures.has(d)&&(this.historicalRuns.set(d,null),this.historicalRunFailures.set(d,{missing:!1,detail:"authorization expired before this historical run could be restored"}))}ingestItem(e,t){const n=We(t),s=We(n==null?void 0:n.record)||n;if(!s)return;const o=BC(s,e),l=Number(n==null?void 0:n.cursor),u=Number.isFinite(l)&&l>0?l:(this.cursors.get(o)||0)+1,d=`${o}:${u}`;if(!this.seenRecords.has(d)){if(this.seenRecords.add(d),this.cursors.set(o,Math.max(this.cursors.get(o)||0,u)),this.set({...this.snapshot,records:[...this.snapshot.records,{cursor:u,record:s,runId:o}]}),this.foldRecord(o,s,d),this.snapshot.messages.some(f=>f.id===`final:${this.rootRunId}`)){const f=Hu(this.snapshot.records).statistics;this.set({...this.snapshot,messages:this.snapshot.messages.map(m=>m.id===`final:${this.rootRunId}`?{...m,statistics:f}:m)})}for(const f of yg(s))f!==o&&this.catchUpAndWatch(f,this.generation)}}foldRecord(e,t,n){var m,g,v;const s=Cd(t),o=Me(s.type).toLowerCase(),l=We(t.result),u=Me(t.status).toLowerCase(),d=vg(t);if(this.foldStopEvidence(e,t,o,u),["llm_call","tool_calls"].includes(o)&&["started","running"].includes(u)){const w=Date.parse(d||"");(!Number.isFinite(w)||w>=this.displayStatusAt)&&(Number.isFinite(w)&&(this.displayStatusAt=w),this.snapshot.displayStatus&&this.set({...this.snapshot,displayStatus:""}))}if(o==="answer_user"&&u==="completed"){const w=Vs(l)||Vs(We(s.payload));w&&this.addRunAssistantMessage(e,{id:`answer:${e}:${n}`,role:"assistant",kind:"answer",runId:e,content:w,ts:d})}if(o==="emit_event"&&u==="completed"){const w=We(s.payload)||{},x=We(l),j=Me(w.name)||Me(x==null?void 0:x.name),b=w.payload!==void 0?w.payload:x==null?void 0:x.payload;if(j==="user_guidance"){const k=We(b),$=k==null?void 0:k.seq;k&&k.status==="accepted"&&Number.isInteger($)&&Number($)>0&&k.run_id===e&&k.id===`${e}:guidance:${$}`&&t.node_id==="__host_user_guidance__"&&t.idempotency_key===`system:user_guidance:${$}`&&typeof k.text=="string"&&k.text.trim()&&this.addMessage({id:k.id,role:"user",kind:"guidance",source:"user_guidance",runId:e,content:k.text,ts:d})}if(j==="public_update"){const k=qy(b,e);k&&this.addMessage({id:`public_update:${e}:${k.id}`,role:"assistant",kind:"public_update",source:"public_update",runId:e,content:k.text,publicUpdate:k,ts:d})}if(["abstract.message","abstractcode.message"].includes(j)){const k=Vs(b);if(k){const $=Me((m=We(b))==null?void 0:m.level).toLowerCase(),S=$==="error"?"error":["warn","warning"].includes($)?"warn":"info";this.addMessage({id:`event:${e}:${n}`,role:"system",title:"Workflow",content:k,level:S,ts:d})}}if(["abstract.status","abstractcode.status"].includes(j)){const k=We(b),$=k?k.status??k.text??k.value:b,S=Date.parse(d||"");!dt(this.snapshot.status)&&typeof $=="string"&&(!Number.isFinite(S)||S>=this.displayStatusAt)&&(Number.isFinite(S)&&(this.displayStatusAt=S),this.set({...this.snapshot,displayStatus:$.trim()}))}if(j==="abstract.tool_policy_decision"){const k=p2(We(b));if(k){this.addMessage({id:`policy:${e}:${n}`,role:"system",kind:"tool_policy_decision",title:"Tool policy",content:ul(k.provenance),ts:d});for(const $ of k.calls){const S={...k.provenance,...$.matched?{matched:$.matched}:{}};this.toolPolicyByCall.set(`${e}:${$.callId}`,S);for(const N of this.toolActivities.values())N.runId===e&&N.callId===$.callId&&this.upsertTool(N)}}}if(["abstract.tool_execution","abstractcode.tool_execution","abstract.tool_result","abstractcode.tool_result"].includes(j)){const k=Vs(b);k&&this.addMessage({id:`event:${e}:${n}`,role:"system",title:"Tool activity",content:k,ts:d})}}const f=nw(t);if(u==="waiting"&&f&&!dt(this.snapshot.status)&&!dt(un(this.runStates.get(e)||null))&&(this.resolvedWaits.delete(`${e}:${Me(f.wait_key)}`),this.set({...this.snapshot,interaction:this.interactionWith({runId:e,wait:f,...Me(t.step_id)?{stepId:Me(t.step_id)}:{}})})),o==="tool_calls")for(const w of Jy(this.toolActivities,{runId:e,cursor:this.cursors.get(e)||0,record:t}))this.upsertTool(w);if(o==="resume"&&(l==null?void 0:l.resumed)===!0){const w=Me((g=We(s.payload))==null?void 0:g.wait_key);w&&this.resolvedWaits.add(`${e}:${w}`),((v=this.snapshot.interaction)==null?void 0:v.runId)===e&&(this.set({...this.snapshot,interaction:null}),this.refreshRunState(e,this.generation))}}foldStopEvidence(e,t,n,s){let o=!1;if(n==="llm_call"){const l=Me(t.step_id);if(l){const u=`${e}:${l}`;s==="started"?(this.openLlmSteps.add(u),o=!0):["completed","failed","cancelled","waiting"].includes(s)&&(o=this.openLlmSteps.delete(u)||o),["completed","failed","cancelled"].includes(s)&&this.closeLiveReply(u)}}if(n==="emit_event"&&s==="completed"){const l=We(Cd(t).payload)||{},u=We(t.result),d=Me(l.name)||Me(u==null?void 0:u.name),f=We(l.payload!==void 0?l.payload:u==null?void 0:u.payload);d==="abstract.status"&&Me(f==null?void 0:f.killed_by)==="kill_switch"&&(this.forcedStop=f,o=!0)}o&&this.recomputeStop()}recomputeStop(){let e=null;this.forcedStop?e={phase:"forced",label:Me(this.forcedStop.text)||"Stop forced: inference killed",record:this.forcedStop}:this.stopRequested&&(e=this.snapshot.status==="cancelled"&&this.openLlmSteps.size===0?{phase:"stopped",label:"Stopped"}:{phase:"stopping",label:"Stopping…"});const t=this.snapshot.stop||null;((t==null?void 0:t.phase)!==(e==null?void 0:e.phase)||(t==null?void 0:t.label)!==(e==null?void 0:e.label))&&this.set({...this.snapshot,stop:e}),(e==null?void 0:e.phase)==="stopping"&&this.snapshot.status==="cancelled"&&this.followStop(this.generation)}async followStop(e){var t;if(!this.stopFollowing){this.stopFollowing=!0;try{let n=500,s=null;for(;this.live(e)&&((t=this.snapshot.stop)==null?void 0:t.phase)==="stopping";){if(await this.waitForRetry(n),!this.live(e))return;const o=this.viewFold?[]:[this.rootRunId,...[...this.watchedRuns].filter(u=>u!==this.rootRunId)];let l=!1;if(this.viewFold)try{await this.refreshView(e)}catch(u){l=!0,this.live(e)&&(this.fail(u,!1),s=this.snapshot.error)}for(const u of o)try{await this.catchUp(u,e)}catch(d){l=!0,this.live(e)&&(this.fail(d,!1),s=this.snapshot.error)}!l&&s&&this.snapshot.error===s&&(this.set({...this.snapshot,error:null}),s=null),n=Math.min(5e3,n*2)}}finally{this.generation===e&&(this.stopFollowing=!1)}}}addMessage(e){const t=Me(e.id)||`${e.role}:${e.content}:${e.ts||""}`;this.seenMessages.has(t)||(this.seenMessages.add(t),this.set({...this.snapshot,messages:[...this.snapshot.messages,{...e,id:t}]}))}toolMessage(e){const t=e.callId?this.toolPolicyByCall.get(`${e.runId}:${e.callId}`):void 0;return tw(t?{...e,policy:t}:e)}upsertTool(e){const t=this.toolMessage(e),n=this.snapshot.messages.findIndex(o=>o.id===t.id);if(n<0){this.addMessage(t);return}const s=[...this.snapshot.messages];s[n]=t,this.set({...this.snapshot,messages:s})}addRunAssistantMessage(e,t){this.closeLiveRepliesOfRun(e);const n=`answer:${e}:`,s=`final:${e}`;this.snapshot.messages.some(o=>o.role==="assistant"&&o.content===t.content&&(o.id===s||String(o.id||"").startsWith(n)))||this.addMessage(t)}ingestDelta(e,t){let n;try{n=bC(t)}catch(d){this.fail(d,!1);return}const s=`${n.run_id}:${n.call_id}`;if(_C(n)){if(n.reason==="unavailable"){this.noteStreamUnavailable(n);return}if(n.reason==="cancelled"&&n.detail==="reinvoked"){this.closeLiveReply(s,"restarted");return}this.closeLiveReply(s,n.reason==="completed"?void 0:n.reason);return}if(this.closedLiveCalls.has(s)||this.runEnded(n.run_id)||this.runEnded(this.rootRunId))return;const o=this.liveReplies.get(s)||{runId:n.run_id,callId:n.call_id,nodeId:n.node_id||"",via:e,text:"",reasoning:"",seq:{content:-1,reasoning:-1}},l=n.channel==="reasoning"?"reasoning":"text",u=o.seq[n.channel];if(n.snapshot){if(n.seq<u)return;o[l]=n.text}else{if(n.seq<=u)return;o[l]+=n.text}o.seq[n.channel]=n.seq,o.via=e,this.liveReplies.set(s,o),this.liveDirty.add(s),this.scheduleLiveRender()}runEnded(e){var n,s;const t=(n=this.viewFold)==null?void 0:n.view;return t?dt(String(((s=t.runs.find(o=>o.run_id===e))==null?void 0:s.status)||""))||e===this.rootRunId&&dt(String(t.status||"")):dt(un(this.runStates.get(e)||null))}scheduleLiveRender(){if(this.liveRenderTimer)return;const e=this.lastLiveRender+this.liveRenderIntervalMs-Date.now();if(e<=0){this.renderLiveReplies();return}this.liveRenderTimer=setTimeout(()=>{this.liveRenderTimer=null,this.renderLiveReplies()},e)}renderLiveReplies(){if(this.lastLiveRender=Date.now(),!this.liveDirty.size)return;const e=[...this.snapshot.messages];for(const t of this.liveDirty){const n=this.liveReplies.get(t);if(!n)continue;const s=this.liveMessage(n),o=e.findIndex(l=>l.id===s.id);o<0?e.push(s):e[o]=s,this.shownLiveCalls.add(t)}this.liveDirty.clear(),this.set({...this.snapshot,messages:e})}liveMessage(e){const t=e.runId!==this.rootRunId;return{id:`live:${e.runId}:${e.callId}`,role:"assistant",content:e.text,runId:e.runId,live:{callId:e.callId,reasoning:e.reasoning,...t?{caption:`sub-agent · ${e.nodeId||e.runId}`}:{}}}}closeLiveReply(e,t){this.closedLiveCalls.add(e);const n=this.liveReplies.get(e);if(!n){t==="restarted"&&this.shownLiveCalls.has(e)&&this.addMessage(this.restartNote(e));return}this.liveReplies.delete(e),this.liveDirty.delete(e);const s=`live:${n.runId}:${n.callId}`,o=this.snapshot.messages.findIndex(u=>u.id===s);if(o<0)return;const l=[...this.snapshot.messages];if(t==="restarted"){const u=this.restartNote(e);this.seenMessages.add(String(u.id)),l[o]=u}else if(t){const u=`live-end:${n.runId}:${n.callId}`;this.seenMessages.add(u),l[o]={id:u,role:"system",level:"warn",title:"Reply",runId:n.runId,content:t==="failed"?"The reply stopped because the model call failed.":"The reply stopped because the model call was cancelled."}}else l.splice(o,1);this.set({...this.snapshot,messages:l})}restartNote(e){const t=e.slice(0,e.indexOf(":"));return{id:`live-end:${e}`,role:"system",level:"info",title:"Reply",runId:t,content:"Reply restarted: the model call was interrupted and is running again."}}noteStreamUnavailable(e){const t=`${e.run_id}:${e.call_id}`;this.closeLiveReply(t),this.addMessage({id:`stream-unavailable:${e.run_id}:${e.detail||"unknown"}`,role:"system",level:"info",title:"Reply",runId:e.run_id,content:kC(e.detail)})}closeLiveRepliesOfRun(e){for(const t of[...this.liveReplies.values()])t.runId===e&&this.closeLiveReply(`${t.runId}:${t.callId}`)}closeLiveRepliesVia(e,t){for(const n of[...this.liveReplies.values()])(n.via===e||n.runId===e)&&this.closeLiveReply(`${n.runId}:${n.callId}`,t)}endLiveRepliesOfRun(e,t){const n=t==="failed"||t==="cancelled"?t:void 0;if(e===this.rootRunId){for(const s of[...this.liveReplies.values()])this.closeLiveReply(`${s.runId}:${s.callId}`,n);this.closedLiveCalls.clear(),this.shownLiveCalls.clear();return}this.closeLiveRepliesVia(e,n);for(const s of[...this.closedLiveCalls])s.startsWith(`${e}:`)&&this.closedLiveCalls.delete(s);for(const s of[...this.shownLiveCalls])s.startsWith(`${e}:`)&&this.shownLiveCalls.delete(s)}dropLiveRepliesVia(e){const t=new Set;for(const[n,s]of this.liveReplies)s.via===e&&(this.liveReplies.delete(n),this.liveDirty.delete(n),t.add(`live:${s.runId}:${s.callId}`));t.size&&this.set({...this.snapshot,messages:this.snapshot.messages.filter(n=>!t.has(String(n.id)))})}fail(e,t=!0){var n,s,o;Cn(e)&&(this.approvalEpoch+=1,this.toolApprovalStopped=!0,this.toolApprovalSuspended=!0,(s=(n=this.options).onAuthError)==null||s.call(n,e)),this.set({...this.snapshot,error:e instanceof Error?e.message:Me((o=We(e))==null?void 0:o.detail)||String(e),...Cn(e)?{autoApproveTools:!1}:{},...t?{connection:"disconnected"}:{}})}newCommandId(){const e=globalThis.crypto;if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(e&&typeof e.getRandomValues=="function"){const t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=Array.from(t,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)}`}return`workflow-${Date.now()}-${Math.random().toString(36).slice(2)}`}updateRunState(e,t){var o;if(this.runStates.set(e,t),dt(un(t))&&this.endLiveRepliesOfRun(e,un(t)),e!==this.rootRunId){dt(un(t))&&((o=this.snapshot.interaction)==null?void 0:o.runId)===e?this.set({...this.snapshot,interaction:null}):this.adoptDurableWait(e,t);return}const n=un(t),s=dt(n);if(s){const l=Vs(t.output);l&&this.upsertFinal(e,l,vg(t))}this.set({...this.snapshot,run:t,status:n,...s?{interaction:null,autoApproveTools:!1,displayStatus:""}:{}}),s||this.adoptDurableWait(e,t),(this.stopRequested||this.forcedStop)&&this.recomputeStop()}upsertFinal(e,t,n){this.closeLiveRepliesOfRun(e);const s=`final:${e}`;this.seenMessages.add(s);const o={id:s,role:"assistant",kind:"final",content:t,ts:n,runId:e,statistics:Hu(this.snapshot.records).statistics},l=this.snapshot.messages.findIndex(d=>d.id===s||String(d.id||"").startsWith(`answer:${e}:`)&&d.content===t);if(l<0){this.set({...this.snapshot,messages:[...this.snapshot.messages,o]});return}const u=[...this.snapshot.messages];u[l]=o,this.set({...this.snapshot,messages:u})}async refreshRunState(e,t){var n;try{const s=We(await this.transport.getRun(e,(n=this.controller)==null?void 0:n.signal));s&&this.live(t)&&this.updateRunState(e,s)}catch(s){this.live(t)&&this.fail(s,!1)}}async pollRootLifecycle(e,t){var n;for(;this.live(t)&&this.rootRunId===e&&!dt(un(this.runStates.get(e)||null));){if(await this.waitForRetry(2e3),!this.live(t)||this.rootRunId!==e||dt(un(this.runStates.get(e)||null)))return;try{const s=We(await this.transport.getRun(e,(n=this.controller)==null?void 0:n.signal));s&&this.live(t)&&this.rootRunId===e&&this.updateRunState(e,s)}catch(s){if(!this.live(t))return;if(Cn(s)){this.fail(s);return}this.fail(s,!1)}}}waitForRetry(e){var s;const t=(s=this.controller)==null?void 0:s.signal;if(!t||t.aborted)return Promise.resolve();const n=t;return new Promise(o=>{const l=setTimeout(d,e),u=()=>{clearTimeout(l),d()};function d(){n.removeEventListener("abort",u),o()}n.addEventListener("abort",u,{once:!0})})}};function VC(e){const t=p.useMemo(()=>new WC(e.transport,{onAuthError:e.onAuthError,clientId:e.clientId,...e.liveRenderIntervalMs!==void 0?{liveRenderIntervalMs:e.liveRenderIntervalMs}:{}}),[e.transport,e.onAuthError,e.clientId,e.authScopeKey,e.liveRenderIntervalMs]),n=p.useSyncExternalStore(o=>t.subscribe(o),()=>t.getSnapshot(),()=>t.getSnapshot()),s=String(e.runId||"").trim();return p.useEffect(()=>{t.setToolApprovalPolicy(e.enabled===!1?{enabledTools:[],autoApproveTools:[]}:e.toolApprovalPolicy??null)},[t,e.toolApprovalPolicy,e.enabled]),p.useEffect(()=>{if(e.enabled===!1||!s){t.reset();return}return t.load(s),()=>t.reset()},[t,s,e.enabled]),{controller:t,snapshot:n}}function Zu(e){try{const t=typeof localStorage>"u"?null:localStorage.getItem(`abstract.conversation:${e}`);if(!t)return{mode:"chat",preferences:bd,error:null};const n=JSON.parse(t),s=Object.fromEntries(["approval","question","completion"].map(o=>{var l,u,d,f,m,g;return[o,{visual:((u=(l=n.preferences)==null?void 0:l[o])==null?void 0:u.visual)!==!1,audio:((f=(d=n.preferences)==null?void 0:d[o])==null?void 0:f.audio)!==!1,haptic:((g=(m=n.preferences)==null?void 0:m[o])==null?void 0:g.haptic)===!0}]}));return{mode:n.mode==="avatar"?"avatar":"chat",preferences:s,error:null}}catch(t){return{mode:"chat",preferences:bd,error:`Conversation preferences could not be loaded: ${String(t)}`}}}function qC(e){const[t,n]=p.useState(()=>({scope:e,...Zu(e)})),s=t.scope===e?t:{scope:e,...Zu(e)},o=p.useRef(s);o.current=s,p.useEffect(()=>{t.scope!==e&&n({scope:e,...Zu(e)})},[e,t.scope]);const l=u=>{const d={...o.current,...u,scope:e,error:null};try{typeof localStorage<"u"&&localStorage.setItem(`abstract.conversation:${e}`,JSON.stringify({mode:d.mode,preferences:d.preferences}))}catch(f){d.error=`Conversation preferences could not be saved: ${String(f)}`}o.current=d,n(d)};return{mode:s.mode,setMode:u=>l({mode:u}),preferences:s.preferences,setPreferences:u=>l({preferences:u}),error:s.error}}async function HC(e){if(!e.channels.audio)return;if(typeof window>"u"||!window.AudioContext)throw new Error("Audio cues are unavailable in this browser.");const t=new window.AudioContext;try{if(await t.resume(),t.state!=="running")throw new Error("Enable audio with a browser interaction before playing conversation cues.");const n=t.createOscillator(),s=t.createGain();n.frequency.value=e.kind==="approval"?440:e.kind==="question"?600:800,s.gain.setValueAtTime(.035,t.currentTime),s.gain.exponentialRampToValueAtTime(.001,t.currentTime+.18),n.connect(s),s.connect(t.destination),n.start(),n.stop(t.currentTime+.2),await new Promise(o=>{n.onended=()=>o()})}finally{await t.close()}}function as(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Gt(e){return typeof e=="string"?e.trim():e==null?"":typeof e=="number"||typeof e=="boolean"?String(e):""}function _g(e){return["session","workflow","run","global"].includes(e)?e:null}function Mr(e){return{scope:Gt(e==null?void 0:e.scope).toLowerCase(),name:Gt(e==null?void 0:e.name)||Gt(e==null?void 0:e.event_name),scopeId:Gt(e==null?void 0:e.scope_id)||Gt(e==null?void 0:e.scopeId),sessionId:Gt(e==null?void 0:e.session_id)||Gt(e==null?void 0:e.sessionId),workflowId:Gt(e==null?void 0:e.workflow_id)||Gt(e==null?void 0:e.workflowId),runId:Gt(e==null?void 0:e.run_id)||Gt(e==null?void 0:e.runId)}}function GC(e,t){const n=e.wait,s=Gt(n.wait_key),o=[Mr(n),Mr(as(n.details))];for(const l of t){if(l.runId!==e.runId)continue;const u=l.record,d=as(u.result),f=as(d==null?void 0:d.wait),m=as(u.effect),g=as(m==null?void 0:m.payload);Gt(f==null?void 0:f.wait_key)!==s&&Gt(g==null?void 0:g.wait_key)!==s||o.push(Mr(u),Mr(g),Mr(as(g==null?void 0:g.details)),Mr(f),Mr(as(f==null?void 0:f.details)))}return o}function ed(e,t){return t.scopeId?t.scopeId:e==="session"?t.sessionId:e==="workflow"?t.workflowId:e==="run"?t.runId:"global"}function rw(e,t,n){return{scope:e,scopeId:t,name:n,...e==="session"?{sessionId:t}:{},...e==="workflow"?{workflowId:t}:{},...e==="run"?{runId:t}:{}}}function KC(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?rw(t,n,o):null}function JC(e,t=[],n){if(!e)return{target:null,error:"No event wait is available."};const s=Gt(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=_g(o[1]);if(!l)return{target:null,error:"The event wait uses an unsupported scope."};const u=GC(e,Array.isArray(t)?t:[]),d=new Map;for(const w of u){const x=_g(w.scope);if(!x||!w.name)continue;if(x!==l)return{target:null,error:"Event metadata conflicts with the canonical wait scope."};const j=`evt:${x}:`,b=`:${w.name}`;if(!s.startsWith(j)||!s.endsWith(b)||s.length<=j.length+b.length)return{target:null,error:"Event metadata does not exactly match the canonical wait key."};const k=s.slice(j.length,-b.length),$=ed(x,w);if($&&$!==k)return{target:null,error:"Event metadata conflicts with the canonical wait target."};const S=rw(x,k,w.name);d.set(`${S.scope}\0${S.scopeId}\0${S.name}`,S)}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 w of u){const x=ed(l,w);x&&f.add(x)}if(Gt(n==null?void 0:n.run_id)===e.runId){const w=Mr(n||null),x=ed(l,w);x&&f.add(x)}const g=[...f].map(w=>KC(s,l,w)).filter(w=>!!w),v=new Map(g.map(w=>[`${w.scope}\0${w.scopeId}\0${w.name}`,w]));return v.size===1?{target:[...v.values()][0]}:v.size>1?{target:null,error:"The event key is ambiguous for the available scope metadata."}:{target:null,error:"The gateway did not provide enough canonical event routing metadata."}}var td=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,Dt=e=>typeof e=="string"?e.trim():"";function YC(e,t,n){var x;const s=e.map(j=>{let b=td(j.arguments);if(!b&&typeof j.arguments=="string")try{b=td(JSON.parse(j.arguments))}catch{}const k=b||{},$=Dt(k.file_path)||Dt(k.path);switch(j.name){case"fetch_url":case"skim_url":{const S=k.method===void 0?"GET":Dt(k.method).toUpperCase(),N=new Set(["url","method","timeout","include_binary_preview","render_js","keep_links","include_full_content"]),C=Object.keys(k).some(R=>!N.has(R)&&k[R]!==void 0&&k[R]!==null);return!["GET","HEAD"].includes(S)||C?{kind:"unknown",label:"A website request that needs a closer look",target:Dt(k.url)}:{kind:"page",label:"Read a webpage",target:Dt(k.url)}}case"web_search":case"skim_websearch":return{kind:"search",label:"Search the web",target:Dt(k.query)};case"read_file":return{kind:"read",label:"Read a file",target:$};case"write_file":return{kind:"write",label:"Write to a file — this can replace its contents",target:$};case"edit_file":return{kind:"edit",label:"Change a file’s contents",target:$};case"list_files":return{kind:"folder",label:"Look through a folder",target:Dt(k.directory_path)||$||"The current workspace"};default:return{kind:"unknown",label:"An action that needs a closer look",target:""}}}),o=(x=s[0])==null?void 0:x.kind,l=s.length>0&&s.every(j=>j.kind===o),u={page:["May I read this webpage?",`May I read these ${s.length} webpages?`],search:["May I search the web?","May I make these web searches?"],read:["May I read this file?",`May I read these ${s.length} files?`],write:["May I write to this file?",`May I write to these ${s.length} files?`],edit:["May I change this file?",`May I change these ${s.length} files?`],folder:["May I look through this folder?","May I look through these folders?"]},d=!s.length||s.some(j=>j.kind==="unknown"||!j.target),f=l&&u[o]?u[o][s.length===1?0:1]:"May I do these things?",m=td(t),g=e.map(j=>Dt(j.call_id)||Dt(j.id)),v=m&&Array.isArray(m.call_ids)?m.call_ids:[],w=m&&Dt(n)&&Dt(m.run_id)===n&&Dt(m.update_id)&&typeof m.iteration=="number"&&Number.isInteger(m.iteration)&&m.iteration>0&&g.length>0&&g.every(Boolean)&&new Set(g).size===g.length&&v.length===g.length&&new Set(v).size===v.length&&v.every(j=>typeof j=="string"&&g.includes(j))&&Dt(m.text)&&Dt(m.text).length<=600&&!/```\s*diary\b|<\s*diary\b|<\s*think\b/i.test(Dt(m.text))?{text:Dt(m.text),updateId:Dt(m.update_id)}:void 0;return{question:f,actions:s,reviewRequired:d,...w?{explanation:w}:{}}}function QC(e){const t=e;return!!(t&&typeof t=="object"&&typeof t.run_id=="string"&&typeof t.wait_key=="string"&&!("wait"in t))}function XC(e,t,n={}){var x;if(!e)return null;const s=QC(e)?ew(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 j=Array.isArray(u.tool_calls)?u.tool_calls:[],b={runId:s.runId,waitKey:String(o.wait_key||""),stepId:s.stepId},k=[...new Set(j.map(P=>String((P==null?void 0:P.name)||"tool")))],$=n.onPermissionsAll,S=n.onAllowForSession,N=String(n.approveAllScope||"").trim(),C=((x=n.remember)==null?void 0:x.call(n,k))||void 0,R=Gs,E=S?{approveForSessionLabel:R.allowForChat,approveForSessionDescription:"Allow for this chat approves this batch and the enabled tools for the rest of this chat. Unchecked tools stay unavailable; questions still need your answer.",onApproveForSession:async()=>{let P;await t.approveWithPolicyChange(b,()=>{P=S()}),P&&await P.catch(K=>{throw new Error(`This batch was allowed, but "Allow for this chat" could not be turned on: ${K instanceof Error?K.message:String(K)}`)})}}:{};let I=E,L=[];const D=n.sessionPolicy;if(D){const P=t.approveAllForSession,K=t.approveKindForSession,se=t.denyToolForSession,Q=t.denyKindForSession,z=t.sessionPolicyStatus;if(typeof P!="function"||typeof K!="function"||typeof se!="function"||typeof Q!="function"||typeof z!="function")throw new Error("presentInteraction: sessionPolicy needs a WorkflowSessionController (approveAllForSession, approveKindForSession, denyToolForSession, denyKindForSession, sessionPolicyStatus).");const T=z.call(t),q=D.ask?[...D.ask]:void 0,J=(M,W)=>{var oe;const Y=String(((oe=M==null?void 0:M.scope)==null?void 0:oe[W])||"").trim();return Y?`Applies: ${Y}`:R.noScopeNote},B=M=>({outcomeNote:[sg(M==null?void 0:M.clamped),J(M,"approve")].filter(Boolean).join(" ")}),O=M=>({outcomeNote:`${R.denyForChatNote} ${J(M,"deny")}`}),Z=sg(T.clamped);if(T.mode==="unavailable")I={scopeNote:R.unavailablePolicyNote(T.reason||"")};else if(T.mode==="gateway"){const M=[...new Set(j.map(de=>{var me;return String((de==null?void 0:de.toolset)||"").trim()||String(((me=D.toolsetOf)==null?void 0:me.call(D,String((de==null?void 0:de.name)||"")))||"").trim()}).filter(Boolean))],W=(q||[]).map(de=>String(de).trim()).filter(Boolean),Y=W.length?`Tools set to Ask keep asking: ${W.join(", ")}.`:"Nothing is set to Ask, so tools that reach destinations the model picks (fetch_url, browser_probe, send_email) are included.",oe=T.policy;L=oe?k.filter(de=>Object.prototype.hasOwnProperty.call(oe.deny||{},de)):[],I={approveForSessionLabel:R.allowForChat,approveForSessionDescription:M.length?`Each of ${(()=>{const de=[`“${R.allowForChat}” (every tool)`,...M.map(me=>`“${R.allowKindForChat(me)}” (that toolset only)`)];return`${de.slice(0,-1).join(", ")} or ${de[de.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. ${Y} Tools the gateway does not authorize stay uncovered.`:`“${R.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. ${Y} 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. ${Y}`,onApproveForSession:async()=>B(await P.call(t,b,{...D.maxRiskRank!==void 0?{maxRiskRank:D.maxRiskRank}:{},...q?{ask:q}:{}})),approveKinds:M.map(de=>({kind:de,label:R.allowKindForChat(de),onApprove:async()=>B(await K.call(t,b,de,q?{ask:q}:{}))})),denyOptions:[...k.map(de=>({key:`tool:${de}`,label:R.denyToolForChat(de),onDeny:async()=>O(await se.call(t,b,de,q?{ask:q}:{}))})),...M.map(de=>({key:`kind:${de}`,label:R.denyKindForChat(de),onDeny:async()=>O(await Q.call(t,b,de,q?{ask:q}:{}))}))],...L.length?{deniedNote:`Denied by this chat's policy: ${L.join(", ")}. The gateway refuses ${L.length===1?"it":"them"} even if allowed once.`}:{},...oe?{policySummary:`This chat's policy: ${Object.keys(oe.approve||{}).length} tools allowed without asking, ${Object.keys(oe.deny||{}).length} denied. ${J(oe,"approve")}`}:{},...Z?{notCovered:Z}:{}}}else I=S?{...E,scopeNote:R.localChatPolicyNote}:{approveForSessionLabel:R.allowForRun,onApproveForSession:async()=>{await P.call(t,b,{})},scopeNote:R.localRunPolicyNote}}return{id:l,kind:"tool-approval",title:`${j.length||"Requested"} ${j.length===1?"action needs":"actions need"} permission`,toolName:k.join(", ")||"the requested tools",publicRequest:YC(j,u.public_action,s.runId),description:"Review the targets below. Allow once approves this batch only.",detail:a.jsxs("div",{className:"pc-approval-summary",children:[a.jsx(gk,{calls:j.map(P=>{const K=fl(P==null?void 0:P.arguments);return{name:String((P==null?void 0:P.name)||"tool"),arguments:K&&typeof K=="object"&&!Array.isArray(K)?K:null}}),label:"Tool calls to approve",heading:"The assistant wants to use these tools:"}),a.jsxs("details",{children:[a.jsx("summary",{children:"Review full tool arguments (JSON)"}),a.jsx(si,{value:j.length?j:u})]})]}),approveLabel:Gs.allowOnce,denyLabel:Gs.deny,approveAllLabel:$?Gs.allowAll:void 0,approveAllDescription:$?`Sets permissions: all${N?` ${N}`:""}, including future turns. Unchecked tools stay unavailable; explicit Ask overrides and Gateway restrictions remain enforced. Questions still need your answer.`:void 0,...$?{broadScopeSummary:`“${Gs.allowAll}” changes your tool permissions for future turns too.`}:{},...I,...n.approveAllDisabledReason?{disabledReason:n.approveAllDisabledReason}:{},...C?{remember:C}:{},...n.onDefer?{onDefer:n.onDefer}:{},onApproveAll:$?async()=>{await t.approveWithPolicyChange(b,()=>{$()})}:void 0,onApprove:async()=>(await t.approve(!0,b),L.length?{outcomeNote:`The gateway refuses ${L.join(", ")}: denied by this chat's policy.`}:void 0),onDeny:async()=>{await t.approve(!1,b)}}}const d={runId:s.runId,waitKey:String(o.wait_key||""),stepId:s.stepId},f=u.question&&typeof u.question=="object"&&u.question.purpose==="conversation"?u.question:null,m=(f==null?void 0:f.importance)==="essential",g=(f==null?void 0:f.importance)==="clarification",v=typeof(f==null?void 0:f.deadline)=="string"&&Number.isFinite(Date.parse(f.deadline))?new Date(f.deadline).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):"";if(o.reason==="user"||o.reason==="ask_user")return{id:l,kind:"ask-user",title:m?"Your answer is required":g?"A clarification for you":"A question for you",...m?{description:"This question needs your answer. I will keep waiting; silence does not grant permission."}:g?{description:`${v?`Answer by ${v}. `:""}${f.fallback?`Without an answer: ${String(f.fallback)}`:""}`}:{},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(j=>typeof j=="object"&&j!==null?{id:String(j.value??j.id??j.label),label:String(j.label??j.text??j.value??j.id),description:j.description}:{id:String(j),label:String(j)}),onSubmit:async j=>{await t.resume(j,d)},...n.allowSkip&&!f?{onSkip:async()=>{await t.resume("",d)}}:{},...n.onDefer?{onDefer:n.onDefer}:{}};const w=String(o.wait_key||"");if(o.reason==="event"||w.startsWith("evt:")){if(s.command){const S=t.answerEvent;if(typeof S!="function")throw new Error("presentInteraction: an event wait from the replay view needs a WorkflowSessionController (answerEvent).");const N={runId:s.runId,waitKey:w,stepId:s.stepId};return{id:l,kind:"event-wait",title:"Waiting for your input",eventName:w,prompt:String(o.prompt||"This workflow is waiting for an event."),description:Array.isArray(o.choices)&&o.choices.length?`Expected: ${o.choices.map(C=>String(typeof C=="object"&&C!==null?C.label??C.value??"":C)).join(", ")}`:"The data you send resumes this wait.",initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send",onSend:async C=>{await S.call(t,JSON.parse(C||"{}"),N)}}}const b=JC(s,n.records||[],n.currentRun??null),k=b.target,$=(k==null?void 0:k.name)||"";return{id:l,kind:"event-wait",title:k?"Waiting for an event":"Event routing unavailable",eventName:$,prompt:String(o.prompt||`This workflow will continue when “${$||"its trigger"}” arrives.`),description:k?"You can also send the expected event here.":`This event cannot be sent safely. ${b.error}`,initialPayload:"{}",payloadLabel:"Event data (JSON)",sendLabel:"Send event",onSend:async S=>{if(!k)throw new Error(b.error);const N=JSON.parse(S||"{}"),C={name:k.name,scope:k.scope,payload:N};k.scope==="session"?C.session_id=k.scopeId:k.scope==="workflow"?C.workflow_id=k.scopeId:k.scope==="run"&&(C.run_id=k.scopeId),await t.emitEvent(C)}}}return null}function ZC(e){const t=Math.max(0,Math.floor(e/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function Ed(e){var n,s;const t=(s=(n=e==null?void 0:e.target)==null?void 0:n.input_data)==null?void 0:s.prompt;return typeof t=="string"?t:""}function eE(e){const{api:t,replace:n,catalog:s,approveTrusted:o,trustScope:l}=e.automations,u=e.summary.automation_id,[d,f]=p.useState(e.summary),[m,g]=p.useState(null),[v,w]=p.useState(null),[x,j]=p.useState(""),[b,k]=p.useState(null),[$,S]=p.useState(Date.now()),[N,C]=p.useState(!1),[R,E]=p.useState(""),[I,L]=p.useState([]),[D,P]=p.useState(()=>by(l,e.summary.automation_id)),[K,se]=p.useState(!1);p.useEffect(()=>void s().then(L,()=>{}),[s]);const Q=p.useRef(!0);p.useEffect(()=>()=>void(Q.current=!1),[]),p.useEffect(()=>f(e.summary),[e.summary]);const z=p.useCallback(async()=>{let ne=await t.getAutomation(u);return await o([ne.summary]).catch(()=>!1)&&(ne=await t.getAutomation(u)),Q.current&&(f(ne.summary),g(ne.definition),n(ne.summary)),ne.summary},[t,u,n]),T=p.useCallback(async()=>{const ne=await t.listOccurrences(u,{limit:gy});Q.current&&w(ne.items)},[t,u]);p.useEffect(()=>{let ne=!1;return(async()=>{try{await T();const $e=await z();if(ne)return;const Pe=$e.attention;Pe.cursor&&(Pe.unseen_count>0||Pe.unread)&&await t.markSeen(u,Pe.cursor).then(async()=>{ne||await z()},()=>{})}catch($e){ne||j(Bn($e))}})(),()=>{ne=!0}},[t,u,T,z]);const q=!!d.current_occurrence||d.attention.pending_waits>0;p.useEffect(()=>{if(!q&&b===null)return;const ne=setInterval(()=>{typeof document<"u"&&document.visibilityState==="hidden"||(S(Date.now()),z().then($e=>{Q.current&&($e.current_occurrence?k(null):(b===null||Date.now()-b>2e4)&&(k(null),T()))},()=>{}))},b!==null?1e3:3e3);return()=>clearInterval(ne)},[q,b,z,T]);const J=async()=>{j(""),C(!0),k(Date.now());try{await t.sendAutomationCommand(u,{type:"automation.run_now"})}catch(ne){k(null);const $e=Xs(ne)?ne:ne.error;Xs($e)&&$e.status===409?(j("It is already running."),z()):j(`Couldn't start it. ${Bn(ne)}`)}finally{C(!1)}},B=async()=>{j(""),C(!0);try{await t.sendAutomationCommand(u,{type:"automation.stop_current"}),await z()}catch{j("Couldn't stop it.")}finally{C(!1)}},O=async ne=>{const $e=Vm(v??[]);if($e===null)throw new Error("It has not run yet: there is nothing to talk about.");const Pe=await t.discuss(u,{occurrence_index:$e,prompt:ne});E(""),e.onOpenConversation(Pe.session_id,Pe.run_id)},Z=async ne=>{try{const $e=await e.client.getRun(ne.run_id),Pe=typeof $e.session_id=="string"?$e.session_id:"";if(!Pe)throw new Error("This run has no conversation to open.");e.onOpenConversation(Pe,ne.run_id)}catch($e){j(Bn($e))}},M=d.attention.waits.filter(ne=>ne.kind==="tool_approval"&&dd(ne)).slice(-1)[0]??null,W=M?dd(M)??[]:[],Y=m?wy(I,m):null,oe=Y&&W.length&&W.every(ne=>Y[ne.name]&&Y[ne.name]!=="off")?z1(I,Y,W.map(ne=>ne.name),D):null,de=async(ne,$e=!1)=>{if(M){se(!0),j("");try{$e&&oe&&(qm(l,u,oe),P(oe)),await xy(e.client,M,ne),await z()}catch(Pe){j(Bn(Pe))}finally{se(!1)}}},me=()=>{qm(l,u,[]),P([])},ee=Ed(m),ce=Number.isSafeInteger(d.occurrence_count)?d.occurrence_count:null,ye=d.status==="paused",Ce=d.status==="completed"||d.status==="failed",ze=d.status==="active"?cy(d.next_run_at,$):"",Ve=M?null:vN(v??[]),Ee=!!d.current_occurrence&&b===null,je=gN(v??[]),Ue=Vm(v??[])!==null;return a.jsx("div",{className:"aa-automation-page","data-automation-id":u,children:a.jsx(Ky,{className:"aa-chat",messages:je,draft:R,onDraftChange:E,onSend:O,disabled:!Ue,placeholder:Ue?"Talk about its latest run":"It has not run yet",emptyState:a.jsx("div",{className:"aa-empty",children:a.jsx("h2",{children:v===null&&!x?"Loading its runs…":"It has not run yet"})}),header:a.jsxs("div",{className:"aa-automation-head",children:[a.jsxs("div",{className:"aa-automation-head__line",children:[a.jsx("h1",{className:"aa-chat__title",title:d.title,children:d.title||"Automation"}),a.jsxs("div",{className:"aa-automation-head__actions",children:[a.jsxs("button",{type:"button",className:"aa-button",onClick:e.onEdit,"aria-label":"Edit",children:[a.jsx(be,{name:"edit",size:16})," Edit"]}),a.jsxs("button",{type:"button",className:`aa-button${Ee?" aa-button--stop":" aa-button--primary"}`,disabled:N||Ce,onClick:()=>void(Ee?B():J()),"aria-label":b!==null?"Starting the run":Ee?"Stop this run":"Run",children:[b!==null?a.jsx(be,{name:"loader",size:16}):a.jsx(be,{name:Ee?"stop":"play",size:16})," ",Ee?"Stop":"Run"]})]})]}),a.jsxs("p",{className:"aa-automation-head__facts",children:[ce!==null&&a.jsxs("span",{title:`Ran ${ce} ${ce===1?"time":"times"}`,children:[a.jsx(be,{name:"loop",size:14})," ",ce]}),a.jsxs("span",{title:d.trigger_text||d.schedule_rule_text||"",children:[a.jsx(be,{name:ye?"pause":Ce?"stop":"clock",size:14})," ",ye?"Paused":Ce?"Ended":ly(d)]}),ze&&a.jsxs("span",{title:"Next run",children:[a.jsx(be,{name:"playCircle",size:14})," ",ze]})]}),b!==null&&a.jsxs("p",{className:"aa-automation-head__starting",role:"status",children:[q?"Running…":"Starting…"," ",ZC($-b)]}),ee&&ee!==d.title&&a.jsxs("p",{className:"aa-automation-head__task",children:[a.jsx("span",{children:"Task"}),ee]}),d.context_mode==="growing"&&a.jsxs("p",{className:"aa-automation-head__note",children:[a.jsx(be,{name:"loop",size:14})," Builds on its earlier runs"]}),D.length>0&&a.jsxs("div",{className:"aa-trust",role:"group","aria-label":"Allowed for its runs",children:[a.jsxs("p",{className:"aa-trust__title",children:[a.jsx(be,{name:"check",size:14})," Allowed for its runs"]}),a.jsx("p",{children:D.map(nl).join(", ")}),a.jsx("p",{className:"aa-trust__note",children:"Approved by this browser when it sees them."}),a.jsx("button",{type:"button",className:"aa-button",onClick:me,children:"Ask again"})]}),M&&a.jsxs("div",{className:"aa-approval",role:"group","aria-label":"A run asks for approval",children:[a.jsx("p",{className:"aa-approval__title",children:"A run asks to:"}),a.jsx("ul",{children:W.map((ne,$e)=>a.jsx("li",{children:Fd(ne).sentence},$e))}),a.jsxs("div",{className:"aa-approval__actions",children:[a.jsx("button",{type:"button",className:"aa-button",disabled:K,onClick:()=>void de(!1),children:"Deny"}),oe&&a.jsx("button",{type:"button",className:"aa-button",disabled:K,onClick:()=>void de(!0,!0),children:"Approve all"}),a.jsx("button",{type:"button",className:"aa-button aa-button--primary",disabled:K,onClick:()=>void de(!0),children:"Approve"})]})]})]}),footer:x||Ve?a.jsxs("div",{className:"aa-chat__notes",children:[Ve?a.jsxs("p",{className:"aa-note",role:"status",children:["A run is waiting for you."," ",a.jsx("button",{type:"button",className:"aa-link",onClick:()=>void Z(Ve),children:"Answer"})]}):null,x?a.jsx("p",{className:"aa-note aa-note--error",role:"alert",children:x}):null]}):null,messageProps:{images:"link"}})})}function tE(e){const{api:t,refresh:n}=e.automations,s=e.summary,[o,l]=p.useState(null),[u,d]=p.useState(!1),[f,m]=p.useState(""),[g,v]=p.useState(!1),[w,x]=p.useState(""),[j,b]=p.useState(s.status!=="paused"),[k,$]=p.useState(Du(s)),[S,N]=p.useState(s.context_mode==="growing"),[C,R]=p.useState(s.growing_max_tokens?String(s.growing_max_tokens):""),[E,I]=p.useState(!1),[L,D]=p.useState(""),[P,K]=p.useState(!1);p.useEffect(()=>{let oe=!1;return t.getAutomation(s.automation_id).then(de=>{oe||(l(de.definition),x(Ed(de.definition)),m(de.definition.title||s.title||""))},()=>!oe&&d(!0)),()=>{oe=!0}},[t,s.automation_id,s.title]);const se=yy(C),Q=(()=>{const oe=mv(s,o);return{...oe,title:f.trim()||oe.title,prompt:o&&w.trim()||oe.prompt,every:k||oe.every,context:S?"growing":"independent",growingMaxTokens:S&&se?se:oe.growingMaxTokens}})(),z=o||!u?rk(s,Q,o):null,T=z&&"errors"in z?z.errors:[],q=z&&!("errors"in z)?z:null,J=j!==(s.status!=="paused"),B=S&&C.trim()!==""&&se===null?"Numbers only, more than 0.":"",O=!!q||J,Z=oe=>{if(x(oe),!g&&o){const de=pN(oe.trim(),o.title,Ed(o));de!==null&&m(de)}},M=async()=>{I(!0),D("");try{q&&await t.reviseAutomation(s.automation_id,{changes:q,expected_revision:(o==null?void 0:o.revision)??s.revision??void 0}),J&&await t.sendAutomationCommand(s.automation_id,{type:j?"automation.resume":"automation.pause"}),await n(),e.onDone()}catch(oe){const de=Xs(oe)?oe:oe.error;D(Xs(de)&&de.status===409?"Changed elsewhere meanwhile. Open it again.":Bn(oe))}finally{I(!1),K(!1)}},W=()=>O?K(!0):e.onDone(),Y=Du(s)!=="";return a.jsx("div",{className:"aa-form-page","data-page":"automation-edit",children:a.jsxs("form",{className:"aa-form",onSubmit:oe=>{oe.preventDefault(),O&&!B&&!T.length&&M()},children:[a.jsx("h1",{children:"Edit"}),o?a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"Title"}),a.jsx("input",{value:f,onChange:oe=>{m(oe.target.value),v(!0)}})]}),a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"Task"}),a.jsx("textarea",{rows:5,value:w,onChange:oe=>Z(oe.target.value)})]})]}):u?a.jsx("p",{className:"aa-note aa-note--error",role:"alert",children:"Couldn't load this automation."}):a.jsx("p",{className:"aa-note",role:"status",children:"Loading…"}),a.jsxs("fieldset",{className:"aa-fieldset",children:[a.jsx("legend",{children:"Runs"}),a.jsx(ii,{variant:"row",label:"Active",checked:j,onChange:b,action:"active"}),Y&&a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"How often"}),a.jsx("select",{value:k,disabled:!j,onChange:oe=>$(oe.target.value),children:dN(Du(s)).map(oe=>a.jsx("option",{value:oe,children:vy(oe)},oe))})]})]}),a.jsxs("fieldset",{className:"aa-fieldset",children:[a.jsx("legend",{children:"Memory"}),a.jsx(ii,{variant:"row",label:"Builds on earlier runs",checked:S,onChange:N,action:"remembers"}),S&&a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"Reads up to (tokens of its earlier runs)"}),a.jsx("input",{inputMode:"numeric",value:C,placeholder:"The gateway's default",onChange:oe=>R(oe.target.value),"aria-invalid":!!B}),B?a.jsx("small",{className:"aa-field__problem",children:B}):null]})]}),T.map(oe=>a.jsx("p",{className:"aa-note aa-note--error",role:"alert",children:oe},oe)),L?a.jsx("p",{className:"aa-note aa-note--error",role:"alert",children:L}):null,P?a.jsxs("div",{className:"aa-form__actions",role:"group","aria-label":"Save your changes?",children:[a.jsx("span",{children:"Save your changes?"}),a.jsx("button",{type:"button",className:"aa-button",onClick:e.onDone,children:"Discard"}),a.jsx("button",{type:"submit",className:"aa-button aa-button--primary",disabled:E||!!B||T.length>0,children:E?"Saving…":"Save"})]}):a.jsxs("div",{className:"aa-form__actions",children:[a.jsx("button",{type:"button",className:"aa-button",onClick:W,children:"Cancel"}),a.jsx("button",{type:"submit",className:"aa-button aa-button--primary",disabled:!O||E||!!B||T.length>0,children:E?"Saving…":"Save"})]})]})})}const nd="daily";function nE(e){return async(t,n)=>{const s=await e.fetchGateway(ut(t),{signal:n.signal,headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`The gateway answered ${s.status} for the workflows.`);return s.json()}}function rE(e){const{api:t,refresh:n}=e.automations,[s,o]=p.useState(""),[l,u]=p.useState({flow_id:"@default",interface:wd}),[d,f]=p.useState("24h"),[m,g]=p.useState("08:00"),[v,w]=p.useState(!1),[x,j]=p.useState(""),[b,k]=p.useState(null),[$,S]=p.useState(!1),[N,C]=p.useState(""),[R,E]=p.useState(null),[I,L]=p.useState(""),[D,P]=p.useState({}),[K,se]=p.useState(!1),Q=e.automations.catalog;p.useEffect(()=>{let M=!1;return Q().then(W=>!M&&E(W),W=>!M&&L(Bn(W))),()=>{M=!0}},[Q]);const z=p.useMemo(()=>({interfaceId:wd,request:nE(e.client)}),[e.client]);p.useEffect(()=>{let M=!1;return e.client.fetchGateway(ut("automations/defaults"),{headers:{Accept:"application/json"}}).then(W=>W.ok?W.json():null).then(W=>{const Y=W==null?void 0:W.growing_max_tokens;!M&&typeof Y=="number"&&Y>0&&k(Y)},()=>{}),()=>{M=!0}},[e.client]);const T=yy(x),q=v&&x.trim()!==""&&T===null?"Numbers only, more than 0.":"",J=fN(m),B=d===nd?J?{kind:"daily",at:J}:null:{kind:"every",every:d},O=s.trim()!==""&&B!==null&&!q&&!$&&R!==null,Z=async()=>{if(B){S(!0),C("");try{const M=s.trim();let W=null;if("bundle_ref"in l){const me=await Fk({...l,input_data:{...l.input_data||{},prompt:M}},z);W={bundle_ref:me.bundle_ref,flow_id:me.flow_id,input_data:me.input_data||{}}}const Y=Ov(R??[],{session:D}),oe=mN({requestId:crypto.randomUUID(),task:M,workflow:W,when:B,buildsOnEarlierRuns:v,growingMaxTokens:v?T:null,tools:Y}),de=await t.createAutomation(oe);await n(),e.onCreated(de.summary)}catch(M){C(Bn(M))}finally{S(!1)}}};return a.jsx("div",{className:"aa-form-page","data-page":"new-automation",children:a.jsxs("form",{className:"aa-form",onSubmit:M=>{M.preventDefault(),O&&Z()},children:[a.jsx("h1",{children:"New automation"}),a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"Task"}),a.jsx("textarea",{rows:5,value:s,placeholder:"What should it do?",onChange:M=>o(M.target.value),autoFocus:!0})]}),a.jsx(Ok,{target:l,options:z,onChange:u}),R?a.jsx(Z1,{catalog:R,layer:"session",value:D,inherited:P1(R,{}),onChange:P,onReset:()=>P({}),rowLabel:"Tools",open:K,onToggle:()=>se(M=>!M),note:"It runs on its own: a tool on Ask waits for you."}):a.jsx("p",{className:`aa-note${I?" aa-note--error":""}`,role:I?"alert":"status",children:I?`Couldn't load your tools. ${I}`:"Loading tools…"}),a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"When"}),a.jsxs("select",{value:d,onChange:M=>f(M.target.value),children:[my.map(M=>a.jsx("option",{value:M,children:vy(M)},M)),a.jsx("option",{value:nd,children:"Every day at a time"})]})]}),d===nd&&a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"Every day at"}),a.jsx("input",{type:"time",value:m,onChange:M=>g(M.target.value),"aria-invalid":!J})]}),a.jsxs("fieldset",{className:"aa-fieldset",children:[a.jsx("legend",{children:"Memory"}),a.jsx(ii,{variant:"row",label:"Builds on earlier runs",checked:v,onChange:w,action:"remembers"}),v&&a.jsxs("label",{className:"aa-field",children:[a.jsx("span",{children:"Reads up to (tokens of its earlier runs)"}),a.jsx("input",{inputMode:"numeric",value:x,placeholder:b?b.toLocaleString():"The gateway's default",onChange:M=>j(M.target.value),"aria-invalid":!!q}),q?a.jsx("small",{className:"aa-field__problem",children:q}):null]})]}),N?a.jsx("p",{className:"aa-note aa-note--error",role:"alert",children:N}):null,a.jsxs("div",{className:"aa-form__actions",children:[a.jsx("button",{type:"button",className:"aa-button",onClick:e.onCancel,children:"Cancel"}),a.jsx("button",{type:"submit",className:"aa-button aa-button--primary",disabled:!O,children:$?"Creating…":"Create"})]})]})})}const sw=["ready","thinking","working","listening","speaking","waiting","error"],bg=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1;function sE(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("Avatar frame must be an object");const t=e;if(Object.keys(t).some(n=>!["schema_version","style","state","time","level","gaze","bands"].includes(n)))throw new Error("Unknown avatar frame field");if(t.schema_version!==1||typeof t.style!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(t.style)||!sw.includes(t.state)||typeof t.time!="number"||!Number.isFinite(t.time)||t.time<0||t.time>86400||!bg(t.level))throw new Error("Invalid avatar frame version, style, state, time or level");if(t.gaze!==void 0&&(!Array.isArray(t.gaze)||t.gaze.length!==2||t.gaze.some(n=>typeof n!="number"||!Number.isFinite(n)||n<-1||n>1)))throw new Error("Avatar gaze requires two normalized coordinates");if(t.bands!==void 0&&(!Array.isArray(t.bands)||t.bands.length!==8||!t.bands.every(bg)))throw new Error("Avatar bands require eight normalized levels");return{schema_version:1,style:t.style,state:t.state,time:t.time,level:t.level,...t.gaze===void 0?{}:{gaze:[...t.gaze]},...t.bands===void 0?{}:{bands:[...t.bands]}}}let Do;async function xg(e){let t;if(e!==void 0)t=e;else{const u=await fetch(new URL(""+new URL("avatar_core-7Jm5QyAS.wasm",import.meta.url).href,import.meta.url));if(!u.ok)throw new Error(`Avatar renderer unavailable (${u.status})`);t=await u.arrayBuffer()}if(t.byteLength>8*1024*1024)throw new Error("Avatar renderer module exceeds the size limit");const n=await WebAssembly.compile(t);if(WebAssembly.Module.imports(n).length!==0)throw new Error("Avatar renderer must not import host capabilities");const o=(await WebAssembly.instantiate(n)).exports,l=["avatar_abi_version","avatar_style_count","avatar_style_field_ptr","avatar_style_field_len","avatar_create","avatar_destroy","avatar_set_shade","avatar_set_gaze","avatar_set_bands","avatar_render","avatar_pixels","avatar_pixels_len"];if(!(o.memory instanceof WebAssembly.Memory)||o.memory.buffer.byteLength>64*1024*1024||l.some(u=>typeof o[u]!="function")||o.avatar_abi_version()!==1)throw new Error("Unsupported avatar renderer version");return o}async function aw(e){return e?xg(e):(Do||(Do=xg().catch(t=>{throw Do=void 0,t})),Do)}function iw(e){const t=new TextDecoder("utf-8",{fatal:!0}),n=(l,u)=>{const d=e.avatar_style_field_ptr(l,u)>>>0,f=e.avatar_style_field_len(l,u);if(!Number.isInteger(f)||f<0||f>512||d+f>e.memory.buffer.byteLength)throw new Error("Invalid avatar catalog field bounds");return t.decode(new Uint8Array(e.memory.buffer,d,f))},s=e.avatar_style_count();if(!Number.isInteger(s)||s<1||s>256)throw new Error("Invalid avatar catalog size");const o=Array.from({length:s},(l,u)=>({id:n(u,0),name:n(u,1),description:n(u,2),watchCode:n(u,3),family:n(u,4),gaze:n(u,5)==="eyes"?"eyes":"none"}));if(new Set(o.map(l=>l.id)).size!==s||o.some(l=>!/^[a-z][a-z0-9_-]{0,63}$/.test(l.id)))throw new Error("Invalid avatar catalog identity");return o}function aE(e,t,n){if((e==null?void 0:e.gaze)!=="eyes"||t.pointerType==="touch"||!(n.width>0)||!(n.height>0))return;const s=o=>Number.isFinite(o)?Math.max(-1,Math.min(1,o)):0;return[s((t.clientX-n.x-n.width/2)/(n.width/2)),s((t.clientY-n.y-n.height/2)/(n.height/2))]}async function iE(e){return iw(await aw(e))}function kg(e){if(e.length!==4||e.some(t=>!Number.isInteger(t)||t<0||t>255))throw new Error("Avatar colors require four bytes");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0}const jg=(e,t,n)=>e.map((s,o)=>Math.round(s+(t[o]-s)*n));class ef{constructor(t,n,s,o){this.core=t;const l=n.getContext("2d");if(!l)throw new Error("Avatar requires a Canvas 2D context");const u=l.createImageData(s,o);this.designs=iw(t);const d=t.avatar_create(s,o);if(!d)throw new Error("Avatar size or live renderer limit exceeded");this.handle=d,this.context=l,n.width=s,n.height=o,this.image=u}static async create(t,n){var d,f;const s=n.width??128,o=n.height??s;if(!Number.isInteger(s)||!Number.isInteger(o)||s<1||o<1||s>512||o>512)throw new Error("Avatar dimensions must be 1–512 pixels");if((d=n.signal)!=null&&d.aborted)throw new DOMException("Avatar renderer creation cancelled","AbortError");const l=await aw(n.source);if((f=n.signal)!=null&&f.aborted)throw new DOMException("Avatar renderer creation cancelled","AbortError");const u=new ef(l,t,s,o);try{return u.setPalette(n.palette),u}catch(m){throw u.dispose(),m}}setPalette(t){if(!this.handle)throw new Error("Avatar renderer disposed");[t.background,t.warm,t.eye,t.shadow,t.highlight,t.muted].forEach(kg);for(const[n,s,o]of[[0,t.warm,t.highlight],[1,t.eye,t.highlight],[2,t.shadow,t.muted]])for(let l=0;l<256;l++){const u=l/255,d=u<.65?jg(t.background,s,u/.65):jg(s,o,(u-.65)/.35);if(this.core.avatar_set_shade(this.handle,n,l,kg(d))!==0)throw new Error("Avatar palette update failed")}}draw(t,n,s,o,l){this.renderFrame({schema_version:1,style:t,state:n,level:s,time:o,...l===void 0?{}:{gaze:l}})}paint(t,n,s,o,l){if(!this.handle)throw new Error("Avatar renderer disposed");const u=this.designs.findIndex(v=>v.id===t),d=sw.indexOf(n);if(u<0||d<0||!Number.isFinite(s)||!Number.isFinite(o))throw new Error("Invalid avatar style, pose, level or time");if(l&&l.some(v=>!Number.isFinite(v)))throw new Error("Invalid avatar gaze");if(this.core.avatar_set_gaze(this.handle,(l==null?void 0:l[0])??0,(l==null?void 0:l[1])??0)!==0)throw new Error("Avatar gaze update failed");const f=this.core.avatar_render(this.handle,u,d,s,o,1);if(f!==0)throw new Error(`Avatar rendering failed (${f})`);const m=this.core.avatar_pixels(this.handle)>>>0,g=this.core.avatar_pixels_len(this.handle);if(g!==this.image.data.length||m+g>this.core.memory.buffer.byteLength||this.core.memory.buffer.byteLength>64*1024*1024)throw new Error("Invalid avatar raster frame bounds");this.image.data.set(new Uint8Array(this.core.memory.buffer,m,g)),this.context.putImageData(this.image,0,0)}renderFrame(t){const n=sE(t);if(!this.handle)throw new Error("Avatar renderer disposed");const s=n.bands??Array(8).fill(n.level);if(this.core.avatar_set_bands(this.handle,s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7])!==0)throw new Error("Avatar audio-band update failed");this.paint(n.style,n.state,n.level,n.time,n.gaze)}dispose(){this.handle&&(this.core.avatar_destroy(this.handle),this.handle=0)}}function Sg(e){const t=getComputedStyle(e),n=e.ownerDocument.createElement("canvas");n.width=n.height=1;const s=n.getContext("2d");if(!s)throw new Error("Avatar theme color conversion unavailable");const o=m=>{const g=t.getPropertyValue(m).trim();if(!g)throw new Error(`Avatar theme token missing: ${m}`);return s.clearRect(0,0,1,1),s.fillStyle=g,s.fillRect(0,0,1,1),Array.from(s.getImageData(0,0,1,1).data)},l=o("--bg-primary"),u=o("--ui-border-2"),d=u[3]/255,f=[Math.round(u[0]*d+l[0]*(1-d)),Math.round(u[1]*d+l[1]*(1-d)),Math.round(u[2]*d+l[2]*(1-d)),255];return{background:l,warm:o("--warning"),eye:o("--error"),shadow:f,highlight:o("--text-primary"),muted:o("--text-secondary")}}const Ng={economy:{pixels:256,ratio:1.5,active:12,ready:2,waiting:6},balanced:{pixels:384,ratio:2,active:24,ready:6,waiting:10},high:{pixels:512,ratio:3,active:30,ready:12,waiting:12}};function ow(e){if(!Object.prototype.hasOwnProperty.call(Ng,e))throw new Error("Unknown avatar quality");return Ng[e]}function oE(e,t,n){if(!Number.isFinite(e)||e<=0||e>4096)throw new Error("Avatar display size must be greater than zero and at most 4096 pixels");const s=ow(n),o=Number.isFinite(t)?Math.max(1,Math.min(s.ratio,t)):1;return Math.max(1,Math.min(s.pixels,Math.round(e*o)))}function lE(e,t,n){const s=ow(e);return 1e3/(t==="ready"&&!n?s.ready:t==="waiting"?s.waiting:s.active)}function cE({design:e="halo",pose:t="ready",level:n=0,bands:s,size:o=128,quality:l="balanced",animated:u=!0,active:d=!0,followCursor:f=!1,palette:m,className:g,label:v,onError:w}){const x=p.useRef(null),j=p.useRef({design:e,pose:t,level:n,bands:s});j.current={design:e,pose:t,level:n,bands:s};const[b,k]=p.useState(!1),$=p.useRef(w),S=p.useRef({elapsed:0,previous:void 0});$.current=w;const[N,C]=p.useState(1);p.useEffect(()=>{let E;const I=()=>{E==null||E.removeEventListener("change",I);const L=window.devicePixelRatio||1;C(L),E=matchMedia(`(resolution: ${L}dppx)`),E.addEventListener("change",I)};return I(),window.addEventListener("resize",I,{passive:!0}),()=>{window.removeEventListener("resize",I),E==null||E.removeEventListener("change",I)}},[]);const R=m?JSON.stringify(m):"theme";return p.useEffect(()=>{const E=x.current;if(!E||!d)return;const I=new AbortController;let L=!1,D,P=!0,K=!1,se,Q,z,T,q,J=[0,0],B,O=!1,Z=0;const M=matchMedia("(prefers-reduced-motion: reduce)"),W=S.current;let Y;const oe=()=>{se!==void 0&&(clearTimeout(se),se=void 0),z!==void 0&&(cancelAnimationFrame(z),z=void 0)},de=()=>{Q!==void 0&&(clearTimeout(Q),Q=void 0),O=!1,q=void 0,J=[0,0],B=void 0},me=je=>{var Ue,ne;L||(oe(),de(),(Ue=E.getContext("2d"))==null||Ue.clearRect(0,0,E.width,E.height),k(!0),(ne=$.current)==null||ne.call($,je instanceof Error?je:new Error(String(je))))},ee=()=>{oe();const je=j.current;if(Y!==je.pose&&(T=void 0,Y=je.pose),(!u||M.matches||!P||K||document.hidden||je.pose!=="ready"||B!==je.design)&&de(),L||!D||!P||K||document.hidden){W.previous=void 0,T=void 0;return}try{const Ue=u&&!M.matches,ne=performance.now();if(Ue&&W.previous!==void 0&&(W.elapsed=(W.elapsed+Math.min(1,(ne-W.previous)/1e3))%86400),W.previous=Ue?ne:void 0,q){const $e=1-Math.exp(-Math.min(250,ne-Z)/150);Z=ne,q=[q[0]+(J[0]-q[0])*$e,q[1]+(J[1]-q[1])*$e],Q===void 0&&Math.hypot(q[0],q[1])<.01&&de()}if(D.renderFrame({schema_version:1,style:je.design,state:je.pose,level:je.level,time:Ue?W.elapsed:0,...q===void 0?{}:{gaze:q},...je.bands===void 0?{}:{bands:je.bands}}),k(!1),u&&!M.matches&&je.pose!=="error"){const $e=lE(l,je.pose,O),Pe=performance.now();T=T===void 0?ne+$e:T+$e,T<Pe&&(T=Pe+$e),se=setTimeout(()=>{se=void 0,z=requestAnimationFrame(()=>{z=void 0,ee()})},Math.max(0,T-Pe))}else T=void 0}catch(Ue){me(Ue)}},ce=je=>{const Ue=j.current.design;if(!D||!P||K||document.hidden||!u||M.matches||j.current.pose!=="ready")return;const ne=aE(D.designs.find(Pe=>Pe.id===Ue),je,E.getBoundingClientRect());if(!ne)return;q||(q=[0,0],Z=performance.now()),J=ne,B=Ue;const $e=O;O=!0,Q!==void 0&&clearTimeout(Q),Q=setTimeout(()=>{Q=void 0,J=[0,0]},2e3),$e||(T=void 0),$e||ee()},ye=je=>{ce(je)},Ce=new IntersectionObserver(je=>{var Ue;P=((Ue=je[0])==null?void 0:Ue.isIntersecting)??!1,ee()});Ce.observe(E),M.addEventListener("change",ee),document.addEventListener("visibilitychange",ee),E.addEventListener("avatar-update",ee),f&&(window.addEventListener("pointermove",ce,{passive:!0}),window.addEventListener("pointerdown",ye,{passive:!0}));const ze=je=>{je.preventDefault(),K=!0,oe(),de(),k(!0)},Ve=()=>{K=!1,ee()};E.addEventListener("contextlost",ze),E.addEventListener("contextrestored",Ve);const Ee=new MutationObserver(()=>{if(D&&!m)try{D.setPalette(Sg(E)),ee()}catch(je){me(je)}});if(!m){const je={attributes:!0,attributeFilter:["data-theme","data-af-theme","class","style"]};Ee.observe(document.documentElement,je),document.body&&Ee.observe(document.body,je)}return Promise.resolve().then(()=>{if(L)return;const je=oE(o,N,l);return ef.create(E,{width:je,height:je,palette:m??Sg(E),signal:I.signal})}).then(je=>{if(je){if(L){je.dispose();return}D=je,k(!1),ee()}}).catch(me),()=>{L=!0,I.abort(),W.previous=void 0,oe(),de(),Ce.disconnect(),Ee.disconnect(),M.removeEventListener("change",ee),document.removeEventListener("visibilitychange",ee),E.removeEventListener("avatar-update",ee),window.removeEventListener("pointermove",ce),window.removeEventListener("pointerdown",ye),E.removeEventListener("contextlost",ze),E.removeEventListener("contextrestored",Ve),D==null||D.dispose()}},[o,N,l,R,u,d,f]),p.useEffect(()=>{var E;(E=x.current)==null||E.dispatchEvent(new Event("avatar-update"))},[e,t]),p.useEffect(()=>{var E;(!u||matchMedia("(prefers-reduced-motion: reduce)").matches)&&((E=x.current)==null||E.dispatchEvent(new Event("avatar-update")))},[n,s,u]),a.jsx("canvas",{ref:x,className:g,style:{width:o,height:o,visibility:d?"visible":"hidden"},"aria-hidden":!d,role:"img","aria-label":b?"Avatar unavailable":v??`${e} · ${t}`})}function lw(e){return a.jsx(cE,{...e,design:e.design??"watch-halo"})}function Cg(e,t="microphone"){const[n,s]=p.useState(0),o=t==="playback"?e==null?void 0:e.subscribe_playback_level:e==null?void 0:e.subscribe_level;return p.useEffect(()=>{if(!o){s(0);return}return o(l=>s(Math.min(1,Math.max(0,Number(l)||0))))},[o]),n}const tf={background:[9,11,22,0],warm:[107,227,204,255],eye:[173,166,255,255],shadow:[33,27,63,255],highlight:[237,242,255,255],muted:[90,109,146,255]},cw={...tf,warm:[237,197,106,255],eye:[240,137,171,255],shadow:[68,45,48,255]},uE={...tf,eye:[255,77,91,255]},dE={...cw,eye:[255,77,91,255]};function uw(e,t){const n=e==="hover"||e==="rover";return t==="error"?n?dE:uE:n?cw:tf}function dw(e){const t=Cg(e.pose==="listening"?e.voice:null),n=Cg(e.pose==="speaking"?e.voice:null,"playback"),s=e.pose==="listening"?t:e.pose==="speaking"?n:0;return a.jsx(lw,{design:e.prefs.design,pose:e.pose,size:e.size??288,level:s,palette:uw(e.prefs.design,e.pose),animated:e.prefs.animated,followCursor:!0,className:"aa-orb",label:`Assistant · ${e.pose}`,onError:e.onError})}function fE(e){const[t,n]=p.useState(!1),s=["playing","paused","loading"].includes(e.voice.tts_playback.status),o=!s&&!e.busy&&!e.voice.voice_ptt_busy&&!e.microphoneReason&&e.voice.voice_ptt_supported,l=s?e.voice.tts_playback.status==="paused"?"Resume reply":"Pause reply":e.busy||e.voice.voice_ptt_busy?"Stop":"Write a message";return a.jsxs("section",{className:"aa-presence","data-pose":e.presence.pose,"aria-label":"Assistant voice",children:[a.jsxs("div",{className:"aa-presence__eyebrow",children:[a.jsx("span",{className:"aa-presence__light"})," Your assistant"]}),a.jsxs("div",{className:`aa-orb-control${o?" aa-orb-control--mic":""}`,children:[a.jsx(dw,{voice:e.voice,pose:e.presence.pose,prefs:e.prefs,onError:()=>n(!0)}),a.jsx(al,{voice:e.voice,mode:e.mode,showStatus:!1,className:`aa-orb-mic${o?"":" is-hidden"}`,unavailableReason:o?null:"Use the current action on the orb.",label:e.mode==="hold"?"Hold the orb to talk":"Tap the orb to talk",onTranscript:e.onTranscript}),!o&&a.jsx("button",{type:"button",className:"aa-orb-hit","aria-label":l,onClick:s?e.onPlayback:e.busy||e.voice.voice_ptt_busy?e.onStop:e.onType})]}),a.jsxs("div",{className:"aa-presence__words","aria-live":"polite",children:[a.jsx("h2",{children:e.presence.label}),a.jsx("p",{children:e.voice.voice_ptt_recording?e.mode==="hold"?"Release to finish recording.":"Tap the orb again to finish.":o?e.mode==="hold"?"Hold the orb to talk.":"Tap the orb to talk.":e.presence.hint}),!e.busy&&!s&&!e.voice.voice_ptt_busy&&a.jsx("span",{className:"aa-presence__caption",children:e.autoSend?"What you say is sent automatically.":"Review your words before sending."})]}),a.jsxs("div",{className:"aa-presence__actions",role:"group","aria-label":"Voice controls",children:[a.jsx("button",{type:"button",className:"aa-icon-button",onClick:e.onType,"aria-label":"Write a message",title:"Write a message",children:a.jsx(be,{name:"edit",size:18})}),e.voice.tts_supported&&a.jsx("button",{type:"button",className:`aa-icon-button${e.readReplies?" is-on":""}`,"aria-pressed":e.readReplies,"aria-label":"Read new replies aloud",title:"Read new replies aloud",onClick:()=>{e.readReplies&&e.voice.stop_tts(),e.onReadRepliesChange(!e.readReplies)},children:a.jsx(be,{name:"speaker",size:18})}),s&&a.jsx("button",{type:"button",className:"aa-icon-button","aria-label":e.voice.tts_playback.status==="paused"?"Resume reply":"Pause reply",onClick:e.onPlayback,children:a.jsx(be,{name:e.voice.tts_playback.status==="paused"?"play":"pause",size:18})}),(e.busy||s||e.voice.voice_ptt_recording||e.voice.voice_ptt_busy)&&a.jsx("button",{type:"button",className:"aa-icon-button",onClick:e.onStop,"aria-label":"Stop",children:a.jsx(be,{name:"stop",size:18})}),a.jsx("button",{type:"button",className:"aa-icon-button",onClick:e.onSettings,"aria-label":"Assistant settings",title:"Assistant settings",children:a.jsx(be,{name:"settings",size:18})})]}),t&&a.jsx("p",{className:"aa-note",role:"status",children:"The avatar could not load. Voice and messages still work."}),e.microphoneReason&&a.jsx("p",{className:"aa-presence__caption",children:e.microphoneReason})]})}const hE=["ready","listening","thinking","working","speaking","waiting","error"];function pE(e){var m;const[t,n]=p.useState([]),[s,o]=p.useState(""),[l,u]=p.useState(0),[d,f]=p.useState("ready");return p.useEffect(()=>{if(!e.active)return;let g=!1;return iE().then(v=>{g||(n(v),o(""))},()=>{g||o("The avatar library could not load.")}),()=>{g=!0}},[e.active,l]),a.jsxs("section",{className:"aa-avatar-settings","aria-label":"Avatar appearance",children:[a.jsx("h2",{className:"aa-settings__heading",children:"Make it yours"}),a.jsx("p",{className:"aa-note",children:"Choose a Watch particle orb, the iPhone woven orb, or a shaded character."}),a.jsx("div",{className:"aa-avatar-preview",children:a.jsx(lw,{design:e.value.design,pose:d,size:260,level:.55,active:e.active,palette:uw(e.value.design,d),animated:e.value.animated,followCursor:!0,label:`Preview · ${d}`})}),a.jsxs("div",{className:"aa-setting",children:[a.jsx("label",{htmlFor:"assistant-avatar-design",children:"Avatar"}),a.jsxs("select",{id:"assistant-avatar-design",value:e.value.design,disabled:!t.length,onChange:g=>e.onChange({...e.value,design:g.target.value}),children:[!t.some(g=>g.id===e.value.design)&&a.jsx("option",{value:e.value.design,children:"Current avatar"}),Array.from(new Set(t.map(g=>g.family))).map(g=>a.jsx("optgroup",{label:g[0].toUpperCase()+g.slice(1),children:t.filter(v=>v.family===g).map(v=>a.jsx("option",{value:v.id,children:v.name},v.id))},g))]})]}),a.jsx("p",{className:"aa-note",children:(m=t.find(g=>g.id===e.value.design))==null?void 0:m.description}),a.jsx("div",{className:"aa-phase-picker",role:"group","aria-label":"Preview activity states",children:hE.map(g=>a.jsx("button",{type:"button","aria-pressed":g===d,onClick:()=>f(g),children:g[0].toUpperCase()+g.slice(1)},g))}),a.jsx("p",{className:"aa-note",children:"Silent preview · Listening and Speaking use a sample level."}),a.jsxs("label",{className:"aa-setting aa-setting--switch",children:[a.jsxs("span",{children:["Animate activity",a.jsx("small",{children:"Your system’s reduced-motion preference always applies."})]}),a.jsx("input",{type:"checkbox",checked:e.value.animated,onChange:g=>e.onChange({...e.value,animated:g.target.checked})})]}),(s||e.error)&&a.jsxs("p",{className:"aa-note",role:"status",children:[s||e.error," ",s&&a.jsx("button",{className:"aa-link",type:"button",onClick:()=>u(g=>g+1),children:"Try again"})]})]})}const Td={capture_mode:"toggle",auto_send:!1};function mE(e){const{client:t}=e;return a.jsxs("div",{className:"aa-settings",children:[a.jsx(pE,{value:e.appearance,onChange:e.onAppearanceChange,active:e.active,error:e.preferenceError}),a.jsx("h2",{className:"aa-settings__heading",children:"Voice"}),a.jsx(R1,{nested:!0,value:e.prefs,onChange:e.onPrefsChange,fetchCatalog:(n,s)=>t.voiceCatalog(n,s),fetchDefaults:()=>t.voiceDefaults(),defaults:e.defaults,overrideOwner:"this app",rows:{mute:!0,capture:!0},captureDefaults:Td})]})}const Eg={waiting:4,running:3,failed:2,done:1,unknown:0},gE={waiting:"waiting",running:"running",failed:"failed",cancelled:"failed",completed:"done"},vE=new Set(["","chat","discussion"]),fn=e=>typeof e=="string"?e.trim():"",Ad=e=>fn(e.updated_at)||fn(e.created_at),rd=e=>fn(e.created_at)||Ad(e),yE=e=>gE[fn(e.status).toLowerCase()]??"unknown";function Fo(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function wE(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.items)?t.items:Array.isArray(t.runs)?t.runs:[],s=t.has_more!==!1,o=new Map;n.forEach((d,f)=>{if(!d||typeof d!="object")return;const m=d;if(!vE.has(fn(m.session_kind))||!dy(m))return;const g=fn(m.session_id),v=fn(m.run_id);if(!g||!v)return;const w=o.get(g)??[];w.push([f,m]),o.set(g,w)});const l=(d,f,m)=>{let g=d[0];for(const v of d.slice(1)){const w=Fo(f(v[1])),x=Fo(f(g[1]));(m?w>x||w===x&&v[0]<g[0]:w<x||w===x&&v[0]<g[0])&&(g=v)}return g[1]},u=[];for(const[d,f]of o){let m="unknown";for(const[,b]of f){const k=yE(b);Eg[k]>Eg[m]&&(m=k)}const g=l(f,Ad,!0),v=l(f,rd,!1),w=l(f,rd,!0),x=f.map(([,b])=>fn(b.session_kind)).find(Boolean)??"",j=f.map(([,b])=>fn(b.automation_id)).find(Boolean)??"";u.push({session_id:d,state:m,updated_at:Ad(g),created_at:rd(v),first_run_id:fn(v.run_id),latest_run_id:fn(w.run_id),turns:f.length,session_kind:x,automation_id:x==="discussion"?j:"",workspace_root:fn(w.workspace_root),workspace_reported:"workspace_root"in w})}return u.sort((d,f)=>d.session_id<f.session_id?-1:d.session_id>f.session_id?1:0),u.sort((d,f)=>{const m=Fo(d.updated_at),g=Fo(f.updated_at);return m===g?0:m>g?-1:1}),{rows:u,truncated:s}}function _E(e){const t=e&&typeof e=="object"?e:{};for(const n of[t.input_data,t]){if(!n||typeof n!="object")continue;const s=n,o=fn(s.prompt);if(o)return o;const l=s.context;if(l&&typeof l=="object"){const u=fn(l.task);if(u)return u}}return""}const bE=4,xE=40;async function kE(e,t,n){const s=new Array(e.length);let o=0;const l=async()=>{for(;o<e.length;){const u=o++;s[u]=await n(e[u])}};return await Promise.all(Array.from({length:Math.max(1,Math.min(t,e.length))},l)),s}async function jE(e,t,n){const s=e.filter(l=>!t.has(l.session_id)).slice(0,xE);let o=0;return await kE(s,bE,async l=>{try{t.set(l.session_id,_E(await n(l.first_run_id)))}catch{o+=1}}),{fetched:s.length-o,failed:o}}function SE(e,t){const n=typeof e.session_id=="string"?e.session_id:"";return n&&t.has(n)?!0:(e.origin&&typeof e.origin=="object"?e.origin:{}).kind==="person"}const NE=200;function CE(e,t){const n=p.useRef(0),s=p.useRef(new Set),[o,l]=p.useState({}),[u,d]=p.useState([]),[f,m]=p.useState(!1),[g,v]=p.useState({}),[w,x]=p.useState(""),[j,b]=p.useState(""),[k,$]=p.useState(""),S=p.useRef(new Map),N=p.useRef(new Set),C=p.useRef(t.onSignedOut);C.current=t.onSignedOut;const R=p.useRef(t.onAttentionSeen);R.current=t.onAttentionSeen;const E=p.useRef(t.onSessionRead);E.current=t.onSessionRead;const I=p.useCallback(async()=>{try{const L=++n.current,[D,P]=await Promise.allSettled([e.listSessionRuns(NE),e.listWaitingRuns()]);if(L!==n.current)return;if(D.status==="rejected")throw D.reason;const K=wE(D.value),se=PS(D.value),Q=P.status==="fulfilled"&&Array.isArray(P.value.items)?P.value.items:[],z=P.status==="fulfilled"&&P.value.has_more===!1;if(!z)for(const J of s.current)se[J]&&(se[J].needsAttention=!0);for(const J of Q)J&&typeof J.session_id=="string"&&uy(J)&&se[J.session_id]&&(se[J.session_id].needsAttention=!0);s.current=new Set(Object.keys(se).filter(J=>se[J].needsAttention)),l(se),d(K.rows),N.current=new Set(K.rows.map(J=>J.session_id)),m(K.truncated),x("");const T=await jE(K.rows,S.current,J=>e.inputData(J));if(L!==n.current)return;const q=P.status==="rejected"?"Pending questions and approvals could not be refreshed. ":z?"":"Pending questions and approvals are partially listed. ";b(q+(T.failed?`${T.failed} conversation title${T.failed===1?"":"s"} could not be loaded; they will be asked again.`:"")),v(Object.fromEntries(S.current))}catch(L){x(L instanceof Error?L.message:String(L)),(L==null?void 0:L.status)===401&&C.current()}},[e,t.scope]);return p.useEffect(()=>(S.current.clear(),s.current.clear(),d([]),l({}),v({}),I(),()=>{n.current++}),[I]),p.useEffect(()=>{const L=new AbortController;let D;return(async()=>{try{const P=await e.meEvents(0,1),K=typeof P.head=="number"?P.head:0;$(""),await e.followMeEvents(K,se=>{var T,q;const Q=String(se.type||"");Q==="session.read"&&((T=E.current)==null||T.call(E));const z=se.data||{};Q==="attention.raised"&&typeof z.wait_key=="string"&&typeof z.session_id=="string"&&s.current.add(z.session_id),(Q==="attention.raised"||Q==="attention.seen"||(Q==="run.started"||Q==="run.finished")&&SE(z,N.current))&&(clearTimeout(D),D=setTimeout(()=>void I(),500)),Q==="attention.seen"&&typeof z.wait_key=="string"&&typeof z.run_id=="string"&&((q=R.current)==null||q.call(R,{run_id:z.run_id,wait_key:z.wait_key,...typeof z.step_id=="string"?{step_id:z.step_id}:{},outcome:String(z.outcome||"answered")}))},L.signal)}catch(P){L.signal.aborted||$(`Updates from your other devices are off: ${P instanceof Error?P.message:String(P)}`)}})(),()=>{L.abort(),clearTimeout(D)}},[e,I]),{rows:u,activity:o,titles:g,truncated:f,error:w,notice:j,eventsError:k,refresh:I}}function fw(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.`}var hw=()=>{var e;return(e=globalThis.navigator)==null?void 0:e.mediaDevices};function EE(e){var o;const t=fw("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=hw())!=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 TE(e){const t=hw();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 pw(){const e=globalThis;return e.AudioContext||e.webkitAudioContext||null}function AE(){const e=pw();return!!(e&&e.prototype&&typeof e.prototype.createMediaStreamDestination=="function")}function $E(e,t,n=1){var d;const s=pw();if(!s)return()=>{};const o=new s,l=o.createMediaStreamSource(e);try{Promise.resolve(o.resume()).catch(()=>{})}catch{}let u;try{u=mw(o,l,t,n)}catch(f){throw l.disconnect(),(d=o.close)==null||d.call(o),f}return()=>{var f;u(),(f=o.close)==null||f.call(o)}}function mw(e,t,n,s=1){const o=e.createAnalyser();o.fftSize=1024,t.connect(o);const l=new Float32Array(o.fftSize);let u=!0;const f=setInterval(()=>{if(!u)return;o.getFloatTimeDomainData(l);let m=0;for(let g=0;g<l.length;g+=1)m+=l[g]*l[g];n(Math.min(1,Math.sqrt(m/l.length)*4*s))},50);return()=>{var m;u=!1,clearInterval(f);try{t.disconnect(o)}catch{}(m=o.disconnect)==null||m.call(o),n(0)}}function Tg(e){const t=Number(e);return e==null||e===""||!Number.isFinite(t)?1:Math.min(1,Math.max(0,t))}function Ag(e){return(e&&typeof e=="object"?e.capture_mode:e)==="toggle"?"toggle":"hold"}function $g(e){if(e==null)return"";if(typeof e=="string")return`s:${e}`;const t=Object.keys(e).filter(n=>e[n]!==void 0&&e[n]!==null&&e[n]!=="").sort();return`o:${JSON.stringify(t.map(n=>[n,e[n]]))}`}function Ba(e,t){const n=String((t==null?void 0:t.message)||t||"").trim().replace(/\.$/,"");return n?`${e}: ${n}.`:`${e}.`}var RE=350;function ME(){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 LE(){if(typeof window>"u")return!1;const e=window;return!!(e!=null&&e.AudioContext||e!=null&&e.webkitAudioContext)}function IE(){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 sd(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 PE(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 OE(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}var Bo=new WeakMap;function DE(e,t){const n=e;if(!(typeof n.setSinkId!="function"||Bo.get(e)===t)){Bo.set(e,t);try{Promise.resolve(n.setSinkId(t)).catch(()=>Bo.delete(e))}catch{Bo.delete(e)}}}function FE(e){const t=p.useRef(e);t.current=e;const n=U=>{var ie,ue;return(ue=(ie=t.current).on_error)==null?void 0:ue.call(ie,U)},s=p.useMemo(()=>LE()&&(typeof e.tts=="function"||typeof e.tts_stream=="function"),[e.tts,e.tts_stream]),o=p.useMemo(()=>ME()&&typeof e.transcribe=="function",[e.transcribe]),l=p.useRef(0),u=p.useRef(new Set),d=p.useRef(null),f=p.useCallback(U=>{const ie=Math.round(Math.min(1,Math.max(0,Number(U)||0))*20)/20;if(ie!==l.current){l.current=ie;for(const ue of Array.from(u.current))ue(ie)}},[]),m=p.useCallback(()=>{const U=d.current;d.current=null,U==null||U(),f(0)},[f]),[g,v]=p.useState({key:"",status:"idle"}),w=p.useRef(g),x=p.useCallback(U=>{w.current=U,U.status!=="playing"&&m(),v(ie=>ie.key===U.key&&ie.status===U.status?ie:U)},[m]),j=p.useRef(""),b=p.useRef(""),k=p.useRef(null),$=p.useRef(null),S=p.useCallback(()=>{if(!u.current.size||d.current||w.current.status!=="playing")return;const U=k.current,ie=$.current;if(!(!U||!ie))try{d.current=mw(U,ie,ue=>f(U.state==="running"&&w.current.status==="playing"?ue:0))}catch{}},[f]),N=p.useCallback(U=>(u.current.add(U),U(l.current),S(),()=>{u.current.delete(U),u.current.size||m()}),[S,m]),C=p.useRef(null),R=p.useRef(null),E=p.useRef(0),I=p.useRef(0),L=p.useRef(0),D=p.useRef(null),P=p.useRef([]),K=p.useRef(0),se=p.useRef([]),Q=p.useRef(!0),z=p.useRef(!1),T=p.useRef(""),q=(U,ie)=>{const ue=$g(t.current.tts_voice);return ue?`${U}${ie}${ue}`:""},J=()=>{try{const U=globalThis,ie=(U==null?void 0:U.AudioContext)||(U==null?void 0:U.webkitAudioContext);if(!ie)return null;if(!k.current){const Ne=new ie,Te=Ne.createGain();Te.gain.value=1,Te.connect(Ne.destination),k.current=Ne,$.current=Te}const ue=k.current,we=$.current;if(!ue||!we)return null;DE(ue,t.current.output_device_id||""),we.gain.value=Tg(t.current.volume)*(t.current.muted?0:1);try{ue.state==="suspended"&&ue.resume()}catch{}return{ctx:ue,gain:we}}catch{return null}};p.useEffect(()=>{const U=$.current;U&&(U.gain.value=Tg(e.volume)*(e.muted?0:1))},[e.volume,e.muted]);const B=p.useCallback(()=>{m();const U=se.current;se.current=[];for(const ue of U){try{ue.src.onended=null}catch{}try{ue.src.stop()}catch{}try{ue.src.disconnect()}catch{}}const ie=C.current;if(C.current=null,!!ie){try{ie.onended=null}catch{}try{ie.stop()}catch{}try{ie.disconnect()}catch{}}},[m]),O=p.useCallback(()=>{var U;B(),L.current+=1,(U=D.current)==null||U.abort(),D.current=null,P.current=[],K.current=0,Q.current=!0,z.current=!1,b.current="",j.current="",R.current=null,T.current="",E.current=0,I.current=0,x({key:"",status:"idle"})},[B,x]),Z=$g(e.tts_voice),M=p.useRef(Z);p.useEffect(()=>{M.current!==Z&&(M.current=Z,w.current.status==="paused"&&O())},[Z,O]),p.useEffect(()=>()=>{var U,ie;O();try{(U=$.current)==null||U.disconnect()}catch{}try{(ie=k.current)==null||ie.close()}catch{}k.current=null,$.current=null,R.current=null},[]);const W=async(U,ie,ue)=>{const we=L.current,Ne=J();if(!Ne)throw new Error("TTS playback is not supported in this browser");const{ctx:Te,gain:Fe}=Ne;try{Te.state==="suspended"&&await Te.resume()}catch{}if(we!==L.current)return;B();const xe=Te.createBufferSource();xe.buffer=ie,xe.connect(Fe);const Be=Number.isFinite(Number(ie.duration))?Number(ie.duration):0,Ke=Math.max(0,Math.min(Number(ue||0),Be>0?Math.max(0,Be-.01):0));I.current=Te.currentTime-Ke,E.current=Ke,C.current=xe,j.current=U,xe.onended=()=>{C.current===xe&&(C.current=null,E.current=0,I.current=0,j.current="",x({key:"",status:"idle"}))},xe.start(0,Ke),x({key:U,status:"playing"}),S()},Y=(U,ie)=>{if(ie!==L.current||z.current)return;const ue=J();if(!ue)return;const we=P.current,Ne=se.current,Te=Ne.length?Ne[Ne.length-1]:null;let Fe=Te?Te.idx+1:K.current;if(!Te&&Fe>=we.length){Q.current&&(j.current="",E.current=0,I.current=0,x({key:"",status:"idle"}));return}const{ctx:xe,gain:Be}=ue;try{xe.state==="suspended"&&xe.resume()}catch{}const Ke=Number(xe.currentTime||0);let ot=Te?Math.max(Te.at+Te.dur,Ke):Ke+.02;for(;Fe<we.length;Fe++){const Ut=we[Fe],tt=Number.isFinite(Number(Ut.duration))?Number(Ut.duration):0,bt=!Te&&Fe===K.current?Math.max(0,Math.min(Number(E.current||0),tt>0?Math.max(0,tt-.01):0)):0,Lt=xe.createBufferSource();Lt.buffer=Ut,Lt.connect(Be);const $n={src:Lt,idx:Fe,at:ot,off:bt,dur:Math.max(0,tt-bt)};Lt.onended=()=>{if(ie!==L.current)return;const hn=se.current,zn=hn.indexOf($n);zn<0||(hn.splice(zn,1),K.current=$n.idx+1,E.current=0,hn.length||Y(U,ie))},Lt.start(ot,bt),se.current.push($n),ot+=$n.dur}I.current=se.current.length?se.current[0].at-se.current[0].off:0,j.current=U,x({key:U,status:"playing"}),S()},oe=U=>{const ie=se.current;if(!ie.length)return{idx:K.current,off:0};for(const we of ie){if(U<we.at)return{idx:we.idx,off:we.off};if(U<we.at+we.dur)return{idx:we.idx,off:we.off+(U-we.at)}}return{idx:ie[ie.length-1].idx+1,off:0}},de=async(U,ie,ue)=>{var xe;const we=J();if(!we){n==null||n("This browser cannot play spoken replies.");return}B();const Ne=++L.current;(xe=D.current)==null||xe.abort();const Te=new AbortController;D.current=Te,P.current=[],K.current=0,Q.current=!1,z.current=!1,R.current=null,E.current=0,I.current=0,j.current=U,b.current=U,T.current=q(U,ie),x({key:U,status:"loading"}),n==null||n("");let Fe=null;try{for await(const Be of ue(ie,Te.signal)){if(Ne!==L.current)return;let Ke;try{Ke=await sd(we.ctx,Be),Fe||(Fe=PE(Be))}catch{if(!Fe)continue;try{Ke=await sd(we.ctx,OE(Fe,Be))}catch{continue}}if(Ne!==L.current)return;P.current.push(Ke),z.current||(b.current="",Y(U,Ne))}if(Ne!==L.current)return;if(Q.current=!0,P.current.length===0){n==null||n("Reading aloud failed: the voice engine returned no audio."),O();return}!se.current.length&&!z.current&&Y(U,Ne)}catch(Be){if(Ne!==L.current)return;n==null||n(Ba("Reading aloud failed",Be)),O()}finally{D.current===Te&&(D.current=null)}},me=p.useCallback(async(U,ie)=>{var Ut;const ue=String(U||"").trim(),we=String(ie||"").trim();if(!ue||!we)return;const Ne=t.current.tts,Te=t.current.tts_stream;if(typeof Ne!="function"&&typeof Te!="function"){n==null||n("Reading aloud is not available on this gateway.");return}const Fe=J();if(!Fe){n==null||n("This browser cannot play spoken replies.");return}const xe=w.current,Be=xe.key===ue;if(Be&&xe.status==="playing"){if(se.current.length){const tt=oe(Number(Fe.ctx.currentTime||0));K.current=tt.idx,E.current=tt.off}else if(C.current){const tt=Math.max(0,Fe.ctx.currentTime-Number(I.current||0));E.current=tt}else E.current=0;z.current=!0,B(),x({key:ue,status:"paused"});return}const Ke=Be&&xe.status==="paused"&&T.current!==""&&T.current===q(ue,we);if(Be&&xe.status==="paused"&&!Ke&&O(),Ke){if(P.current.length>0){n==null||n(""),z.current=!1,x({key:ue,status:"playing"}),Y(ue,L.current);return}const tt=R.current;if(tt){n==null||n(""),z.current=!1;try{await W(ue,tt,E.current)}catch(bt){n==null||n(Ba("Reading aloud failed",bt)),x({key:"",status:"idle"})}return}}if(Be&&xe.status==="loading")return;if(typeof Te=="function"){await de(ue,we,Te);return}B(),L.current+=1,(Ut=D.current)==null||Ut.abort(),D.current=null;const ot=L.current;P.current=[],K.current=0,Q.current=!0,z.current=!1,R.current=null,E.current=0,I.current=0,j.current=ue,b.current=ue,T.current=q(ue,we),x({key:ue,status:"loading"}),n==null||n("");try{const tt=await Ne(we);if(b.current!==ue||L.current!==ot)return;const bt=await sd(Fe.ctx,tt);if(b.current!==ue||L.current!==ot)return;R.current=bt,E.current=0,await W(ue,bt,0)}catch(tt){if(L.current!==ot)return;b.current===ue&&(b.current="",j.current="",x({key:"",status:"idle"})),n==null||n(Ba("Reading aloud failed",tt))}},[]),[ee,ce]=p.useState(!1),[ye,Ce]=p.useState(!1),ze=p.useRef(!1),Ve=p.useRef(o);Ve.current=o;const Ee=p.useCallback(U=>{ze.current=U,ce(ie=>ie===U?ie:U)},[]),je=p.useRef(!1),Ue=p.useRef(null),ne=p.useRef(null),$e=p.useRef([]),Pe=p.useRef(""),Ge=p.useRef(0),G=p.useRef(!1),fe=p.useRef(!1),[te,pe]=p.useState(0),Se=p.useRef(0),Ze=p.useRef(null),Ye=p.useRef(0),rt=p.useRef(new Set),V=p.useRef(null),he=p.useCallback(U=>{const ie=Math.round(Math.min(1,Math.max(0,Number(U)||0))*20)/20;if(ie!==Ye.current){Ye.current=ie;for(const ue of Array.from(rt.current))ue(ie)}},[]),Je=p.useCallback(U=>(rt.current.add(U),U(Ye.current),()=>{rt.current.delete(U)}),[]),Oe=p.useRef(new Set),_t=p.useCallback(U=>(Oe.current.add(U),()=>{Oe.current.delete(U)}),[]);function Nt(){var ue,we;const U=V.current;V.current=null;try{U==null||U()}catch{}he(0);try{(we=(ue=Ue.current)==null?void 0:ue.getTracks)==null||we.call(ue).forEach(Ne=>{try{Ne.stop()}catch{}})}catch{}Ue.current=null;const ie=Ze.current;Ze.current=null;try{ie==null||ie.close()}catch{}}const zt=p.useCallback(()=>{Ge.current+=1,G.current=!1;const U=ne.current;if(U){U.onstop=null,U.ondataavailable=null,U.onerror=null;try{U.stop()}catch{}}ne.current=null,Nt(),Ee(!1),je.current=!1,Ce(!1),pe(0),$e.current=[]},[Ee]);p.useEffect(()=>()=>zt(),[zt]);async function An(U,ie){var Te,Fe;if(n==null||n(""),je.current)return;const ue=Se.current?Date.now()-Se.current:1/0;if(!U||!U.size||ue<RE){pe(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 we=t.current.transcribe;if(typeof we!="function"){n==null||n("Speech to text is not available on this gateway.");return}je.current=!0;const Ne=Ge.current;Ce(!0),pe(Date.now());try{const xe=await we(U,ie),Be=typeof xe=="string"||!xe?{text:String(xe||"")}:xe,Ke=String(Be.text||"").trim();if(Ne!==Ge.current)return;if(Ke){(Fe=(Te=t.current).on_transcript)==null||Fe.call(Te,Ke,{...Be,text:Ke});for(const ot of Array.from(Oe.current))ot(Ke,{...Be,text:Ke})}else n==null||n("Nothing was heard. Check the microphone in Settings → Voice (Test), then try again.")}catch(xe){if(Ne===Ge.current){const Be=String((xe==null?void 0:xe.message)||xe||"").trim().replace(/\.$/,"");n==null||n(Be?`Transcription failed: ${Be}.`:"Transcription failed.")}}finally{Ne===Ge.current&&(je.current=!1,Ce(!1),pe(0))}}const ht=p.useCallback(async()=>{if(n==null||n(""),!Ve.current){n==null||n(fw("the microphone")??"Voice recording is not supported in this browser (MediaRecorder/getUserMedia unavailable).");return}if(je.current||G.current||ze.current||ne.current)return;$e.current=[];const U=Ge.current;G.current=!0,fe.current=!1;try{const ie=await TE(t.current.input_device_id||"");if(U!==Ge.current){ie.getTracks().forEach(xe=>xe.stop());return}if(fe.current){fe.current=!1,ie.getTracks().forEach(xe=>xe.stop()),pe(0);return}Ue.current=ie;const ue=Number(t.current.input_gain??1);try{V.current=$E(ie,he,Number.isFinite(ue)&&ue>0?ue:1)}catch{}const we=IE();Pe.current=we;let Ne=ie;const Te=Number(t.current.input_gain??1);if(Number.isFinite(Te)&&Te>0&&Te!==1&&AE()){const xe=globalThis.AudioContext||globalThis.webkitAudioContext,Be=new xe,Ke=Be.createGain();Ke.gain.value=Te;const ot=Be.createMediaStreamDestination();Be.createMediaStreamSource(ie).connect(Ke),Ke.connect(ot),Ze.current=Be,Ne=ot.stream}const Fe=we?new MediaRecorder(Ne,{mimeType:we}):new MediaRecorder(Ne);ne.current=Fe,Fe.ondataavailable=xe=>{if(U===Ge.current)try{xe!=null&&xe.data&&$e.current.push(xe.data)}catch{}},Fe.onerror=()=>{U===Ge.current&&(n==null||n("Recording failed. Try again, or pick another microphone in Settings → Voice."))},Fe.onstop=()=>{if(U===Ge.current){Ee(!1),Nt(),ne.current=null;try{const xe=new Blob($e.current,{type:Pe.current||""});An(xe,Pe.current)}catch(xe){n==null||n(Ba("The recording could not be prepared",xe))}}},Fe.start(),Se.current=Date.now(),pe(Se.current),Ee(!0)}catch(ie){if(U!==Ge.current)return;Nt(),ne.current=null,Ee(!1),pe(0),n==null||n(EE(ie))}finally{U===Ge.current&&(G.current=!1)}},[]),Tt=p.useCallback(()=>{const U=ne.current;if(G.current&&!U){fe.current=!0;return}if(!(!ze.current||!U)){Ee(!1);try{U.stop()}catch(ie){n==null||n(Ba("The recording could not stop",ie))}}},[]);return p.useEffect(()=>{if(!ee||t.current.stop_on_pointerup===!1||t.current.stop_on_pointerup===void 0&&Ag(t.current.capture_mode)==="toggle")return;const U=()=>Tt();return window.addEventListener("pointerup",U),window.addEventListener("pointercancel",U),()=>{window.removeEventListener("pointerup",U),window.removeEventListener("pointercancel",U)}},[ee]),{tts_supported:s,tts_playback:g,toggle_tts:me,stop_tts:O,voice_ptt_supported:o,voice_ptt_recording:ee,voice_ptt_busy:ye,start_voice_ptt_recording:ht,stop_voice_ptt_recording:Tt,cancel_voice_ptt_recording:zt,voice_ptt_since:te,subscribe_level:Je,subscribe_playback_level:N,voice_capture_mode:Ag(e.capture_mode),add_transcript_listener:_t}}function BE(e,t){return{getRun:n=>e.getRun(n),getHistory:n=>e.historyBundle(n),getLedger:(n,s)=>e.ledgerPage(n,s),async streamLedger(n,s,o,l,u,d){await e.streamLedger(n,s,{onStep:f=>o({cursor:f.cursor,record:f.record}),onOpen:u,...d?{onDelta:(f,m)=>{let g;try{g=ZS(f,m)}catch(v){t.onDeltaError(v instanceof Error?v.message:String(v));return}g&&d(g)}}:{}},l)},submitCommand:n=>e.submitCommand({...n,client_id:n.client_id||"abstractassistant-web"}),replayView:sN({fetch:e.replayFetch})}}function zE(e,t){const n=[];for(const s of e||[]){if(!s||typeof s!="object")continue;const o=String(s.role??"").trim();if(!["user","assistant","system"].includes(o))continue;const l=String(s.content??"");l.trim()&&n.push({role:o,content:l})}return t<=0?n:n.slice(-t)}const zo=e=>typeof e=="number"&&Number.isFinite(e),Rg=e=>!!e&&typeof e=="object"&&!!e.$artifact;function UE(e){const t=String(e.prompt??""),n=String(e.system??""),s=!!(e.use_context??!1),o=e.use_session_history??!0,l=(e.attachments||[]).filter(Rg).map($=>({...$})),u=s?zE(e.messages||[],200):[],d=Rg(e.primary_image_artifact)&&String(e.primary_image_artifact.$artifact).trim()?{...e.primary_image_artifact}:null,f={task:t,messages:u};l.length&&(f.attachments=l,f.media=l),d&&(f.primary_image_artifact=d);const m={};zo(e.temperature)&&(m.temperature=e.temperature),zo(e.seed)&&Number.isInteger(e.seed)&&(m.seed=e.seed);const g=String(e.provider??"").trim(),v=String(e.model??"").trim(),w=String(e.base_url??"").trim(),x=!!(g&&v);x&&(m.provider=g,m.model=v,w&&(m.base_url=w));const j=String(e.thinking??"").trim().toLowerCase();if(j&&(m.thinking=j),e.stream!==void 0&&e.stream!==null){if(typeof e.stream!="boolean")throw new Error(`stream must be null, true or false, not ${JSON.stringify(e.stream)}`);m.stream=e.stream}const b={prompt:t,context:f,use_context:s,use_session_history:!!o,_runtime:m,max_iterations:Math.max(1,Math.trunc(e.max_iterations??50)),has_primary_image_context:d!==null};x&&(b.provider=g,b.model=v,w&&(b.base_url=w)),n&&(b.system=n),l.length&&(b.attachments=l),d&&(b.primary_image_artifact=d),zo(e.temperature)&&(b.temperature=e.temperature),zo(e.seed)&&Number.isInteger(e.seed)&&(b.seed=e.seed);const k=String(e.workspace_root??"").trim();return k&&(b.workspace_root=k),b}const WE="abstractassistant.agent.v1",VE="abstractassistant-orchestrator";class Uo extends Error{constructor(t){super(t),this.name="WorkflowUnavailable"}}const Fn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),wn=e=>typeof e=="string"?e.trim():"";function qE(e,t){if(!Fn(e))return"The gateway's workflow list was not a JSON object.";const n=wn(e.executable_for);if(n!==t)return n?`The gateway listed workflows for ${n}, not ${t}.`:"This gateway does not filter workflows per app (no executable_for in its answer): update the gateway.";if(!Array.isArray(e.items))return"The gateway's workflow list has no items.";for(const s of e.items){if(!Fn(s)||!wn(s.bundle_id))return"The gateway listed a workflow without a bundle id.";const o=wn(s.bundle_id),l=s.owner;if(!Fn(l)||!["gateway","user"].includes(String(l.kind)))return`The gateway did not say who owns ${o} (owner missing): update the gateway.`;if(typeof s.shipped!="boolean")return`The gateway did not say whether ${o} ships with it (shipped missing): update the gateway.`;for(const u of Array.isArray(s.entrypoints)?s.entrypoints:[]){if(!Fn(u))return`The gateway listed an invalid entrypoint for ${o}.`;if(!(Array.isArray(u.interfaces)?u.interfaces.map(f=>String(f).trim()):[]).includes(t))return`The gateway offered ${o}:${wn(u.flow_id)}, which does not declare ${t}: update the gateway.`}}return"default_agent_workflows"in e?"":"This gateway does not report its default agent workflows (contract D): update the gateway."}function HE(e){let t=wn(e);if(!t)return"@default";let n="private";t.startsWith("catalog:")?(n="tenant_catalog",t=t.slice(8)):t.startsWith("private:")&&(t=t.slice(8));const s=t.indexOf(":");if(s<0)return"@default";const o=t.slice(0,s).split("@")[0].trim(),l=t.slice(s+1).trim();return!o||!l?"@default":{bundle_id:o,flow_id:l,registry_scope:n}}function Mg(e){return e.split(/[.\-+]/).map(t=>/^\d+$/.test(t)?Number(t):-1)}function GE(e,t){const n=Mg(e),s=Mg(t);for(let o=0;o<Math.max(n.length,s.length);o++){const l=(n[o]??-1)-(s[o]??-1);if(l)return l>0}return!1}function KE(e){const t=[];for(const n of e.items){const s=wn(n.bundle_id),o=wn(n.bundle_version);if(!(!s||!o))for(const l of Array.isArray(n.entrypoints)?n.entrypoints:[]){const u=wn(l.flow_id);u&&t.push({bundle_id:s,bundle_version:o,flow_id:u,registry_scope:wn(n.registry_scope)||"private",label:wn(l.name)||u})}}return t}function Lg(e){let t;for(const n of e)(!t||GE(n.bundle_version,t.bundle_version))&&(t=n);return t}function JE(e,t,n=WE){const s=qE(e,n);if(s)throw new Uo(s);const o=e,l=Fn(t)?t.preferences:void 0,u=Fn(l)?l.default_workflow:void 0;if(!Fn(u))throw new Uo("This gateway does not keep account preferences (preferences.default_workflow): update the gateway.");const d=HE(u[n]),f=KE(o);if(d==="@default"){const v=o.default_agent_workflows,w=Fn(v)?v[n]:void 0;if(Fn(w))return{flow_id:"@default",interface:n,label:wn(w.name)||wn(w.bundle_id)||"Gateway default",source:"gateway_default"};const x=Lg(f.filter(k=>k.bundle_id===VE));if(x)return{...x,source:"built_in"};const j=o.default_agent_workflows_unavailable,b=Fn(j)&&Fn(j[n])?wn(j[n].reason):"";throw new Uo(`No Assistant workflow is available on this gateway${b?`: ${b}`:""}. Open the desktop Assistant once, or ask the gateway's admin to install it: this page never installs workflows.`)}const m=f.filter(v=>v.bundle_id===d.bundle_id&&v.flow_id===d.flow_id),g=Lg(m);if(!g)throw new Uo(`The workflow chosen for your account (${d.bundle_id}:${d.flow_id}) is not available on this gateway any more. Choose another in the Assistant's settings.`);return{...g,source:"account_choice"}}function YE(e){const t=[],n=[];for(const s of e)s.role==="system"&&s.level==="info"&&String(s.id||"").startsWith("stream-unavailable:")?t.push(s):n.push(s.role==="assistant"&&!s.title?{...s,title:"Assistant"}:s);return{conversation:n,diagnostics:t}}function QE(e){return e.recording?{pose:"listening",label:"Listening",hint:"Your words will appear here before you send."}:e.transcribing?{pose:"thinking",label:"Writing down what you said",hint:"One moment…"}:e.pending?{pose:"waiting",label:"Needs you",hint:"There’s a request to review in the conversation."}:e.loading?{pose:"thinking",label:"Opening your conversation",hint:"Reading the history from your Gateway."}:e.busy?e.working?{pose:"working",label:"Working",hint:"Taking care of your request."}:{pose:"thinking",label:"Thinking",hint:"Making sense of your question."}:e.playback==="playing"?{pose:"speaking",label:"Speaking",hint:"Tap to pause. Your answer is below."}:e.playback==="paused"?{pose:"waiting",label:"Paused",hint:"Tap to keep listening."}:e.playback==="loading"?{pose:"thinking",label:"Getting ready to speak",hint:"Preparing your answer’s audio."}:e.failed?{pose:"error",label:"Something went wrong",hint:"The conversation explains what happened."}:{pose:"ready",label:"Ready when you are",hint:"Talk to me, or write a message below."}}function XE(e,t){return[...e].reverse().find(n=>n.role==="assistant"&&n.runId===t&&!n.live&&!n.toolActivity&&n.content.trim())}function ZE(){return`sess_${crypto.randomUUID().replace(/-/g,"")}`}const Zo=new Set(["completed","failed","cancelled"]);function eT(e){const t=new Map,n=e&&typeof e=="object"&&Array.isArray(e.items)?e.items:[];for(const s of n){if(!s||typeof s!="object")continue;const o=s,l=typeof o.name=="string"?o.name.trim():"",u=typeof o.toolset=="string"?o.toolset.trim():"";l&&u&&t.set(l,u)}return t}function tT(e,t,n,s){if(!e||!Zo.has(t)||t==="cancelled")return"";if(t==="failed"){const l=typeof(n==null?void 0:n.error)=="string"?n.error.trim():"";return l?`The run failed: ${l}`:"The run failed (the gateway gave no reason)."}return s.some(l=>{var u;return l.role==="assistant"&&!l.live&&!l.toolActivity&&(l.id===`final:${e}`||String(l.id||"").startsWith(`answer:${e}:`)||l.runId===e&&!!((u=l.content)!=null&&u.trim()))})?"":"The run ended without a written reply."}function nT(e,t){return!e||!t||e.run_id!==t.runId||e.wait_key!==t.waitKey?!1:!e.step_id||!t.stepId||e.step_id===t.stepId}function rT(e){var Pe,Ge;const{client:t,host:n}=e,[s,o]=p.useState(""),l=qC(`abstractassistant:${e.readScope}`),u=l.mode==="avatar",[d,f]=p.useState(null),[m,g]=p.useState(!1);p.useEffect(()=>f(null),[e.readScope,e.sessionId]);const[v,w]=p.useState(""),[x,j]=p.useState(!1),b=p.useRef(null),k=p.useRef(!0),$=p.useRef(""),S=p.useRef(""),N=p.useCallback(()=>e.sessionId?e.sessionId:(S.current||(S.current=ZE()),S.current),[e.sessionId]);p.useEffect(()=>{!e.sessionId&&!e.runId&&(S.current="")},[e.sessionId,e.runId]);const C=p.useRef(e.onSignedOut);C.current=e.onSignedOut;const R=p.useCallback(()=>C.current(),[]),E=p.useMemo(()=>BE(t,{onDeltaError:G=>w(`A live reply frame was malformed and skipped: ${G}`)}),[t]),{controller:I,snapshot:L}=VC({transport:E,runId:e.runId,clientId:"abstractassistant-web",onAuthError:R}),D=p.useRef(null);p.useEffect(()=>{let G=!1;const fe=e.sessionId;if(!fe){I.setSessionToolPolicyClient(null);return}return D.current??(D.current=t.capabilities()),D.current.then(te=>{if(G)return;const pe=V1(te);I.setSessionToolPolicyClient(pe?H1(t.policyRequest,fe,pe,{client:"abstractassistant-web"}):null)},te=>{D.current=null,G||I.setSessionToolPolicyClient(null,{reason:`Could not read the gateway's capabilities (${te instanceof Error?te.message:String(te)}).`})}),()=>{G=!0}},[I,t,e.sessionId]);const[P,K]=p.useState(new Map);p.useEffect(()=>{let G=!1;return t.discoveryTools().then(fe=>!G&&K(eT(fe)),()=>{}),()=>{G=!0}},[t]);const se=p.useRef("");p.useEffect(()=>{e.runId&&Zo.has(L.status)&&se.current!==e.runId&&(se.current=e.runId,e.onTurnEnded())},[e.runId,L.status,e]);const Q=iN(L),z=Q?{runId:Q.runId,waitKey:String(Q.wait.wait_key||""),stepId:Q.stepId}:null,T=z?`${z.runId}|${z.waitKey}|${z.stepId||""}`:"",[q,J]=p.useState(""),B=nT(e.seen,z),O=p.useMemo(()=>Q?XC(Q,I,{records:L.records,currentRun:L.run,allowSkip:!0,onDefer:()=>J(T),sessionPolicy:{toolsetOf:G=>P.get(G)}}):null,[Q,I,L.records,L.run,L.sessionPolicyMode,L.sessionPolicyReason,L.sessionPolicyClamped,L.sessionPolicy,P,T]),Z=O&&q!==T&&!B?O:null,M=p.useRef(e.runId);M.current=e.runId;const W=p.useRef(e.voicePrefs);W.current=e.voicePrefs;const Y=FE({...Tv(e.voicePrefs),capture_mode:e.captureMode,tts_stream:n.capabilities.audioPlayback.available?async function*(G,fe){const te=M.current;if(!te)throw new Error("Read aloud needs a conversation turn on the gateway");yield*Zx({path:n.gatewayUrl(`runs/${encodeURIComponent(te)}/voice/tts/stream`),headers:n.auth.headers(!0),body:{text:G,...Wd(W.current)},...fe?{signal:fe}:{}})}:void 0,transcribe:n.capabilities.microphone.available?async(G,fe)=>{const te=N(),pe=(fe||"audio/webm").split(";")[0],Se=pe.includes("mp4")?"m4a":pe.includes("ogg")?"ogg":"webm",Ze=await t.uploadAttachment(te,G,`ask.${Se}`,{content_type:pe,source_path:`voice/dictation/${crypto.randomUUID()}.${Se}`}),Ye=Object.fromEntries(Object.entries(N1(W.current)).filter(([,rt])=>typeof rt=="string"&&rt));return t.transcribe(Ze.ownerRunId||`session_memory_${te}`,String(Ze.ref.$artifact),Ye)}:void 0,on_error:G=>w(G)}),oe=p.useRef(Y);oe.current=Y,p.useEffect(()=>(k.current=!0,()=>{var G,fe;k.current=!1,oe.current.stop_tts(),(fe=(G=oe.current).cancel_voice_ptt_recording)==null||fe.call(G)}),[]);const de=JS({upload:async G=>(await t.uploadAttachment(N(),G,G.name,G.type?{content_type:G.type}:{})).ref}),me=!!e.runId&&!Zo.has(L.status)&&!(L.error&&!L.run),ee=p.useCallback(async G=>{var Je;if(oe.current.stop_tts(),me){if(!u)throw new Error("The assistant is still working.");if((O==null?void 0:O.kind)==="ask-user")await O.onSubmit(G);else{if(O)throw new Error("Use the request controls to answer it. A message does not grant permission.");const Oe=Y2(G,d,e.runId,((Je=L.view)==null?void 0:Je.root_run_id)===e.runId?L.view.runs.map(Nt=>Nt.run_id):[]),_t=await I.sendCommand("inject_guidance",{guidance:Oe,display_text:G});if((_t==null?void 0:_t.accepted)===!1)throw new Error("Your message was not accepted. Please try again.")}if(!k.current)return;o(""),f(null),w("Sent. Your message is available to the assistant.");return}const fe=N(),te=de.attached,[pe,Se,Ze]=await Promise.all([t.executableBundles("abstractassistant.agent.v1"),t.accountPreferences(),t.discoveryTools()]),Ye=JE(pe,Se);if(!k.current)return;const rt=te.find(Oe=>String(Oe.content_type||"").startsWith("image/")),V=B1(UE({prompt:G,attachments:te,primary_image_artifact:rt??null,stream:!0}),Ov(Lv(Ze))),{run_id:he}=await t.startRun(Ye.source==="gateway_default"?{flow_id:"@default",interface:Ye.interface,session_id:fe,input_data:V,...u?{conversation:!0}:{}}:{flow_id:Ye.flow_id,bundle_id:Ye.bundle_id,bundle_version:Ye.bundle_version,registry_scope:Ye.registry_scope,session_id:fe,input_data:V,...u?{conversation:!0}:{}});k.current&&($.current=he,de.clear(),o(""),w(""),e.onStarted(he,fe))},[t,N,de,e,me,u,O,d,I,L.view]),ce=p.useMemo(()=>YE(L.messages),[L.messages]),ye=ce.conversation,Ce=XE(ye,e.runId);p.useEffect(()=>{L.status!=="completed"||$.current!==e.runId||!Ce||($.current="",e.voicePrefs.read_aloud===!0&&!e.voicePrefs.reply_muted&&Y.tts_supported&&!Y.voice_ptt_recording&&!Y.voice_ptt_busy&&(!u||!m&&!s.trim())&&Y.toggle_tts(String(Ce.id||e.runId),Ce.content))},[L.status,e.runId,e.voicePrefs.read_aloud,e.voicePrefs.reply_muted,Ce,Y]);const ze=Q&&!B?"Needs you":"",Ve=tT(e.runId,L.status,L.run,L.messages),Ee=QE({recording:Y.voice_ptt_recording,transcribing:Y.voice_ptt_busy,playback:Y.tts_playback.status,pending:!!(Q&&!B),busy:me,working:ye.some(G=>{var fe;return((fe=G.toolActivity)==null?void 0:fe.status)==="running"}),failed:L.status==="failed",loading:L.loading}),je=()=>{var G,fe;return(fe=(G=b.current)==null?void 0:G.querySelector("textarea"))==null?void 0:fe.focus()},Ue=G=>{const fe=s.trim()?`${s.trim()}
83
+ ${G}`:G;o(fe),je(),e.autoSend&&(!me||u)&&ee(fe).catch(te=>w(`Not sent: ${te instanceof Error?te.message:String(te)}`))},ne=()=>{const G=ye.find(fe=>String(fe.id||"")===Y.tts_playback.key.replace(/^brief:/,""));G?Y.toggle_tts(Y.tts_playback.key,G.content):Y.stop_tts()},$e=()=>{var G;Y.stop_tts(),(G=Y.cancel_voice_ptt_recording)==null||G.call(Y),me&&I.cancel().catch(fe=>w(fe instanceof Error?fe.message:String(fe)))};return a.jsxs("div",{className:"aa-experience",ref:b,"data-has-messages":ye.length>0,"data-view":u?"avatar":"chat",children:[!u&&a.jsx(fE,{voice:Y,presence:Ee,prefs:e.appearance,mode:e.captureMode,busy:me,microphoneReason:n.capabilities.microphone.available?null:n.capabilities.microphone.reason,readReplies:e.voicePrefs.read_aloud===!0,onReadRepliesChange:G=>e.onVoicePrefsChange({...e.voicePrefs,read_aloud:G}),onTranscript:Ue,onPlayback:ne,onStop:$e,onType:je,onSettings:e.onSettings,autoSend:e.autoSend}),a.jsx(Ky,{composerTrailingActions:a.jsx(al,{voice:Y,mode:e.captureMode,label:"Talk",showStatus:!1,onTranscript:Ue,unavailableReason:n.capabilities.microphone.available?null:n.capabilities.microphone.reason}),avatarConversation:u?{onTechnicalView:()=>{Y.stop_tts(),l.setMode("chat")},sessionKey:`${e.readScope}:${e.sessionId||"new"}`,avatar:a.jsx(dw,{voice:Y,prefs:e.appearance,pose:Y.voice_ptt_recording?"listening":Y.tts_playback.status==="playing"?"speaking":((Pe=L.run)==null?void 0:Pe.paused)===!0&&!Zo.has(L.status)?"waiting":Ee.pose,size:320,onError:()=>w("The avatar could not load. Voice and messages still work.")}),...eC(L),listening:Y.voice_ptt_recording,speaking:Y.tts_playback.status==="playing",preferences:l.preferences,onPreferencesChange:l.setPreferences,onCue:G=>{HC(G).catch(fe=>w(fe instanceof Error?fe.message:String(fe)))},onInterruptSpeech:()=>Y.stop_tts(),onReplyContext:f,onAttendedChange:g,narrate:e.voicePrefs.read_aloud===!0&&!e.voicePrefs.reply_muted,onNarrate:G=>{Y.tts_supported&&Y.toggle_tts(`brief:${G.id}`,G.content)},voiceControl:a.jsx("span",{onPointerDown:()=>Y.stop_tts(),children:a.jsx(al,{voice:Y,mode:e.captureMode,label:"Talk",onTranscript:Ue,unavailableReason:n.capabilities.microphone.available?null:n.capabilities.microphone.reason})}),playbackControl:a.jsxs("span",{role:"group","aria-label":"Voice controls",children:[Y.tts_supported&&a.jsx("button",{type:"button","aria-pressed":e.voicePrefs.read_aloud===!0,onClick:()=>{Y.stop_tts(),e.onVoicePrefsChange({...e.voicePrefs,read_aloud:!e.voicePrefs.read_aloud})},children:"Read new replies aloud"}),["playing","paused"].includes(Y.tts_playback.status)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",onClick:ne,children:Y.tts_playback.status==="paused"?"Resume voice":"Pause voice"}),a.jsx("button",{type:"button",onClick:()=>Y.stop_tts(),children:"Silence voice"})]})]})}:void 0,artifactFetch:t.fetchGateway,attachmentScope:JSON.stringify([e.readScope,e.sessionId]),attachmentRun:{runId:e.runId,output:(Ge=L.run)==null?void 0:Ge.output},className:"aa-chat",messages:ye,draft:s,onDraftChange:o,onSend:ee,busy:me,steer:u&&me?{modes:["guide"],onSteer:async G=>(await ee(G),{accepted:!0}),parked:L.status==="waiting"}:void 0,busyLabel:Q&&!B?"Waiting for you…":L.loading?"Opening…":Ee.pose==="working"?"Working…":"Thinking…",onCancel:()=>I.cancel(),stopState:L.stop||null,placeholder:"Message the Assistant",emptyState:a.jsxs("div",{className:"aa-empty",children:[a.jsx("h2",{children:"What’s on your mind?"}),a.jsx("p",{children:"Ask a question, work through an idea, or just talk."}),a.jsx("div",{className:"aa-starters",children:["Help me think through an idea","Summarize something for me","What can you help me with?"].map(G=>a.jsxs("button",{type:"button",onClick:()=>{o(G),je()},children:[G,a.jsx(be,{name:"chevronRight",size:14})]},G))}),a.jsx("span",{className:"aa-empty__foot",children:"Your conversations follow you across devices."})]}),header:a.jsxs("div",{className:"aa-chat__header",children:[a.jsxs("div",{className:"aa-view-choice",role:"group","aria-label":"Conversation view",children:[a.jsx("button",{type:"button","aria-pressed":!u,onClick:()=>{Y.stop_tts(),l.setMode("chat")},children:"Conversation"}),a.jsx("button",{type:"button","aria-pressed":u,onClick:()=>{Y.stop_tts(),l.setMode("avatar")},children:"Avatar"})]}),a.jsx("h1",{className:"aa-chat__title",title:e.title,children:e.title}),ze?a.jsx("span",{className:"aa-state aa-state--waiting",children:ze}):null,L.connection==="reconnecting"?a.jsx("span",{className:"aa-chat__status",role:"status",children:"Reconnecting…"}):null,L.displayStatus?a.jsx("span",{className:"aa-chat__status",role:"status",children:L.displayStatus}):null,a.jsxs("details",{className:"aa-chat-details",onToggle:G=>j(G.currentTarget.open),children:[a.jsxs("summary",{children:[a.jsx(be,{name:"info",size:15})," Details"]}),a.jsxs("div",{children:[a.jsx("p",{className:L.source==="ledger_fold"?"aa-chat__source":void 0,children:aN(L)||"Your conversation is kept on Gateway."}),ce.diagnostics.map(G=>a.jsx("p",{children:G.content},G.id)),!ce.diagnostics.length&&a.jsx("p",{children:"Message usage and timing appear below each reply while these details are open."})]})]})]}),toolbar:{onNewSession:e.onNewChat,copyTranscript:!0,exportTranscript:{filename:"conversation.md",heading:e.title}},footer:L.error||Ve||v||e.eventsNotice||B||O&&q===T?a.jsxs("div",{className:"aa-chat__notes",children:[Ve?a.jsx("p",{className:`aa-note${L.status==="failed"?" aa-note--error":""}`,role:"status",children:Ve}):null,L.error?a.jsx("p",{className:"aa-note aa-note--error",role:"alert",children:L.error}):null,v?a.jsxs("p",{className:"aa-note",role:"status",children:[v," ",a.jsx("button",{type:"button",className:"aa-link",onClick:()=>w(""),children:"Dismiss"})]}):null,e.eventsNotice?a.jsx("p",{className:"aa-note",role:"status",children:e.eventsNotice}):null,B&&e.seen?a.jsxs("p",{className:"aa-note",role:"status",children:["Answered (",e.seen.outcome,")."]}):null,O&&q===T&&!B?a.jsxs("p",{className:"aa-note",role:"status",children:["A request is waiting for you."," ",a.jsx("button",{type:"button",className:"aa-link",onClick:()=>J(""),children:"Review"})]}):null]}):null,interaction:Z,onFiles:G=>void de.add(G),attachmentItems:de.items,onRemoveAttachment:de.remove,onRetryAttachment:de.retry,messageProps:{renderFooter:G=>{var pe,Se,Ze;const fe=G.runId===e.runId?L.status:(Se=(pe=e.sessionActivity)==null?void 0:pe.content.find(Ye=>Ye.runId===G.runId))==null?void 0:Se.status;if(!fe)return null;const te=hy(G.kind==="attachments"?[...ye,G]:ye,G.runId||"",fe);return te.message===G&&!L.loading&&!L.historyLoading&&!L.error&&e.readScope?a.jsxs(a.Fragment,{children:[a.jsx("span",{children:te.outcome}),a.jsx(US,{ownerKey:e.readScope,receipt:{sessionId:e.sessionId,revision:vd(G.runId||"",fe),updatedAt:""},relatedReceipts:OS(ye,(Ze=e.sessionActivity)==null?void 0:Ze.content,G.runId||""),enabled:e.canConsume,onRead:e.onRead})]}):null},stats:x?void 0:[],images:"link",...Y.tts_supported?{onSpeakToggle:G=>void Y.toggle_tts(String(G.id||""),G.content),getSpeakState:G=>Y.tts_playback.key===String(G.id||"")?Y.tts_playback.status:"idle"}:{}}})]})}const Wo="abstractassistant.companion",gw={design:"watch-halo",animated:!0};function Ig(e){try{const t=JSON.parse(e||"null");return{design:typeof(t==null?void 0:t.design)=="string"&&/^[a-z][a-z0-9_-]{0,63}$/.test(t.design)?t.design:"watch-halo",animated:typeof(t==null?void 0:t.animated)=="boolean"?t.animated:!0}}catch{return gw}}function sT(){const[e,t]=p.useState(()=>{try{return Ig(localStorage.getItem(Wo))}catch{return gw}}),[n,s]=p.useState(""),o=p.useCallback(l=>{t(l);try{localStorage.setItem(Wo,JSON.stringify(l)),s("")}catch{s("This browser could not save the choice. It still applies in this tab.")}},[]);return p.useEffect(()=>{const l=u=>{if(u.key===Wo||u.key===null)try{t(Ig(localStorage.getItem(Wo)))}catch{}};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]),{value:e,change:o,error:n}}function aT(){try{return typeof matchMedia=="function"&&matchMedia("(prefers-color-scheme: light)").matches}catch{return!1}}function iT(e){return e.conn.phase==="loading"?a.jsx("div",{className:"aa-splash","aria-busy":"true",children:a.jsx("p",{children:"Connecting to your gateway…"})}):a.jsxs("div",{className:"aa-splash",children:[a.jsx("p",{children:"Sign in to your gateway to talk with the Assistant."}),a.jsx("button",{type:"button",className:"aa-button aa-button--primary",onClick:e.conn.openModal,children:"Sign in"})]})}const vw="abstractassistant.voice";function oT(e){return a.jsxs("div",{className:"aa-nav-choice",role:"group","aria-label":"Show",children:[a.jsx("button",{type:"button","aria-pressed":e.tab==="conversations",onClick:()=>e.onChange("conversations"),children:"Conversations"}),a.jsx("button",{type:"button","aria-pressed":e.tab==="automations",onClick:()=>e.onChange("automations"),children:"Automations"})]})}function lT(e){const[t,n]=Rv(vw),{client:s,conn:o}=e,[l,u]=p.useState({sessionId:"",runId:""}),[d,f]=p.useState(null),[m,g]=p.useState(!1),[v,w]=p.useState(0),x=p.useCallback(()=>void o.refresh(),[o]),j=fy(o.status),b=p.useRef(j);b.current=j;const k=p.useRef(l);k.current=l;const $=p.useRef(async()=>{}),S=CE(s,{scope:j,onSignedOut:x,onAttentionSeen:f,onSessionRead:()=>void $.current()}),N=p.useMemo(()=>Object.values(S.activity).flatMap(T=>T.content),[S.activity]),C=p.useMemo(()=>DS(s.fetchGateway),[s]),R=zS(j,N,C);$.current=R.refresh;const E=l.sessionId?S.titles[l.sessionId]||"Conversation":"New conversation",I=kN(s,j),[L,D]=p.useState("conversations"),[P,K]=p.useState({kind:"chat"}),se=a.jsx(oT,{tab:L,onChange:D}),Q=T=>{var q;return(q=I.state.page)==null?void 0:q.items.find(J=>J.automation_id===T)},z=(T,q)=>{w(J=>J+1),g(!1),D("conversations"),K({kind:"chat"}),u({sessionId:T,runId:q}),S.refresh()};return a.jsx(Fv,{className:"aa-shell",topBar:e.topBar,drawers:e.drawers,nav:{label:L==="automations"?"Automations":"Conversations",width:264,open:m,onOpenChange:g,content:L==="automations"?a.jsx(jN,{automations:I,heading:se,activeId:P.kind==="automation"||P.kind==="edit"?P.summary.automation_id:"",onOpen:T=>{g(!1),K({kind:"automation",summary:T})},onNew:()=>{g(!1),K({kind:"new"})},onSettings:e.onSettings}):a.jsx(cN,{heading:se,rows:S.rows,activity:S.activity,isUnread:T=>{const q=S.activity[T.session_id];return!!(q&&q.content.some(R.isUnread))},onArchive:async T=>{const q=j;await s.archiveSession(T.session_id),b.current===q&&(k.current.sessionId===T.session_id&&(w(J=>J+1),u({sessionId:"",runId:""})),await S.refresh())},titles:S.titles,truncated:S.truncated,error:S.error,notice:[S.notice,R.error].filter(Boolean).join(" "),activeId:l.sessionId,onOpen:T=>{w(q=>q+1),g(!1),K({kind:"chat"}),u({sessionId:T.session_id,runId:T.latest_run_id})},onNew:()=>{w(T=>T+1),g(!1),K({kind:"chat"}),u({sessionId:"",runId:""})},onRefresh:()=>void S.refresh(),onSettings:e.onSettings})},children:P.kind==="automation"?a.jsx(eE,{client:s,automations:I,summary:Q(P.summary.automation_id)??P.summary,onEdit:()=>K({kind:"edit",summary:Q(P.summary.automation_id)??P.summary}),onOpenConversation:z},P.summary.automation_id):P.kind==="edit"?a.jsx(tE,{automations:I,summary:P.summary,onDone:()=>K({kind:"automation",summary:Q(P.summary.automation_id)??P.summary})},`edit:${P.summary.automation_id}`):P.kind==="new"?a.jsx(rE,{client:s,automations:I,onCreated:T=>K({kind:"automation",summary:T}),onCancel:()=>K({kind:"chat"})}):a.jsx(rT,{client:s,host:e.host,sessionId:l.sessionId,runId:l.runId,title:E,seen:d,onRead:R.markRead,sessionActivity:S.activity[l.sessionId],readScope:j,canConsume:!m&&!e.drawers.active,eventsNotice:S.eventsError,voicePrefs:t,onVoicePrefsChange:n,appearance:e.appearance,onSettings:e.onSettings,captureMode:t.capture_mode?hs(t.capture_mode):Td.capture_mode,autoSend:typeof t.auto_send=="boolean"?t.auto_send:Td.auto_send,onStarted:(T,q)=>{u({sessionId:q,runId:T}),S.refresh()},onNewChat:()=>{w(T=>T+1),u({sessionId:"",runId:""})},onTurnEnded:()=>void S.refresh(),onSignedOut:x},v)})}function cT({host:e}){const t=ax({appName:"AbstractAssistant",variant:"blocking"}),n=p.useMemo(()=>new oN(e),[e]),[s,o]=Fx("abstractassistant",{defaults:{theme:aT()?"light":"dark"}});p.useEffect(()=>{document.documentElement.dataset.theme=lN(s.theme)},[s.theme]);const[l,u]=p.useState(null),d=p.useMemo(()=>Ex("abstractassistant",WS),[]),[f,m]=Rv(vw),g=sT(),v=L1(t.connected?()=>n.voiceDefaults():null,n),w=p.useMemo(()=>[x(),...t.connected?[{id:"settings",label:"Settings",icon:"settings",mode:"drawer",defaultWidth:420,content:a.jsx(mE,{client:n,prefs:f,onPrefsChange:m,defaults:v.value,appearance:g.value,onAppearanceChange:g.change,preferenceError:g.error,active:l==="settings"})}]:[]],[n,t.connected,l,f,m,v.value,g.value,g.change,g.error]);function x(){const k=TS({app:"assistant-web",name:"AbstractAssistant"},n.fetchGateway,{connected:t.connected,visible:l==="docs",voicePreferences:f,placeholder:"Ask about the Assistant…",suggestions:["How do I use voice?","How do conversations work?","What can the Assistant do?"]});return{...k,fill:!0,content:a.jsxs("div",{className:"aa-docs-panel",children:[k.content,a.jsx("p",{className:"aa-docs-grounding",children:"Answers use the Assistant documentation."})]})}}const j={brand:{name:"Assistant",mark:a.jsx("span",{className:"aa-brand-mark",children:a.jsx(be,{name:"sparkle",size:18})})},connection:t,identity:"menu",appearance:{value:s,onChange:o},about:{identity:d,fetch:n.fetchGateway},docs:{open:l==="docs",onToggle:()=>u(k=>k==="docs"?null:"docs")}},b={panels:w,active:l,onActiveChange:k=>u(k),ariaLabel:"Assistant panels",storageKey:"abstractassistant.panels",overlay:!0,restoreActive:!1};return a.jsxs(a.Fragment,{children:[a.jsx(ux,{...t.modalProps}),t.connected?a.jsx(lT,{client:n,host:e,conn:t,topBar:j,drawers:b,appearance:g.value,onSettings:()=>u("settings")},fy(t.status)):a.jsx(Fv,{topBar:j,drawers:b,children:a.jsx(iT,{conn:t})})]})}function uT({host:e}){if(e.signIn==="app-server-modal")return a.jsx(cT,{host:e});throw new Error(`Host sign-in "${e.signIn}" is not implemented in this build (ADR 0007, Hosts).`)}const dT="abstractassistant",fT=`${dT}_gateway_csrf`,hT="X-AbstractAssistant-CSRF";function pT(e,t){for(const n of String(e||"").split(";")){const s=n.trim();if(s.startsWith(`${t}=`))try{return decodeURIComponent(s.slice(t.length+1))}catch{return""}}return""}const is=e=>({available:!1,reason:e});function mT(e){let t={available:!0};return e.secureContext?(!e.hasGetUserMedia||!e.hasMediaRecorder)&&(t=is("This browser cannot record audio (no getUserMedia or MediaRecorder).")):t=is("Dictation needs a secure page: open the Assistant over https:// (or on the gateway machine at http://127.0.0.1)."),{tray:is("A browser tab has no menu-bar icon; the desktop app has one."),globalHotkey:is("A browser tab cannot listen for a system-wide shortcut."),systemNotifications:is("Not in this version: notifications while the tab is closed need a service worker and web push (ADR 0007, v2)."),autostart:is("A browser tab does not start with your session."),microphone:t,audioPlayback:e.hasAudioContext?{available:!0}:is("This browser has no Web Audio: read aloud is unavailable.")}}function gT(){var t,n;const e=globalThis;return{kind:"browser",gatewayUrl:s=>Md("",ut(s)),auth:{kind:"app-cookie-session",credentials:"same-origin",headers(s){if(!s)return{};const o=pT(typeof document>"u"?"":document.cookie,fT);if(!o)throw new Error("You are signed out of the gateway (no session cookie on this page): sign in again.");return{[hT]:o}}},signIn:"app-server-modal",capabilities:mT({secureContext:!!e.isSecureContext,hasGetUserMedia:typeof((n=(t=e.navigator)==null?void 0:t.mediaDevices)==null?void 0:n.getUserMedia)=="function",hasMediaRecorder:typeof e.MediaRecorder=="function",hasAudioContext:typeof e.AudioContext=="function"||typeof e.webkitAudioContext=="function"})}}function vT(e,t){const n=e&&typeof e=="object"?e.host:void 0;if(n==="browser"||n===void 0&&t)return gT();throw n==="tauri"?new Error("The desktop (Tauri) host is not implemented yet: see ADR 0007, 'Hosts', and the coming ADR 0008."):n===void 0?new Error("This page was not served by the AbstractAssistant web server (no host configuration in the page)."):new Error(`Unknown host ${JSON.stringify(n)} in the page configuration.`)}const Pg=bb.createRoot(document.getElementById("root"));try{const e=window.__ABSTRACT_UI_CONFIG__,t=vT(e,!1);Pg.render(a.jsx(it.StrictMode,{children:a.jsx(uT,{host:t})}))}catch(e){Pg.render(a.jsxs("main",{className:"aa-fatal",role:"alert",children:[a.jsx("h1",{children:"AbstractAssistant cannot start"}),a.jsx("p",{children:e instanceof Error?e.message:String(e)})]}))}