teodor-new-chat-ui 4.3.358 → 4.3.360

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(Te,b){typeof exports=="object"&&typeof module<"u"?b(exports,require("react"),require("lucide-react"),require("@radix-ui/react-slot"),require("class-variance-authority"),require("clsx"),require("tailwind-merge"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react","lucide-react","@radix-ui/react-slot","class-variance-authority","clsx","tailwind-merge","react-dom"],b):(Te=typeof globalThis<"u"?globalThis:Te||self,b(Te.NewChatUI={},Te.React,Te.LucideReact,Te.reactSlot,Te.classVarianceAuthority,Te.clsx,Te.tailwindMerge,Te.ReactDOM))})(this,function(Te,b,oe,Wn,mo,Jp,Zp,Js){"use strict";var $T=Object.defineProperty;var FT=(Te,b,oe)=>b in Te?$T(Te,b,{enumerable:!0,configurable:!0,writable:!0,value:oe}):Te[b]=oe;var Yp=(Te,b,oe)=>FT(Te,typeof b!="symbol"?b+"":b,oe);var Zs=typeof document<"u"?document.currentScript:null;function Ga(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const v=Ga(b),go=Ga(Js);var Qs={exports:{}},_r={};/**
1
+ (function(Ae,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react"),require("lucide-react"),require("@radix-ui/react-slot"),require("class-variance-authority"),require("clsx"),require("tailwind-merge"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react","lucide-react","@radix-ui/react-slot","class-variance-authority","clsx","tailwind-merge","react-dom"],w):(Ae=typeof globalThis<"u"?globalThis:Ae||self,w(Ae.NewChatUI={},Ae.React,Ae.LucideReact,Ae.reactSlot,Ae.classVarianceAuthority,Ae.clsx,Ae.tailwindMerge,Ae.ReactDOM))})(this,function(Ae,w,ue,Kn,ko,Am,jm,ii){"use strict";var Bk=Object.defineProperty;var zk=(Ae,w,ue)=>w in Ae?Bk(Ae,w,{enumerable:!0,configurable:!0,writable:!0,value:ue}):Ae[w]=ue;var Em=(Ae,w,ue)=>zk(Ae,typeof w!="symbol"?w+"":w,ue);var ai=typeof document<"u"?document.currentScript:null;function pl(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const m=pl(w),Io=pl(ii);var li={exports:{}},$r={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var Ya;function Qp(){if(Ya)return _r;Ya=1;var e=b,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,l,c){var d,f={},h=null,p=null;c!==void 0&&(h=""+c),l.key!==void 0&&(h=""+l.key),l.ref!==void 0&&(p=l.ref);for(d in l)r.call(l,d)&&!s.hasOwnProperty(d)&&(f[d]=l[d]);if(a&&a.defaultProps)for(d in l=a.defaultProps,l)f[d]===void 0&&(f[d]=l[d]);return{$$typeof:t,type:a,key:h,ref:p,props:f,_owner:o.current}}return _r.Fragment=n,_r.jsx=i,_r.jsxs=i,_r}var Mr={};/**
9
+ */var hl;function _m(){if(hl)return $r;hl=1;var e=w,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,l,c){var d,f={},p=null,h=null;c!==void 0&&(p=""+c),l.key!==void 0&&(p=""+l.key),l.ref!==void 0&&(h=l.ref);for(d in l)r.call(l,d)&&!s.hasOwnProperty(d)&&(f[d]=l[d]);if(a&&a.defaultProps)for(d in l=a.defaultProps,l)f[d]===void 0&&(f[d]=l[d]);return{$$typeof:t,type:a,key:p,ref:h,props:f,_owner:o.current}}return $r.Fragment=n,$r.jsx=i,$r.jsxs=i,$r}var Fr={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,33 +14,33 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var Xa;function em(){return Xa||(Xa=1,process.env.NODE_ENV!=="production"&&function(){var e=b,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),y=Symbol.iterator,m="@@iterator";function x(E){if(E===null||typeof E!="object")return null;var G=y&&E[y]||E[m];return typeof G=="function"?G:null}var g=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function w(E){{for(var G=arguments.length,se=new Array(G>1?G-1:0),Ee=1;Ee<G;Ee++)se[Ee-1]=arguments[Ee];S("error",E,se)}}function S(E,G,se){{var Ee=g.ReactDebugCurrentFrame,Ye=Ee.getStackAddendum();Ye!==""&&(G+="%s",se=se.concat([Ye]));var nt=se.map(function(Fe){return String(Fe)});nt.unshift("Warning: "+G),Function.prototype.apply.call(console[E],console,nt)}}var k=!1,C=!1,T=!1,I=!1,j=!1,_;_=Symbol.for("react.module.reference");function O(E){return!!(typeof E=="string"||typeof E=="function"||E===r||E===s||j||E===o||E===c||E===d||I||E===p||k||C||T||typeof E=="object"&&E!==null&&(E.$$typeof===h||E.$$typeof===f||E.$$typeof===i||E.$$typeof===a||E.$$typeof===l||E.$$typeof===_||E.getModuleId!==void 0))}function B(E,G,se){var Ee=E.displayName;if(Ee)return Ee;var Ye=G.displayName||G.name||"";return Ye!==""?se+"("+Ye+")":se}function K(E){return E.displayName||"Context"}function V(E){if(E==null)return null;if(typeof E.tag=="number"&&w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof E=="function")return E.displayName||E.name||null;if(typeof E=="string")return E;switch(E){case r:return"Fragment";case n:return"Portal";case s:return"Profiler";case o:return"StrictMode";case c:return"Suspense";case d:return"SuspenseList"}if(typeof E=="object")switch(E.$$typeof){case a:var G=E;return K(G)+".Consumer";case i:var se=E;return K(se._context)+".Provider";case l:return B(E,E.render,"ForwardRef");case f:var Ee=E.displayName||null;return Ee!==null?Ee:V(E.type)||"Memo";case h:{var Ye=E,nt=Ye._payload,Fe=Ye._init;try{return V(Fe(nt))}catch{return null}}}return null}var P=Object.assign,M=0,N,z,L,R,W,Y,ne;function pe(){}pe.__reactDisabledLog=!0;function be(){{if(M===0){N=console.log,z=console.info,L=console.warn,R=console.error,W=console.group,Y=console.groupCollapsed,ne=console.groupEnd;var E={configurable:!0,enumerable:!0,value:pe,writable:!0};Object.defineProperties(console,{info:E,log:E,warn:E,error:E,group:E,groupCollapsed:E,groupEnd:E})}M++}}function Ie(){{if(M--,M===0){var E={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:P({},E,{value:N}),info:P({},E,{value:z}),warn:P({},E,{value:L}),error:P({},E,{value:R}),group:P({},E,{value:W}),groupCollapsed:P({},E,{value:Y}),groupEnd:P({},E,{value:ne})})}M<0&&w("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ve=g.ReactCurrentDispatcher,te;function F(E,G,se){{if(te===void 0)try{throw Error()}catch(Ye){var Ee=Ye.stack.trim().match(/\n( *(at )?)/);te=Ee&&Ee[1]||""}return`
18
- `+te+E}}var X=!1,A;{var $=typeof WeakMap=="function"?WeakMap:Map;A=new $}function H(E,G){if(!E||X)return"";{var se=A.get(E);if(se!==void 0)return se}var Ee;X=!0;var Ye=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var nt;nt=ve.current,ve.current=null,be();try{if(G){var Fe=function(){throw Error()};if(Object.defineProperty(Fe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Fe,[])}catch(qe){Ee=qe}Reflect.construct(E,[],Fe)}else{try{Fe.call()}catch(qe){Ee=qe}E.call(Fe.prototype)}}else{try{throw Error()}catch(qe){Ee=qe}E()}}catch(qe){if(qe&&Ee&&typeof qe.stack=="string"){for(var Le=qe.stack.split(`
19
- `),Et=Ee.stack.split(`
20
- `),ht=Le.length-1,gt=Et.length-1;ht>=1&&gt>=0&&Le[ht]!==Et[gt];)gt--;for(;ht>=1&&gt>=0;ht--,gt--)if(Le[ht]!==Et[gt]){if(ht!==1||gt!==1)do if(ht--,gt--,gt<0||Le[ht]!==Et[gt]){var de=`
21
- `+Le[ht].replace(" at new "," at ");return E.displayName&&de.includes("<anonymous>")&&(de=de.replace("<anonymous>",E.displayName)),typeof E=="function"&&A.set(E,de),de}while(ht>=1&&gt>=0);break}}}finally{X=!1,ve.current=nt,Ie(),Error.prepareStackTrace=Ye}var Ce=E?E.displayName||E.name:"",Ae=Ce?F(Ce):"";return typeof E=="function"&&A.set(E,Ae),Ae}function fe(E,G,se){return H(E,!1)}function re(E){var G=E.prototype;return!!(G&&G.isReactComponent)}function Z(E,G,se){if(E==null)return"";if(typeof E=="function")return H(E,re(E));if(typeof E=="string")return F(E);switch(E){case c:return F("Suspense");case d:return F("SuspenseList")}if(typeof E=="object")switch(E.$$typeof){case l:return fe(E.render);case f:return Z(E.type,G,se);case h:{var Ee=E,Ye=Ee._payload,nt=Ee._init;try{return Z(nt(Ye),G,se)}catch{}}}return""}var ce=Object.prototype.hasOwnProperty,me={},$e=g.ReactDebugCurrentFrame;function Re(E){if(E){var G=E._owner,se=Z(E.type,E._source,G?G.type:null);$e.setExtraStackFrame(se)}else $e.setExtraStackFrame(null)}function Be(E,G,se,Ee,Ye){{var nt=Function.call.bind(ce);for(var Fe in E)if(nt(E,Fe)){var Le=void 0;try{if(typeof E[Fe]!="function"){var Et=Error((Ee||"React class")+": "+se+" type `"+Fe+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof E[Fe]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Et.name="Invariant Violation",Et}Le=E[Fe](G,Fe,Ee,se,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ht){Le=ht}Le&&!(Le instanceof Error)&&(Re(Ye),w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Ee||"React class",se,Fe,typeof Le),Re(null)),Le instanceof Error&&!(Le.message in me)&&(me[Le.message]=!0,Re(Ye),w("Failed %s type: %s",se,Le.message),Re(null))}}}var Xe=Array.isArray;function Qe(E){return Xe(E)}function Je(E){{var G=typeof Symbol=="function"&&Symbol.toStringTag,se=G&&E[Symbol.toStringTag]||E.constructor.name||"Object";return se}}function et(E){try{return it(E),!1}catch{return!0}}function it(E){return""+E}function Mt(E){if(et(E))return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Je(E)),it(E)}var pt=g.ReactCurrentOwner,Ct={key:!0,ref:!0,__self:!0,__source:!0},mt,wt;function Pt(E){if(ce.call(E,"ref")){var G=Object.getOwnPropertyDescriptor(E,"ref").get;if(G&&G.isReactWarning)return!1}return E.ref!==void 0}function $t(E){if(ce.call(E,"key")){var G=Object.getOwnPropertyDescriptor(E,"key").get;if(G&&G.isReactWarning)return!1}return E.key!==void 0}function cn(E,G){typeof E.ref=="string"&&pt.current}function We(E,G){{var se=function(){mt||(mt=!0,w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",G))};se.isReactWarning=!0,Object.defineProperty(E,"key",{get:se,configurable:!0})}}function In(E,G){{var se=function(){wt||(wt=!0,w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",G))};se.isReactWarning=!0,Object.defineProperty(E,"ref",{get:se,configurable:!0})}}var rt=function(E,G,se,Ee,Ye,nt,Fe){var Le={$$typeof:t,type:E,key:G,ref:se,props:Fe,_owner:nt};return Le._store={},Object.defineProperty(Le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(Le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Ee}),Object.defineProperty(Le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Ye}),Object.freeze&&(Object.freeze(Le.props),Object.freeze(Le)),Le};function J(E,G,se,Ee,Ye){{var nt,Fe={},Le=null,Et=null;se!==void 0&&(Mt(se),Le=""+se),$t(G)&&(Mt(G.key),Le=""+G.key),Pt(G)&&(Et=G.ref,cn(G,Ye));for(nt in G)ce.call(G,nt)&&!Ct.hasOwnProperty(nt)&&(Fe[nt]=G[nt]);if(E&&E.defaultProps){var ht=E.defaultProps;for(nt in ht)Fe[nt]===void 0&&(Fe[nt]=ht[nt])}if(Le||Et){var gt=typeof E=="function"?E.displayName||E.name||"Unknown":E;Le&&We(Fe,gt),Et&&In(Fe,gt)}return rt(E,Le,Et,Ye,Ee,pt.current,Fe)}}var le=g.ReactCurrentOwner,ze=g.ReactDebugCurrentFrame;function Se(E){if(E){var G=E._owner,se=Z(E.type,E._source,G?G.type:null);ze.setExtraStackFrame(se)}else ze.setExtraStackFrame(null)}var ft;ft=!1;function U(E){return typeof E=="object"&&E!==null&&E.$$typeof===t}function ge(){{if(le.current){var E=V(le.current.type);if(E)return`
17
+ */var ml;function Mm(){return ml||(ml=1,process.env.NODE_ENV!=="production"&&function(){var e=w,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),h=Symbol.for("react.offscreen"),v=Symbol.iterator,g="@@iterator";function y(E){if(E===null||typeof E!="object")return null;var J=v&&E[v]||E[g];return typeof J=="function"?J:null}var x=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(E){{for(var J=arguments.length,de=new Array(J>1?J-1:0),Ce=1;Ce<J;Ce++)de[Ce-1]=arguments[Ce];C("error",E,de)}}function C(E,J,de){{var Ce=x.ReactDebugCurrentFrame,qe=Ce.getStackAddendum();qe!==""&&(J+="%s",de=de.concat([qe]));var Ze=de.map(function(Be){return String(Be)});Ze.unshift("Warning: "+J),Function.prototype.apply.call(console[E],console,Ze)}}var k=!1,T=!1,S=!1,I=!1,A=!1,R;R=Symbol.for("react.module.reference");function D(E){return!!(typeof E=="string"||typeof E=="function"||E===r||E===s||A||E===o||E===c||E===d||I||E===h||k||T||S||typeof E=="object"&&E!==null&&(E.$$typeof===p||E.$$typeof===f||E.$$typeof===i||E.$$typeof===a||E.$$typeof===l||E.$$typeof===R||E.getModuleId!==void 0))}function F(E,J,de){var Ce=E.displayName;if(Ce)return Ce;var qe=J.displayName||J.name||"";return qe!==""?de+"("+qe+")":de}function q(E){return E.displayName||"Context"}function W(E){if(E==null)return null;if(typeof E.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof E=="function")return E.displayName||E.name||null;if(typeof E=="string")return E;switch(E){case r:return"Fragment";case n:return"Portal";case s:return"Profiler";case o:return"StrictMode";case c:return"Suspense";case d:return"SuspenseList"}if(typeof E=="object")switch(E.$$typeof){case a:var J=E;return q(J)+".Consumer";case i:var de=E;return q(de._context)+".Provider";case l:return F(E,E.render,"ForwardRef");case f:var Ce=E.displayName||null;return Ce!==null?Ce:W(E.type)||"Memo";case p:{var qe=E,Ze=qe._payload,Be=qe._init;try{return W(Be(Ze))}catch{return null}}}return null}var _=Object.assign,j=0,N,z,L,P,V,ne,M;function Y(){}Y.__reactDisabledLog=!0;function ae(){{if(j===0){N=console.log,z=console.info,L=console.warn,P=console.error,V=console.group,ne=console.groupCollapsed,M=console.groupEnd;var E={configurable:!0,enumerable:!0,value:Y,writable:!0};Object.defineProperties(console,{info:E,log:E,warn:E,error:E,group:E,groupCollapsed:E,groupEnd:E})}j++}}function Q(){{if(j--,j===0){var E={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:_({},E,{value:N}),info:_({},E,{value:z}),warn:_({},E,{value:L}),error:_({},E,{value:P}),group:_({},E,{value:V}),groupCollapsed:_({},E,{value:ne}),groupEnd:_({},E,{value:M})})}j<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ce=x.ReactCurrentDispatcher,G;function O(E,J,de){{if(G===void 0)try{throw Error()}catch(qe){var Ce=qe.stack.trim().match(/\n( *(at )?)/);G=Ce&&Ce[1]||""}return`
18
+ `+G+E}}var K=!1,B;{var te=typeof WeakMap=="function"?WeakMap:Map;B=new te}function Z(E,J){if(!E||K)return"";{var de=B.get(E);if(de!==void 0)return de}var Ce;K=!0;var qe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var Ze;Ze=ce.current,ce.current=null,ae();try{if(J){var Be=function(){throw Error()};if(Object.defineProperty(Be.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Be,[])}catch(Ye){Ce=Ye}Reflect.construct(E,[],Be)}else{try{Be.call()}catch(Ye){Ce=Ye}E.call(Be.prototype)}}else{try{throw Error()}catch(Ye){Ce=Ye}E()}}catch(Ye){if(Ye&&Ce&&typeof Ye.stack=="string"){for(var ze=Ye.stack.split(`
19
+ `),It=Ce.stack.split(`
20
+ `),ft=ze.length-1,mt=It.length-1;ft>=1&&mt>=0&&ze[ft]!==It[mt];)mt--;for(;ft>=1&&mt>=0;ft--,mt--)if(ze[ft]!==It[mt]){if(ft!==1||mt!==1)do if(ft--,mt--,mt<0||ze[ft]!==It[mt]){var ge=`
21
+ `+ze[ft].replace(" at new "," at ");return E.displayName&&ge.includes("<anonymous>")&&(ge=ge.replace("<anonymous>",E.displayName)),typeof E=="function"&&B.set(E,ge),ge}while(ft>=1&&mt>=0);break}}}finally{K=!1,ce.current=Ze,Q(),Error.prepareStackTrace=qe}var Ne=E?E.displayName||E.name:"",Re=Ne?O(Ne):"";return typeof E=="function"&&B.set(E,Re),Re}function ye(E,J,de){return Z(E,!1)}function fe(E){var J=E.prototype;return!!(J&&J.isReactComponent)}function oe(E,J,de){if(E==null)return"";if(typeof E=="function")return Z(E,fe(E));if(typeof E=="string")return O(E);switch(E){case c:return O("Suspense");case d:return O("SuspenseList")}if(typeof E=="object")switch(E.$$typeof){case l:return ye(E.render);case f:return oe(E.type,J,de);case p:{var Ce=E,qe=Ce._payload,Ze=Ce._init;try{return oe(Ze(qe),J,de)}catch{}}}return""}var xe=Object.prototype.hasOwnProperty,Se={},$e=x.ReactDebugCurrentFrame;function _e(E){if(E){var J=E._owner,de=oe(E.type,E._source,J?J.type:null);$e.setExtraStackFrame(de)}else $e.setExtraStackFrame(null)}function Ue(E,J,de,Ce,qe){{var Ze=Function.call.bind(xe);for(var Be in E)if(Ze(E,Be)){var ze=void 0;try{if(typeof E[Be]!="function"){var It=Error((Ce||"React class")+": "+de+" type `"+Be+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof E[Be]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw It.name="Invariant Violation",It}ze=E[Be](J,Be,Ce,de,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ft){ze=ft}ze&&!(ze instanceof Error)&&(_e(qe),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",Ce||"React class",de,Be,typeof ze),_e(null)),ze instanceof Error&&!(ze.message in Se)&&(Se[ze.message]=!0,_e(qe),b("Failed %s type: %s",de,ze.message),_e(null))}}}var U=Array.isArray;function le(E){return U(E)}function ke(E){{var J=typeof Symbol=="function"&&Symbol.toStringTag,de=J&&E[Symbol.toStringTag]||E.constructor.name||"Object";return de}}function Ke(E){try{return tt(E),!1}catch{return!0}}function tt(E){return""+E}function St(E){if(Ke(E))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ke(E)),tt(E)}var ut=x.ReactCurrentOwner,yt={key:!0,ref:!0,__self:!0,__source:!0},pt,wt;function Mt(E){if(xe.call(E,"ref")){var J=Object.getOwnPropertyDescriptor(E,"ref").get;if(J&&J.isReactWarning)return!1}return E.ref!==void 0}function Wt(E){if(xe.call(E,"key")){var J=Object.getOwnPropertyDescriptor(E,"key").get;if(J&&J.isReactWarning)return!1}return E.key!==void 0}function nn(E,J){typeof E.ref=="string"&&ut.current}function Ve(E,J){{var de=function(){pt||(pt=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",J))};de.isReactWarning=!0,Object.defineProperty(E,"key",{get:de,configurable:!0})}}function Sn(E,J){{var de=function(){wt||(wt=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",J))};de.isReactWarning=!0,Object.defineProperty(E,"ref",{get:de,configurable:!0})}}var nt=function(E,J,de,Ce,qe,Ze,Be){var ze={$$typeof:t,type:E,key:J,ref:de,props:Be,_owner:Ze};return ze._store={},Object.defineProperty(ze._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ze,"_self",{configurable:!1,enumerable:!1,writable:!1,value:Ce}),Object.defineProperty(ze,"_source",{configurable:!1,enumerable:!1,writable:!1,value:qe}),Object.freeze&&(Object.freeze(ze.props),Object.freeze(ze)),ze};function Ge(E,J,de,Ce,qe){{var Ze,Be={},ze=null,It=null;de!==void 0&&(St(de),ze=""+de),Wt(J)&&(St(J.key),ze=""+J.key),Mt(J)&&(It=J.ref,nn(J,qe));for(Ze in J)xe.call(J,Ze)&&!yt.hasOwnProperty(Ze)&&(Be[Ze]=J[Ze]);if(E&&E.defaultProps){var ft=E.defaultProps;for(Ze in ft)Be[Ze]===void 0&&(Be[Ze]=ft[Ze])}if(ze||It){var mt=typeof E=="function"?E.displayName||E.name||"Unknown":E;ze&&Ve(Be,mt),It&&Sn(Be,mt)}return nt(E,ze,It,qe,Ce,ut.current,Be)}}var dt=x.ReactCurrentOwner,Rt=x.ReactDebugCurrentFrame;function Je(E){if(E){var J=E._owner,de=oe(E.type,E._source,J?J.type:null);Rt.setExtraStackFrame(de)}else Rt.setExtraStackFrame(null)}var Pt;Pt=!1;function X(E){return typeof E=="object"&&E!==null&&E.$$typeof===t}function H(){{if(dt.current){var E=W(dt.current.type);if(E)return`
22
22
 
23
- Check the render method of \``+E+"`."}return""}}function ye(E){return""}var Ke={};function De(E){{var G=ge();if(!G){var se=typeof E=="string"?E:E.displayName||E.name;se&&(G=`
23
+ Check the render method of \``+E+"`."}return""}}function re(E){return""}var Ee={};function we(E){{var J=H();if(!J){var de=typeof E=="string"?E:E.displayName||E.name;de&&(J=`
24
24
 
25
- Check the top-level render call using <`+se+">.")}return G}}function ct(E,G){{if(!E._store||E._store.validated||E.key!=null)return;E._store.validated=!0;var se=De(G);if(Ke[se])return;Ke[se]=!0;var Ee="";E&&E._owner&&E._owner!==le.current&&(Ee=" It was passed a child from "+V(E._owner.type)+"."),Se(E),w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',se,Ee),Se(null)}}function Ve(E,G){{if(typeof E!="object")return;if(Qe(E))for(var se=0;se<E.length;se++){var Ee=E[se];U(Ee)&&ct(Ee,G)}else if(U(E))E._store&&(E._store.validated=!0);else if(E){var Ye=x(E);if(typeof Ye=="function"&&Ye!==E.entries)for(var nt=Ye.call(E),Fe;!(Fe=nt.next()).done;)U(Fe.value)&&ct(Fe.value,G)}}}function bt(E){{var G=E.type;if(G==null||typeof G=="string")return;var se;if(typeof G=="function")se=G.propTypes;else if(typeof G=="object"&&(G.$$typeof===l||G.$$typeof===f))se=G.propTypes;else return;if(se){var Ee=V(G);Be(se,E.props,"prop",Ee,E)}else if(G.PropTypes!==void 0&&!ft){ft=!0;var Ye=V(G);w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Ye||"Unknown")}typeof G.getDefaultProps=="function"&&!G.getDefaultProps.isReactClassApproved&&w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function zn(E){{for(var G=Object.keys(E.props),se=0;se<G.length;se++){var Ee=G[se];if(Ee!=="children"&&Ee!=="key"){Se(E),w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Ee),Se(null);break}}E.ref!==null&&(Se(E),w("Invalid attribute `ref` supplied to `React.Fragment`."),Se(null))}}var ar={};function En(E,G,se,Ee,Ye,nt){{var Fe=O(E);if(!Fe){var Le="";(E===void 0||typeof E=="object"&&E!==null&&Object.keys(E).length===0)&&(Le+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Et=ye();Et?Le+=Et:Le+=ge();var ht;E===null?ht="null":Qe(E)?ht="array":E!==void 0&&E.$$typeof===t?(ht="<"+(V(E.type)||"Unknown")+" />",Le=" Did you accidentally export a JSX literal instead of a component?"):ht=typeof E,w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ht,Le)}var gt=J(E,G,se,Ye,nt);if(gt==null)return gt;if(Fe){var de=G.children;if(de!==void 0)if(Ee)if(Qe(de)){for(var Ce=0;Ce<de.length;Ce++)Ve(de[Ce],E);Object.freeze&&Object.freeze(de)}else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Ve(de,E)}if(ce.call(G,"key")){var Ae=V(E),qe=Object.keys(G).filter(function(LT){return LT!=="key"}),Hn=qe.length>0?"{key: someKey, "+qe.join(": ..., ")+": ...}":"{key: someKey}";if(!ar[Ae+Hn]){var en=qe.length>0?"{"+qe.join(": ..., ")+": ...}":"{}";w(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+de+">.")}return J}}function Qe(E,J){{if(!E._store||E._store.validated||E.key!=null)return;E._store.validated=!0;var de=we(J);if(Ee[de])return;Ee[de]=!0;var Ce="";E&&E._owner&&E._owner!==dt.current&&(Ce=" It was passed a child from "+W(E._owner.type)+"."),Je(E),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',de,Ce),Je(null)}}function Pe(E,J){{if(typeof E!="object")return;if(le(E))for(var de=0;de<E.length;de++){var Ce=E[de];X(Ce)&&Qe(Ce,J)}else if(X(E))E._store&&(E._store.validated=!0);else if(E){var qe=y(E);if(typeof qe=="function"&&qe!==E.entries)for(var Ze=qe.call(E),Be;!(Be=Ze.next()).done;)X(Be.value)&&Qe(Be.value,J)}}}function ht(E){{var J=E.type;if(J==null||typeof J=="string")return;var de;if(typeof J=="function")de=J.propTypes;else if(typeof J=="object"&&(J.$$typeof===l||J.$$typeof===f))de=J.propTypes;else return;if(de){var Ce=W(J);Ue(de,E.props,"prop",Ce,E)}else if(J.PropTypes!==void 0&&!Pt){Pt=!0;var qe=W(J);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",qe||"Unknown")}typeof J.getDefaultProps=="function"&&!J.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Cn(E){{for(var J=Object.keys(E.props),de=0;de<J.length;de++){var Ce=J[de];if(Ce!=="children"&&Ce!=="key"){Je(E),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",Ce),Je(null);break}}E.ref!==null&&(Je(E),b("Invalid attribute `ref` supplied to `React.Fragment`."),Je(null))}}var An={};function Or(E,J,de,Ce,qe,Ze){{var Be=D(E);if(!Be){var ze="";(E===void 0||typeof E=="object"&&E!==null&&Object.keys(E).length===0)&&(ze+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var It=re();It?ze+=It:ze+=H();var ft;E===null?ft="null":le(E)?ft="array":E!==void 0&&E.$$typeof===t?(ft="<"+(W(E.type)||"Unknown")+" />",ze=" Did you accidentally export a JSX literal instead of a component?"):ft=typeof E,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ft,ze)}var mt=Ge(E,J,de,qe,Ze);if(mt==null)return mt;if(Be){var ge=J.children;if(ge!==void 0)if(Ce)if(le(ge)){for(var Ne=0;Ne<ge.length;Ne++)Pe(ge[Ne],E);Object.freeze&&Object.freeze(ge)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Pe(ge,E)}if(xe.call(J,"key")){var Re=W(E),Ye=Object.keys(J).filter(function(Fk){return Fk!=="key"}),Vn=Ye.length>0?"{key: someKey, "+Ye.join(": ..., ")+": ...}":"{key: someKey}";if(!An[Re+Vn]){var rn=Ye.length>0?"{"+Ye.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
26
26
  let props = %s;
27
27
  <%s {...props} />
28
28
  React keys must be passed directly to JSX without using spread:
29
29
  let props = %s;
30
- <%s key={someKey} {...props} />`,Hn,Ae,en,Ae),ar[Ae+Hn]=!0}}return E===r?zn(gt):bt(gt),gt}}function jr(E,G,se){return En(E,G,se,!0)}function Un(E,G,se){return En(E,G,se,!1)}var po=Un,lr=jr;Mr.Fragment=r,Mr.jsx=po,Mr.jsxs=lr}()),Mr}process.env.NODE_ENV==="production"?Qs.exports=Qp():Qs.exports=em();var u=Qs.exports;function Ja(e,t){return function(){return e.apply(t,arguments)}}const{toString:tm}=Object.prototype,{getPrototypeOf:ei}=Object,{iterator:xo,toStringTag:Za}=Symbol,yo=(e=>t=>{const n=tm.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),tn=e=>(e=e.toLowerCase(),t=>yo(t)===e),vo=e=>t=>typeof t===e,{isArray:cr}=Array,ur=vo("undefined");function Pr(e){return e!==null&&!ur(e)&&e.constructor!==null&&!ur(e.constructor)&&Ft(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Qa=tn("ArrayBuffer");function nm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Qa(e.buffer),t}const rm=vo("string"),Ft=vo("function"),el=vo("number"),Rr=e=>e!==null&&typeof e=="object",om=e=>e===!0||e===!1,wo=e=>{if(yo(e)!=="object")return!1;const t=ei(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Za in e)&&!(xo in e)},sm=e=>{if(!Rr(e)||Pr(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},im=tn("Date"),am=tn("File"),lm=tn("Blob"),cm=tn("FileList"),um=e=>Rr(e)&&Ft(e.pipe),dm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Ft(e.append)&&((t=yo(e))==="formdata"||t==="object"&&Ft(e.toString)&&e.toString()==="[object FormData]"))},fm=tn("URLSearchParams"),[hm,pm,mm,gm]=["ReadableStream","Request","Response","Headers"].map(tn),xm=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Or(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),cr(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Pr(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(r=0;r<i;r++)a=s[r],t.call(null,e[a],a,e)}}function tl(e,t){if(Pr(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Vn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nl=e=>!ur(e)&&e!==Vn;function ti(){const{caseless:e,skipUndefined:t}=nl(this)&&this||{},n={},r=(o,s)=>{const i=e&&tl(n,s)||s;wo(n[i])&&wo(o)?n[i]=ti(n[i],o):wo(o)?n[i]=ti({},o):cr(o)?n[i]=o.slice():(!t||!ur(o))&&(n[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Or(arguments[o],r);return n}const ym=(e,t,n,{allOwnKeys:r}={})=>(Or(t,(o,s)=>{n&&Ft(o)?e[s]=Ja(o,n):e[s]=o},{allOwnKeys:r}),e),vm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),wm=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},bm=(e,t,n,r)=>{let o,s,i;const a={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),s=o.length;s-- >0;)i=o[s],(!r||r(i,e,t))&&!a[i]&&(t[i]=e[i],a[i]=!0);e=n!==!1&&ei(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Sm=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Cm=e=>{if(!e)return null;if(cr(e))return e;let t=e.length;if(!el(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Tm=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ei(Uint8Array)),km=(e,t)=>{const r=(e&&e[xo]).call(e);let o;for(;(o=r.next())&&!o.done;){const s=o.value;t.call(e,s[0],s[1])}},Im=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},Em=tn("HTMLFormElement"),Nm=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),rl=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Am=tn("RegExp"),ol=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Or(n,(o,s)=>{let i;(i=t(o,s,e))!==!1&&(r[s]=i||o)}),Object.defineProperties(e,r)},jm=e=>{ol(e,(t,n)=>{if(Ft(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Ft(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},_m=(e,t)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return cr(e)?r(e):r(String(e).split(t)),n},Mm=()=>{},Pm=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Rm(e){return!!(e&&Ft(e.append)&&e[Za]==="FormData"&&e[xo])}const Om=e=>{const t=new Array(10),n=(r,o)=>{if(Rr(r)){if(t.indexOf(r)>=0)return;if(Pr(r))return r;if(!("toJSON"in r)){t[o]=r;const s=cr(r)?[]:{};return Or(r,(i,a)=>{const l=n(i,o+1);!ur(l)&&(s[a]=l)}),t[o]=void 0,s}}return r};return n(e,0)},Dm=tn("AsyncFunction"),Lm=e=>e&&(Rr(e)||Ft(e))&&Ft(e.then)&&Ft(e.catch),sl=((e,t)=>e?setImmediate:t?((n,r)=>(Vn.addEventListener("message",({source:o,data:s})=>{o===Vn&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),Vn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ft(Vn.postMessage)),$m=typeof queueMicrotask<"u"?queueMicrotask.bind(Vn):typeof process<"u"&&process.nextTick||sl,D={isArray:cr,isArrayBuffer:Qa,isBuffer:Pr,isFormData:dm,isArrayBufferView:nm,isString:rm,isNumber:el,isBoolean:om,isObject:Rr,isPlainObject:wo,isEmptyObject:sm,isReadableStream:hm,isRequest:pm,isResponse:mm,isHeaders:gm,isUndefined:ur,isDate:im,isFile:am,isBlob:lm,isRegExp:Am,isFunction:Ft,isStream:um,isURLSearchParams:fm,isTypedArray:Tm,isFileList:cm,forEach:Or,merge:ti,extend:ym,trim:xm,stripBOM:vm,inherits:wm,toFlatObject:bm,kindOf:yo,kindOfTest:tn,endsWith:Sm,toArray:Cm,forEachEntry:km,matchAll:Im,isHTMLForm:Em,hasOwnProperty:rl,hasOwnProp:rl,reduceDescriptors:ol,freezeMethods:jm,toObjectSet:_m,toCamelCase:Nm,noop:Mm,toFiniteNumber:Pm,findKey:tl,global:Vn,isContextDefined:nl,isSpecCompliantForm:Rm,toJSONObject:Om,isAsyncFn:Dm,isThenable:Lm,setImmediate:sl,asap:$m,isIterable:e=>e!=null&&Ft(e[xo])};function Me(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}D.inherits(Me,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:D.toJSONObject(this.config),code:this.code,status:this.status}}});const il=Me.prototype,al={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{al[e]={value:e}}),Object.defineProperties(Me,al),Object.defineProperty(il,"isAxiosError",{value:!0}),Me.from=(e,t,n,r,o,s)=>{const i=Object.create(il);D.toFlatObject(e,i,function(d){return d!==Error.prototype},c=>c!=="isAxiosError");const a=e&&e.message?e.message:"Error",l=t==null&&e?e.code:t;return Me.call(i,a,l,n,r,o),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",s&&Object.assign(i,s),i};const Fm=null;function ni(e){return D.isPlainObject(e)||D.isArray(e)}function ll(e){return D.endsWith(e,"[]")?e.slice(0,-2):e}function cl(e,t,n){return e?e.concat(t).map(function(o,s){return o=ll(o),!n&&s?"["+o+"]":o}).join(n?".":""):t}function Bm(e){return D.isArray(e)&&!e.some(ni)}const zm=D.toFlatObject(D,{},null,function(t){return/^is[A-Z]/.test(t)});function bo(e,t,n){if(!D.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=D.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,x){return!D.isUndefined(x[m])});const r=n.metaTokens,o=n.visitor||d,s=n.dots,i=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&D.isSpecCompliantForm(t);if(!D.isFunction(o))throw new TypeError("visitor must be a function");function c(y){if(y===null)return"";if(D.isDate(y))return y.toISOString();if(D.isBoolean(y))return y.toString();if(!l&&D.isBlob(y))throw new Me("Blob is not supported. Use a Buffer instead.");return D.isArrayBuffer(y)||D.isTypedArray(y)?l&&typeof Blob=="function"?new Blob([y]):Buffer.from(y):y}function d(y,m,x){let g=y;if(y&&!x&&typeof y=="object"){if(D.endsWith(m,"{}"))m=r?m:m.slice(0,-2),y=JSON.stringify(y);else if(D.isArray(y)&&Bm(y)||(D.isFileList(y)||D.endsWith(m,"[]"))&&(g=D.toArray(y)))return m=ll(m),g.forEach(function(S,k){!(D.isUndefined(S)||S===null)&&t.append(i===!0?cl([m],k,s):i===null?m:m+"[]",c(S))}),!1}return ni(y)?!0:(t.append(cl(x,m,s),c(y)),!1)}const f=[],h=Object.assign(zm,{defaultVisitor:d,convertValue:c,isVisitable:ni});function p(y,m){if(!D.isUndefined(y)){if(f.indexOf(y)!==-1)throw Error("Circular reference detected in "+m.join("."));f.push(y),D.forEach(y,function(g,w){(!(D.isUndefined(g)||g===null)&&o.call(t,g,D.isString(w)?w.trim():w,m,h))===!0&&p(g,m?m.concat(w):[w])}),f.pop()}}if(!D.isObject(e))throw new TypeError("data must be an object");return p(e),t}function ul(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function ri(e,t){this._pairs=[],e&&bo(e,this,t)}const dl=ri.prototype;dl.append=function(t,n){this._pairs.push([t,n])},dl.toString=function(t){const n=t?function(r){return t.call(this,r,ul)}:ul;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function Um(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function fl(e,t,n){if(!t)return e;const r=n&&n.encode||Um;D.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(t,n):s=D.isURLSearchParams(t)?t.toString():new ri(t,n).toString(r),s){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class hl{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){D.forEach(this.handlers,function(r){r!==null&&t(r)})}}const pl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Hm={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:ri,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},oi=typeof window<"u"&&typeof document<"u",si=typeof navigator=="object"&&navigator||void 0,Wm=oi&&(!si||["ReactNative","NativeScript","NS"].indexOf(si.product)<0),Vm=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Km=oi&&window.location.href||"http://localhost",Nt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:oi,hasStandardBrowserEnv:Wm,hasStandardBrowserWebWorkerEnv:Vm,navigator:si,origin:Km},Symbol.toStringTag,{value:"Module"})),...Hm};function qm(e,t){return bo(e,new Nt.classes.URLSearchParams,{visitor:function(n,r,o,s){return Nt.isNode&&D.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function Gm(e){return D.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Ym(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r<o;r++)s=n[r],t[s]=e[s];return t}function ml(e){function t(n,r,o,s){let i=n[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),l=s>=n.length;return i=!i&&D.isArray(o)?o.length:i,l?(D.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!a):((!o[i]||!D.isObject(o[i]))&&(o[i]=[]),t(n,r,o[i],s)&&D.isArray(o[i])&&(o[i]=Ym(o[i])),!a)}if(D.isFormData(e)&&D.isFunction(e.entries)){const n={};return D.forEachEntry(e,(r,o)=>{t(Gm(r),o,n,0)}),n}return null}function Xm(e,t,n){if(D.isString(e))try{return(t||JSON.parse)(e),D.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Dr={transitional:pl,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=D.isObject(t);if(s&&D.isHTMLForm(t)&&(t=new FormData(t)),D.isFormData(t))return o?JSON.stringify(ml(t)):t;if(D.isArrayBuffer(t)||D.isBuffer(t)||D.isStream(t)||D.isFile(t)||D.isBlob(t)||D.isReadableStream(t))return t;if(D.isArrayBufferView(t))return t.buffer;if(D.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return qm(t,this.formSerializer).toString();if((a=D.isFileList(t))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return bo(a?{"files[]":t}:t,l&&new l,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),Xm(t)):t}],transformResponse:[function(t){const n=this.transitional||Dr.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(D.isResponse(t)||D.isReadableStream(t))return t;if(t&&D.isString(t)&&(r&&!this.responseType||o)){const i=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?Me.from(a,Me.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Nt.classes.FormData,Blob:Nt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};D.forEach(["delete","get","head","post","put","patch"],e=>{Dr.headers[e]={}});const Jm=D.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Zm=e=>{const t={};let n,r,o;return e&&e.split(`
31
- `).forEach(function(i){o=i.indexOf(":"),n=i.substring(0,o).trim().toLowerCase(),r=i.substring(o+1).trim(),!(!n||t[n]&&Jm[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},gl=Symbol("internals");function Lr(e){return e&&String(e).trim().toLowerCase()}function So(e){return e===!1||e==null?e:D.isArray(e)?e.map(So):String(e)}function Qm(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const eg=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ii(e,t,n,r,o){if(D.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!D.isString(t)){if(D.isString(r))return t.indexOf(r)!==-1;if(D.isRegExp(r))return r.test(t)}}function tg(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function ng(e,t){const n=D.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,s,i){return this[r].call(this,t,o,s,i)},configurable:!0})})}let Bt=class{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function s(a,l,c){const d=Lr(l);if(!d)throw new Error("header name must be a non-empty string");const f=D.findKey(o,d);(!f||o[f]===void 0||c===!0||c===void 0&&o[f]!==!1)&&(o[f||l]=So(a))}const i=(a,l)=>D.forEach(a,(c,d)=>s(c,d,l));if(D.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(D.isString(t)&&(t=t.trim())&&!eg(t))i(Zm(t),n);else if(D.isObject(t)&&D.isIterable(t)){let a={},l,c;for(const d of t){if(!D.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[c=d[0]]=(l=a[c])?D.isArray(l)?[...l,d[1]]:[l,d[1]]:d[1]}i(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Lr(t),t){const r=D.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return Qm(o);if(D.isFunction(n))return n.call(this,o,r);if(D.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Lr(t),t){const r=D.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||ii(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function s(i){if(i=Lr(i),i){const a=D.findKey(r,i);a&&(!n||ii(r,r[a],a,n))&&(delete r[a],o=!0)}}return D.isArray(t)?t.forEach(s):s(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!t||ii(this,this[s],s,t,!0))&&(delete this[s],o=!0)}return o}normalize(t){const n=this,r={};return D.forEach(this,(o,s)=>{const i=D.findKey(r,s);if(i){n[i]=So(o),delete n[s];return}const a=t?tg(s):String(s).trim();a!==s&&delete n[s],n[a]=So(o),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return D.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&D.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
32
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[gl]=this[gl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Lr(i);r[a]||(ng(o,i),r[a]=!0)}return D.isArray(t)?t.forEach(s):s(t),this}};Bt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),D.reduceDescriptors(Bt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),D.freezeMethods(Bt);function ai(e,t){const n=this||Dr,r=t||n,o=Bt.from(r.headers);let s=r.data;return D.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function xl(e){return!!(e&&e.__CANCEL__)}function dr(e,t,n){Me.call(this,e??"canceled",Me.ERR_CANCELED,t,n),this.name="CanceledError"}D.inherits(dr,Me,{__CANCEL__:!0});function yl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Me("Request failed with status code "+n.status,[Me.ERR_BAD_REQUEST,Me.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function rg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function og(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(h*1e3/p):void 0}}function sg(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const Co=(e,t,n=3)=>{let r=0;const o=og(50,250);return sg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},vl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},wl=e=>(...t)=>D.asap(()=>e(...t)),ig=Nt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Nt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Nt.origin),Nt.navigator&&/(msie|trident)/i.test(Nt.navigator.userAgent)):()=>!0,ag=Nt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];D.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),D.isString(r)&&i.push("path="+r),D.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function lg(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function cg(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function bl(e,t,n){let r=!lg(t);return e&&(r||n==!1)?cg(e,t):t}const Sl=e=>e instanceof Bt?{...e}:e;function Kn(e,t){t=t||{};const n={};function r(c,d,f,h){return D.isPlainObject(c)&&D.isPlainObject(d)?D.merge.call({caseless:h},c,d):D.isPlainObject(d)?D.merge({},d):D.isArray(d)?d.slice():d}function o(c,d,f,h){if(D.isUndefined(d)){if(!D.isUndefined(c))return r(void 0,c,f,h)}else return r(c,d,f,h)}function s(c,d){if(!D.isUndefined(d))return r(void 0,d)}function i(c,d){if(D.isUndefined(d)){if(!D.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(Sl(c),Sl(d),f,!0)};return D.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,h=f(e[d],t[d],d);D.isUndefined(h)&&f!==a||(n[d]=h)}),n}const Cl=e=>{const t=Kn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Bt.from(i),t.url=fl(bl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),D.isFormData(n)){if(Nt.hasStandardBrowserEnv||Nt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(D.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Nt.hasStandardBrowserEnv&&(r&&D.isFunction(r)&&(r=r(t)),r||r!==!1&&ig(t.url))){const l=o&&s&&ag.read(s);l&&i.set(o,l)}return t},ug=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=Cl(e);let s=o.data;const i=Bt.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,h,p,y;function m(){p&&p(),y&&y(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let x=new XMLHttpRequest;x.open(o.method.toUpperCase(),o.url,!0),x.timeout=o.timeout;function g(){if(!x)return;const S=Bt.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:S,config:e,request:x};yl(function(I){n(I),m()},function(I){r(I),m()},C),x=null}"onloadend"in x?x.onloadend=g:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(g)},x.onabort=function(){x&&(r(new Me("Request aborted",Me.ECONNABORTED,e,x)),x=null)},x.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new Me(C,Me.ERR_NETWORK,e,x);T.event=k||null,r(T),x=null},x.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||pl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new Me(k,C.clarifyTimeoutError?Me.ETIMEDOUT:Me.ECONNABORTED,e,x)),x=null},s===void 0&&i.setContentType(null),"setRequestHeader"in x&&D.forEach(i.toJSON(),function(k,C){x.setRequestHeader(C,k)}),D.isUndefined(o.withCredentials)||(x.withCredentials=!!o.withCredentials),a&&a!=="json"&&(x.responseType=o.responseType),c&&([h,y]=Co(c,!0),x.addEventListener("progress",h)),l&&x.upload&&([f,p]=Co(l),x.upload.addEventListener("progress",f),x.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(d=S=>{x&&(r(!S||S.type?new dr(null,e,x):S),x.abort(),x=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=rg(o.url);if(w&&Nt.protocols.indexOf(w)===-1){r(new Me("Unsupported protocol "+w+":",Me.ERR_BAD_REQUEST,e));return}x.send(s||null)})},dg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof Me?d:new dr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Me(`timeout ${t} of ms exceeded`,Me.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>D.asap(a),l}},fg=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},hg=async function*(e,t){for await(const n of pg(e))yield*fg(n,t)},pg=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Tl=(e,t,n,r)=>{const o=hg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let h=s+=f;n(h)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},kl=64*1024,{isFunction:To}=D,mg=(({Request:e,Response:t})=>({Request:e,Response:t}))(D.global),{ReadableStream:Il,TextEncoder:El}=D.global,Nl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},gg=e=>{e=D.merge.call({skipUndefined:!0},mg,e);const{fetch:t,Request:n,Response:r}=e,o=t?To(t):typeof fetch=="function",s=To(n),i=To(r);if(!o)return!1;const a=o&&To(Il),l=o&&(typeof El=="function"?(y=>m=>y.encode(m))(new El):async y=>new Uint8Array(await new n(y).arrayBuffer())),c=s&&a&&Nl(()=>{let y=!1;const m=new n(Nt.origin,{body:new Il,method:"POST",get duplex(){return y=!0,"half"}}).headers.has("Content-Type");return y&&!m}),d=i&&a&&Nl(()=>D.isReadableStream(new r("").body)),f={stream:d&&(y=>y.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(y=>{!f[y]&&(f[y]=(m,x)=>{let g=m&&m[y];if(g)return g.call(m);throw new Me(`Response type '${y}' is not supported`,Me.ERR_NOT_SUPPORT,x)})});const h=async y=>{if(y==null)return 0;if(D.isBlob(y))return y.size;if(D.isSpecCompliantForm(y))return(await new n(Nt.origin,{method:"POST",body:y}).arrayBuffer()).byteLength;if(D.isArrayBufferView(y)||D.isArrayBuffer(y))return y.byteLength;if(D.isURLSearchParams(y)&&(y=y+""),D.isString(y))return(await l(y)).byteLength},p=async(y,m)=>{const x=D.toFiniteNumber(y.getContentLength());return x??h(m)};return async y=>{let{url:m,method:x,data:g,signal:w,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:I,headers:j,withCredentials:_="same-origin",fetchOptions:O}=Cl(y),B=t||fetch;I=I?(I+"").toLowerCase():"text";let K=dg([w,S&&S.toAbortSignal()],k),V=null;const P=K&&K.unsubscribe&&(()=>{K.unsubscribe()});let M;try{if(T&&c&&x!=="get"&&x!=="head"&&(M=await p(j,g))!==0){let Y=new n(m,{method:"POST",body:g,duplex:"half"}),ne;if(D.isFormData(g)&&(ne=Y.headers.get("content-type"))&&j.setContentType(ne),Y.body){const[pe,be]=vl(M,Co(wl(T)));g=Tl(Y.body,kl,pe,be)}}D.isString(_)||(_=_?"include":"omit");const N=s&&"credentials"in n.prototype,z={...O,signal:K,method:x.toUpperCase(),headers:j.normalize().toJSON(),body:g,duplex:"half",credentials:N?_:void 0};V=s&&new n(m,z);let L=await(s?B(V,O):B(m,z));const R=d&&(I==="stream"||I==="response");if(d&&(C||R&&P)){const Y={};["status","statusText","headers"].forEach(Ie=>{Y[Ie]=L[Ie]});const ne=D.toFiniteNumber(L.headers.get("content-length")),[pe,be]=C&&vl(ne,Co(wl(C),!0))||[];L=new r(Tl(L.body,kl,pe,()=>{be&&be(),P&&P()}),Y)}I=I||"text";let W=await f[D.findKey(f,I)||"text"](L,y);return!R&&P&&P(),await new Promise((Y,ne)=>{yl(Y,ne,{data:W,headers:Bt.from(L.headers),status:L.status,statusText:L.statusText,config:y,request:V})})}catch(N){throw P&&P(),N&&N.name==="TypeError"&&/Load failed|fetch/i.test(N.message)?Object.assign(new Me("Network Error",Me.ERR_NETWORK,y,V),{cause:N.cause||N}):Me.from(N,N&&N.code,y,V)}}},xg=new Map,Al=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=xg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:gg(t)),d=c;return c};Al();const li={http:Fm,xhr:ug,fetch:{get:Al}};D.forEach(li,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const jl=e=>`- ${e}`,yg=e=>D.isFunction(e)||e===null||e===!1,_l={getAdapter:(e,t)=>{e=D.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!yg(r)&&(o=li[(a=String(r)).toLowerCase()],o===void 0))throw new Me(`Unknown adapter '${a}'`);if(o&&(D.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
33
- `+i.map(jl).join(`
34
- `):" "+jl(i[0]):"as no adapter specified";throw new Me("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:li};function ci(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new dr(null,e)}function Ml(e){return ci(e),e.headers=Bt.from(e.headers),e.data=ai.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),_l.getAdapter(e.adapter||Dr.adapter,e)(e).then(function(r){return ci(e),r.data=ai.call(e,e.transformResponse,r),r.headers=Bt.from(r.headers),r},function(r){return xl(r)||(ci(e),r&&r.response&&(r.response.data=ai.call(e,e.transformResponse,r.response),r.response.headers=Bt.from(r.response.headers))),Promise.reject(r)})}const Pl="1.12.2",ko={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ko[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Rl={};ko.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Pl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Me(o(i," has been removed"+(n?" in "+n:"")),Me.ERR_DEPRECATED);return n&&!Rl[i]&&(Rl[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},ko.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function vg(e,t,n){if(typeof e!="object")throw new Me("options must be an object",Me.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new Me("option "+s+" must be "+l,Me.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Me("Unknown option "+s,Me.ERR_BAD_OPTION)}}const Io={assertOptions:vg,validators:ko},un=Io.validators;let qn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new hl,response:new hl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
35
- `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Kn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Io.assertOptions(r,{silentJSONParsing:un.transitional(un.boolean),forcedJSONParsing:un.transitional(un.boolean),clarifyTimeoutError:un.transitional(un.boolean)},!1),o!=null&&(D.isFunction(o)?n.paramsSerializer={serialize:o}:Io.assertOptions(o,{encode:un.function,serialize:un.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Io.assertOptions(n,{baseUrl:un.spelling("baseURL"),withXsrfToken:un.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&D.merge(s.common,s[n.method]);s&&D.forEach(["delete","get","head","post","put","patch","common"],y=>{delete s[y]}),n.headers=Bt.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,h;if(!l){const y=[Ml.bind(this),void 0];for(y.unshift(...a),y.push(...c),h=y.length,d=Promise.resolve(n);f<h;)d=d.then(y[f++],y[f++]);return d}h=a.length;let p=n;for(;f<h;){const y=a[f++],m=a[f++];try{p=y(p)}catch(x){m.call(this,x);break}}try{d=Ml.call(this,p)}catch(y){return Promise.reject(y)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Kn(this.defaults,t);const n=bl(t.baseURL,t.url,t.allowAbsoluteUrls);return fl(n,t.params,t.paramsSerializer)}};D.forEach(["delete","get","head","options"],function(t){qn.prototype[t]=function(n,r){return this.request(Kn(r||{},{method:t,url:n,data:(r||{}).data}))}}),D.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Kn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}qn.prototype[t]=n(),qn.prototype[t+"Form"]=n(!0)});let wg=class Xp{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new dr(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Xp(function(o){t=o}),cancel:t}}};function bg(e){return function(n){return e.apply(null,n)}}function Sg(e){return D.isObject(e)&&e.isAxiosError===!0}const ui={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ui).forEach(([e,t])=>{ui[t]=e});function Ol(e){const t=new qn(e),n=Ja(qn.prototype.request,t);return D.extend(n,qn.prototype,t,{allOwnKeys:!0}),D.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Ol(Kn(e,o))},n}const xt=Ol(Dr);xt.Axios=qn,xt.CanceledError=dr,xt.CancelToken=wg,xt.isCancel=xl,xt.VERSION=Pl,xt.toFormData=bo,xt.AxiosError=Me,xt.Cancel=xt.CanceledError,xt.all=function(t){return Promise.all(t)},xt.spread=bg,xt.isAxiosError=Sg,xt.mergeConfig=Kn,xt.AxiosHeaders=Bt,xt.formToJSON=e=>ml(D.isHTMLForm(e)?new FormData(e):e),xt.getAdapter=_l.getAdapter,xt.HttpStatusCode=ui,xt.default=xt;const{Axios:KT,AxiosError:qT,CanceledError:GT,isCancel:YT,CancelToken:XT,VERSION:JT,all:ZT,Cancel:QT,isAxiosError:ek,spread:tk,toFormData:nk,AxiosHeaders:rk,HttpStatusCode:ok,formToJSON:sk,getAdapter:ik,mergeConfig:ak}=xt,Dl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ll=Dl?wn(Dl):void 0;function wn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Eo=null;const di=new Set;function $l(){return Eo}function No(e){Eo=e,di.forEach(t=>t(e))}function Fl(e){return di.add(e),()=>di.delete(e)}const Cg=3e4,Tg=9e4,qt=xt.create({...Ll?{baseURL:Ll}:{},timeout:Cg,withCredentials:!0});qt.interceptors.request.use(e=>(Eo&&(e.headers.Authorization=`Bearer ${Eo}`),e)),qt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),No(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Ut(e,t){return qt.defaults.baseURL?(await qt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Ao(e,t,n){return qt.defaults.baseURL?(await qt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Bl(e,t,n){return qt.defaults.baseURL?(await qt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function fi(e,t){return qt.defaults.baseURL?(await qt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Rt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class zl{get baseUrl(){const t=qt.defaults.baseURL;return t?wn(String(t)):""}updateConfig(t){t.baseUrl&&(qt.defaults.baseURL=wn(String(t.baseUrl))),t.authToken!==void 0&&No(t.authToken)}getAuthToken(){return $l()}setAuthToken(t){No(t)}onTokenChange(t){return Fl(t)}async listThreads(){const t=await Ut("/threads"),n=Rt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Ut("/threads/shared"),n=Rt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Ao("/threads",t?{title:t}:void 0);return Rt(r)}async updateThread(t,n){const r=await Bl(`/threads/${t}`,{title:n});return Rt(r)}async deleteThread(t){const n=await fi(`/threads/${t}`);return Rt(n)}async shareThread(t,n){const r=await Ao(`/threads/${t}/share`,{shared_with_user_id:n});return Rt(r)}async threadInfo(t){const n=await Ut(`/threads/${t}/info`);return Rt(n)}async listAgents(){const t=await Ut("/agents"),n=Rt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Ut(`/agents/${t}`);return Rt(n)}async getAgentSchema(t){const n=await Ut(`/agents/${t}/schema`);return Rt(n)}async getState(t){const n=await Ut(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Rt(n)}async getStateHistory(t){const n=await Ut(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Tg});return Rt(n)}async cancelRun(t){const n=await Ao("/runs/cancel",{threadId:t});return Rt(n)}async listCheckpointSummaries(t){const n=await Ut(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Rt(n);return(r==null?void 0:r.items)??[]}async unshareThread(t,n){const r=await fi(`/threads/${t}/share/${n}`);return Rt(r)}}const Nn=new zl,Ul=b.createContext(null);function kg({children:e,apiConfig:t}){const n=Nn;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(Ul.Provider,{value:r,children:e})}function hi(){const e=b.useContext(Ul);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Ig(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Eg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Ig(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Hl=120;function Ng(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>Hl?`${n.slice(0,Hl-3)}…`:n:""}function Wl(e){return Ng(e.content)||""}function Ag(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=Wl(n);r&&t.set(n.id,r)}return t}function jg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=Wl(o);s&&t.set(r.checkpointId,s)}}return t}const _g={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function pi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Mg(e,t){return`${e??""}::${t??""}`}function fr(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!pi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Rg(t),i=Vl(r,0),a=Og(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Vl(e,t){if(!pi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,O)=>Wg(_,O)).filter(_=>!!_),d=Ot(e.config),f=Ot(d==null?void 0:d.configurable),h=ut(f,["checkpoint_id","checkpointId"]),p=ut(f,["checkpoint_ns","checkpointNs"]),y=Ot(e==null?void 0:e.parentConfig),m=Ot(y==null?void 0:y.configurable),x=ut(m,["checkpoint_id","checkpointId"])??null,g=ut(m,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,S=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Ot(e==null?void 0:e.metadata),T=ut(C,["branch_label","branchLabel"]),I=ut(m,["checkpoint_id","checkpointId"]),j=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:x,nextCursorNs:g,interrupt:Pg(a,c,t),createdAt:S,parentId:I??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:y??null,next:j??null,tasks:l??null,values:i??null}}function Pg(e,t,n){const r=Ug(e,n);return r||zg(t,n)}function Rg(e){const t=new Map;e.forEach((o,s)=>{if(!pi(o))return;const i=Vl(o,s);if(!(i!=null&&i.checkpointId))return;const a=Mg(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,$g(l,i))});const n=Array.from(t.values());n.sort((o,s)=>ql(s.createdAt??"")-ql(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function Og(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=ut(i,["label"])??ut(i,["branch_label","branchLabel"])??ut(i,["description"])??"User input",l=Lg(i,["step"]),c=ut(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,h=o.lastUserMessageId??f,p=Dg(o.next);t.push({id:s,label:a,messageId:h,step:l,source:c??null,createdAt:d,next:p??void 0,parentConfig:o.parentConfig??null})}return t}function Dg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Lg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function $g(e,t){return{...e,metadata:jo(e.metadata,t.metadata)??null,config:jo(e.config,t.config)??null,parentConfig:jo(e.parentConfig,t.parentConfig)??null,next:Fg(e.next,t.next)??null,tasks:Bg(e.tasks,t.tasks)??null,values:jo(e.values,t.values)??null}}function jo(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Fg(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Bg(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function zg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Ug(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Hg(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=$r(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=$r(r.state,`${o}-state`);if(s)return s}}return null}function Hg(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,y=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,x=h.length?h[h.length-1]:void 0;return{id:p,name:y,interrupts:m,state:x!==void 0?x:f}}const n=Ot(e);if(!n)return null;const r=ut(n,["id","thread_id","taskId"])??t,o=ut(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function $r(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Kl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=$r(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=$r(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=$r(l,t,n+1,r);if(c)return c}}return null}function Kl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=ut(n,["type","event","kind"]),o=ut(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Kl(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function ql(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Wg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ot(e)??{},o=Ot(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=_g[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ot(o.additional_kwargs)??Ot(o.additionalKwargs),d=Ot(o.response_metadata)??Ot(o.responseMetadata),f=ut(c,["createdAt","created_at"])??ut(o,["created_at","createdAt"]),h=ut(c,["checkpointId","checkpoint_id"]),p=ut(c,["checkpointNs","checkpoint_ns"]),y=Vg(o.content),m={id:l,role:i,content:y};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),h&&(m.checkpointId=h),p&&(m.checkpointNs=p);const x=Gg(Ot(o.artifact??r.artifact??o.artifacts??r.artifacts));x&&(m.artifact=x);const g=Zg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),w=d?{...d}:void 0;g&&Object.keys(g).length&&(m.additionalKwargs=g),w&&Object.keys(w).length&&(m.responseMetadata=w);const S=Kg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=qg(o,m.content);k&&(m.content=k)}return m}function Vg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Gl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Gl(e);return t?[t]:[]}return[]}function Gl(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=ut(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=ut(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Yl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=ut(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Yl(e,t){var s;const n=ut(e,["id","call_id"])??t,r=ut(e,["name"])??ut(Ot(e.function),["name"]);if(!n||!r)return null;const o=Jg(e.args??e.arguments??((s=Ot(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Kg(e){return Array.isArray(e)?e.map((t,n)=>Yl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function qg(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Gg(e){return e?{plots:Yg(e.plots)}:void 0}function Yg(e){return Array.isArray(e)?e.map(t=>Xg(t)).filter(t=>!!t):[]}function Xg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Jg(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function Ot(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function ut(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function Zg(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}const Xl="aiNav:tool-progress";function mi(){return typeof window<"u"&&typeof window.localStorage<"u"}function Jl(e){return`${Xl}:${e}`}function Qg(e,t,n){if(!mi()||!e)return;const r=Jl(e);if(!t.length){window.localStorage.removeItem(r);return}const o={messageId:e,entries:t,updatedAt:Date.now(),...n??{}};try{window.localStorage.setItem(r,JSON.stringify(o))}catch{}}function ex(e){if(!mi()||!e)return;const t=Jl(e),n=window.localStorage.getItem(t);if(n)try{const r=JSON.parse(n);return!(r!=null&&r.entries)||!Array.isArray(r.entries)?void 0:r.entries}catch{window.localStorage.removeItem(t);return}}function Zl(){if(!mi())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(Xl)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const Tt=[];for(let e=0;e<256;++e)Tt.push((e+256).toString(16).slice(1));function tx(e,t=0){return(Tt[e[t+0]]+Tt[e[t+1]]+Tt[e[t+2]]+Tt[e[t+3]]+"-"+Tt[e[t+4]]+Tt[e[t+5]]+"-"+Tt[e[t+6]]+Tt[e[t+7]]+"-"+Tt[e[t+8]]+Tt[e[t+9]]+"-"+Tt[e[t+10]]+Tt[e[t+11]]+Tt[e[t+12]]+Tt[e[t+13]]+Tt[e[t+14]]+Tt[e[t+15]]).toLowerCase()}let gi;const nx=new Uint8Array(16);function rx(){if(!gi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");gi=crypto.getRandomValues.bind(crypto)}return gi(nx)}const Ql={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ox(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??rx();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,tx(r)}function sx(e,t,n){return Ql.randomUUID&&!e?Ql.randomUUID():ox(e)}function xi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function _o(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function ec(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function tc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function nc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function ix(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=hx(e);for(const o of r)n.add(o);return Array.from(n)}function rc(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function ax(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};for(const l of t)s(l);const i=Array.from(o),a={};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function Mo(e,t,n){const r=e.findIndex(c=>c.id===t);if(r===-1)return e;const o=e[r],s=[...e],i={...o.additionalKwargs??{}},a=Array.isArray(i.toolProgress)?[...i.toolProgress]:[],l={id:sx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Qg(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function oc(e,t){return e.includes(t)?e:[...e,t]}function lx(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function hr(e,t){let n=!1;const r={},o=e.map(s=>{const i=px(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??ex(s.id);if(a!=null&&a.length){const l=[...a];r[s.id]=l,n=!0;const c={...s.additionalKwargs??{},toolProgress:l};return{...s,additionalKwargs:c}}return s});return{messages:n?o:e,toolTimelines:r}}function sc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function cx(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??sc(e);let l="",c=e.slice();if(s){const f=ux(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",y={...h,text:p+l};c=[...c.slice(0,c.length-1),y]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function ic(e){return e.replace(/\s+/g," ").trim()}function ux(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=ic(e),o=ic(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function dx(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return _o(e,r,s)}return e}function fx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function hx(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function px(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const mx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function gx(e,t){var n;switch(t.type){case"reset":return{messages:xi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"seed":{const r=xi(t.payload.messages),{messages:o,toolTimelines:s}=hr(r,e.toolTimelines),i={...e,messages:o,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,toolStreamingMessageId:null,toolStreamingStack:[],toolTimelines:s};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(i.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(i.lastCheckpointNs=t.payload.checkpointNs??null),i}case"prepend":{const r=xi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(c=>c.id)),s=r.filter(c=>!o.has(c.id));if(!s.length)return e;const i=[...s,...e.messages],{messages:a,toolTimelines:l}=hr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return lc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>lc(o,s),e):e}case"interrupt_response":return{...e,messages:ec(e.messages),pendingInterrupt:null};default:return e}}function ac(e=[]){const[t,n]=b.useReducer(gx,{...mx,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function lc(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=fx(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message.delta"){const i=e.assemblingId??tc(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:sc(c.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof f.lastSeq=="number"&&h<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:f.lastSeq}),e;const{newParts:p,newMeta:y,changed:m}=cx(c.content,t.delta,f,h);if(!m)return e;const x={...c,content:p},g=_o(a,l,x),w={...d,[i]:y};return{...e,messages:g,messagesStreamMeta:w}}if(t.type==="message.end"){const i=e.assemblingId??tc(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.content)==null?void 0:n.some(f=>{var h;return(f==null?void 0:f.type)==="text"&&((h=f.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=c.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool.start"){const i=nc(t),a=i[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),l=t.name??t.tool??"tool";!a&&i.length===0&&i.push(`${l}-${Date.now()}`);const c=i.length?i:a?[a]:[],d=c[0]??`${l}-${Date.now()}`,f={type:"tool_call",id:d,name:l,args:t.args},h={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},p=e.toolStreamingMessageId;if(!p){const w={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...ax(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},S=ix(w,c.length?c:[d]),k=[...e.messages,w],C=Mo(k,w.id,h),{messages:T,toolTimelines:I}=hr(C,e.toolTimelines);return{...e,messages:T,toolIndex:rc(e.toolIndex,w.id,S),toolStreamingMessageId:w.id,toolStreamingStack:oc(e.toolStreamingStack??[],a??d),toolTimelines:I}}const y=Mo(e.messages,p,h),{messages:m,toolTimelines:x}=hr(y,e.toolTimelines);return{...e,messages:m,toolIndex:rc(e.toolIndex,p,c),toolStreamingStack:oc(e.toolStreamingStack??[],a??d),toolTimelines:x}}if(t.type==="tool.end"){const i=nc(t);if(!i.length&&!(typeof t.id=="string"&&t.id))return e;const a=i[0]??(typeof t.id=="string"?t.id:null);if(!a)return e;const l=e.toolStreamingStack??[],c=l[0]??null,d=lx(l,a),f=d[0]?e.toolIndex[d[0]]:null,h=e.toolStreamingMessageId,p=c===a,y=t.name??((s=e.messages.find(C=>C.id===h))==null?void 0:s.name)??"tool",m=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),x={type:"tool.end",toolId:a,toolName:y,content:m==null?void 0:m.slice(0,200)};let g=e.messages;if(h&&(g=Mo(g,h,x)),p&&h){const C=g.findIndex(T=>T.id===h);if(C>=0){const T=g[C],j={type:"text",text:(()=>{if(typeof t.output=="string"){const O=t.output.trim();try{return O}catch{return O}}return JSON.stringify(t.output??"")})()},_={...T,content:[j],artifact:t.artifact??T.artifact,additionalKwargs:{...T.additionalKwargs??{}}};g=_o(g,C,_)}}const w=d,{messages:S,toolTimelines:k}=hr(g,e.toolTimelines);return{...e,messages:S,toolTimelines:k,toolStreamingMessageId:p?f:h,toolStreamingStack:w}}if(t.type==="tool.progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"tool.progress",content:t.content??null},l=Mo(e.messages,i,a),c=l.findIndex(x=>x.id===i);if(c===-1)return e;const d=l[c],f={...d.additionalKwargs??{},toolStreaming:!0},h={...d,additionalKwargs:f},p=_o(l,c,h),{messages:y,toolTimelines:m}=hr(p,e.toolTimelines);return{...e,messages:y,toolTimelines:m}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=dx(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="state_history"){const i=fr(t),a=i.interrupt,l=i.latest,c=a===null?ec(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function cc(e={}){const t=b.useMemo(()=>wn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,h]=b.useState(""),[p,y]=b.useState(null),[m,x]=b.useState(0),[g,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),C=b.useRef(0),T=b.useRef(null),I=b.useRef(null),j=b.useRef(null),_=b.useRef(null),O=b.useCallback(P=>{o(P)},[]),B=b.useCallback(()=>{h(""),y(null),d(null),I.current=null,j.current=null,_.current=null},[]),K=b.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=S.current)==null||P.abort(),S.current=null,T.current=null,l(!1),w(!1),C.current=0,x(0)},[]),V=b.useCallback((P,M,N)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),y(null),I.current=null,j.current=null,_.current=null;const z=new AbortController;S.current=z;let L=null,R=null,W=!1;return T.current={threadId:P.threadId??null,headers:{}},(async()=>{var ne,pe,be,Ie,ve,te,F,X,A,$,H,fe,re,Z,ce,me,$e,Re;const Y=Be=>{var Xe;try{const Qe=JSON.parse(JSON.stringify(Be));return(Xe=Qe==null?void 0:Qe.payload)!=null&&Xe.files_info&&Array.isArray(Qe.payload.files_info)&&(Qe.payload.files_info=Qe.payload.files_info.map(Je=>({...Je,data:Je!=null&&Je.data?`<base64 ${String(Je.data).length} chars>`:Je==null?void 0:Je.data}))),Qe}catch{return Be}};try{let Be={};try{if(r)Be={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const J=window.__AUTH_TOKEN__,le=((ne=window.localStorage)==null?void 0:ne.getItem("authToken"))||null;let ze=null;try{const ft=(pe=window.localStorage)==null?void 0:pe.getItem("chat-settings");ft&&(ze=((be=JSON.parse(ft))==null?void 0:be.apiKey)||null)}catch{}const Se=J||le||ze||null;Se&&(Be={Authorization:`Bearer ${Se}`})}}catch{}console.debug("[use-chat] POST",t+n,Y(P));let Xe={};if(typeof window<"u")try{const rt=(Ie=window.localStorage)==null?void 0:Ie.getItem("authSessionId");rt&&(Xe={"X-Session-Id":rt})}catch{}const Qe={...Be,...Xe,...s.current},Je={"Content-Type":"application/json",Accept:"text/event-stream",...Qe},et=await fetch(t+n,{method:"POST",headers:Je,body:JSON.stringify(P),signal:z.signal,credentials:i});if(T.current&&(T.current.headers=Qe),!et.ok||!et.body){const rt=await et.text().catch(()=>"");console.debug("[use-chat] non-OK response",et.status,rt==null?void 0:rt.slice(0,500));const J=`stream ${et.status}${rt?": "+rt:""}`;throw(ve=N==null?void 0:N.onConnectionError)==null||ve.call(N,J),W=!0,L="error",R=J,new Error(J)}w(!0);const it=et.body.getReader(),Mt=new TextDecoder;let pt="",Ct=[];C.current=0,x(0);let mt=0,wt=null;const Pt=()=>{if(Ct.length){const rt=Ct.join("");Ct=[],k.current&&h(J=>J+rt)}wt=null},$t=()=>{typeof window<"u"&&wt==null&&(wt=requestAnimationFrame(Pt))};let cn=Date.now();const We=setInterval(()=>{var rt;if(Date.now()-cn>18e5){const J="Stream idle timeout";d(J),L="error",R=J,z.abort(),(rt=N==null?void 0:N.onError)==null||rt.call(N,J)}},5e3),In=1024*1024;try{const rt=et.headers.get("X-Thread-Id")||et.headers.get("x-thread-id"),J=et.headers.get("X-Thread-Created")||et.headers.get("x-thread-created"),le=rt??null,ze=String(J??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:le}),(te=N==null?void 0:N.onOpen)==null||te.call(N,{threadId:le,created:ze});;){const{value:Se,done:ft}=await it.read();if(ft)break;pt+=Mt.decode(Se,{stream:!0}),pt.length>In&&(pt="",console.warn("Stream buffer reset: exceeded 1MB"));let U;for(;(U=pt.indexOf(`
30
+ <%s key={someKey} {...props} />`,Vn,Re,rn,Re),An[Re+Vn]=!0}}return E===r?Cn(mt):ht(mt),mt}}function Dr(E,J,de){return Or(E,J,de,!0)}function ur(E,J,de){return Or(E,J,de,!1)}var Lr=ur,dr=Dr;Fr.Fragment=r,Fr.jsx=Lr,Fr.jsxs=dr}()),Fr}process.env.NODE_ENV==="production"?li.exports=_m():li.exports=Mm();var u=li.exports;function gl(e,t){return function(){return e.apply(t,arguments)}}const{toString:Rm}=Object.prototype,{getPrototypeOf:ci}=Object,{iterator:Eo,toStringTag:xl}=Symbol,No=(e=>t=>{const n=Rm.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),on=e=>(e=e.toLowerCase(),t=>No(t)===e),Ao=e=>t=>typeof t===e,{isArray:fr}=Array,pr=Ao("undefined");function Br(e){return e!==null&&!pr(e)&&e.constructor!==null&&!pr(e.constructor)&&Ft(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const yl=on("ArrayBuffer");function Pm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&yl(e.buffer),t}const Om=Ao("string"),Ft=Ao("function"),vl=Ao("number"),zr=e=>e!==null&&typeof e=="object",Dm=e=>e===!0||e===!1,jo=e=>{if(No(e)!=="object")return!1;const t=ci(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(xl in e)&&!(Eo in e)},Lm=e=>{if(!zr(e)||Br(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},$m=on("Date"),Fm=on("File"),Bm=on("Blob"),zm=on("FileList"),Um=e=>zr(e)&&Ft(e.pipe),Hm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Ft(e.append)&&((t=No(e))==="formdata"||t==="object"&&Ft(e.toString)&&e.toString()==="[object FormData]"))},Wm=on("URLSearchParams"),[Vm,Km,qm,Gm]=["ReadableStream","Request","Response","Headers"].map(on),Ym=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ur(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),fr(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Br(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let a;for(r=0;r<i;r++)a=s[r],t.call(null,e[a],a,e)}}function bl(e,t){if(Br(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}const qn=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,wl=e=>!pr(e)&&e!==qn;function ui(){const{caseless:e,skipUndefined:t}=wl(this)&&this||{},n={},r=(o,s)=>{const i=e&&bl(n,s)||s;jo(n[i])&&jo(o)?n[i]=ui(n[i],o):jo(o)?n[i]=ui({},o):fr(o)?n[i]=o.slice():(!t||!pr(o))&&(n[i]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Ur(arguments[o],r);return n}const Xm=(e,t,n,{allOwnKeys:r}={})=>(Ur(t,(o,s)=>{n&&Ft(o)?e[s]=gl(o,n):e[s]=o},{allOwnKeys:r}),e),Jm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Zm=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Qm=(e,t,n,r)=>{let o,s,i;const a={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),s=o.length;s-- >0;)i=o[s],(!r||r(i,e,t))&&!a[i]&&(t[i]=e[i],a[i]=!0);e=n!==!1&&ci(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},eg=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},tg=e=>{if(!e)return null;if(fr(e))return e;let t=e.length;if(!vl(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},ng=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ci(Uint8Array)),rg=(e,t)=>{const r=(e&&e[Eo]).call(e);let o;for(;(o=r.next())&&!o.done;){const s=o.value;t.call(e,s[0],s[1])}},og=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},sg=on("HTMLFormElement"),ig=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),Sl=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),ag=on("RegExp"),Cl=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Ur(n,(o,s)=>{let i;(i=t(o,s,e))!==!1&&(r[s]=i||o)}),Object.defineProperties(e,r)},lg=e=>{Cl(e,(t,n)=>{if(Ft(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Ft(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},cg=(e,t)=>{const n={},r=o=>{o.forEach(s=>{n[s]=!0})};return fr(e)?r(e):r(String(e).split(t)),n},ug=()=>{},dg=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function fg(e){return!!(e&&Ft(e.append)&&e[xl]==="FormData"&&e[Eo])}const pg=e=>{const t=new Array(10),n=(r,o)=>{if(zr(r)){if(t.indexOf(r)>=0)return;if(Br(r))return r;if(!("toJSON"in r)){t[o]=r;const s=fr(r)?[]:{};return Ur(r,(i,a)=>{const l=n(i,o+1);!pr(l)&&(s[a]=l)}),t[o]=void 0,s}}return r};return n(e,0)},hg=on("AsyncFunction"),mg=e=>e&&(zr(e)||Ft(e))&&Ft(e.then)&&Ft(e.catch),Tl=((e,t)=>e?setImmediate:t?((n,r)=>(qn.addEventListener("message",({source:o,data:s})=>{o===qn&&s===n&&r.length&&r.shift()()},!1),o=>{r.push(o),qn.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ft(qn.postMessage)),gg=typeof queueMicrotask<"u"?queueMicrotask.bind(qn):typeof process<"u"&&process.nextTick||Tl,$={isArray:fr,isArrayBuffer:yl,isBuffer:Br,isFormData:Hm,isArrayBufferView:Pm,isString:Om,isNumber:vl,isBoolean:Dm,isObject:zr,isPlainObject:jo,isEmptyObject:Lm,isReadableStream:Vm,isRequest:Km,isResponse:qm,isHeaders:Gm,isUndefined:pr,isDate:$m,isFile:Fm,isBlob:Bm,isRegExp:ag,isFunction:Ft,isStream:Um,isURLSearchParams:Wm,isTypedArray:ng,isFileList:zm,forEach:Ur,merge:ui,extend:Xm,trim:Ym,stripBOM:Jm,inherits:Zm,toFlatObject:Qm,kindOf:No,kindOfTest:on,endsWith:eg,toArray:tg,forEachEntry:rg,matchAll:og,isHTMLForm:sg,hasOwnProperty:Sl,hasOwnProp:Sl,reduceDescriptors:Cl,freezeMethods:lg,toObjectSet:cg,toCamelCase:ig,noop:ug,toFiniteNumber:dg,findKey:bl,global:qn,isContextDefined:wl,isSpecCompliantForm:fg,toJSONObject:pg,isAsyncFn:hg,isThenable:mg,setImmediate:Tl,asap:gg,isIterable:e=>e!=null&&Ft(e[Eo])};function De(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}$.inherits(De,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:$.toJSONObject(this.config),code:this.code,status:this.status}}});const kl=De.prototype,Il={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Il[e]={value:e}}),Object.defineProperties(De,Il),Object.defineProperty(kl,"isAxiosError",{value:!0}),De.from=(e,t,n,r,o,s)=>{const i=Object.create(kl);$.toFlatObject(e,i,function(d){return d!==Error.prototype},c=>c!=="isAxiosError");const a=e&&e.message?e.message:"Error",l=t==null&&e?e.code:t;return De.call(i,a,l,n,r,o),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",s&&Object.assign(i,s),i};const xg=null;function di(e){return $.isPlainObject(e)||$.isArray(e)}function El(e){return $.endsWith(e,"[]")?e.slice(0,-2):e}function Nl(e,t,n){return e?e.concat(t).map(function(o,s){return o=El(o),!n&&s?"["+o+"]":o}).join(n?".":""):t}function yg(e){return $.isArray(e)&&!e.some(di)}const vg=$.toFlatObject($,{},null,function(t){return/^is[A-Z]/.test(t)});function _o(e,t,n){if(!$.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=$.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,y){return!$.isUndefined(y[g])});const r=n.metaTokens,o=n.visitor||d,s=n.dots,i=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&$.isSpecCompliantForm(t);if(!$.isFunction(o))throw new TypeError("visitor must be a function");function c(v){if(v===null)return"";if($.isDate(v))return v.toISOString();if($.isBoolean(v))return v.toString();if(!l&&$.isBlob(v))throw new De("Blob is not supported. Use a Buffer instead.");return $.isArrayBuffer(v)||$.isTypedArray(v)?l&&typeof Blob=="function"?new Blob([v]):Buffer.from(v):v}function d(v,g,y){let x=v;if(v&&!y&&typeof v=="object"){if($.endsWith(g,"{}"))g=r?g:g.slice(0,-2),v=JSON.stringify(v);else if($.isArray(v)&&yg(v)||($.isFileList(v)||$.endsWith(g,"[]"))&&(x=$.toArray(v)))return g=El(g),x.forEach(function(C,k){!($.isUndefined(C)||C===null)&&t.append(i===!0?Nl([g],k,s):i===null?g:g+"[]",c(C))}),!1}return di(v)?!0:(t.append(Nl(y,g,s),c(v)),!1)}const f=[],p=Object.assign(vg,{defaultVisitor:d,convertValue:c,isVisitable:di});function h(v,g){if(!$.isUndefined(v)){if(f.indexOf(v)!==-1)throw Error("Circular reference detected in "+g.join("."));f.push(v),$.forEach(v,function(x,b){(!($.isUndefined(x)||x===null)&&o.call(t,x,$.isString(b)?b.trim():b,g,p))===!0&&h(x,g?g.concat(b):[b])}),f.pop()}}if(!$.isObject(e))throw new TypeError("data must be an object");return h(e),t}function Al(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function fi(e,t){this._pairs=[],e&&_o(e,this,t)}const jl=fi.prototype;jl.append=function(t,n){this._pairs.push([t,n])},jl.toString=function(t){const n=t?function(r){return t.call(this,r,Al)}:Al;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function bg(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function _l(e,t,n){if(!t)return e;const r=n&&n.encode||bg;$.isFunction(n)&&(n={serialize:n});const o=n&&n.serialize;let s;if(o?s=o(t,n):s=$.isURLSearchParams(t)?t.toString():new fi(t,n).toString(r),s){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class Ml{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){$.forEach(this.handlers,function(r){r!==null&&t(r)})}}const Rl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},wg={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:fi,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},pi=typeof window<"u"&&typeof document<"u",hi=typeof navigator=="object"&&navigator||void 0,Sg=pi&&(!hi||["ReactNative","NativeScript","NS"].indexOf(hi.product)<0),Cg=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Tg=pi&&window.location.href||"http://localhost",Et={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:pi,hasStandardBrowserEnv:Sg,hasStandardBrowserWebWorkerEnv:Cg,navigator:hi,origin:Tg},Symbol.toStringTag,{value:"Module"})),...wg};function kg(e,t){return _o(e,new Et.classes.URLSearchParams,{visitor:function(n,r,o,s){return Et.isNode&&$.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function Ig(e){return $.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Eg(e){const t={},n=Object.keys(e);let r;const o=n.length;let s;for(r=0;r<o;r++)s=n[r],t[s]=e[s];return t}function Pl(e){function t(n,r,o,s){let i=n[s++];if(i==="__proto__")return!0;const a=Number.isFinite(+i),l=s>=n.length;return i=!i&&$.isArray(o)?o.length:i,l?($.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!a):((!o[i]||!$.isObject(o[i]))&&(o[i]=[]),t(n,r,o[i],s)&&$.isArray(o[i])&&(o[i]=Eg(o[i])),!a)}if($.isFormData(e)&&$.isFunction(e.entries)){const n={};return $.forEachEntry(e,(r,o)=>{t(Ig(r),o,n,0)}),n}return null}function Ng(e,t,n){if($.isString(e))try{return(t||JSON.parse)(e),$.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Hr={transitional:Rl,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,s=$.isObject(t);if(s&&$.isHTMLForm(t)&&(t=new FormData(t)),$.isFormData(t))return o?JSON.stringify(Pl(t)):t;if($.isArrayBuffer(t)||$.isBuffer(t)||$.isStream(t)||$.isFile(t)||$.isBlob(t)||$.isReadableStream(t))return t;if($.isArrayBufferView(t))return t.buffer;if($.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return kg(t,this.formSerializer).toString();if((a=$.isFileList(t))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return _o(a?{"files[]":t}:t,l&&new l,this.formSerializer)}}return s||o?(n.setContentType("application/json",!1),Ng(t)):t}],transformResponse:[function(t){const n=this.transitional||Hr.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if($.isResponse(t)||$.isReadableStream(t))return t;if(t&&$.isString(t)&&(r&&!this.responseType||o)){const i=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(a){if(i)throw a.name==="SyntaxError"?De.from(a,De.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Et.classes.FormData,Blob:Et.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};$.forEach(["delete","get","head","post","put","patch"],e=>{Hr.headers[e]={}});const Ag=$.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),jg=e=>{const t={};let n,r,o;return e&&e.split(`
31
+ `).forEach(function(i){o=i.indexOf(":"),n=i.substring(0,o).trim().toLowerCase(),r=i.substring(o+1).trim(),!(!n||t[n]&&Ag[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},Ol=Symbol("internals");function Wr(e){return e&&String(e).trim().toLowerCase()}function Mo(e){return e===!1||e==null?e:$.isArray(e)?e.map(Mo):String(e)}function _g(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const Mg=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function mi(e,t,n,r,o){if($.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!$.isString(t)){if($.isString(r))return t.indexOf(r)!==-1;if($.isRegExp(r))return r.test(t)}}function Rg(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Pg(e,t){const n=$.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,s,i){return this[r].call(this,t,o,s,i)},configurable:!0})})}let Bt=class{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function s(a,l,c){const d=Wr(l);if(!d)throw new Error("header name must be a non-empty string");const f=$.findKey(o,d);(!f||o[f]===void 0||c===!0||c===void 0&&o[f]!==!1)&&(o[f||l]=Mo(a))}const i=(a,l)=>$.forEach(a,(c,d)=>s(c,d,l));if($.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if($.isString(t)&&(t=t.trim())&&!Mg(t))i(jg(t),n);else if($.isObject(t)&&$.isIterable(t)){let a={},l,c;for(const d of t){if(!$.isArray(d))throw TypeError("Object iterator must return a key-value pair");a[c=d[0]]=(l=a[c])?$.isArray(l)?[...l,d[1]]:[l,d[1]]:d[1]}i(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Wr(t),t){const r=$.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return _g(o);if($.isFunction(n))return n.call(this,o,r);if($.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Wr(t),t){const r=$.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||mi(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function s(i){if(i=Wr(i),i){const a=$.findKey(r,i);a&&(!n||mi(r,r[a],a,n))&&(delete r[a],o=!0)}}return $.isArray(t)?t.forEach(s):s(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const s=n[r];(!t||mi(this,this[s],s,t,!0))&&(delete this[s],o=!0)}return o}normalize(t){const n=this,r={};return $.forEach(this,(o,s)=>{const i=$.findKey(r,s);if(i){n[i]=Mo(o),delete n[s];return}const a=t?Rg(s):String(s).trim();a!==s&&delete n[s],n[a]=Mo(o),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return $.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&$.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
32
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[Ol]=this[Ol]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Wr(i);r[a]||(Pg(o,i),r[a]=!0)}return $.isArray(t)?t.forEach(s):s(t),this}};Bt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),$.reduceDescriptors(Bt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),$.freezeMethods(Bt);function gi(e,t){const n=this||Hr,r=t||n,o=Bt.from(r.headers);let s=r.data;return $.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function Dl(e){return!!(e&&e.__CANCEL__)}function hr(e,t,n){De.call(this,e??"canceled",De.ERR_CANCELED,t,n),this.name="CanceledError"}$.inherits(hr,De,{__CANCEL__:!0});function Ll(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new De("Request failed with status code "+n.status,[De.ERR_BAD_REQUEST,De.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Og(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Dg(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,p=0;for(;f!==o;)p+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=d&&c-d;return h?Math.round(p*1e3/h):void 0}}function Lg(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const Ro=(e,t,n=3)=>{let r=0;const o=Dg(50,250);return Lg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},$l=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Fl=e=>(...t)=>$.asap(()=>e(...t)),$g=Et.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Et.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Et.origin),Et.navigator&&/(msie|trident)/i.test(Et.navigator.userAgent)):()=>!0,Fg=Et.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];$.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),$.isString(r)&&i.push("path="+r),$.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Bg(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function zg(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Bl(e,t,n){let r=!Bg(t);return e&&(r||n==!1)?zg(e,t):t}const zl=e=>e instanceof Bt?{...e}:e;function Gn(e,t){t=t||{};const n={};function r(c,d,f,p){return $.isPlainObject(c)&&$.isPlainObject(d)?$.merge.call({caseless:p},c,d):$.isPlainObject(d)?$.merge({},d):$.isArray(d)?d.slice():d}function o(c,d,f,p){if($.isUndefined(d)){if(!$.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function s(c,d){if(!$.isUndefined(d))return r(void 0,d)}function i(c,d){if($.isUndefined(d)){if(!$.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(zl(c),zl(d),f,!0)};return $.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,p=f(e[d],t[d],d);$.isUndefined(p)&&f!==a||(n[d]=p)}),n}const Ul=e=>{const t=Gn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Bt.from(i),t.url=_l(Bl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),$.isFormData(n)){if(Et.hasStandardBrowserEnv||Et.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if($.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Et.hasStandardBrowserEnv&&(r&&$.isFunction(r)&&(r=r(t)),r||r!==!1&&$g(t.url))){const l=o&&s&&Fg.read(s);l&&i.set(o,l)}return t},Ug=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=Ul(e);let s=o.data;const i=Bt.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,p,h,v;function g(){h&&h(),v&&v(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function x(){if(!y)return;const C=Bt.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),T={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:C,config:e,request:y};Ll(function(I){n(I),g()},function(I){r(I),g()},T),y=null}"onloadend"in y?y.onloadend=x:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(x)},y.onabort=function(){y&&(r(new De("Request aborted",De.ECONNABORTED,e,y)),y=null)},y.onerror=function(k){const T=k&&k.message?k.message:"Network Error",S=new De(T,De.ERR_NETWORK,e,y);S.event=k||null,r(S),y=null},y.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const T=o.transitional||Rl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new De(k,T.clarifyTimeoutError?De.ETIMEDOUT:De.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&$.forEach(i.toJSON(),function(k,T){y.setRequestHeader(T,k)}),$.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([p,v]=Ro(c,!0),y.addEventListener("progress",p)),l&&y.upload&&([f,h]=Ro(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",h)),(o.cancelToken||o.signal)&&(d=C=>{y&&(r(!C||C.type?new hr(null,e,y):C),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const b=Og(o.url);if(b&&Et.protocols.indexOf(b)===-1){r(new De("Unsupported protocol "+b+":",De.ERR_BAD_REQUEST,e));return}y.send(s||null)})},Hg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof De?d:new hr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new De(`timeout ${t} of ms exceeded`,De.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>$.asap(a),l}},Wg=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},Vg=async function*(e,t){for await(const n of Kg(e))yield*Wg(n,t)},Kg=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Hl=(e,t,n,r)=>{const o=Vg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let p=s+=f;n(p)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},Wl=64*1024,{isFunction:Po}=$,qg=(({Request:e,Response:t})=>({Request:e,Response:t}))($.global),{ReadableStream:Vl,TextEncoder:Kl}=$.global,ql=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Gg=e=>{e=$.merge.call({skipUndefined:!0},qg,e);const{fetch:t,Request:n,Response:r}=e,o=t?Po(t):typeof fetch=="function",s=Po(n),i=Po(r);if(!o)return!1;const a=o&&Po(Vl),l=o&&(typeof Kl=="function"?(v=>g=>v.encode(g))(new Kl):async v=>new Uint8Array(await new n(v).arrayBuffer())),c=s&&a&&ql(()=>{let v=!1;const g=new n(Et.origin,{body:new Vl,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!g}),d=i&&a&&ql(()=>$.isReadableStream(new r("").body)),f={stream:d&&(v=>v.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!f[v]&&(f[v]=(g,y)=>{let x=g&&g[v];if(x)return x.call(g);throw new De(`Response type '${v}' is not supported`,De.ERR_NOT_SUPPORT,y)})});const p=async v=>{if(v==null)return 0;if($.isBlob(v))return v.size;if($.isSpecCompliantForm(v))return(await new n(Et.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if($.isArrayBufferView(v)||$.isArrayBuffer(v))return v.byteLength;if($.isURLSearchParams(v)&&(v=v+""),$.isString(v))return(await l(v)).byteLength},h=async(v,g)=>{const y=$.toFiniteNumber(v.getContentLength());return y??p(g)};return async v=>{let{url:g,method:y,data:x,signal:b,cancelToken:C,timeout:k,onDownloadProgress:T,onUploadProgress:S,responseType:I,headers:A,withCredentials:R="same-origin",fetchOptions:D}=Ul(v),F=t||fetch;I=I?(I+"").toLowerCase():"text";let q=Hg([b,C&&C.toAbortSignal()],k),W=null;const _=q&&q.unsubscribe&&(()=>{q.unsubscribe()});let j;try{if(S&&c&&y!=="get"&&y!=="head"&&(j=await h(A,x))!==0){let ne=new n(g,{method:"POST",body:x,duplex:"half"}),M;if($.isFormData(x)&&(M=ne.headers.get("content-type"))&&A.setContentType(M),ne.body){const[Y,ae]=$l(j,Ro(Fl(S)));x=Hl(ne.body,Wl,Y,ae)}}$.isString(R)||(R=R?"include":"omit");const N=s&&"credentials"in n.prototype,z={...D,signal:q,method:y.toUpperCase(),headers:A.normalize().toJSON(),body:x,duplex:"half",credentials:N?R:void 0};W=s&&new n(g,z);let L=await(s?F(W,D):F(g,z));const P=d&&(I==="stream"||I==="response");if(d&&(T||P&&_)){const ne={};["status","statusText","headers"].forEach(Q=>{ne[Q]=L[Q]});const M=$.toFiniteNumber(L.headers.get("content-length")),[Y,ae]=T&&$l(M,Ro(Fl(T),!0))||[];L=new r(Hl(L.body,Wl,Y,()=>{ae&&ae(),_&&_()}),ne)}I=I||"text";let V=await f[$.findKey(f,I)||"text"](L,v);return!P&&_&&_(),await new Promise((ne,M)=>{Ll(ne,M,{data:V,headers:Bt.from(L.headers),status:L.status,statusText:L.statusText,config:v,request:W})})}catch(N){throw _&&_(),N&&N.name==="TypeError"&&/Load failed|fetch/i.test(N.message)?Object.assign(new De("Network Error",De.ERR_NETWORK,v,W),{cause:N.cause||N}):De.from(N,N&&N.code,v,W)}}},Yg=new Map,Gl=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=Yg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:Gg(t)),d=c;return c};Gl();const xi={http:xg,xhr:Ug,fetch:{get:Gl}};$.forEach(xi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Yl=e=>`- ${e}`,Xg=e=>$.isFunction(e)||e===null||e===!1,Xl={getAdapter:(e,t)=>{e=$.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!Xg(r)&&(o=xi[(a=String(r)).toLowerCase()],o===void 0))throw new De(`Unknown adapter '${a}'`);if(o&&($.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
33
+ `+i.map(Yl).join(`
34
+ `):" "+Yl(i[0]):"as no adapter specified";throw new De("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:xi};function yi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new hr(null,e)}function Jl(e){return yi(e),e.headers=Bt.from(e.headers),e.data=gi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Xl.getAdapter(e.adapter||Hr.adapter,e)(e).then(function(r){return yi(e),r.data=gi.call(e,e.transformResponse,r),r.headers=Bt.from(r.headers),r},function(r){return Dl(r)||(yi(e),r&&r.response&&(r.response.data=gi.call(e,e.transformResponse,r.response),r.response.headers=Bt.from(r.response.headers))),Promise.reject(r)})}const Zl="1.12.2",Oo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Oo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ql={};Oo.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Zl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new De(o(i," has been removed"+(n?" in "+n:"")),De.ERR_DEPRECATED);return n&&!Ql[i]&&(Ql[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},Oo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Jg(e,t,n){if(typeof e!="object")throw new De("options must be an object",De.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new De("option "+s+" must be "+l,De.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new De("Unknown option "+s,De.ERR_BAD_OPTION)}}const Do={assertOptions:Jg,validators:Oo},fn=Do.validators;let Yn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ml,response:new Ml}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Gn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Do.assertOptions(r,{silentJSONParsing:fn.transitional(fn.boolean),forcedJSONParsing:fn.transitional(fn.boolean),clarifyTimeoutError:fn.transitional(fn.boolean)},!1),o!=null&&($.isFunction(o)?n.paramsSerializer={serialize:o}:Do.assertOptions(o,{encode:fn.function,serialize:fn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Do.assertOptions(n,{baseUrl:fn.spelling("baseURL"),withXsrfToken:fn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&$.merge(s.common,s[n.method]);s&&$.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=Bt.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,f=0,p;if(!l){const v=[Jl.bind(this),void 0];for(v.unshift(...a),v.push(...c),p=v.length,d=Promise.resolve(n);f<p;)d=d.then(v[f++],v[f++]);return d}p=a.length;let h=n;for(;f<p;){const v=a[f++],g=a[f++];try{h=v(h)}catch(y){g.call(this,y);break}}try{d=Jl.call(this,h)}catch(v){return Promise.reject(v)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Gn(this.defaults,t);const n=Bl(t.baseURL,t.url,t.allowAbsoluteUrls);return _l(n,t.params,t.paramsSerializer)}};$.forEach(["delete","get","head","options"],function(t){Yn.prototype[t]=function(n,r){return this.request(Gn(r||{},{method:t,url:n,data:(r||{}).data}))}}),$.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Gn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Yn.prototype[t]=n(),Yn.prototype[t+"Form"]=n(!0)});let Zg=class Nm{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new hr(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Nm(function(o){t=o}),cancel:t}}};function Qg(e){return function(n){return e.apply(null,n)}}function ex(e){return $.isObject(e)&&e.isAxiosError===!0}const vi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(vi).forEach(([e,t])=>{vi[t]=e});function ec(e){const t=new Yn(e),n=gl(Yn.prototype.request,t);return $.extend(n,Yn.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return ec(Gn(e,o))},n}const gt=ec(Hr);gt.Axios=Yn,gt.CanceledError=hr,gt.CancelToken=Zg,gt.isCancel=Dl,gt.VERSION=Zl,gt.toFormData=_o,gt.AxiosError=De,gt.Cancel=gt.CanceledError,gt.all=function(t){return Promise.all(t)},gt.spread=Qg,gt.isAxiosError=ex,gt.mergeConfig=Gn,gt.AxiosHeaders=Bt,gt.formToJSON=e=>Pl($.isHTMLForm(e)?new FormData(e):e),gt.getAdapter=Xl.getAdapter,gt.HttpStatusCode=vi,gt.default=gt;const{Axios:Gk,AxiosError:Yk,CanceledError:Xk,isCancel:Jk,CancelToken:Zk,VERSION:Qk,all:eI,Cancel:tI,isAxiosError:nI,spread:rI,toFormData:oI,AxiosHeaders:sI,HttpStatusCode:iI,formToJSON:aI,getAdapter:lI,mergeConfig:cI}=gt,tc=typeof window<"u"?window.__API_BASE_URL__:void 0,nc=tc?Tn(tc):void 0;function Tn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Lo=null;const bi=new Set;function rc(){return Lo}function $o(e){Lo=e,bi.forEach(t=>t(e))}function oc(e){return bi.add(e),()=>bi.delete(e)}const tx=3e4,nx=9e4,Yt=gt.create({...nc?{baseURL:nc}:{},timeout:tx,withCredentials:!0});Yt.interceptors.request.use(e=>(Lo&&(e.headers.Authorization=`Bearer ${Lo}`),e)),Yt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),$o(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function zt(e,t){return Yt.defaults.baseURL?(await Yt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fo(e,t,n){return Yt.defaults.baseURL?(await Yt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function sc(e,t,n){return Yt.defaults.baseURL?(await Yt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function wi(e,t){return Yt.defaults.baseURL?(await Yt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Nt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class ic{get baseUrl(){const t=Yt.defaults.baseURL;return t?Tn(String(t)):""}updateConfig(t){t.baseUrl&&(Yt.defaults.baseURL=Tn(String(t.baseUrl))),t.authToken!==void 0&&$o(t.authToken)}getAuthToken(){return rc()}setAuthToken(t){$o(t)}onTokenChange(t){return oc(t)}async listThreads(){const t=await zt("/threads"),n=Nt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await zt("/threads/shared"),n=Nt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSmartOrgUsers(){const t=await zt("/auth/users"),n=Nt(t);return(n==null?void 0:n.users)??[]}async createThread(t){const r=await Fo("/threads",t?{title:t}:void 0);return Nt(r)}async updateThread(t,n){const r=await sc(`/threads/${t}`,{title:n});return Nt(r)}async deleteThread(t){const n=await wi(`/threads/${t}`);return Nt(n)}async shareThread(t,n){const r=await Fo(`/threads/${t}/share`,{shared_with_user_id:n});return Nt(r)}async threadInfo(t){const n=await zt(`/threads/${t}/info`);return Nt(n)}async listAgents(){const t=await zt("/agents"),n=Nt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await zt(`/agents/${t}`);return Nt(n)}async getAgentSchema(t){const n=await zt(`/agents/${t}/schema`);return Nt(n)}async getState(t){const n=await zt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Nt(n)}async getStateHistory(t){const n=await zt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:nx});return Nt(n)}async cancelRun(t){const n=await Fo("/runs/cancel",{threadId:t});return Nt(n)}async listCheckpointSummaries(t){const n=await zt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Nt(n);return(r==null?void 0:r.items)??[]}async unshareThread(t,n){const r=await wi(`/threads/${t}/share/${n}`);return Nt(r)}}const jn=new ic,ac=w.createContext(null);function rx({children:e,apiConfig:t}){const n=jn;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(ac.Provider,{value:r,children:e})}function Si(){const e=w.useContext(ac);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function ox(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function sx(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await ox(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const lc=120;function ix(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>lc?`${n.slice(0,lc-3)}…`:n:""}function cc(e){return ix(e.content)||""}function ax(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=cc(n);r&&t.set(n.id,r)}return t}function lx(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=cc(o);s&&t.set(r.checkpointId,s)}}return t}const cx={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Ci(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function ux(e,t){return`${e??""}::${t??""}`}function mr(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!Ci(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=fx(t),i=uc(r,0),a=px(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function uc(e,t){if(!Ci(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(R=>!!R&&typeof R=="object").map(R=>({...R})):a===null?null:void 0,c=r.map((R,D)=>Sx(R,D)).filter(R=>!!R),d=Ot(e.config),f=Ot(d==null?void 0:d.configurable),p=lt(f,["checkpoint_id","checkpointId"]),h=lt(f,["checkpoint_ns","checkpointNs"]),v=Ot(e==null?void 0:e.parentConfig),g=Ot(v==null?void 0:v.configurable),y=lt(g,["checkpoint_id","checkpointId"])??null,x=lt(g,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,C=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(R=>R.role==="user")??null,T=Ot(e==null?void 0:e.metadata),S=lt(T,["branch_label","branchLabel"]),I=lt(g,["checkpoint_id","checkpointId"]),A=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:y,nextCursorNs:x,interrupt:dx(a,c,t),createdAt:C,parentId:I??null,branchLabel:S??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:T??null,config:d??null,parentConfig:v??null,next:A??null,tasks:l??null,values:i??null}}function dx(e,t,n){const r=bx(e,n);return r||vx(t,n)}function fx(e){const t=new Map;e.forEach((o,s)=>{if(!Ci(o))return;const i=uc(o,s);if(!(i!=null&&i.checkpointId))return;const a=ux(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,gx(l,i))});const n=Array.from(t.values());n.sort((o,s)=>fc(s.createdAt??"")-fc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function px(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=lt(i,["label"])??lt(i,["branch_label","branchLabel"])??lt(i,["description"])??"User input",l=mx(i,["step"]),c=lt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=hx(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0,parentConfig:o.parentConfig??null})}return t}function hx(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function mx(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function gx(e,t){return{...e,metadata:Bo(e.metadata,t.metadata)??null,config:Bo(e.config,t.config)??null,parentConfig:Bo(e.parentConfig,t.parentConfig)??null,next:xx(e.next,t.next)??null,tasks:yx(e.tasks,t.tasks)??null,values:Bo(e.values,t.values)??null}}function Bo(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function xx(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function yx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function vx(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function bx(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=wx(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Vr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Vr(r.state,`${o}-state`);if(s)return s}}return null}function wx(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,v=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",g=Array.isArray(d)?d:void 0,y=p.length?p[p.length-1]:void 0;return{id:h,name:v,interrupts:g,state:y!==void 0?y:f}}const n=Ot(e);if(!n)return null;const r=lt(n,["id","thread_id","taskId"])??t,o=lt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Vr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=dc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Vr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Vr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=Vr(l,t,n+1,r);if(c)return c}}return null}function dc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=lt(n,["type","event","kind"]),o=lt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=dc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function fc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Sx(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ot(e)??{},o=Ot(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=cx[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ot(o.additional_kwargs)??Ot(o.additionalKwargs),d=Ot(o.response_metadata)??Ot(o.responseMetadata),f=lt(c,["createdAt","created_at"])??lt(o,["created_at","createdAt"]),p=lt(c,["checkpointId","checkpoint_id"]),h=lt(c,["checkpointNs","checkpoint_ns"]),v=Cx(o.content),g={id:l,role:i,content:v};f&&(g.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(g.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(g.model=String(d.model_name)),!g.model&&typeof o.model=="string"&&(g.model=o.model),p&&(g.checkpointId=p),h&&(g.checkpointNs=h);const y=Ix(Ot(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(g.artifact=y);const x=jx(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;x&&Object.keys(x).length&&(g.additionalKwargs=x),b&&Object.keys(b).length&&(g.responseMetadata=b);const C=Tx((c==null?void 0:c.tool_calls)??o.tool_calls);if(C.length&&(g.content=[...g.content,...C]),i==="tool"){const k=kx(o,g.content);k&&(g.content=k)}return g}function Cx(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>pc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=pc(e);return t?[t]:[]}return[]}function pc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=lt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=lt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return hc(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=lt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function hc(e,t){var s;const n=lt(e,["id","call_id"])??t,r=lt(e,["name"])??lt(Ot(e.function),["name"]);if(!n||!r)return null;const o=Ax(e.args??e.arguments??((s=Ot(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Tx(e){return Array.isArray(e)?e.map((t,n)=>hc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function kx(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Ix(e){return e?{plots:Ex(e.plots)}:void 0}function Ex(e){return Array.isArray(e)?e.map(t=>Nx(t)).filter(t=>!!t):[]}function Nx(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Ax(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function Ot(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function lt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function jx(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}const mc="aiNav:tool-progress";function Ti(){return typeof window<"u"&&typeof window.localStorage<"u"}function gc(e){return`${mc}:${e}`}function _x(e,t,n){if(!Ti()||!e)return;const r=gc(e);if(!t.length){window.localStorage.removeItem(r);return}const o={messageId:e,entries:t,updatedAt:Date.now(),...n??{}};try{window.localStorage.setItem(r,JSON.stringify(o))}catch{}}function Mx(e){if(!Ti()||!e)return;const t=gc(e),n=window.localStorage.getItem(t);if(n)try{const r=JSON.parse(n);return!(r!=null&&r.entries)||!Array.isArray(r.entries)?void 0:r.entries}catch{window.localStorage.removeItem(t);return}}function xc(){if(!Ti())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(mc)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const Ct=[];for(let e=0;e<256;++e)Ct.push((e+256).toString(16).slice(1));function Rx(e,t=0){return(Ct[e[t+0]]+Ct[e[t+1]]+Ct[e[t+2]]+Ct[e[t+3]]+"-"+Ct[e[t+4]]+Ct[e[t+5]]+"-"+Ct[e[t+6]]+Ct[e[t+7]]+"-"+Ct[e[t+8]]+Ct[e[t+9]]+"-"+Ct[e[t+10]]+Ct[e[t+11]]+Ct[e[t+12]]+Ct[e[t+13]]+Ct[e[t+14]]+Ct[e[t+15]]).toLowerCase()}let ki;const Px=new Uint8Array(16);function Ox(){if(!ki){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ki=crypto.getRandomValues.bind(crypto)}return ki(Px)}const yc={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Dx(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??Ox();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Rx(r)}function Lx(e,t,n){return yc.randomUUID&&!e?yc.randomUUID():Dx(e)}function Ii(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function zo(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function vc(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function bc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function wc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function $x(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Vx(e);for(const o of r)n.add(o);return Array.from(n)}function Sc(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function Fx(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};for(const l of t)s(l);const i=Array.from(o),a={};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function Uo(e,t,n){const r=e.findIndex(c=>c.id===t);if(r===-1)return e;const o=e[r],s=[...e],i={...o.additionalKwargs??{}},a=Array.isArray(i.toolProgress)?[...i.toolProgress]:[],l={id:Lx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),_x(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function Cc(e,t){return e.includes(t)?e:[...e,t]}function Bx(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function gr(e,t){let n=!1;const r={},o=e.map(s=>{const i=Kx(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Mx(s.id);if(a!=null&&a.length){const l=[...a];r[s.id]=l,n=!0;const c={...s.additionalKwargs??{},toolProgress:l};return{...s,additionalKwargs:c}}return s});return{messages:n?o:e,toolTimelines:r}}function Tc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function zx(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??Tc(e);let l="",c=e.slice();if(s){const f=Ux(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",v={...p,text:h+l};c=[...c.slice(0,c.length-1),v]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function kc(e){return e.replace(/\s+/g," ").trim()}function Ux(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=kc(e),o=kc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Hx(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return zo(e,r,s)}return e}function Wx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Vx(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function Kx(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const qx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function Gx(e,t){var n;switch(t.type){case"reset":return{messages:Ii(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"seed":{const r=Ii(t.payload.messages),{messages:o,toolTimelines:s}=gr(r,e.toolTimelines),i={...e,messages:o,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,toolStreamingMessageId:null,toolStreamingStack:[],toolTimelines:s};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(i.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(i.lastCheckpointNs=t.payload.checkpointNs??null),i}case"prepend":{const r=Ii(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(c=>c.id)),s=r.filter(c=>!o.has(c.id));if(!s.length)return e;const i=[...s,...e.messages],{messages:a,toolTimelines:l}=gr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return Ec(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Ec(o,s),e):e}case"interrupt_response":return{...e,messages:vc(e.messages),pendingInterrupt:null};default:return e}}function Ic(e=[]){const[t,n]=w.useReducer(Gx,{...qx,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=w.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function Ec(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=Wx(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message.delta"){const i=e.assemblingId??bc(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(C=>C.id===i&&C.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:Tc(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof f.lastSeq=="number"&&p<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:f.lastSeq}),e;const{newParts:h,newMeta:v,changed:g}=zx(c.content,t.delta,f,p);if(!g)return e;const y={...c,content:h},x=zo(a,l,y),b={...d,[i]:v};return{...e,messages:x,messagesStreamMeta:b}}if(t.type==="message.end"){const i=e.assemblingId??bc(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.content)==null?void 0:n.some(f=>{var p;return(f==null?void 0:f.type)==="text"&&((p=f.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=c.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool.start"){const i=wc(t),a=i[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),l=t.name??t.tool??"tool";!a&&i.length===0&&i.push(`${l}-${Date.now()}`);const c=i.length?i:a?[a]:[],d=c[0]??`${l}-${Date.now()}`,f={type:"tool_call",id:d,name:l,args:t.args},p={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},h=e.toolStreamingMessageId;if(!h){const b={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...Fx(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},C=$x(b,c.length?c:[d]),k=[...e.messages,b],T=Uo(k,b.id,p),{messages:S,toolTimelines:I}=gr(T,e.toolTimelines);return{...e,messages:S,toolIndex:Sc(e.toolIndex,b.id,C),toolStreamingMessageId:b.id,toolStreamingStack:Cc(e.toolStreamingStack??[],a??d),toolTimelines:I}}const v=Uo(e.messages,h,p),{messages:g,toolTimelines:y}=gr(v,e.toolTimelines);return{...e,messages:g,toolIndex:Sc(e.toolIndex,h,c),toolStreamingStack:Cc(e.toolStreamingStack??[],a??d),toolTimelines:y}}if(t.type==="tool.end"){const i=wc(t);if(!i.length&&!(typeof t.id=="string"&&t.id))return e;const a=i[0]??(typeof t.id=="string"?t.id:null);if(!a)return e;const l=e.toolStreamingStack??[],c=l[0]??null,d=Bx(l,a),f=d[0]?e.toolIndex[d[0]]:null,p=e.toolStreamingMessageId,h=c===a,v=t.name??((s=e.messages.find(T=>T.id===p))==null?void 0:s.name)??"tool",g=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:v,content:g==null?void 0:g.slice(0,200)};let x=e.messages;if(p&&(x=Uo(x,p,y)),h&&p){const T=x.findIndex(S=>S.id===p);if(T>=0){const S=x[T],A={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},R={...S,content:[A],artifact:t.artifact??S.artifact,additionalKwargs:{...S.additionalKwargs??{}}};x=zo(x,T,R)}}const b=d,{messages:C,toolTimelines:k}=gr(x,e.toolTimelines);return{...e,messages:C,toolTimelines:k,toolStreamingMessageId:h?f:p,toolStreamingStack:b}}if(t.type==="tool.progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"tool.progress",content:t.content??null},l=Uo(e.messages,i,a),c=l.findIndex(y=>y.id===i);if(c===-1)return e;const d=l[c],f={...d.additionalKwargs??{},toolStreaming:!0},p={...d,additionalKwargs:f},h=zo(l,c,p),{messages:v,toolTimelines:g}=gr(h,e.toolTimelines);return{...e,messages:v,toolTimelines:g}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=Hx(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="state_history"){const i=mr(t),a=i.interrupt,l=i.latest,c=a===null?vc(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function Nc(e={}){const t=w.useMemo(()=>Tn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,p]=w.useState(""),[h,v]=w.useState(null),[g,y]=w.useState(0),[x,b]=w.useState(!1),C=w.useRef(null),k=w.useRef(!0),T=w.useRef(0),S=w.useRef(null),I=w.useRef(null),A=w.useRef(null),R=w.useRef(null),D=w.useCallback(_=>{o(_)},[]),F=w.useCallback(()=>{p(""),v(null),d(null),I.current=null,A.current=null,R.current=null},[]),q=w.useCallback(()=>{var _;console.debug("[use-chat] stop() invoked - aborting stream"),(_=C.current)==null||_.abort(),C.current=null,S.current=null,l(!1),b(!1),T.current=0,y(0)},[]),W=w.useCallback((_,j,N)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),v(null),I.current=null,A.current=null,R.current=null;const z=new AbortController;C.current=z;let L=null,P=null,V=!1;return S.current={threadId:_.threadId??null,headers:{}},(async()=>{var M,Y,ae,Q,ce,G,O,K,B,te,Z,ye,fe,oe,xe,Se,$e,_e;const ne=Ue=>{var U;try{const le=JSON.parse(JSON.stringify(Ue));return(U=le==null?void 0:le.payload)!=null&&U.files_info&&Array.isArray(le.payload.files_info)&&(le.payload.files_info=le.payload.files_info.map(ke=>({...ke,data:ke!=null&&ke.data?`<base64 ${String(ke.data).length} chars>`:ke==null?void 0:ke.data}))),le}catch{return Ue}};try{let Ue={};try{if(r)Ue={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ge=window.__AUTH_TOKEN__,dt=((M=window.localStorage)==null?void 0:M.getItem("authToken"))||null;let Rt=null;try{const Pt=(Y=window.localStorage)==null?void 0:Y.getItem("chat-settings");Pt&&(Rt=((ae=JSON.parse(Pt))==null?void 0:ae.apiKey)||null)}catch{}const Je=Ge||dt||Rt||null;Je&&(Ue={Authorization:`Bearer ${Je}`})}}catch{}console.debug("[use-chat] POST",t+n,ne(_));let U={};if(typeof window<"u")try{const nt=(Q=window.localStorage)==null?void 0:Q.getItem("authSessionId");nt&&(U={"X-Session-Id":nt})}catch{}const le={...Ue,...U,...s.current},ke={"Content-Type":"application/json",Accept:"text/event-stream",...le},Ke=await fetch(t+n,{method:"POST",headers:ke,body:JSON.stringify(_),signal:z.signal,credentials:i});if(S.current&&(S.current.headers=le),!Ke.ok||!Ke.body){const nt=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,nt==null?void 0:nt.slice(0,500));const Ge=`stream ${Ke.status}${nt?": "+nt:""}`;throw(ce=N==null?void 0:N.onConnectionError)==null||ce.call(N,Ge),V=!0,L="error",P=Ge,new Error(Ge)}b(!0);const tt=Ke.body.getReader(),St=new TextDecoder;let ut="",yt=[];T.current=0,y(0);let pt=0,wt=null;const Mt=()=>{if(yt.length){const nt=yt.join("");yt=[],k.current&&p(Ge=>Ge+nt)}wt=null},Wt=()=>{typeof window<"u"&&wt==null&&(wt=requestAnimationFrame(Mt))};let nn=Date.now();const Ve=setInterval(()=>{var nt;if(Date.now()-nn>18e5){const Ge="Stream idle timeout";d(Ge),L="error",P=Ge,z.abort(),(nt=N==null?void 0:N.onError)==null||nt.call(N,Ge)}},5e3),Sn=1024*1024;try{const nt=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),Ge=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),dt=nt??null,Rt=String(Ge??"").toLowerCase()==="true";for(S.current&&!S.current.threadId&&(S.current={...S.current,threadId:dt}),(G=N==null?void 0:N.onOpen)==null||G.call(N,{threadId:dt,created:Rt});;){const{value:Je,done:Pt}=await tt.read();if(Pt)break;ut+=St.decode(Je,{stream:!0}),ut.length>Sn&&(ut="",console.warn("Stream buffer reset: exceeded 1MB"));let X;for(;(X=ut.indexOf(`
36
36
 
37
- `))>=0;){const ge=pt.slice(0,U);pt=pt.slice(U+2);const ye=yx(ge);if(!ye)continue;let Ke;try{Ke=JSON.parse(ye)}catch{console.debug("[use-chat] malformed SSE:",ye.slice(0,200));continue}const De=xx(Ke)?Ke.data:Ke;cn=Date.now();const ct=De.seq;if(ct!==void 0){if(ct<=mt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:ct,lastProcessedSeq:mt,type:De.type});continue}mt>0&&ct>mt+1&&((F=N==null?void 0:N.onGap)==null||F.call(N,{from:mt,to:ct})),mt=ct,C.current=ct,x(ct)}if(De.type==="checkpoint")I.current=De.checkpointId??null,j.current=De.checkpointNs??null,y(De.checkpointId??null);else if(De.type==="state_history"){_.current=De;try{const bt=fr(De).latest;bt&&(I.current=bt.checkpointId??null,j.current=bt.checkpointNs??null,y(bt.checkpointId??null))}catch(Ve){console.warn("[use-chat] Failed to hydrate state_history payload",Ve)}}try{M==null||M(De)}catch(Ve){console.error("[use-chat] Error in onEvent callback:",Ve,"for event:",De.type)}if(De.type==="message.delta"){const Ve=De.delta.filter(bt=>bt.type==="text").map(bt=>bt.text).join("");Ve&&e.autoAppendAssistant!==!1&&(Ct.push(Ve),$t())}else if(De.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(X=N==null?void 0:N.onHeartbeat)==null||X.call(N,De)}catch(Ve){console.warn("[use-chat] heartbeat callback failed",Ve)}}else if(wt!==null&&cancelAnimationFrame(wt),Pt(),De.type==="checkpoint")y(De.checkpointId);else if(De.type==="error"){const Ve=De;if(d(Ve.message),L="error",R=Ve.message,Ve.error_type==="auth_error"||Ve.code==="TOKEN_EXPIRED"||((A=Ve.message)==null?void 0:A.includes("token"))||(($=Ve.message)==null?void 0:$.includes("401"))||((H=Ve.message)==null?void 0:H.includes("unauthorized"))||((fe=Ve.message)==null?void 0:fe.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Ve.message);try{(re=N==null?void 0:N.onAuthError)==null||re.call(N,Ve.message)}catch(zn){console.warn("[use-chat] onAuthError handler failed",zn)}z.abort()}}}}Pt(),L===null&&!z.signal.aborted&&(L="complete")}catch(rt){if(rt.name==="AbortError")L=L??"aborted";else{const J=rt.message||String(rt);L="error",R=J,d(J),(Z=N==null?void 0:N.onError)==null||Z.call(N,J)}}finally{try{await it.cancel()}catch{}finally{(ce=it.releaseLock)==null||ce.call(it)}wt!==null&&typeof window<"u"&&window.cancelAnimationFrame(wt),clearInterval(We)}}catch(Be){if(Be.name==="AbortError")L=L??"aborted";else{const Xe=Be.message||String(Be);L="error",R=Xe,d(Xe),(me=N==null?void 0:N.onError)==null||me.call(N,Xe),W||(($e=N==null?void 0:N.onConnectionError)==null||$e.call(N,Xe),W=!0)}}finally{const Be=C.current,Xe=I.current,Qe=j.current,Je=_.current,et=L??(z.signal.aborted?"aborted":R?"error":"complete");try{(Re=N==null?void 0:N.onClosed)==null||Re.call(N,{reason:et,lastSeq:Be,lastCheckpointId:Xe,lastCheckpointNs:Qe,lastStateHistory:Je,error:R})}catch(it){console.warn("[use-chat] onClosed callback failed",it)}l(!1),w(!1),S.current=null,C.current=0,x(0),T.current=null}})(),{close:()=>z.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var P;k.current=!1,(P=S.current)==null||P.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:m,connected:g,stream:V,stop:K,clear:B,setToken:O}}function xx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function yx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
38
- `)}const vx=["message.start","message.delta","message.end"],wx=["tool.start","tool.end","tool.progress"],bx=["thread_info","checkpoint"],Sx=["error","interrupt","heartbeat","state_history","cancelled"],Cx=[...vx,...wx,...bx,...Sx],Tx=new Set(Cx);function kx(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return Tx.has(t)}const uc=200;function Ix({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),h=b.useRef(new Map),p=b.useRef(null),y=b.useRef(null),m=b.useCallback(M=>{try{const N=globalThis.structuredClone;if(typeof N=="function")return N(M)}catch{}try{return JSON.parse(JSON.stringify(M))}catch{return M}},[]),x=b.useCallback((M,N)=>{if(!M)return;const z=h.current.get(M)??[],L=m(N),R=z.length>=uc?[...z.slice(z.length-uc+1),L]:[...z,L];h.current.set(M,R)},[m]),g=b.useCallback(M=>{M&&h.current.set(M,[])},[]),w=b.useCallback(M=>{const N=M??f.current;if(!N)return;const z=h.current.get(N);z!=null&&z.length&&z.forEach(L=>{try{n(L)}catch(R){console.error("[useChatStreamingService] Failed to replay buffered event",R)}})},[n]),S=b.useCallback(M=>{f.current=M.threadId,p.current&&(p.current.threadIdGuess=M.threadId),y.current=M,g(M.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",M);try{t(M)}catch(N){console.error("[useChatStreamingService] Error in onThreadInfo handler:",N)}},[g,t]),k=b.useCallback(M=>{try{c==null||c(M)}catch(N){console.error("[useChatStreamingService] Error in onHeartbeat handler:",N)}},[c]),C=b.useCallback(M=>{var L,R,W,Y;const N=M;if(N.error_type==="auth_error"||N.code==="TOKEN_EXPIRED"||((L=N.message)==null?void 0:L.includes("token"))||((R=N.message)==null?void 0:R.includes("401"))||((W=N.message)==null?void 0:W.includes("unauthorized"))||((Y=N.message)==null?void 0:Y.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",N.message);try{l==null||l(N.message)}catch(ne){console.warn("[useChatStreamingService] onAuthError handler failed",ne)}}},[l]),T=b.useMemo(()=>({thread_info:M=>(S(M),!0),heartbeat:M=>(k(M),!0),error:M=>(C(M),!1)}),[S,k,C]),I=b.useCallback(M=>{var R;const N=M.seq??null;if(N!==null){const W=d.current;if(W!==null){if(N<=W)return;N>W+1&&(s==null||s({from:W,to:N}))}d.current=N}const z=T[M.type];if(z&&z(M))return;const L=M.threadId??(M.type==="state_history"?M.threadId:void 0)??f.current??((R=p.current)==null?void 0:R.threadIdGuess)??null;if(M.type==="state_history"){f.current=L??f.current;try{r==null||r(M)}catch(W){console.error("[useChatStreamingService] onStateHistory handler failed",W)}}if(kx(M)){M.type==="checkpoint"||M.type==="state_history"?g(L??null):x(L??null,M);try{n(M)}catch(W){console.error("[useChatStreamingService] Error in onMessageEvent handler:",W)}return}try{o==null||o(M)}catch(W){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",W)}},[x,g,n,s,r,o,T]),{stream:j,stop:_,isStreaming:O,error:B,setToken:K}=cc({baseUrl:e,token:void 0}),V=b.useCallback((M,N)=>{d.current=null,y.current=null,f.current=M.threadId??null,p.current={request:M,callbacks:N,manualStop:!1,threadIdGuess:M.threadId??null},j(M,I,{onOpen:N==null?void 0:N.onOpen,onError:z=>{var L;(L=N==null?void 0:N.onError)==null||L.call(N,z)},onGap:(N==null?void 0:N.onGap)??s,onConnectionError:z=>{var L;a==null||a(z),(L=N==null?void 0:N.onConnectionError)==null||L.call(N,z)},onAuthError:z=>{var L;l==null||l(z),(L=N==null?void 0:N.onAuthError)==null||L.call(N,z)},onHeartbeat:z=>{var L;try{c==null||c(z)}catch(R){console.warn("[useChatStreamingService] onHeartbeat handler failed",R)}try{(L=N==null?void 0:N.onHeartbeat)==null||L.call(N,z)}catch(R){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",R)}},onClosed:z=>{var Y,ne,pe,be;const L=((Y=p.current)==null?void 0:Y.manualStop)??!1,R=f.current??((ne=p.current)==null?void 0:ne.threadIdGuess)??((pe=z.lastStateHistory)==null?void 0:pe.threadId)??null;(z.reason==="complete"||z.reason==="aborted"&&L)&&g(R);const W={...z,threadId:R,threadInfo:y.current,manualStop:L};try{i==null||i(W)}catch(Ie){console.warn("[useChatStreamingService] onStreamClosed handler failed",Ie)}try{(be=N==null?void 0:N.onClosed)==null||be.call(N,W)}catch(Ie){console.warn("[useChatStreamingService] downstream onClosed handler failed",Ie)}p.current&&(p.current=null)}})},[g,I,l,a,c,s,i,j]),P=b.useCallback(()=>{p.current&&(p.current.manualStop=!0),_()},[_]);return b.useMemo(()=>({startStream:V,stop:P,isStreaming:O,error:B,setAuthToken:K,replayBufferedEvents:w}),[V,P,O,B,K,w])}function Ex({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:l=!0,isStreaming:c,getMessages:d}){const[f,h]=b.useState([]),[p,y]=b.useState([]),[m,x]=b.useState(!1),[g,w]=b.useState(null),[S,k]=b.useState(!1),[C,T]=b.useState(!1),[I,j]=b.useState(!1),[_,O]=b.useState(null),B=b.useRef(o),K=b.useRef(null),V=b.useRef(null),P=b.useRef(null),M=b.useRef(null),N=b.useRef(!1),z=b.useRef(null),L=b.useRef(new Map);b.useEffect(()=>{B.current=o},[o]);const R=b.useCallback(async A=>{var H,fe;if(!A.threadId)return;const $=A.threadId;(H=A.onStart)==null||H.call(A),A.setLoading(!0);try{await A.action($)}catch(re){if(B.current===$){const Z=String(re);(fe=A.handleError)==null||fe.call(A,Z),r==null||r(Z)}throw re}finally{A.setLoading(!1)}},[r]),W=b.useCallback(async(A,$)=>{if(!A)return;const H=`${A}:${$??"latest"}`,fe=L.current.get(H);if(fe)return fe;const re=R({threadId:A,setLoading:k,onStart:()=>O(null),handleError:Z=>O(Z),action:async Z=>{const ce=await e.getStateHistory({threadId:Z,checkpointId:$??void 0});if(B.current!==Z){console.log(`[useThreadHistoryState] Thread changed during load (was ${Z}, now ${B.current}), discarding stale data`);return}const{checkpoints:me,timeline:$e}=fr(ce),Re=me.find(Be=>Be.messages&&Be.messages.length>0)??($?me.find(Be=>Be.checkpointId===$):null)??me[0];t((Re==null?void 0:Re.messages)??[],{checkpointId:(Re==null?void 0:Re.checkpointId)??null,checkpointNs:(Re==null?void 0:Re.checkpointNs)??null}),y($e),h(me),x(!!(Re!=null&&Re.nextCursor)),w((Re==null?void 0:Re.nextCursor)??null)}});L.current.set(H,re);try{await re}finally{L.current.delete(H)}return B.current===A&&(z.current=H),re},[e,t,R]),Y=b.useCallback(async(A,$,H)=>{H!=null&&H.clearProgress&&Zl(),M.current=A;try{await W(A,$)}finally{M.current===A&&(M.current=null)}},[W]),ne=b.useCallback(A=>{V.current=A},[]),pe=b.useCallback(A=>{P.current=A},[]),be=b.useCallback(A=>{const $=A.threadId??B.current;if(!$||B.current&&B.current!==$)return;const{checkpoints:H,timeline:fe}=fr(A);if(!H.length)return;const re=H.find(Z=>Z.messages&&Z.messages.length>0)??H.find(Z=>!!Z.checkpointId)??H[0];t((re==null?void 0:re.messages)??[],{checkpointId:(re==null?void 0:re.checkpointId)??null,checkpointNs:(re==null?void 0:re.checkpointNs)??null}),y(fe),h(H),x(!!(re!=null&&re.nextCursor)),w((re==null?void 0:re.nextCursor)??null),z.current=`${$}:latest`,V.current=null,P.current=null},[t]),Ie=b.useCallback(async(A,$)=>{Zl();const H=B.current;await R({threadId:H,setLoading:j,action:async fe=>{const re=await e.getStateHistory({threadId:fe,checkpointId:A,checkpointNs:$??void 0});if(B.current!==fe){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${fe}, now ${B.current}), discarding stale data`);return}const{checkpoints:Z,timeline:ce}=fr(re),me=Z.find($e=>$e.checkpointId===A&&($?$e.checkpointNs===$:!0));if(!me){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:A,checkpointNs:$});return}y(ce),h(Z),t(me.messages??[],{checkpointId:me.checkpointId??null,checkpointNs:me.checkpointNs??null})}}).catch(()=>{})},[e,t,R]),ve=b.useCallback((A,$)=>{t(d(),{checkpointId:A??null,checkpointNs:$??null})},[d,t]),te=b.useCallback(async()=>{B.current&&await Y(B.current)},[Y]),F=b.useCallback(async()=>{const A=B.current;!A||!g||await R({threadId:A,setLoading:T,action:async $=>{const H=await e.getStateHistory({threadId:$,checkpointId:g});if(B.current!==$)return;const{checkpoints:fe}=fr(H);if(fe.length>0){const re=fe[fe.length-1];n((re==null?void 0:re.messages)??[]),x(!!(re!=null&&re.nextCursor)),w((re==null?void 0:re.nextCursor)??null)}}}).catch(()=>{})},[e,g,r,n,R]);b.useEffect(()=>{if(!l||!o||S||c)return;if(V.current===o){V.current=null,K.current=o;return}if(P.current===o){K.current=o;return}if(M.current===o){M.current=null,K.current=o;return}if(K.current===o)return;K.current=o;const A=!N.current&&!!i&&o===s;let $;A&&i?($=i,N.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",$,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const H=`${o}:${$??"latest"}`;z.current!==H&&Y(o,$)},[l,o,i,a,s,S,c,Y]);const X=b.useCallback(()=>{h([]),y([]),x(!1),w(null),k(!1),T(!1),j(!1),O(null),V.current=null,P.current=null,K.current=null,z.current=null,M.current=null},[]);return{threadCheckpoints:f,threadTimeline:p,isLoadingThread:S,isHistoryLoading:C,isLoadingCheckpoint:I,threadStateError:_,hasMoreHistory:m,loadThread:Y,navigateToCheckpoint:Ie,loadOlderMessages:F,setCurrentCheckpointId:ve,returnToLatest:te,handleStateHistoryEvent:be,markSkipNextLoad:ne,markStreamPendingThread:pe,resetHistoryState:X}}const dc=b.createContext(null),fc=b.createContext(null),hc=b.createContext(null);b.createContext(!1);function Nx({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l}){const{api:c,baseUrl:d}=hi(),f=b.useMemo(()=>wn(d),[d]),[h,p]=b.useState([]),[y,m]=b.useState(t),[x,g]=b.useState(!1),[w,S]=b.useState(null),[k,C]=b.useState([]),[T,I]=b.useState(!1),[,j]=b.useState(null),{state:_,seed:O,prepend:B,pushUser:K,onEvent:V}=ac(),[P,M]=b.useState(!1),N=b.useCallback(()=>_.messages,[_.messages]),{threadCheckpoints:z,threadTimeline:L,isLoadingThread:R,isHistoryLoading:W,isLoadingCheckpoint:Y,threadStateError:ne,hasMoreHistory:pe,loadThread:be,navigateToCheckpoint:Ie,loadOlderMessages:ve,setCurrentCheckpointId:te,returnToLatest:F,handleStateHistoryEvent:X,markSkipNextLoad:A,markStreamPendingThread:$,resetHistoryState:H}=Ex({api:c,seed:O,prepend:B,onError:s,currentThreadId:y,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:P,getMessages:N}),fe=b.useMemo(()=>jg(z),[z]),re=b.useRef(y),Z=b.useRef(new Map);b.useEffect(()=>{re.current=y},[y]);const ce=b.useCallback(async()=>{g(!0),S(null);try{const J=await c.listThreads();p(J??[])}catch(J){const le=String(J);S(le),s==null||s(le)}finally{g(!1)}},[c,s]),me=b.useCallback(async()=>{I(!0),j(null);try{const J=await c.listSharedThreads();C(J??[])}catch(J){const le=String(J);j(le),s==null||s(le)}finally{I(!1)}},[c,s]),$e=b.useCallback(J=>{if(!(J!=null&&J.threadId))return;const le={threadId:J.threadId,title:J.title||`Thread ${J.threadId.slice(0,8)}`,createdAt:J.createdAt||new Date().toISOString(),updatedAt:J.updatedAt||new Date().toISOString(),messageCount:J.messageCount??1};p(ze=>{let Se=!1;const ft=ze.map(U=>U.threadId===le.threadId?(Se=!0,console.debug("[ChatSessionProvider] thread_info: updating existing thread",le.threadId),{...U,title:le.title??U.title,updatedAt:le.updatedAt??U.updatedAt,messageCount:le.messageCount??U.messageCount}):U);return Se?ft:(console.debug("[ChatSessionProvider] thread_info: adding thread to list",le.threadId),[le,...ze])})},[]),Re=b.useCallback(J=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",J.threadId),$e(J),re.current!==J.threadId&&((J.created??!re.current)&&A(J.threadId),$(J.threadId),console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),m(J.threadId))},[$e,A,$]),{startStream:Be,stop:Xe,isStreaming:Qe,error:Je,setAuthToken:et}=Ix({baseUrl:f,onThreadInfo:Re,onMessageEvent:V,onStateHistory:X,onUnhandledEvent:J=>{console.warn("[ChatSessionProvider] Unhandled event:",J.type)},onAuthError:i,onConnectionError:l});b.useEffect(()=>{M(Qe)},[Qe]);const it=b.useCallback(async J=>{try{const le=await c.createThread(J);return m(le.threadId),await ce(),le.threadId}catch(le){return s==null||s(String(le)),null}},[c,ce,s]),Mt=b.useCallback(async J=>{const le=h;p(Se=>Se.filter(ft=>ft.threadId!==J));const ze=new AbortController;Z.current.set(J,ze);try{await c.deleteThread(J),re.current===J&&(m(null),O([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",J)}catch(Se){console.error("[ChatSessionProvider] Delete failed, restoring thread:",J,Se),p(le),s==null||s(`Failed to delete thread: ${String(Se)}`)}finally{Z.current.delete(J)}},[h,c,O,s]),pt=b.useCallback(async(J,le)=>{try{await c.updateThread(J,le),await ce()}catch(ze){s==null||s(String(ze))}},[c,ce,s]),Ct=b.useCallback(async(J,le)=>{try{await c.shareThread(J,le),await me()}catch(ze){const Se=String(ze);throw s==null||s(Se),ze}},[c,s,me]),mt=b.useCallback(async(J,le)=>{try{await c.unshareThread(J,le),await me()}catch(ze){const Se=String(ze);throw s==null||s(Se),ze}},[c,s,me]),wt=b.useCallback(async()=>{O([],{}),m(null),Xe(),H();try{await c.getAgent("default")}catch(J){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",J)}},[O,Xe,c,H]),Pt=b.useCallback(async(J,le,ze)=>{const Se=re.current;if(!Se)throw new Error("No active thread to handle interrupt");const ft=le?ze??!0:!1;try{const U={threadId:Se,checkpointId:_.lastCheckpointId??void 0,checkpointNs:_.lastCheckpointNs??void 0,command:{kind:"resume",value:ft}};Be(U)}catch(U){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${J}:`,U),U}},[_.lastCheckpointId,_.lastCheckpointNs,Be]);b.useEffect(()=>{ce()},[ce]),b.useEffect(()=>{me()},[me]),b.useEffect(()=>{a==null||a(y)},[y,a]);const $t=b.useCallback(async(J,le)=>{let ze=re.current;const Se=(J==null?void 0:J.text)??"",ft=(J==null?void 0:J.attachments)??[],U=(Se==null?void 0:Se.trim())??"",ge={...(J==null?void 0:J.payload)??{}},ye=Array.isArray(ge.messages)?ge.messages:void 0;ye&&delete ge.messages;const Ke=!!(ye&&ye.length);if(!ze&&!U&&ft.length===0&&!Ke)return;if(!ze){const lr=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),E=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);ze=`${lr}${E}`,A(ze),m(ze)}const{contentParts:De,filesInfo:ct}=await Eg(c,ft),Ve=[...De];U&&Ve.push({type:"text",text:Se});const bt=le==null?void 0:le.originalMessageId,zn=!!(le!=null&&le.edit&&bt),ar=!Ke&&Ve.length>0;let En=null;ar&&(En={id:zn?bt:`msg-${Date.now()}`,role:"user",content:Ve,createdAt:new Date().toISOString()},zn||K(En));const jr=Ke?ye:En?[En]:[],Un={...ge,...ct.length?{files_info:ct}:{}};jr.length?Un.messages=jr:"messages"in Un||(Un.messages=[]);const po={threadId:ze,payload:Un,checkpointId:(le==null?void 0:le.checkpointId)??_.lastCheckpointId??void 0,checkpointNs:(le==null?void 0:le.checkpointNs)??_.lastCheckpointNs??void 0,edit:!!(le!=null&&le.edit),timelineCheckpoints:L};Be(po)},[c,K,_,Be,L]),cn=b.useMemo(()=>({threads:h,currentThreadId:y,setCurrentThreadId:m,isLoading:x,error:w,sharedThreads:k,isLoadingSharedThreads:T,actions:{createThread:it,deleteThread:Mt,renameThread:pt,refreshThreads:ce,refreshSharedThreads:me,shareThread:Ct,unshareThread:mt}}),[h,y,x,w,k,T,it,Mt,pt,ce,me,Ct,mt]),We=b.useMemo(()=>{const J=_.assemblingId??null;return J?{assemblingMessageId:J}:null},[_.assemblingId]),In=b.useMemo(()=>({threadId:y,messages:_.messages,interrupt:null,checkpoint:{id:_.lastCheckpointId??null,namespace:_.lastCheckpointNs??null},checkpoints:z,timelineCheckpoints:L,metadata:We,isLoading:R,isHistoryLoading:W,isLoadingCheckpoint:Y,error:ne,hasMore:pe,loadOlder:ve,clearState:wt,navigateToCheckpoint:Ie,setCurrentCheckpointId:te,returnToLatest:F,loadThread:be,clearThread:wt,respondToInterrupt:Pt,messagePreviews:fe}),[y,_,z,L,R,W,Y,ne,pe,ve,wt,Ie,te,F,be,Pt,fe,We]),rt=b.useMemo(()=>({isStreaming:Qe,error:Je,connectionState:Qe?"connected":"idle",submit:$t,send:$t,stop:Xe,setAuthToken:et}),[Qe,Je,$t,Xe,et]);return u.jsx(dc.Provider,{value:cn,children:u.jsx(fc.Provider,{value:In,children:u.jsx(hc.Provider,{value:rt,children:e})})})}function Po(){const e=b.useContext(dc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Ro(){const e=b.useContext(fc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function pc(){const e=b.useContext(hc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Oo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(kg,{apiConfig:t,children:u.jsx(Nx,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function ee(...e){return Zp.twMerge(Jp.clsx(e))}const Ax=mo.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),tt=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Wn.Slot:"button";return u.jsx(i,{className:ee(Ax({variant:t,size:n,className:e})),ref:s,...o})});tt.displayName="Button";const mc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:ee("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));mc.displayName="Textarea";function gc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const y=i!==void 0,[m,x]=b.useState(e),g=(y?i:m)??"",[w,S]=b.useTransition(),k=b.useRef(null),C=b.useRef(0),T=b.useRef(null);b.useEffect(()=>{y||(x(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,y]);const I=b.useCallback(()=>{const M=k.current;M&&(M.style.height="auto",M.style.height=`${M.scrollHeight}px`)},[]);b.useEffect(()=>{I()},[I,g]);const j=b.useCallback((M,{fromUser:N})=>{y||x(M),N&&(a==null||a(M))},[y,a]),_=b.useCallback(async M=>{M&&M.preventDefault();const N=(g??"").trim();if(!N&&!p)return;const z=++C.current;T.current={id:z,shouldClear:!0},S(()=>{var L,R,W;try{const Y=l(N);Y&&typeof Y.then=="function"?Y.then(()=>{var ne,pe;((ne=T.current)==null?void 0:ne.id)===z&&T.current.shouldClear&&(y||(x(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((pe=T.current)==null?void 0:pe.id)===z&&(T.current=null)}).catch(()=>{var ne;((ne=T.current)==null?void 0:ne.id)===z&&(T.current=null)}):(((L=T.current)==null?void 0:L.id)===z&&T.current.shouldClear&&(y||(x(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=T.current)==null?void 0:R.id)===z&&(T.current=null))}catch{((W=T.current)==null?void 0:W.id)===z&&(T.current=null)}})},[g,l,p,y,a]),O=b.useCallback(M=>{const N=M.target.value;j(N,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[j]),B=b.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),_()):M.key==="Escape"&&t&&(M.preventDefault(),c==null||c())},[_,t,c]),P=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:M=>void _(M),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(mc,{ref:k,value:g,onChange:O,onKeyDown:B,placeholder:t?"Edit your message...":n,className:P,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(tt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(oe.Square,{size:16})}):u.jsx(tt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!p||w,children:u.jsx(oe.Send,{size:16})})})]})})}const jx=b.memo(gc);function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function xc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function yi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=xc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():xc(e[o],null)}}}}function Ue(...e){return v.useCallback(yi(...e),e)}function _x(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function bn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:h,children:p,...y}=f,m=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,x=v.useMemo(()=>y,Object.values(y));return u.jsx(m.Provider,{value:x,children:p})};c.displayName=s+"Provider";function d(f,h){var m;const p=((m=h==null?void 0:h[e])==null?void 0:m[l])||a,y=v.useContext(p);if(y)return y;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Mx(o,...t)]}function Mx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},Px=v[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Rx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const h=Ox(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function Rx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return Px(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Ox(e){return typeof e=="function"}var Dx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],_e=Dx.reduce((e,t)=>{const n=Wn.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function yc(e,t){e&&go.flushSync(()=>e.dispatchEvent(t))}function vi(e){const t=e+"CollectionProvider",[n,r]=bn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:x,children:g}=m,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:x,itemMap:S,collectionRef:w,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=Wn.createSlot(a),c=b.forwardRef((m,x)=>{const{scope:g,children:w}=m,S=s(a,g),k=Ue(x,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=Wn.createSlot(d),p=b.forwardRef((m,x)=>{const{scope:g,children:w,...S}=m,k=b.useRef(null),C=Ue(x,k),T=s(d,g);return b.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(h,{[f]:"",ref:C,children:w})});p.displayName=d;function y(m){const x=s(e+"CollectionConsumer",m);return b.useCallback(()=>{const w=x.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(x.itemMap.values()).sort((T,I)=>S.indexOf(T.ref.current)-S.indexOf(I.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},y,r]}var Lx=v.createContext(void 0);function Do(e){const t=v.useContext(Lx);return e||t||"ltr"}function It(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function $x(e,t=globalThis==null?void 0:globalThis.document){const n=It(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Fx="DismissableLayer",wi="dismissableLayer.update",Bx="dismissableLayer.pointerDownOutside",zx="dismissableLayer.focusOutside",vc,wc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Lo=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(wc),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),y=Ue(t,I=>f(I)),m=Array.from(c.layers),[x]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=m.indexOf(x),w=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=g,C=Wx(I=>{const j=I.target,_=[...c.branches].some(O=>O.contains(j));!k||_||(o==null||o(I),i==null||i(I),I.defaultPrevented||a==null||a())},h),T=Vx(I=>{const j=I.target;[...c.branches].some(O=>O.contains(j))||(s==null||s(I),i==null||i(I),I.defaultPrevented||a==null||a())},h);return $x(I=>{w===c.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(vc=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),bc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=vc)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),bc())},[d,c]),v.useEffect(()=>{const I=()=>p({});return document.addEventListener(wi,I),()=>document.removeEventListener(wi,I)},[]),u.jsx(_e.div,{...l,ref:y,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,T.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,C.onPointerDownCapture)})});Lo.displayName=Fx;var Ux="DismissableLayerBranch",Hx=v.forwardRef((e,t)=>{const n=v.useContext(wc),r=v.useRef(null),o=Ue(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(_e.div,{...e,ref:o})});Hx.displayName=Ux;function Wx(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){Sc(Bx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Vx(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&Sc(zx,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function bc(){const e=new CustomEvent(wi);document.dispatchEvent(e)}function Sc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?yc(o,s):o.dispatchEvent(s)}var bi=0;function Si(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Cc()),document.body.insertAdjacentElement("beforeend",e[1]??Cc()),bi++,()=>{bi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),bi--}},[])}function Cc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Ci="focusScope.autoFocusOnMount",Ti="focusScope.autoFocusOnUnmount",Tc={bubbles:!1,cancelable:!0},Kx="FocusScope",$o=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=It(o),d=It(s),f=v.useRef(null),h=Ue(t,m=>l(m)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(S){if(p.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:An(f.current,{select:!0})},x=function(S){if(p.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||An(f.current,{select:!0}))},g=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&An(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",x);const w=new MutationObserver(g);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",x),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){Ec.add(p);const m=document.activeElement;if(!a.contains(m)){const g=new CustomEvent(Ci,Tc);a.addEventListener(Ci,c),a.dispatchEvent(g),g.defaultPrevented||(qx(Zx(kc(a)),{select:!0}),document.activeElement===m&&An(a))}return()=>{a.removeEventListener(Ci,c),setTimeout(()=>{const g=new CustomEvent(Ti,Tc);a.addEventListener(Ti,d),a.dispatchEvent(g),g.defaultPrevented||An(m??document.body,{select:!0}),a.removeEventListener(Ti,d),Ec.remove(p)},0)}}},[a,c,d,p]);const y=v.useCallback(m=>{if(!n&&!r||p.paused)return;const x=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,g=document.activeElement;if(x&&g){const w=m.currentTarget,[S,k]=Gx(w);S&&k?!m.shiftKey&&g===k?(m.preventDefault(),n&&An(S,{select:!0})):m.shiftKey&&g===S&&(m.preventDefault(),n&&An(k,{select:!0})):g===w&&m.preventDefault()}},[n,r,p.paused]);return u.jsx(_e.div,{tabIndex:-1,...i,ref:h,onKeyDown:y})});$o.displayName=Kx;function qx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(An(r,{select:t}),document.activeElement!==n)return}function Gx(e){const t=kc(e),n=Ic(t,e),r=Ic(t.reverse(),e);return[n,r]}function kc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Ic(e,t){for(const n of e)if(!Yx(n,{upTo:t}))return n}function Yx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Xx(e){return e instanceof HTMLInputElement&&"select"in e}function An(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Xx(e)&&t&&e.select()}}var Ec=Jx();function Jx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Nc(e,t),e.unshift(t)},remove(t){var n;e=Nc(e,t),(n=e[0])==null||n.resume()}}}function Nc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Zx(e){return e.filter(t=>t.tagName!=="A")}var Qx=v[" useId ".trim().toString()]||(()=>{}),ey=0;function Sn(e){const[t,n]=v.useState(Qx());return kt(()=>{n(r=>r??String(ey++))},[e]),t?`radix-${t}`:""}const ty=["top","right","bottom","left"],jn=Math.min,Ht=Math.max,Fo=Math.round,Bo=Math.floor,dn=e=>({x:e,y:e}),ny={left:"right",right:"left",bottom:"top",top:"bottom"},ry={start:"end",end:"start"};function ki(e,t,n){return Ht(e,jn(t,n))}function Cn(e,t){return typeof e=="function"?e(t):e}function Tn(e){return e.split("-")[0]}function mr(e){return e.split("-")[1]}function Ii(e){return e==="x"?"y":"x"}function Ei(e){return e==="y"?"height":"width"}const oy=new Set(["top","bottom"]);function fn(e){return oy.has(Tn(e))?"y":"x"}function Ni(e){return Ii(fn(e))}function sy(e,t,n){n===void 0&&(n=!1);const r=mr(e),o=Ni(e),s=Ei(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=zo(i)),[i,zo(i)]}function iy(e){const t=zo(e);return[Ai(e),t,Ai(t)]}function Ai(e){return e.replace(/start|end/g,t=>ry[t])}const Ac=["left","right"],jc=["right","left"],ay=["top","bottom"],ly=["bottom","top"];function cy(e,t,n){switch(e){case"top":case"bottom":return n?t?jc:Ac:t?Ac:jc;case"left":case"right":return t?ay:ly;default:return[]}}function uy(e,t,n,r){const o=mr(e);let s=cy(Tn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ai)))),s}function zo(e){return e.replace(/left|right|bottom|top/g,t=>ny[t])}function dy(e){return{top:0,right:0,bottom:0,left:0,...e}}function _c(e){return typeof e!="number"?dy(e):{top:e,right:e,bottom:e,left:e}}function Uo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Mc(e,t,n){let{reference:r,floating:o}=e;const s=fn(t),i=Ni(t),a=Ei(i),l=Tn(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(mr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const fy=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Mc(c,r,l),h=r,p={},y=0;for(let m=0;m<a.length;m++){const{name:x,fn:g}=a[m],{x:w,y:S,data:k,reset:C}=await g({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,p={...p,[x]:{...p[x],...k}},C&&y<=50&&(y++,typeof C=="object"&&(C.placement&&(h=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=Mc(c,h,l)),m=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Fr(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=Cn(t,e),y=_c(p),x=a[h?f==="floating"?"reference":"floating":f],g=Uo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(x)))==null||n?x:x.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},C=Uo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(g.top-C.top+y.top)/k.y,bottom:(C.bottom-g.bottom+y.bottom)/k.y,left:(g.left-C.left+y.left)/k.x,right:(C.right-g.right+y.right)/k.x}}const hy=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=Cn(e,t)||{};if(c==null)return{};const f=_c(d),h={x:n,y:r},p=Ni(o),y=Ei(p),m=await i.getDimensions(c),x=p==="y",g=x?"top":"left",w=x?"bottom":"right",S=x?"clientHeight":"clientWidth",k=s.reference[y]+s.reference[p]-h[p]-s.floating[y],C=h[p]-s.reference[p],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let I=T?T[S]:0;(!I||!await(i.isElement==null?void 0:i.isElement(T)))&&(I=a.floating[S]||s.floating[y]);const j=k/2-C/2,_=I/2-m[y]/2-1,O=jn(f[g],_),B=jn(f[w],_),K=O,V=I-m[y]-B,P=I/2-m[y]/2+j,M=ki(K,P,V),N=!l.arrow&&mr(o)!=null&&P!==M&&s.reference[y]/2-(P<K?O:B)-m[y]/2<0,z=N?P<K?P-K:P-V:0;return{[p]:h[p]+z,data:{[p]:M,centerOffset:P-M-z,...N&&{alignmentOffset:z}},reset:N}}}),py=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:m=!0,...x}=Cn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=Tn(o),w=fn(a),S=Tn(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=h||(S||!m?[zo(a)]:iy(a)),T=y!=="none";!h&&T&&C.push(...uy(a,m,y,k));const I=[a,...C],j=await Fr(t,x),_=[];let O=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(j[g]),f){const P=sy(o,i,k);_.push(j[P[0]],j[P[1]])}if(O=[...O,{placement:o,overflows:_}],!_.every(P=>P<=0)){var B,K;const P=(((B=s.flip)==null?void 0:B.index)||0)+1,M=I[P];if(M&&(!(f==="alignment"?w!==fn(M):!1)||O.every(L=>fn(L.placement)===w?L.overflows[0]>0:!0)))return{data:{index:P,overflows:O},reset:{placement:M}};let N=(K=O.filter(z=>z.overflows[0]<=0).sort((z,L)=>z.overflows[1]-L.overflows[1])[0])==null?void 0:K.placement;if(!N)switch(p){case"bestFit":{var V;const z=(V=O.filter(L=>{if(T){const R=fn(L.placement);return R===w||R==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(R=>R>0).reduce((R,W)=>R+W,0)]).sort((L,R)=>L[1]-R[1])[0])==null?void 0:V[0];z&&(N=z);break}case"initialPlacement":N=a;break}if(o!==N)return{reset:{placement:N}}}return{}}}};function Pc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Rc(e){return ty.some(t=>e[t]>=0)}const my=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Cn(e,t);switch(r){case"referenceHidden":{const s=await Fr(t,{...o,elementContext:"reference"}),i=Pc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Rc(i)}}}case"escaped":{const s=await Fr(t,{...o,altBoundary:!0}),i=Pc(s,n.floating);return{data:{escapedOffsets:i,escaped:Rc(i)}}}default:return{}}}}},Oc=new Set(["left","top"]);async function gy(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Tn(n),a=mr(n),l=fn(n)==="y",c=Oc.has(i)?-1:1,d=s&&l?-1:1,f=Cn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:y}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof y=="number"&&(p=a==="end"?y*-1:y),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const xy=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await gy(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},yy=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:x=>{let{x:g,y:w}=x;return{x:g,y:w}}},...l}=Cn(e,t),c={x:n,y:r},d=await Fr(t,l),f=fn(Tn(o)),h=Ii(f);let p=c[h],y=c[f];if(s){const x=h==="y"?"top":"left",g=h==="y"?"bottom":"right",w=p+d[x],S=p-d[g];p=ki(w,p,S)}if(i){const x=f==="y"?"top":"left",g=f==="y"?"bottom":"right",w=y+d[x],S=y-d[g];y=ki(w,y,S)}const m=a.fn({...t,[h]:p,[f]:y});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[h]:s,[f]:i}}}}}},vy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=Cn(e,t),d={x:n,y:r},f=fn(o),h=Ii(f);let p=d[h],y=d[f];const m=Cn(a,t),x=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=h==="y"?"height":"width",k=s.reference[h]-s.floating[S]+x.mainAxis,C=s.reference[h]+s.reference[S]-x.mainAxis;p<k?p=k:p>C&&(p=C)}if(c){var g,w;const S=h==="y"?"width":"height",k=Oc.has(Tn(o)),C=s.reference[f]-s.floating[S]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:x.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?x.crossAxis:0);y<C?y=C:y>T&&(y=T)}return{[h]:p,[f]:y}}}},wy=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=Cn(e,t),d=await Fr(t,c),f=Tn(o),h=mr(o),p=fn(o)==="y",{width:y,height:m}=s.floating;let x,g;f==="top"||f==="bottom"?(x=f,g=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,x=h==="end"?"top":"bottom");const w=m-d.top-d.bottom,S=y-d.left-d.right,k=jn(m-d[x],w),C=jn(y-d[g],S),T=!t.middlewareData.shift;let I=k,j=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(I=w),T&&!h){const O=Ht(d.left,0),B=Ht(d.right,0),K=Ht(d.top,0),V=Ht(d.bottom,0);p?j=y-2*(O!==0||B!==0?O+B:Ht(d.left,d.right)):I=m-2*(K!==0||V!==0?K+V:Ht(d.top,d.bottom))}await l({...t,availableWidth:j,availableHeight:I});const _=await i.getDimensions(a.floating);return y!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function Ho(){return typeof window<"u"}function gr(e){return Dc(e)?(e.nodeName||"").toLowerCase():"#document"}function Wt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function hn(e){var t;return(t=(Dc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dc(e){return Ho()?e instanceof Node||e instanceof Wt(e).Node:!1}function nn(e){return Ho()?e instanceof Element||e instanceof Wt(e).Element:!1}function pn(e){return Ho()?e instanceof HTMLElement||e instanceof Wt(e).HTMLElement:!1}function Lc(e){return!Ho()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wt(e).ShadowRoot}const by=new Set(["inline","contents"]);function Br(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=rn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!by.has(o)}const Sy=new Set(["table","td","th"]);function Cy(e){return Sy.has(gr(e))}const Ty=[":popover-open",":modal"];function Wo(e){return Ty.some(t=>{try{return e.matches(t)}catch{return!1}})}const ky=["transform","translate","scale","rotate","perspective"],Iy=["transform","translate","scale","rotate","perspective","filter"],Ey=["paint","layout","strict","content"];function ji(e){const t=_i(),n=nn(e)?rn(e):e;return ky.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Iy.some(r=>(n.willChange||"").includes(r))||Ey.some(r=>(n.contain||"").includes(r))}function Ny(e){let t=_n(e);for(;pn(t)&&!xr(t);){if(ji(t))return t;if(Wo(t))return null;t=_n(t)}return null}function _i(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Ay=new Set(["html","body","#document"]);function xr(e){return Ay.has(gr(e))}function rn(e){return Wt(e).getComputedStyle(e)}function Vo(e){return nn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function _n(e){if(gr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Lc(e)&&e.host||hn(e);return Lc(t)?t.host:t}function $c(e){const t=_n(e);return xr(t)?e.ownerDocument?e.ownerDocument.body:e.body:pn(t)&&Br(t)?t:$c(t)}function zr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=$c(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Wt(o);if(s){const a=Mi(i);return t.concat(i,i.visualViewport||[],Br(o)?o:[],a&&n?zr(a):[])}return t.concat(o,zr(o,[],n))}function Mi(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Fc(e){const t=rn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=pn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Fo(n)!==s||Fo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Pi(e){return nn(e)?e:e.contextElement}function yr(e){const t=Pi(e);if(!pn(t))return dn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Fc(t);let i=(s?Fo(n.width):n.width)/r,a=(s?Fo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const jy=dn(0);function Bc(e){const t=Wt(e);return!_i()||!t.visualViewport?jy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function _y(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Wt(e)?!1:t}function Gn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Pi(e);let i=dn(1);t&&(r?nn(r)&&(i=yr(r)):i=yr(e));const a=_y(s,n,r)?Bc(s):dn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=Wt(s),p=r&&nn(r)?Wt(r):r;let y=h,m=Mi(y);for(;m&&r&&p!==y;){const x=yr(m),g=m.getBoundingClientRect(),w=rn(m),S=g.left+(m.clientLeft+parseFloat(w.paddingLeft))*x.x,k=g.top+(m.clientTop+parseFloat(w.paddingTop))*x.y;l*=x.x,c*=x.y,d*=x.x,f*=x.y,l+=S,c+=k,y=Wt(m),m=Mi(y)}}return Uo({width:d,height:f,x:l,y:c})}function Ko(e,t){const n=Vo(e).scrollLeft;return t?t.left+n:Gn(hn(e)).left+n}function zc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Ko(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function My(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=hn(r),a=t?Wo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=dn(1);const d=dn(0),f=pn(r);if((f||!f&&!s)&&((gr(r)!=="body"||Br(i))&&(l=Vo(r)),pn(r))){const p=Gn(r);c=yr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?zc(i,l):dn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function Py(e){return Array.from(e.getClientRects())}function Ry(e){const t=hn(e),n=Vo(e),r=e.ownerDocument.body,o=Ht(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ht(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Ko(e);const a=-n.scrollTop;return rn(r).direction==="rtl"&&(i+=Ht(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Uc=25;function Oy(e,t){const n=Wt(e),r=hn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=_i();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Ko(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,y=Math.abs(r.clientWidth-f.clientWidth-p);y<=Uc&&(s-=y)}else c<=Uc&&(s+=c);return{width:s,height:i,x:a,y:l}}const Dy=new Set(["absolute","fixed"]);function Ly(e,t){const n=Gn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=pn(e)?yr(e):dn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Hc(e,t,n){let r;if(t==="viewport")r=Oy(e,n);else if(t==="document")r=Ry(hn(e));else if(nn(t))r=Ly(t,n);else{const o=Bc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Uo(r)}function Wc(e,t){const n=_n(e);return n===t||!nn(n)||xr(n)?!1:rn(n).position==="fixed"||Wc(n,t)}function $y(e,t){const n=t.get(e);if(n)return n;let r=zr(e,[],!1).filter(a=>nn(a)&&gr(a)!=="body"),o=null;const s=rn(e).position==="fixed";let i=s?_n(e):e;for(;nn(i)&&!xr(i);){const a=rn(i),l=ji(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Dy.has(o.position)||Br(i)&&!l&&Wc(e,i))?r=r.filter(d=>d!==i):o=a,i=_n(i)}return t.set(e,r),r}function Fy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Wo(t)?[]:$y(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Hc(t,d,o);return c.top=Ht(f.top,c.top),c.right=jn(f.right,c.right),c.bottom=jn(f.bottom,c.bottom),c.left=Ht(f.left,c.left),c},Hc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function By(e){const{width:t,height:n}=Fc(e);return{width:t,height:n}}function zy(e,t,n){const r=pn(t),o=hn(t),s=n==="fixed",i=Gn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=dn(0);function c(){l.x=Ko(o)}if(r||!r&&!s)if((gr(t)!=="body"||Br(o))&&(a=Vo(t)),r){const p=Gn(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?zc(o,a):dn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function Ri(e){return rn(e).position==="static"}function Vc(e,t){if(!pn(e)||rn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return hn(e)===n&&(n=n.ownerDocument.body),n}function Kc(e,t){const n=Wt(e);if(Wo(e))return n;if(!pn(e)){let o=_n(e);for(;o&&!xr(o);){if(nn(o)&&!Ri(o))return o;o=_n(o)}return n}let r=Vc(e,t);for(;r&&Cy(r)&&Ri(r);)r=Vc(r,t);return r&&xr(r)&&Ri(r)&&!ji(r)?n:r||Ny(e)||n}const Uy=async function(e){const t=this.getOffsetParent||Kc,n=this.getDimensions,r=await n(e.floating);return{reference:zy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Hy(e){return rn(e).direction==="rtl"}const Wy={convertOffsetParentRelativeRectToViewportRelativeRect:My,getDocumentElement:hn,getClippingRect:Fy,getOffsetParent:Kc,getElementRects:Uy,getClientRects:Py,getDimensions:By,getScale:yr,isElement:nn,isRTL:Hy};function qc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Vy(e,t){let n=null,r;const o=hn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const y=Bo(f),m=Bo(o.clientWidth-(d+h)),x=Bo(o.clientHeight-(f+p)),g=Bo(d),S={rootMargin:-y+"px "+-m+"px "+-x+"px "+-g+"px",threshold:Ht(0,jn(1,l))||1};let k=!0;function C(T){const I=T[0].intersectionRatio;if(I!==l){if(!k)return i();I?i(!1,I):r=setTimeout(()=>{i(!1,1e-7)},1e3)}I===1&&!qc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Ky(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Pi(e),d=o||s?[...c?zr(c):[],...zr(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?Vy(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(g=>{let[w]=g;w&&w.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=p)==null||S.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let y,m=l?Gn(e):null;l&&x();function x(){const g=Gn(e);m&&!qc(m,g)&&n(),m=g,y=requestAnimationFrame(x)}return n(),()=>{var g;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(g=p)==null||g.disconnect(),p=null,l&&cancelAnimationFrame(y)}}const qy=xy,Gy=yy,Yy=py,Xy=wy,Jy=my,Gc=hy,Zy=vy,Qy=(e,t,n)=>{const r=new Map,o={platform:Wy,...n},s={...o.platform,_c:r};return fy(e,t,{...o,platform:s})};var ev=typeof document<"u",tv=function(){},qo=ev?b.useLayoutEffect:tv;function Go(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Go(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Go(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Yc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Xc(e,t){const n=Yc(e);return Math.round(t*n)/n}function Oi(e){const t=v.useRef(e);return qo(()=>{t.current=e}),t}function nv(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=v.useState(r);Go(h,r)||p(r);const[y,m]=v.useState(null),[x,g]=v.useState(null),w=v.useCallback(L=>{L!==T.current&&(T.current=L,m(L))},[]),S=v.useCallback(L=>{L!==I.current&&(I.current=L,g(L))},[]),k=s||y,C=i||x,T=v.useRef(null),I=v.useRef(null),j=v.useRef(d),_=l!=null,O=Oi(l),B=Oi(o),K=Oi(c),V=v.useCallback(()=>{if(!T.current||!I.current)return;const L={placement:t,strategy:n,middleware:h};B.current&&(L.platform=B.current),Qy(T.current,I.current,L).then(R=>{const W={...R,isPositioned:K.current!==!1};P.current&&!Go(j.current,W)&&(j.current=W,go.flushSync(()=>{f(W)}))})},[h,t,n,B,K]);qo(()=>{c===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f(L=>({...L,isPositioned:!1})))},[c]);const P=v.useRef(!1);qo(()=>(P.current=!0,()=>{P.current=!1}),[]),qo(()=>{if(k&&(T.current=k),C&&(I.current=C),k&&C){if(O.current)return O.current(k,C,V);V()}},[k,C,V,O,_]);const M=v.useMemo(()=>({reference:T,floating:I,setReference:w,setFloating:S}),[w,S]),N=v.useMemo(()=>({reference:k,floating:C}),[k,C]),z=v.useMemo(()=>{const L={position:n,left:0,top:0};if(!N.floating)return L;const R=Xc(N.floating,d.x),W=Xc(N.floating,d.y);return a?{...L,transform:"translate("+R+"px, "+W+"px)",...Yc(N.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:W}},[n,a,N.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:M,elements:N,floatingStyles:z}),[d,V,M,N,z])}const rv=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Gc({element:r.current,padding:o}).fn(n):{}:r?Gc({element:r,padding:o}).fn(n):{}}}},ov=(e,t)=>({...qy(e),options:[e,t]}),sv=(e,t)=>({...Gy(e),options:[e,t]}),iv=(e,t)=>({...Zy(e),options:[e,t]}),av=(e,t)=>({...Yy(e),options:[e,t]}),lv=(e,t)=>({...Xy(e),options:[e,t]}),cv=(e,t)=>({...Jy(e),options:[e,t]}),uv=(e,t)=>({...rv(e),options:[e,t]});var dv="Arrow",Jc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(_e.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Jc.displayName=dv;var fv=Jc;function Zc(e){const[t,n]=v.useState(void 0);return kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Di="Popper",[Qc,Yo]=bn(Di),[hv,eu]=Qc(Di),tu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(hv,{scope:t,anchor:r,onAnchorChange:o,children:n})};tu.displayName=Di;var nu="PopperAnchor",ru=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=eu(nu,n),i=v.useRef(null),a=Ue(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(_e.div,{...o,ref:a})});ru.displayName=nu;var Li="PopperContent",[pv,mv]=Qc(Li),ou=v.forwardRef((e,t)=>{var te,F,X,A,$,H;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:y,...m}=e,x=eu(Li,n),[g,w]=v.useState(null),S=Ue(t,fe=>w(fe)),[k,C]=v.useState(null),T=Zc(k),I=(T==null?void 0:T.width)??0,j=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),O=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},B=Array.isArray(c)?c:[c],K=B.length>0,V={padding:O,boundary:B.filter(xv),altBoundary:K},{refs:P,floatingStyles:M,placement:N,isPositioned:z,middlewareData:L}=nv({strategy:"fixed",placement:_,whileElementsMounted:(...fe)=>Ky(...fe,{animationFrame:p==="always"}),elements:{reference:x.anchor},middleware:[ov({mainAxis:o+j,alignmentAxis:i}),l&&sv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?iv():void 0,...V}),l&&av({...V}),lv({...V,apply:({elements:fe,rects:re,availableWidth:Z,availableHeight:ce})=>{const{width:me,height:$e}=re.reference,Re=fe.floating.style;Re.setProperty("--radix-popper-available-width",`${Z}px`),Re.setProperty("--radix-popper-available-height",`${ce}px`),Re.setProperty("--radix-popper-anchor-width",`${me}px`),Re.setProperty("--radix-popper-anchor-height",`${$e}px`)}}),k&&uv({element:k,padding:a}),yv({arrowWidth:I,arrowHeight:j}),h&&cv({strategy:"referenceHidden",...V})]}),[R,W]=au(N),Y=It(y);kt(()=>{z&&(Y==null||Y())},[z,Y]);const ne=(te=L.arrow)==null?void 0:te.x,pe=(F=L.arrow)==null?void 0:F.y,be=((X=L.arrow)==null?void 0:X.centerOffset)!==0,[Ie,ve]=v.useState();return kt(()=>{g&&ve(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:P.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:z?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ie,"--radix-popper-transform-origin":[(A=L.transformOrigin)==null?void 0:A.x,($=L.transformOrigin)==null?void 0:$.y].join(" "),...((H=L.hide)==null?void 0:H.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(pv,{scope:n,placedSide:R,onArrowChange:C,arrowX:ne,arrowY:pe,shouldHideArrow:be,children:u.jsx(_e.div,{"data-side":R,"data-align":W,...m,ref:S,style:{...m.style,animation:z?void 0:"none"}})})})});ou.displayName=Li;var su="PopperArrow",gv={top:"bottom",right:"left",bottom:"top",left:"right"},iu=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=mv(su,r),i=gv[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(fv,{...o,ref:n,style:{...o.style,display:"block"}})})});iu.displayName=su;function xv(e){return e!==null}var yv=e=>({name:"transformOrigin",options:e,fn(t){var x,g,w;const{placement:n,rects:r,middlewareData:o}=t,i=((x=o.arrow)==null?void 0:x.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=au(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let y="",m="";return c==="bottom"?(y=i?f:`${h}px`,m=`${-l}px`):c==="top"?(y=i?f:`${h}px`,m=`${r.floating.height+l}px`):c==="right"?(y=`${-l}px`,m=i?f:`${p}px`):c==="left"&&(y=`${r.floating.width+l}px`,m=i?f:`${p}px`),{data:{x:y,y:m}}}});function au(e){const[t,n="center"]=e.split("-");return[t,n]}var lu=tu,cu=ru,uu=ou,du=iu,vv="Portal",Xo=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Js.createPortal(u.jsx(_e.div,{...r,ref:t}),i):null});Xo.displayName=vv;function wv(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Gt=e=>{const{present:t,children:n}=e,r=bv(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Ue(r.ref,Sv(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Gt.displayName="Presence";function bv(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=wv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Jo(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Jo(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const m=Jo(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&m&&(l("ANIMATION_END"),!o.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},h=p=>{p.target===t&&(s.current=Jo(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Jo(e){return(e==null?void 0:e.animationName)||"none"}function Sv(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var $i="rovingFocusGroup.onEntryFocus",Cv={bubbles:!1,cancelable:!0},Ur="RovingFocusGroup",[Fi,fu,Tv]=vi(Ur),[kv,hu]=bn(Ur,[Tv]),[Iv,Ev]=kv(Ur),pu=v.forwardRef((e,t)=>u.jsx(Fi.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Fi.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Nv,{...e,ref:t})})}));pu.displayName=Ur;var Nv=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=v.useRef(null),p=Ue(t,h),y=Do(s),[m,x]=pr({prop:i,defaultProp:a??null,onChange:l,caller:Ur}),[g,w]=v.useState(!1),S=It(c),k=fu(n),C=v.useRef(!1),[T,I]=v.useState(0);return v.useEffect(()=>{const j=h.current;if(j)return j.addEventListener($i,S),()=>j.removeEventListener($i,S)},[S]),u.jsx(Iv,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:m,onItemFocus:v.useCallback(j=>x(j),[x]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>I(j=>j+1),[]),onFocusableItemRemove:v.useCallback(()=>I(j=>j-1),[]),children:u.jsx(_e.div,{tabIndex:g||T===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{C.current=!0}),onFocus:ue(e.onFocus,j=>{const _=!C.current;if(j.target===j.currentTarget&&_&&!g){const O=new CustomEvent($i,Cv);if(j.currentTarget.dispatchEvent(O),!O.defaultPrevented){const B=k().filter(N=>N.focusable),K=B.find(N=>N.active),V=B.find(N=>N.id===m),M=[K,V,...B].filter(Boolean).map(N=>N.ref.current);xu(M,d)}}C.current=!1}),onBlur:ue(e.onBlur,()=>w(!1))})})}),mu="RovingFocusGroupItem",gu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=Sn(),c=s||l,d=Ev(mu,n),f=d.currentTabStopId===c,h=fu(n),{onFocusableItemAdd:p,onFocusableItemRemove:y,currentTabStopId:m}=d;return v.useEffect(()=>{if(r)return p(),()=>y()},[r,p,y]),u.jsx(Fi.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(_e.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(c):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const g=_v(x,d.orientation,d.dir);if(g!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let S=h().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")S.reverse();else if(g==="prev"||g==="next"){g==="prev"&&S.reverse();const k=S.indexOf(x.currentTarget);S=d.loop?Mv(S,k+1):S.slice(k+1)}setTimeout(()=>xu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});gu.displayName=mu;var Av={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function jv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function _v(e,t,n){const r=jv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Av[r]}function xu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Mv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Pv=pu,Rv=gu,Ov=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},vr=new WeakMap,Zo=new WeakMap,Qo={},Bi=0,yu=function(e){return e&&(e.host||yu(e.parentNode))},Dv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=yu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Lv=function(e,t,n,r){var o=Dv(t,Array.isArray(e)?e:[e]);Qo[n]||(Qo[n]=new WeakMap);var s=Qo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),y=p!==null&&p!=="false",m=(vr.get(h)||0)+1,x=(s.get(h)||0)+1;vr.set(h,m),s.set(h,x),i.push(h),m===1&&y&&Zo.set(h,!0),x===1&&h.setAttribute(n,"true"),y||h.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",h,g)}})};return d(t),a.clear(),Bi++,function(){i.forEach(function(f){var h=vr.get(f)-1,p=s.get(f)-1;vr.set(f,h),s.set(f,p),h||(Zo.has(f)||f.removeAttribute(r),Zo.delete(f)),p||f.removeAttribute(n)}),Bi--,Bi||(vr=new WeakMap,vr=new WeakMap,Zo=new WeakMap,Qo={})}},zi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Ov(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Lv(r,o,n,"aria-hidden")):function(){return null}},mn=function(){return mn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},mn.apply(this,arguments)};function vu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function $v(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var es="right-scroll-bar-position",ts="width-before-scroll-bar",Fv="with-scroll-bars-hidden",Bv="--removed-body-scroll-bar-size";function Ui(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function zv(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Uv=typeof window<"u"?v.useLayoutEffect:v.useEffect,wu=new WeakMap;function Hv(e,t){var n=zv(null,function(r){return e.forEach(function(o){return Ui(o,r)})});return Uv(function(){var r=wu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Ui(a,null)}),s.forEach(function(a){o.has(a)||Ui(a,i)})}wu.set(n,e)},[e]),n}function Wv(e){return e}function Vv(e,t){t===void 0&&(t=Wv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Kv(e){e===void 0&&(e={});var t=Vv(null);return t.options=mn({async:!0,ssr:!1},e),t}var bu=function(e){var t=e.sideCar,n=vu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,mn({},n))};bu.isSideCarExport=!0;function qv(e,t){return e.useMedium(t),bu}var Su=Kv(),Hi=function(){},ns=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:Hi,onWheelCapture:Hi,onTouchMoveCapture:Hi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,y=e.noIsolation,m=e.inert,x=e.allowPinchZoom,g=e.as,w=g===void 0?"div":g,S=e.gapMode,k=vu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=h,T=Hv([n,t]),I=mn(mn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(C,{sideCar:Su,removeScrollBar:c,shards:f,noRelative:p,noIsolation:y,inert:m,setCallbacks:s,allowPinchZoom:!!x,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),mn(mn({},I),{ref:T})):v.createElement(w,mn({},I,{className:l,ref:T}),a))});ns.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ns.classNames={fullWidth:ts,zeroRight:es};var Gv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Yv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Gv();return t&&e.setAttribute("nonce",t),e}function Xv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Jv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Zv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Yv())&&(Xv(t,n),Jv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Qv=function(){var e=Zv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Cu=function(){var e=Qv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},ew={left:0,top:0,right:0,gap:0},Wi=function(e){return parseInt(e||"",10)||0},tw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Wi(n),Wi(r),Wi(o)]},nw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return ew;var t=tw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},rw=Cu(),wr="data-scroll-locked",ow=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
39
- .`.concat(Fv,` {
37
+ `))>=0;){const H=ut.slice(0,X);ut=ut.slice(X+2);const re=Xx(H);if(!re)continue;let Ee;try{Ee=JSON.parse(re)}catch{console.debug("[use-chat] malformed SSE:",re.slice(0,200));continue}const we=Yx(Ee)?Ee.data:Ee;nn=Date.now();const Qe=we.seq;if(Qe!==void 0){if(Qe<=pt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Qe,lastProcessedSeq:pt,type:we.type});continue}pt>0&&Qe>pt+1&&((O=N==null?void 0:N.onGap)==null||O.call(N,{from:pt,to:Qe})),pt=Qe,T.current=Qe,y(Qe)}if(we.type==="checkpoint")I.current=we.checkpointId??null,A.current=we.checkpointNs??null,v(we.checkpointId??null);else if(we.type==="state_history"){R.current=we;try{const ht=mr(we).latest;ht&&(I.current=ht.checkpointId??null,A.current=ht.checkpointNs??null,v(ht.checkpointId??null))}catch(Pe){console.warn("[use-chat] Failed to hydrate state_history payload",Pe)}}try{j==null||j(we)}catch(Pe){console.error("[use-chat] Error in onEvent callback:",Pe,"for event:",we.type)}if(we.type==="message.delta"){const Pe=we.delta.filter(ht=>ht.type==="text").map(ht=>ht.text).join("");Pe&&e.autoAppendAssistant!==!1&&(yt.push(Pe),Wt())}else if(we.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(K=N==null?void 0:N.onHeartbeat)==null||K.call(N,we)}catch(Pe){console.warn("[use-chat] heartbeat callback failed",Pe)}}else if(wt!==null&&cancelAnimationFrame(wt),Mt(),we.type==="checkpoint")v(we.checkpointId);else if(we.type==="error"){const Pe=we;if(d(Pe.message),L="error",P=Pe.message,Pe.error_type==="auth_error"||Pe.code==="TOKEN_EXPIRED"||((B=Pe.message)==null?void 0:B.includes("token"))||((te=Pe.message)==null?void 0:te.includes("401"))||((Z=Pe.message)==null?void 0:Z.includes("unauthorized"))||((ye=Pe.message)==null?void 0:ye.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Pe.message);try{(fe=N==null?void 0:N.onAuthError)==null||fe.call(N,Pe.message)}catch(Cn){console.warn("[use-chat] onAuthError handler failed",Cn)}z.abort()}}}}Mt(),L===null&&!z.signal.aborted&&(L="complete")}catch(nt){if(nt.name==="AbortError")L=L??"aborted";else{const Ge=nt.message||String(nt);L="error",P=Ge,d(Ge),(oe=N==null?void 0:N.onError)==null||oe.call(N,Ge)}}finally{try{await tt.cancel()}catch{}finally{(xe=tt.releaseLock)==null||xe.call(tt)}wt!==null&&typeof window<"u"&&window.cancelAnimationFrame(wt),clearInterval(Ve)}}catch(Ue){if(Ue.name==="AbortError")L=L??"aborted";else{const U=Ue.message||String(Ue);L="error",P=U,d(U),(Se=N==null?void 0:N.onError)==null||Se.call(N,U),V||(($e=N==null?void 0:N.onConnectionError)==null||$e.call(N,U),V=!0)}}finally{const Ue=T.current,U=I.current,le=A.current,ke=R.current,Ke=L??(z.signal.aborted?"aborted":P?"error":"complete");try{(_e=N==null?void 0:N.onClosed)==null||_e.call(N,{reason:Ke,lastSeq:Ue,lastCheckpointId:U,lastCheckpointNs:le,lastStateHistory:ke,error:P})}catch(tt){console.warn("[use-chat] onClosed callback failed",tt)}l(!1),b(!1),C.current=null,T.current=0,y(0),S.current=null}})(),{close:()=>z.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var _;k.current=!1,(_=C.current)==null||_.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:h,lastSeq:g,connected:x,stream:W,stop:q,clear:F,setToken:D}}function Yx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Xx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
38
+ `)}const Jx=["message.start","message.delta","message.end"],Zx=["tool.start","tool.end","tool.progress"],Qx=["thread_info","checkpoint"],ey=["error","interrupt","heartbeat","state_history","cancelled"],ty=[...Jx,...Zx,...Qx,...ey],ny=new Set(ty);function ry(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return ny.has(t)}const Ac=200;function oy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=w.useRef(null),f=w.useRef(null),p=w.useRef(new Map),h=w.useRef(null),v=w.useRef(null),g=w.useCallback(j=>{try{const N=globalThis.structuredClone;if(typeof N=="function")return N(j)}catch{}try{return JSON.parse(JSON.stringify(j))}catch{return j}},[]),y=w.useCallback((j,N)=>{if(!j)return;const z=p.current.get(j)??[],L=g(N),P=z.length>=Ac?[...z.slice(z.length-Ac+1),L]:[...z,L];p.current.set(j,P)},[g]),x=w.useCallback(j=>{j&&p.current.set(j,[])},[]),b=w.useCallback(j=>{const N=j??f.current;if(!N)return;const z=p.current.get(N);z!=null&&z.length&&z.forEach(L=>{try{n(L)}catch(P){console.error("[useChatStreamingService] Failed to replay buffered event",P)}})},[n]),C=w.useCallback(j=>{f.current=j.threadId,h.current&&(h.current.threadIdGuess=j.threadId),v.current=j,x(j.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",j);try{t(j)}catch(N){console.error("[useChatStreamingService] Error in onThreadInfo handler:",N)}},[x,t]),k=w.useCallback(j=>{try{c==null||c(j)}catch(N){console.error("[useChatStreamingService] Error in onHeartbeat handler:",N)}},[c]),T=w.useCallback(j=>{var L,P,V,ne;const N=j;if(N.error_type==="auth_error"||N.code==="TOKEN_EXPIRED"||((L=N.message)==null?void 0:L.includes("token"))||((P=N.message)==null?void 0:P.includes("401"))||((V=N.message)==null?void 0:V.includes("unauthorized"))||((ne=N.message)==null?void 0:ne.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",N.message);try{l==null||l(N.message)}catch(M){console.warn("[useChatStreamingService] onAuthError handler failed",M)}}},[l]),S=w.useMemo(()=>({thread_info:j=>(C(j),!0),heartbeat:j=>(k(j),!0),error:j=>(T(j),!1)}),[C,k,T]),I=w.useCallback(j=>{var P;const N=j.seq??null;if(N!==null){const V=d.current;if(V!==null){if(N<=V)return;N>V+1&&(s==null||s({from:V,to:N}))}d.current=N}const z=S[j.type];if(z&&z(j))return;const L=j.threadId??(j.type==="state_history"?j.threadId:void 0)??f.current??((P=h.current)==null?void 0:P.threadIdGuess)??null;if(j.type==="state_history"){f.current=L??f.current;try{r==null||r(j)}catch(V){console.error("[useChatStreamingService] onStateHistory handler failed",V)}}if(ry(j)){j.type==="checkpoint"||j.type==="state_history"?x(L??null):y(L??null,j);try{n(j)}catch(V){console.error("[useChatStreamingService] Error in onMessageEvent handler:",V)}return}try{o==null||o(j)}catch(V){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",V)}},[y,x,n,s,r,o,S]),{stream:A,stop:R,isStreaming:D,error:F,setToken:q}=Nc({baseUrl:e,token:void 0}),W=w.useCallback((j,N)=>{d.current=null,v.current=null,f.current=j.threadId??null,h.current={request:j,callbacks:N,manualStop:!1,threadIdGuess:j.threadId??null},A(j,I,{onOpen:N==null?void 0:N.onOpen,onError:z=>{var L;(L=N==null?void 0:N.onError)==null||L.call(N,z)},onGap:(N==null?void 0:N.onGap)??s,onConnectionError:z=>{var L;a==null||a(z),(L=N==null?void 0:N.onConnectionError)==null||L.call(N,z)},onAuthError:z=>{var L;l==null||l(z),(L=N==null?void 0:N.onAuthError)==null||L.call(N,z)},onHeartbeat:z=>{var L;try{c==null||c(z)}catch(P){console.warn("[useChatStreamingService] onHeartbeat handler failed",P)}try{(L=N==null?void 0:N.onHeartbeat)==null||L.call(N,z)}catch(P){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",P)}},onClosed:z=>{var ne,M,Y,ae;const L=((ne=h.current)==null?void 0:ne.manualStop)??!1,P=f.current??((M=h.current)==null?void 0:M.threadIdGuess)??((Y=z.lastStateHistory)==null?void 0:Y.threadId)??null;(z.reason==="complete"||z.reason==="aborted"&&L)&&x(P);const V={...z,threadId:P,threadInfo:v.current,manualStop:L};try{i==null||i(V)}catch(Q){console.warn("[useChatStreamingService] onStreamClosed handler failed",Q)}try{(ae=N==null?void 0:N.onClosed)==null||ae.call(N,V)}catch(Q){console.warn("[useChatStreamingService] downstream onClosed handler failed",Q)}h.current&&(h.current=null)}})},[x,I,l,a,c,s,i,A]),_=w.useCallback(()=>{h.current&&(h.current.manualStop=!0),R()},[R]);return w.useMemo(()=>({startStream:W,stop:_,isStreaming:D,error:F,setAuthToken:q,replayBufferedEvents:b}),[W,_,D,F,q,b])}function sy({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:l=!0,isStreaming:c,getMessages:d}){const[f,p]=w.useState([]),[h,v]=w.useState([]),[g,y]=w.useState(!1),[x,b]=w.useState(null),[C,k]=w.useState(!1),[T,S]=w.useState(!1),[I,A]=w.useState(!1),[R,D]=w.useState(null),F=w.useRef(o),q=w.useRef(null),W=w.useRef(null),_=w.useRef(null),j=w.useRef(null),N=w.useRef(!1),z=w.useRef(null),L=w.useRef(new Map);w.useEffect(()=>{F.current=o},[o]);const P=w.useCallback(async B=>{var Z,ye;if(!B.threadId)return;const te=B.threadId;(Z=B.onStart)==null||Z.call(B),B.setLoading(!0);try{await B.action(te)}catch(fe){if(F.current===te){const oe=String(fe);(ye=B.handleError)==null||ye.call(B,oe),r==null||r(oe)}throw fe}finally{B.setLoading(!1)}},[r]),V=w.useCallback(async(B,te)=>{if(!B)return;const Z=`${B}:${te??"latest"}`,ye=L.current.get(Z);if(ye)return ye;const fe=P({threadId:B,setLoading:k,onStart:()=>D(null),handleError:oe=>D(oe),action:async oe=>{const xe=await e.getStateHistory({threadId:oe,checkpointId:te??void 0});if(F.current!==oe){console.log(`[useThreadHistoryState] Thread changed during load (was ${oe}, now ${F.current}), discarding stale data`);return}const{checkpoints:Se,timeline:$e}=mr(xe),_e=Se.find(Ue=>Ue.messages&&Ue.messages.length>0)??(te?Se.find(Ue=>Ue.checkpointId===te):null)??Se[0];t((_e==null?void 0:_e.messages)??[],{checkpointId:(_e==null?void 0:_e.checkpointId)??null,checkpointNs:(_e==null?void 0:_e.checkpointNs)??null}),v($e),p(Se),y(!!(_e!=null&&_e.nextCursor)),b((_e==null?void 0:_e.nextCursor)??null)}});L.current.set(Z,fe);try{await fe}finally{L.current.delete(Z)}return F.current===B&&(z.current=Z),fe},[e,t,P]),ne=w.useCallback(async(B,te,Z)=>{Z!=null&&Z.clearProgress&&xc(),j.current=B;try{await V(B,te)}finally{j.current===B&&(j.current=null)}},[V]),M=w.useCallback(B=>{W.current=B},[]),Y=w.useCallback(B=>{_.current=B},[]),ae=w.useCallback(B=>{const te=B.threadId??F.current;if(!te||F.current&&F.current!==te)return;const{checkpoints:Z,timeline:ye}=mr(B);if(!Z.length)return;const fe=Z.find(oe=>oe.messages&&oe.messages.length>0)??Z.find(oe=>!!oe.checkpointId)??Z[0];t((fe==null?void 0:fe.messages)??[],{checkpointId:(fe==null?void 0:fe.checkpointId)??null,checkpointNs:(fe==null?void 0:fe.checkpointNs)??null}),v(ye),p(Z),y(!!(fe!=null&&fe.nextCursor)),b((fe==null?void 0:fe.nextCursor)??null),z.current=`${te}:latest`,W.current=null,_.current=null},[t]),Q=w.useCallback(async(B,te)=>{xc();const Z=F.current;await P({threadId:Z,setLoading:A,action:async ye=>{const fe=await e.getStateHistory({threadId:ye,checkpointId:B,checkpointNs:te??void 0});if(F.current!==ye){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${ye}, now ${F.current}), discarding stale data`);return}const{checkpoints:oe,timeline:xe}=mr(fe),Se=oe.find($e=>$e.checkpointId===B&&(te?$e.checkpointNs===te:!0));if(!Se){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:B,checkpointNs:te});return}v(xe),p(oe),t(Se.messages??[],{checkpointId:Se.checkpointId??null,checkpointNs:Se.checkpointNs??null})}}).catch(()=>{})},[e,t,P]),ce=w.useCallback((B,te)=>{t(d(),{checkpointId:B??null,checkpointNs:te??null})},[d,t]),G=w.useCallback(async()=>{F.current&&await ne(F.current)},[ne]),O=w.useCallback(async()=>{const B=F.current;!B||!x||await P({threadId:B,setLoading:S,action:async te=>{const Z=await e.getStateHistory({threadId:te,checkpointId:x});if(F.current!==te)return;const{checkpoints:ye}=mr(Z);if(ye.length>0){const fe=ye[ye.length-1];n((fe==null?void 0:fe.messages)??[]),y(!!(fe!=null&&fe.nextCursor)),b((fe==null?void 0:fe.nextCursor)??null)}}}).catch(()=>{})},[e,x,r,n,P]);w.useEffect(()=>{if(!l||!o||C||c)return;if(W.current===o){W.current=null,q.current=o;return}if(_.current===o){q.current=o;return}if(j.current===o){j.current=null,q.current=o;return}if(q.current===o)return;q.current=o;const B=!N.current&&!!i&&o===s;let te;B&&i?(te=i,N.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",te,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const Z=`${o}:${te??"latest"}`;z.current!==Z&&ne(o,te)},[l,o,i,a,s,C,c,ne]);const K=w.useCallback(()=>{p([]),v([]),y(!1),b(null),k(!1),S(!1),A(!1),D(null),W.current=null,_.current=null,q.current=null,z.current=null,j.current=null},[]);return{threadCheckpoints:f,threadTimeline:h,isLoadingThread:C,isHistoryLoading:T,isLoadingCheckpoint:I,threadStateError:R,hasMoreHistory:g,loadThread:ne,navigateToCheckpoint:Q,loadOlderMessages:O,setCurrentCheckpointId:ce,returnToLatest:G,handleStateHistoryEvent:ae,markSkipNextLoad:M,markStreamPendingThread:Y,resetHistoryState:K}}const jc=w.createContext(null),_c=w.createContext(null),Mc=w.createContext(null);w.createContext(!1);function iy({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l}){const{api:c,baseUrl:d}=Si(),f=w.useMemo(()=>Tn(d),[d]),[p,h]=w.useState([]),[v,g]=w.useState(t),[y,x]=w.useState(!1),[b,C]=w.useState(null),[k,T]=w.useState([]),[S,I]=w.useState(!1),[,A]=w.useState(null),[R,D]=w.useState([]),[F,q]=w.useState(!1),[,W]=w.useState(null),{state:_,seed:j,prepend:N,pushUser:z,onEvent:L}=Ic(),[P,V]=w.useState(!1),ne=w.useCallback(()=>_.messages,[_.messages]),{threadCheckpoints:M,threadTimeline:Y,isLoadingThread:ae,isHistoryLoading:Q,isLoadingCheckpoint:ce,threadStateError:G,hasMoreHistory:O,loadThread:K,navigateToCheckpoint:B,loadOlderMessages:te,setCurrentCheckpointId:Z,returnToLatest:ye,handleStateHistoryEvent:fe,markSkipNextLoad:oe,markStreamPendingThread:xe,resetHistoryState:Se}=sy({api:c,seed:j,prepend:N,onError:s,currentThreadId:v,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:P,getMessages:ne}),$e=w.useMemo(()=>lx(M),[M]),_e=w.useRef(v),Ue=w.useRef(new Map);w.useEffect(()=>{_e.current=v},[v]);const U=w.useCallback(async()=>{x(!0),C(null);try{const H=await c.listThreads();h(H??[])}catch(H){const re=String(H);C(re),s==null||s(re)}finally{x(!1)}},[c,s]),le=w.useCallback(async()=>{I(!0),A(null);try{const H=await c.listSharedThreads();T(H??[])}catch(H){const re=String(H);A(re),s==null||s(re)}finally{I(!1)}},[c,s]),ke=w.useCallback(async()=>{q(!0),W(null);try{const H=await c.listSmartOrgUsers();D(H??[])}catch(H){const re=String(H);W(re),s==null||s(re)}finally{q(!1)}},[c,s]),Ke=w.useCallback(H=>{if(!(H!=null&&H.threadId))return;const re={threadId:H.threadId,title:H.title||`Thread ${H.threadId.slice(0,8)}`,createdAt:H.createdAt||new Date().toISOString(),updatedAt:H.updatedAt||new Date().toISOString(),messageCount:H.messageCount??1};h(Ee=>{let we=!1;const Qe=Ee.map(Pe=>Pe.threadId===re.threadId?(we=!0,console.debug("[ChatSessionProvider] thread_info: updating existing thread",re.threadId),{...Pe,title:re.title??Pe.title,updatedAt:re.updatedAt??Pe.updatedAt,messageCount:re.messageCount??Pe.messageCount}):Pe);return we?Qe:(console.debug("[ChatSessionProvider] thread_info: adding thread to list",re.threadId),[re,...Ee])})},[]),tt=w.useCallback(H=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",H.threadId),Ke(H),_e.current!==H.threadId&&((H.created??!_e.current)&&oe(H.threadId),xe(H.threadId),console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),g(H.threadId))},[Ke,oe,xe]),{startStream:St,stop:ut,isStreaming:yt,error:pt,setAuthToken:wt}=oy({baseUrl:f,onThreadInfo:tt,onMessageEvent:L,onStateHistory:fe,onUnhandledEvent:H=>{console.warn("[ChatSessionProvider] Unhandled event:",H.type)},onAuthError:i,onConnectionError:l});w.useEffect(()=>{V(yt)},[yt]);const Mt=w.useCallback(async H=>{try{const re=await c.createThread(H);return g(re.threadId),await U(),re.threadId}catch(re){return s==null||s(String(re)),null}},[c,U,s]),Wt=w.useCallback(async H=>{const re=p;h(we=>we.filter(Qe=>Qe.threadId!==H));const Ee=new AbortController;Ue.current.set(H,Ee);try{await c.deleteThread(H),_e.current===H&&(g(null),j([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",H)}catch(we){console.error("[ChatSessionProvider] Delete failed, restoring thread:",H,we),h(re),s==null||s(`Failed to delete thread: ${String(we)}`)}finally{Ue.current.delete(H)}},[p,c,j,s]),nn=w.useCallback(async(H,re)=>{try{await c.updateThread(H,re),await U()}catch(Ee){s==null||s(String(Ee))}},[c,U,s]),Ve=w.useCallback(async(H,re)=>{try{await c.shareThread(H,re),await le()}catch(Ee){const we=String(Ee);throw s==null||s(we),Ee}},[c,s,le]),Sn=w.useCallback(async(H,re)=>{try{await c.unshareThread(H,re),await le()}catch(Ee){const we=String(Ee);throw s==null||s(we),Ee}},[c,s,le]),nt=w.useCallback(async()=>{j([],{}),g(null),ut(),Se();try{await c.getAgent("default")}catch(H){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",H)}},[j,ut,c,Se]),Ge=w.useCallback(async(H,re,Ee)=>{const we=_e.current;if(!we)throw new Error("No active thread to handle interrupt");const Qe=re?Ee??!0:!1;try{const Pe={threadId:we,checkpointId:_.lastCheckpointId??void 0,checkpointNs:_.lastCheckpointNs??void 0,command:{kind:"resume",value:Qe}};St(Pe)}catch(Pe){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${H}:`,Pe),Pe}},[_.lastCheckpointId,_.lastCheckpointNs,St]);w.useEffect(()=>{U(),ke()},[U,ke]),w.useEffect(()=>{le()},[le]),w.useEffect(()=>{a==null||a(v)},[v,a]);const dt=w.useCallback(async(H,re)=>{let Ee=_e.current;const we=(H==null?void 0:H.text)??"",Qe=(H==null?void 0:H.attachments)??[],Pe=(we==null?void 0:we.trim())??"",ht={...(H==null?void 0:H.payload)??{}},Cn=Array.isArray(ht.messages)?ht.messages:void 0;Cn&&delete ht.messages;const An=!!(Cn&&Cn.length);if(!Ee&&!Pe&&Qe.length===0&&!An)return;if(!Ee){const Ze=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Be=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);Ee=`${Ze}${Be}`,oe(Ee),g(Ee)}const{contentParts:Or,filesInfo:Dr}=await sx(c,Qe),ur=[...Or];Pe&&ur.push({type:"text",text:we});const Lr=re==null?void 0:re.originalMessageId,dr=!!(re!=null&&re.edit&&Lr),E=!An&&ur.length>0;let J=null;E&&(J={id:dr?Lr:`msg-${Date.now()}`,role:"user",content:ur,createdAt:new Date().toISOString()},dr||z(J));const de=An?Cn:J?[J]:[],Ce={...ht,...Dr.length?{files_info:Dr}:{}};de.length?Ce.messages=de:"messages"in Ce||(Ce.messages=[]);const qe={threadId:Ee,payload:Ce,checkpointId:(re==null?void 0:re.checkpointId)??_.lastCheckpointId??void 0,checkpointNs:(re==null?void 0:re.checkpointNs)??_.lastCheckpointNs??void 0,edit:!!(re!=null&&re.edit),timelineCheckpoints:Y};St(qe)},[c,z,_,St,Y]),Rt=w.useMemo(()=>({threads:p,currentThreadId:v,setCurrentThreadId:g,isLoading:y,error:b,sharedThreads:k,isLoadingSharedThreads:S,smartOrgUsers:R,isLoadingSmartOrgUsers:F,actions:{createThread:Mt,deleteThread:Wt,renameThread:nn,refreshThreads:U,refreshSharedThreads:le,refreshSmartOrgUsers:ke,shareThread:Ve,unshareThread:Sn}}),[p,v,y,b,k,S,R,F,Mt,Wt,nn,U,le,ke,Ve,Sn]),Je=w.useMemo(()=>{const H=_.assemblingId??null;return H?{assemblingMessageId:H}:null},[_.assemblingId]),Pt=w.useMemo(()=>({threadId:v,messages:_.messages,interrupt:null,checkpoint:{id:_.lastCheckpointId??null,namespace:_.lastCheckpointNs??null},checkpoints:M,timelineCheckpoints:Y,metadata:Je,isLoading:ae,isHistoryLoading:Q,isLoadingCheckpoint:ce,error:G,hasMore:O,loadOlder:te,clearState:nt,navigateToCheckpoint:B,setCurrentCheckpointId:Z,returnToLatest:ye,loadThread:K,clearThread:nt,respondToInterrupt:Ge,messagePreviews:$e}),[v,_,M,Y,ae,Q,ce,G,O,te,nt,B,Z,ye,K,Ge,$e,Je]),X=w.useMemo(()=>({isStreaming:yt,error:pt,connectionState:yt?"connected":"idle",submit:dt,send:dt,stop:ut,setAuthToken:wt}),[yt,pt,dt,ut,wt]);return u.jsx(jc.Provider,{value:Rt,children:u.jsx(_c.Provider,{value:Pt,children:u.jsx(Mc.Provider,{value:X,children:e})})})}function Ho(){const e=w.useContext(jc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Wo(){const e=w.useContext(_c);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Rc(){const e=w.useContext(Mc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Vo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(rx,{apiConfig:t,children:u.jsx(iy,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function se(...e){return jm.twMerge(Am.clsx(e))}const ay=ko.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),rt=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Kn.Slot:"button";return u.jsx(i,{className:se(ay({variant:t,size:n,className:e})),ref:s,...o})});rt.displayName="Button";const Pc=m.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:se("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Pc.displayName="Textarea";function Oc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const v=i!==void 0,[g,y]=w.useState(e),x=(v?i:g)??"",[b,C]=w.useTransition(),k=w.useRef(null),T=w.useRef(0),S=w.useRef(null);w.useEffect(()=>{v||(y(e??""),S.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,v]);const I=w.useCallback(()=>{const j=k.current;j&&(j.style.height="auto",j.style.height=`${j.scrollHeight}px`)},[]);w.useEffect(()=>{I()},[I,x]);const A=w.useCallback((j,{fromUser:N})=>{v||y(j),N&&(a==null||a(j))},[v,a]),R=w.useCallback(async j=>{j&&j.preventDefault();const N=(x??"").trim();if(!N&&!h)return;const z=++T.current;S.current={id:z,shouldClear:!0},C(()=>{var L,P,V;try{const ne=l(N);ne&&typeof ne.then=="function"?ne.then(()=>{var M,Y;((M=S.current)==null?void 0:M.id)===z&&S.current.shouldClear&&(v||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((Y=S.current)==null?void 0:Y.id)===z&&(S.current=null)}).catch(()=>{var M;((M=S.current)==null?void 0:M.id)===z&&(S.current=null)}):(((L=S.current)==null?void 0:L.id)===z&&S.current.shouldClear&&(v||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((P=S.current)==null?void 0:P.id)===z&&(S.current=null))}catch{((V=S.current)==null?void 0:V.id)===z&&(S.current=null)}})},[x,l,h,v,a]),D=w.useCallback(j=>{const N=j.target.value;A(N,{fromUser:!0}),S.current&&(S.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[A]),F=w.useCallback(j=>{j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),R()):j.key==="Escape"&&t&&(j.preventDefault(),c==null||c())},[R,t,c]),_=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${p}`;return u.jsx("form",{onSubmit:j=>void R(j),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Pc,{ref:k,value:x,onChange:D,onKeyDown:F,placeholder:t?"Edit your message...":n,className:_,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(rt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ue.Square,{size:16})}):u.jsx(rt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!h||b,children:u.jsx(ue.Send,{size:16})})})]})})}const ly=w.memo(Oc);function me(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Dc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _n(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Dc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Dc(e[o],null)}}}}function He(...e){return m.useCallback(_n(...e),e)}function cy(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=m.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function kn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:p,children:h,...v}=f,g=((x=p==null?void 0:p[e])==null?void 0:x[l])||a,y=m.useMemo(()=>v,Object.values(v));return u.jsx(g.Provider,{value:y,children:h})};c.displayName=s+"Provider";function d(f,p){var g;const h=((g=p==null?void 0:p[e])==null?void 0:g[l])||a,v=m.useContext(h);if(v)return v;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>m.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return m.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,uy(o,...t)]}function uy(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Tt=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},dy=m[" useInsertionEffect ".trim().toString()]||Tt;function xr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=fy({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=m.useRef(e!==void 0);m.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=m.useCallback(d=>{var f;if(a){const p=py(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function fy({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return dy(()=>{s.current=t},[t]),m.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function py(e){return typeof e=="function"}var hy=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ie=hy.reduce((e,t)=>{const n=Kn.createSlot(`Primitive.${t}`),r=m.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Lc(e,t){e&&Io.flushSync(()=>e.dispatchEvent(t))}function Ei(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:y,children:x}=g,b=w.useRef(null),C=w.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:C,collectionRef:b,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=Kn.createSlot(a),c=w.forwardRef((g,y)=>{const{scope:x,children:b}=g,C=s(a,x),k=He(y,C.collectionRef);return u.jsx(l,{ref:k,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=Kn.createSlot(d),h=w.forwardRef((g,y)=>{const{scope:x,children:b,...C}=g,k=w.useRef(null),T=He(y,k),S=s(d,x);return w.useEffect(()=>(S.itemMap.set(k,{ref:k,...C}),()=>void S.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:T,children:b})});h.displayName=d;function v(g){const y=s(e+"CollectionConsumer",g);return w.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const C=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((S,I)=>C.indexOf(S.ref.current)-C.indexOf(I.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},v,r]}var my=m.createContext(void 0);function Ko(e){const t=m.useContext(my);return e||t||"ltr"}function kt(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function gy(e,t=globalThis==null?void 0:globalThis.document){const n=kt(e);m.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var xy="DismissableLayer",Ni="dismissableLayer.update",yy="dismissableLayer.pointerDownOutside",vy="dismissableLayer.focusOutside",$c,Fc=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),qo=m.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=m.useContext(Fc),[d,f]=m.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=m.useState({}),v=He(t,I=>f(I)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(y),b=d?g.indexOf(d):-1,C=c.layersWithOutsidePointerEventsDisabled.size>0,k=b>=x,T=Sy(I=>{const A=I.target,R=[...c.branches].some(D=>D.contains(A));!k||R||(o==null||o(I),i==null||i(I),I.defaultPrevented||a==null||a())},p),S=Cy(I=>{const A=I.target;[...c.branches].some(D=>D.contains(A))||(s==null||s(I),i==null||i(I),I.defaultPrevented||a==null||a())},p);return gy(I=>{b===c.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},p),m.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&($c=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),Bc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=$c)}},[d,p,n,c]),m.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),Bc())},[d,c]),m.useEffect(()=>{const I=()=>h({});return document.addEventListener(Ni,I),()=>document.removeEventListener(Ni,I)},[]),u.jsx(Ie.div,{...l,ref:v,style:{pointerEvents:C?k?"auto":"none":void 0,...e.style},onFocusCapture:me(e.onFocusCapture,S.onFocusCapture),onBlurCapture:me(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:me(e.onPointerDownCapture,T.onPointerDownCapture)})});qo.displayName=xy;var by="DismissableLayerBranch",wy=m.forwardRef((e,t)=>{const n=m.useContext(Fc),r=m.useRef(null),o=He(t,r);return m.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ie.div,{...e,ref:o})});wy.displayName=by;function Sy(e,t=globalThis==null?void 0:globalThis.document){const n=kt(e),r=m.useRef(!1),o=m.useRef(()=>{});return m.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){zc(yy,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Cy(e,t=globalThis==null?void 0:globalThis.document){const n=kt(e),r=m.useRef(!1);return m.useEffect(()=>{const o=s=>{s.target&&!r.current&&zc(vy,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Bc(){const e=new CustomEvent(Ni);document.dispatchEvent(e)}function zc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Lc(o,s):o.dispatchEvent(s)}var Ai=0;function ji(){m.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Uc()),document.body.insertAdjacentElement("beforeend",e[1]??Uc()),Ai++,()=>{Ai===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ai--}},[])}function Uc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var _i="focusScope.autoFocusOnMount",Mi="focusScope.autoFocusOnUnmount",Hc={bubbles:!1,cancelable:!0},Ty="FocusScope",Go=m.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=m.useState(null),c=kt(o),d=kt(s),f=m.useRef(null),p=He(t,g=>l(g)),h=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let g=function(C){if(h.paused||!a)return;const k=C.target;a.contains(k)?f.current=k:Mn(f.current,{select:!0})},y=function(C){if(h.paused||!a)return;const k=C.relatedTarget;k!==null&&(a.contains(k)||Mn(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const T of C)T.removedNodes.length>0&&Mn(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const b=new MutationObserver(x);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),b.disconnect()}}},[r,a,h.paused]),m.useEffect(()=>{if(a){Kc.add(h);const g=document.activeElement;if(!a.contains(g)){const x=new CustomEvent(_i,Hc);a.addEventListener(_i,c),a.dispatchEvent(x),x.defaultPrevented||(ky(jy(Wc(a)),{select:!0}),document.activeElement===g&&Mn(a))}return()=>{a.removeEventListener(_i,c),setTimeout(()=>{const x=new CustomEvent(Mi,Hc);a.addEventListener(Mi,d),a.dispatchEvent(x),x.defaultPrevented||Mn(g??document.body,{select:!0}),a.removeEventListener(Mi,d),Kc.remove(h)},0)}}},[a,c,d,h]);const v=m.useCallback(g=>{if(!n&&!r||h.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(y&&x){const b=g.currentTarget,[C,k]=Iy(b);C&&k?!g.shiftKey&&x===k?(g.preventDefault(),n&&Mn(C,{select:!0})):g.shiftKey&&x===C&&(g.preventDefault(),n&&Mn(k,{select:!0})):x===b&&g.preventDefault()}},[n,r,h.paused]);return u.jsx(Ie.div,{tabIndex:-1,...i,ref:p,onKeyDown:v})});Go.displayName=Ty;function ky(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Mn(r,{select:t}),document.activeElement!==n)return}function Iy(e){const t=Wc(e),n=Vc(t,e),r=Vc(t.reverse(),e);return[n,r]}function Wc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Vc(e,t){for(const n of e)if(!Ey(n,{upTo:t}))return n}function Ey(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Ny(e){return e instanceof HTMLInputElement&&"select"in e}function Mn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Ny(e)&&t&&e.select()}}var Kc=Ay();function Ay(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=qc(e,t),e.unshift(t)},remove(t){var n;e=qc(e,t),(n=e[0])==null||n.resume()}}}function qc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function jy(e){return e.filter(t=>t.tagName!=="A")}var _y=m[" useId ".trim().toString()]||(()=>{}),My=0;function Dt(e){const[t,n]=m.useState(_y());return Tt(()=>{n(r=>r??String(My++))},[e]),t?`radix-${t}`:""}const Ry=["top","right","bottom","left"],Rn=Math.min,Vt=Math.max,Yo=Math.round,Xo=Math.floor,pn=e=>({x:e,y:e}),Py={left:"right",right:"left",bottom:"top",top:"bottom"},Oy={start:"end",end:"start"};function Ri(e,t,n){return Vt(e,Rn(t,n))}function In(e,t){return typeof e=="function"?e(t):e}function En(e){return e.split("-")[0]}function yr(e){return e.split("-")[1]}function Pi(e){return e==="x"?"y":"x"}function Oi(e){return e==="y"?"height":"width"}const Dy=new Set(["top","bottom"]);function hn(e){return Dy.has(En(e))?"y":"x"}function Di(e){return Pi(hn(e))}function Ly(e,t,n){n===void 0&&(n=!1);const r=yr(e),o=Di(e),s=Oi(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Jo(i)),[i,Jo(i)]}function $y(e){const t=Jo(e);return[Li(e),t,Li(t)]}function Li(e){return e.replace(/start|end/g,t=>Oy[t])}const Gc=["left","right"],Yc=["right","left"],Fy=["top","bottom"],By=["bottom","top"];function zy(e,t,n){switch(e){case"top":case"bottom":return n?t?Yc:Gc:t?Gc:Yc;case"left":case"right":return t?Fy:By;default:return[]}}function Uy(e,t,n,r){const o=yr(e);let s=zy(En(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Li)))),s}function Jo(e){return e.replace(/left|right|bottom|top/g,t=>Py[t])}function Hy(e){return{top:0,right:0,bottom:0,left:0,...e}}function Xc(e){return typeof e!="number"?Hy(e):{top:e,right:e,bottom:e,left:e}}function Zo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Jc(e,t,n){let{reference:r,floating:o}=e;const s=hn(t),i=Di(t),a=Oi(i),l=En(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(yr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const Wy=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Jc(c,r,l),p=r,h={},v=0;for(let g=0;g<a.length;g++){const{name:y,fn:x}=a[g],{x:b,y:C,data:k,reset:T}=await x({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=C??f,h={...h,[y]:{...h[y],...k}},T&&v<=50&&(v++,typeof T=="object"&&(T.placement&&(p=T.placement),T.rects&&(c=T.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):T.rects),{x:d,y:f}=Jc(c,p,l)),g=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function Kr(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=In(t,e),v=Xc(h),y=a[p?f==="floating"?"reference":"floating":f],x=Zo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),b=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,C=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(C))?await(s.getScale==null?void 0:s.getScale(C))||{x:1,y:1}:{x:1,y:1},T=Zo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:C,strategy:l}):b);return{top:(x.top-T.top+v.top)/k.y,bottom:(T.bottom-x.bottom+v.bottom)/k.y,left:(x.left-T.left+v.left)/k.x,right:(T.right-x.right+v.right)/k.x}}const Vy=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=In(e,t)||{};if(c==null)return{};const f=Xc(d),p={x:n,y:r},h=Di(o),v=Oi(h),g=await i.getDimensions(c),y=h==="y",x=y?"top":"left",b=y?"bottom":"right",C=y?"clientHeight":"clientWidth",k=s.reference[v]+s.reference[h]-p[h]-s.floating[v],T=p[h]-s.reference[h],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let I=S?S[C]:0;(!I||!await(i.isElement==null?void 0:i.isElement(S)))&&(I=a.floating[C]||s.floating[v]);const A=k/2-T/2,R=I/2-g[v]/2-1,D=Rn(f[x],R),F=Rn(f[b],R),q=D,W=I-g[v]-F,_=I/2-g[v]/2+A,j=Ri(q,_,W),N=!l.arrow&&yr(o)!=null&&_!==j&&s.reference[v]/2-(_<q?D:F)-g[v]/2<0,z=N?_<q?_-q:_-W:0;return{[h]:p[h]+z,data:{[h]:j,centerOffset:_-j-z,...N&&{alignmentOffset:z}},reset:N}}}),Ky=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:g=!0,...y}=In(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=En(o),b=hn(a),C=En(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),T=p||(C||!g?[Jo(a)]:$y(a)),S=v!=="none";!p&&S&&T.push(...Uy(a,g,v,k));const I=[a,...T],A=await Kr(t,y),R=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&R.push(A[x]),f){const _=Ly(o,i,k);R.push(A[_[0]],A[_[1]])}if(D=[...D,{placement:o,overflows:R}],!R.every(_=>_<=0)){var F,q;const _=(((F=s.flip)==null?void 0:F.index)||0)+1,j=I[_];if(j&&(!(f==="alignment"?b!==hn(j):!1)||D.every(L=>hn(L.placement)===b?L.overflows[0]>0:!0)))return{data:{index:_,overflows:D},reset:{placement:j}};let N=(q=D.filter(z=>z.overflows[0]<=0).sort((z,L)=>z.overflows[1]-L.overflows[1])[0])==null?void 0:q.placement;if(!N)switch(h){case"bestFit":{var W;const z=(W=D.filter(L=>{if(S){const P=hn(L.placement);return P===b||P==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(P=>P>0).reduce((P,V)=>P+V,0)]).sort((L,P)=>L[1]-P[1])[0])==null?void 0:W[0];z&&(N=z);break}case"initialPlacement":N=a;break}if(o!==N)return{reset:{placement:N}}}return{}}}};function Zc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Qc(e){return Ry.some(t=>e[t]>=0)}const qy=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=In(e,t);switch(r){case"referenceHidden":{const s=await Kr(t,{...o,elementContext:"reference"}),i=Zc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Qc(i)}}}case"escaped":{const s=await Kr(t,{...o,altBoundary:!0}),i=Zc(s,n.floating);return{data:{escapedOffsets:i,escaped:Qc(i)}}}default:return{}}}}},eu=new Set(["left","top"]);async function Gy(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=En(n),a=yr(n),l=hn(n)==="y",c=eu.has(i)?-1:1,d=s&&l?-1:1,f=In(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:v}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof v=="number"&&(h=a==="end"?v*-1:v),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const Yy=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await Gy(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},Xy=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:b}=y;return{x,y:b}}},...l}=In(e,t),c={x:n,y:r},d=await Kr(t,l),f=hn(En(o)),p=Pi(f);let h=c[p],v=c[f];if(s){const y=p==="y"?"top":"left",x=p==="y"?"bottom":"right",b=h+d[y],C=h-d[x];h=Ri(b,h,C)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",b=v+d[y],C=v-d[x];v=Ri(b,v,C)}const g=a.fn({...t,[p]:h,[f]:v});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[p]:s,[f]:i}}}}}},Jy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=In(e,t),d={x:n,y:r},f=hn(o),p=Pi(f);let h=d[p],v=d[f];const g=In(a,t),y=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const C=p==="y"?"height":"width",k=s.reference[p]-s.floating[C]+y.mainAxis,T=s.reference[p]+s.reference[C]-y.mainAxis;h<k?h=k:h>T&&(h=T)}if(c){var x,b;const C=p==="y"?"width":"height",k=eu.has(En(o)),T=s.reference[f]-s.floating[C]+(k&&((x=i.offset)==null?void 0:x[f])||0)+(k?0:y.crossAxis),S=s.reference[f]+s.reference[C]+(k?0:((b=i.offset)==null?void 0:b[f])||0)-(k?y.crossAxis:0);v<T?v=T:v>S&&(v=S)}return{[p]:h,[f]:v}}}},Zy=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=In(e,t),d=await Kr(t,c),f=En(o),p=yr(o),h=hn(o)==="y",{width:v,height:g}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=p==="end"?"top":"bottom");const b=g-d.top-d.bottom,C=v-d.left-d.right,k=Rn(g-d[y],b),T=Rn(v-d[x],C),S=!t.middlewareData.shift;let I=k,A=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(A=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(I=b),S&&!p){const D=Vt(d.left,0),F=Vt(d.right,0),q=Vt(d.top,0),W=Vt(d.bottom,0);h?A=v-2*(D!==0||F!==0?D+F:Vt(d.left,d.right)):I=g-2*(q!==0||W!==0?q+W:Vt(d.top,d.bottom))}await l({...t,availableWidth:A,availableHeight:I});const R=await i.getDimensions(a.floating);return v!==R.width||g!==R.height?{reset:{rects:!0}}:{}}}};function Qo(){return typeof window<"u"}function vr(e){return tu(e)?(e.nodeName||"").toLowerCase():"#document"}function Kt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(tu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function tu(e){return Qo()?e instanceof Node||e instanceof Kt(e).Node:!1}function sn(e){return Qo()?e instanceof Element||e instanceof Kt(e).Element:!1}function gn(e){return Qo()?e instanceof HTMLElement||e instanceof Kt(e).HTMLElement:!1}function nu(e){return!Qo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Kt(e).ShadowRoot}const Qy=new Set(["inline","contents"]);function qr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Qy.has(o)}const ev=new Set(["table","td","th"]);function tv(e){return ev.has(vr(e))}const nv=[":popover-open",":modal"];function es(e){return nv.some(t=>{try{return e.matches(t)}catch{return!1}})}const rv=["transform","translate","scale","rotate","perspective"],ov=["transform","translate","scale","rotate","perspective","filter"],sv=["paint","layout","strict","content"];function $i(e){const t=Fi(),n=sn(e)?an(e):e;return rv.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||ov.some(r=>(n.willChange||"").includes(r))||sv.some(r=>(n.contain||"").includes(r))}function iv(e){let t=Pn(e);for(;gn(t)&&!br(t);){if($i(t))return t;if(es(t))return null;t=Pn(t)}return null}function Fi(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const av=new Set(["html","body","#document"]);function br(e){return av.has(vr(e))}function an(e){return Kt(e).getComputedStyle(e)}function ts(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(vr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||nu(e)&&e.host||mn(e);return nu(t)?t.host:t}function ru(e){const t=Pn(e);return br(t)?e.ownerDocument?e.ownerDocument.body:e.body:gn(t)&&qr(t)?t:ru(t)}function Gr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=ru(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Kt(o);if(s){const a=Bi(i);return t.concat(i,i.visualViewport||[],qr(o)?o:[],a&&n?Gr(a):[])}return t.concat(o,Gr(o,[],n))}function Bi(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ou(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=gn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Yo(n)!==s||Yo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function zi(e){return sn(e)?e:e.contextElement}function wr(e){const t=zi(e);if(!gn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=ou(t);let i=(s?Yo(n.width):n.width)/r,a=(s?Yo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const lv=pn(0);function su(e){const t=Kt(e);return!Fi()||!t.visualViewport?lv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function cv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Kt(e)?!1:t}function Xn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=zi(e);let i=pn(1);t&&(r?sn(r)&&(i=wr(r)):i=wr(e));const a=cv(s,n,r)?su(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=Kt(s),h=r&&sn(r)?Kt(r):r;let v=p,g=Bi(v);for(;g&&r&&h!==v;){const y=wr(g),x=g.getBoundingClientRect(),b=an(g),C=x.left+(g.clientLeft+parseFloat(b.paddingLeft))*y.x,k=x.top+(g.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=C,c+=k,v=Kt(g),g=Bi(v)}}return Zo({width:d,height:f,x:l,y:c})}function ns(e,t){const n=ts(e).scrollLeft;return t?t.left+n:Xn(mn(e)).left+n}function iu(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ns(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function uv(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=mn(r),a=t?es(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=gn(r);if((f||!f&&!s)&&((vr(r)!=="body"||qr(i))&&(l=ts(r)),gn(r))){const h=Xn(r);c=wr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?iu(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function dv(e){return Array.from(e.getClientRects())}function fv(e){const t=mn(e),n=ts(e),r=e.ownerDocument.body,o=Vt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Vt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+ns(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Vt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const au=25;function pv(e,t){const n=Kt(e),r=mn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Fi();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=ns(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,v=Math.abs(r.clientWidth-f.clientWidth-h);v<=au&&(s-=v)}else c<=au&&(s+=c);return{width:s,height:i,x:a,y:l}}const hv=new Set(["absolute","fixed"]);function mv(e,t){const n=Xn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=gn(e)?wr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function lu(e,t,n){let r;if(t==="viewport")r=pv(e,n);else if(t==="document")r=fv(mn(e));else if(sn(t))r=mv(t,n);else{const o=su(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Zo(r)}function cu(e,t){const n=Pn(e);return n===t||!sn(n)||br(n)?!1:an(n).position==="fixed"||cu(n,t)}function gv(e,t){const n=t.get(e);if(n)return n;let r=Gr(e,[],!1).filter(a=>sn(a)&&vr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!br(i);){const a=an(i),l=$i(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&hv.has(o.position)||qr(i)&&!l&&cu(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function xv(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?es(t)?[]:gv(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=lu(t,d,o);return c.top=Vt(f.top,c.top),c.right=Rn(f.right,c.right),c.bottom=Rn(f.bottom,c.bottom),c.left=Vt(f.left,c.left),c},lu(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function yv(e){const{width:t,height:n}=ou(e);return{width:t,height:n}}function vv(e,t,n){const r=gn(t),o=mn(t),s=n==="fixed",i=Xn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=ns(o)}if(r||!r&&!s)if((vr(t)!=="body"||qr(o))&&(a=ts(t)),r){const h=Xn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?iu(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Ui(e){return an(e).position==="static"}function uu(e,t){if(!gn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function du(e,t){const n=Kt(e);if(es(e))return n;if(!gn(e)){let o=Pn(e);for(;o&&!br(o);){if(sn(o)&&!Ui(o))return o;o=Pn(o)}return n}let r=uu(e,t);for(;r&&tv(r)&&Ui(r);)r=uu(r,t);return r&&br(r)&&Ui(r)&&!$i(r)?n:r||iv(e)||n}const bv=async function(e){const t=this.getOffsetParent||du,n=this.getDimensions,r=await n(e.floating);return{reference:vv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function wv(e){return an(e).direction==="rtl"}const Sv={convertOffsetParentRelativeRectToViewportRelativeRect:uv,getDocumentElement:mn,getClippingRect:xv,getOffsetParent:du,getElementRects:bv,getClientRects:dv,getDimensions:yv,getScale:wr,isElement:sn,isRTL:wv};function fu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Cv(e,t){let n=null,r;const o=mn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const v=Xo(f),g=Xo(o.clientWidth-(d+p)),y=Xo(o.clientHeight-(f+h)),x=Xo(d),C={rootMargin:-v+"px "+-g+"px "+-y+"px "+-x+"px",threshold:Vt(0,Rn(1,l))||1};let k=!0;function T(S){const I=S[0].intersectionRatio;if(I!==l){if(!k)return i();I?i(!1,I):r=setTimeout(()=>{i(!1,1e-7)},1e3)}I===1&&!fu(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(T,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(T,C)}n.observe(e)}return i(!0),s}function Tv(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=zi(e),d=o||s?[...c?Gr(c):[],...Gr(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Cv(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(x=>{let[b]=x;b&&b.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var C;(C=h)==null||C.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let v,g=l?Xn(e):null;l&&y();function y(){const x=Xn(e);g&&!fu(g,x)&&n(),g=x,v=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(x=h)==null||x.disconnect(),h=null,l&&cancelAnimationFrame(v)}}const kv=Yy,Iv=Xy,Ev=Ky,Nv=Zy,Av=qy,pu=Vy,jv=Jy,_v=(e,t,n)=>{const r=new Map,o={platform:Sv,...n},s={...o.platform,_c:r};return Wy(e,t,{...o,platform:s})};var Mv=typeof document<"u",Rv=function(){},rs=Mv?w.useLayoutEffect:Rv;function os(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!os(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!os(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function hu(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function mu(e,t){const n=hu(e);return Math.round(t*n)/n}function Hi(e){const t=m.useRef(e);return rs(()=>{t.current=e}),t}function Pv(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=m.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=m.useState(r);os(p,r)||h(r);const[v,g]=m.useState(null),[y,x]=m.useState(null),b=m.useCallback(L=>{L!==S.current&&(S.current=L,g(L))},[]),C=m.useCallback(L=>{L!==I.current&&(I.current=L,x(L))},[]),k=s||v,T=i||y,S=m.useRef(null),I=m.useRef(null),A=m.useRef(d),R=l!=null,D=Hi(l),F=Hi(o),q=Hi(c),W=m.useCallback(()=>{if(!S.current||!I.current)return;const L={placement:t,strategy:n,middleware:p};F.current&&(L.platform=F.current),_v(S.current,I.current,L).then(P=>{const V={...P,isPositioned:q.current!==!1};_.current&&!os(A.current,V)&&(A.current=V,Io.flushSync(()=>{f(V)}))})},[p,t,n,F,q]);rs(()=>{c===!1&&A.current.isPositioned&&(A.current.isPositioned=!1,f(L=>({...L,isPositioned:!1})))},[c]);const _=m.useRef(!1);rs(()=>(_.current=!0,()=>{_.current=!1}),[]),rs(()=>{if(k&&(S.current=k),T&&(I.current=T),k&&T){if(D.current)return D.current(k,T,W);W()}},[k,T,W,D,R]);const j=m.useMemo(()=>({reference:S,floating:I,setReference:b,setFloating:C}),[b,C]),N=m.useMemo(()=>({reference:k,floating:T}),[k,T]),z=m.useMemo(()=>{const L={position:n,left:0,top:0};if(!N.floating)return L;const P=mu(N.floating,d.x),V=mu(N.floating,d.y);return a?{...L,transform:"translate("+P+"px, "+V+"px)",...hu(N.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:P,top:V}},[n,a,N.floating,d.x,d.y]);return m.useMemo(()=>({...d,update:W,refs:j,elements:N,floatingStyles:z}),[d,W,j,N,z])}const Ov=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?pu({element:r.current,padding:o}).fn(n):{}:r?pu({element:r,padding:o}).fn(n):{}}}},Dv=(e,t)=>({...kv(e),options:[e,t]}),Lv=(e,t)=>({...Iv(e),options:[e,t]}),$v=(e,t)=>({...jv(e),options:[e,t]}),Fv=(e,t)=>({...Ev(e),options:[e,t]}),Bv=(e,t)=>({...Nv(e),options:[e,t]}),zv=(e,t)=>({...Av(e),options:[e,t]}),Uv=(e,t)=>({...Ov(e),options:[e,t]});var Hv="Arrow",gu=m.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Ie.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});gu.displayName=Hv;var Wv=gu;function xu(e){const[t,n]=m.useState(void 0);return Tt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Wi="Popper",[yu,ss]=kn(Wi),[Vv,vu]=yu(Wi),bu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=m.useState(null);return u.jsx(Vv,{scope:t,anchor:r,onAnchorChange:o,children:n})};bu.displayName=Wi;var wu="PopperAnchor",Su=m.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=vu(wu,n),i=m.useRef(null),a=He(t,i),l=m.useRef(null);return m.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Ie.div,{...o,ref:a})});Su.displayName=wu;var Vi="PopperContent",[Kv,qv]=yu(Vi),Cu=m.forwardRef((e,t)=>{var G,O,K,B,te,Z;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:v,...g}=e,y=vu(Vi,n),[x,b]=m.useState(null),C=He(t,ye=>b(ye)),[k,T]=m.useState(null),S=xu(k),I=(S==null?void 0:S.width)??0,A=(S==null?void 0:S.height)??0,R=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},F=Array.isArray(c)?c:[c],q=F.length>0,W={padding:D,boundary:F.filter(Yv),altBoundary:q},{refs:_,floatingStyles:j,placement:N,isPositioned:z,middlewareData:L}=Pv({strategy:"fixed",placement:R,whileElementsMounted:(...ye)=>Tv(...ye,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[Dv({mainAxis:o+A,alignmentAxis:i}),l&&Lv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?$v():void 0,...W}),l&&Fv({...W}),Bv({...W,apply:({elements:ye,rects:fe,availableWidth:oe,availableHeight:xe})=>{const{width:Se,height:$e}=fe.reference,_e=ye.floating.style;_e.setProperty("--radix-popper-available-width",`${oe}px`),_e.setProperty("--radix-popper-available-height",`${xe}px`),_e.setProperty("--radix-popper-anchor-width",`${Se}px`),_e.setProperty("--radix-popper-anchor-height",`${$e}px`)}}),k&&Uv({element:k,padding:a}),Xv({arrowWidth:I,arrowHeight:A}),p&&zv({strategy:"referenceHidden",...W})]}),[P,V]=Iu(N),ne=kt(v);Tt(()=>{z&&(ne==null||ne())},[z,ne]);const M=(G=L.arrow)==null?void 0:G.x,Y=(O=L.arrow)==null?void 0:O.y,ae=((K=L.arrow)==null?void 0:K.centerOffset)!==0,[Q,ce]=m.useState();return Tt(()=>{x&&ce(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:_.setFloating,"data-radix-popper-content-wrapper":"",style:{...j,transform:z?j.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[(B=L.transformOrigin)==null?void 0:B.x,(te=L.transformOrigin)==null?void 0:te.y].join(" "),...((Z=L.hide)==null?void 0:Z.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Kv,{scope:n,placedSide:P,onArrowChange:T,arrowX:M,arrowY:Y,shouldHideArrow:ae,children:u.jsx(Ie.div,{"data-side":P,"data-align":V,...g,ref:C,style:{...g.style,animation:z?void 0:"none"}})})})});Cu.displayName=Vi;var Tu="PopperArrow",Gv={top:"bottom",right:"left",bottom:"top",left:"right"},ku=m.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=qv(Tu,r),i=Gv[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(Wv,{...o,ref:n,style:{...o.style,display:"block"}})})});ku.displayName=Tu;function Yv(e){return e!==null}var Xv=e=>({name:"transformOrigin",options:e,fn(t){var y,x,b;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=Iu(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,h=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let v="",g="";return c==="bottom"?(v=i?f:`${p}px`,g=`${-l}px`):c==="top"?(v=i?f:`${p}px`,g=`${r.floating.height+l}px`):c==="right"?(v=`${-l}px`,g=i?f:`${h}px`):c==="left"&&(v=`${r.floating.width+l}px`,g=i?f:`${h}px`),{data:{x:v,y:g}}}});function Iu(e){const[t,n="center"]=e.split("-");return[t,n]}var Eu=bu,Nu=Su,Au=Cu,ju=ku,Jv="Portal",is=m.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=m.useState(!1);Tt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?ii.createPortal(u.jsx(Ie.div,{...r,ref:t}),i):null});is.displayName=Jv;function Zv(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=Qv(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=He(r.ref,eb(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function Qv(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Zv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const c=as(r.current);s.current=a==="mounted"?c:"none"},[a]),Tt(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=as(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Tt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const g=as(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&g&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=h=>{h.target===t&&(s.current=as(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function as(e){return(e==null?void 0:e.animationName)||"none"}function eb(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Ki="rovingFocusGroup.onEntryFocus",tb={bubbles:!1,cancelable:!0},Yr="RovingFocusGroup",[qi,_u,nb]=Ei(Yr),[rb,Mu]=kn(Yr,[nb]),[ob,sb]=rb(Yr),Ru=m.forwardRef((e,t)=>u.jsx(qi.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(qi.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(ib,{...e,ref:t})})}));Ru.displayName=Yr;var ib=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=m.useRef(null),h=He(t,p),v=Ko(s),[g,y]=xr({prop:i,defaultProp:a??null,onChange:l,caller:Yr}),[x,b]=m.useState(!1),C=kt(c),k=_u(n),T=m.useRef(!1),[S,I]=m.useState(0);return m.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(Ki,C),()=>A.removeEventListener(Ki,C)},[C]),u.jsx(ob,{scope:n,orientation:r,dir:v,loop:o,currentTabStopId:g,onItemFocus:m.useCallback(A=>y(A),[y]),onItemShiftTab:m.useCallback(()=>b(!0),[]),onFocusableItemAdd:m.useCallback(()=>I(A=>A+1),[]),onFocusableItemRemove:m.useCallback(()=>I(A=>A-1),[]),children:u.jsx(Ie.div,{tabIndex:x||S===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:me(e.onMouseDown,()=>{T.current=!0}),onFocus:me(e.onFocus,A=>{const R=!T.current;if(A.target===A.currentTarget&&R&&!x){const D=new CustomEvent(Ki,tb);if(A.currentTarget.dispatchEvent(D),!D.defaultPrevented){const F=k().filter(N=>N.focusable),q=F.find(N=>N.active),W=F.find(N=>N.id===g),j=[q,W,...F].filter(Boolean).map(N=>N.ref.current);Du(j,d)}}T.current=!1}),onBlur:me(e.onBlur,()=>b(!1))})})}),Pu="RovingFocusGroupItem",Ou=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=Dt(),c=s||l,d=sb(Pu,n),f=d.currentTabStopId===c,p=_u(n),{onFocusableItemAdd:h,onFocusableItemRemove:v,currentTabStopId:g}=d;return m.useEffect(()=>{if(r)return h(),()=>v()},[r,h,v]),u.jsx(qi.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Ie.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:me(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:me(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:me(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=cb(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let C=p().filter(k=>k.focusable).map(k=>k.ref.current);if(x==="last")C.reverse();else if(x==="prev"||x==="next"){x==="prev"&&C.reverse();const k=C.indexOf(y.currentTarget);C=d.loop?ub(C,k+1):C.slice(k+1)}setTimeout(()=>Du(C))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:g!=null}):i})})});Ou.displayName=Pu;var ab={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lb(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cb(e,t,n){const r=lb(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return ab[r]}function Du(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function ub(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var db=Ru,fb=Ou,pb=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Sr=new WeakMap,ls=new WeakMap,cs={},Gi=0,Lu=function(e){return e&&(e.host||Lu(e.parentNode))},hb=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Lu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},mb=function(e,t,n,r){var o=hb(t,Array.isArray(e)?e:[e]);cs[n]||(cs[n]=new WeakMap);var s=cs[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),v=h!==null&&h!=="false",g=(Sr.get(p)||0)+1,y=(s.get(p)||0)+1;Sr.set(p,g),s.set(p,y),i.push(p),g===1&&v&&ls.set(p,!0),y===1&&p.setAttribute(n,"true"),v||p.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",p,x)}})};return d(t),a.clear(),Gi++,function(){i.forEach(function(f){var p=Sr.get(f)-1,h=s.get(f)-1;Sr.set(f,p),s.set(f,h),p||(ls.has(f)||f.removeAttribute(r),ls.delete(f)),h||f.removeAttribute(n)}),Gi--,Gi||(Sr=new WeakMap,Sr=new WeakMap,ls=new WeakMap,cs={})}},Yi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=pb(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),mb(r,o,n,"aria-hidden")):function(){return null}},xn=function(){return xn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},xn.apply(this,arguments)};function $u(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function gb(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var us="right-scroll-bar-position",ds="width-before-scroll-bar",xb="with-scroll-bars-hidden",yb="--removed-body-scroll-bar-size";function Xi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function vb(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var bb=typeof window<"u"?m.useLayoutEffect:m.useEffect,Fu=new WeakMap;function wb(e,t){var n=vb(null,function(r){return e.forEach(function(o){return Xi(o,r)})});return bb(function(){var r=Fu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Xi(a,null)}),s.forEach(function(a){o.has(a)||Xi(a,i)})}Fu.set(n,e)},[e]),n}function Sb(e){return e}function Cb(e,t){t===void 0&&(t=Sb);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Tb(e){e===void 0&&(e={});var t=Cb(null);return t.options=xn({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,n=$u(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return m.createElement(r,xn({},n))};Bu.isSideCarExport=!0;function kb(e,t){return e.useMedium(t),Bu}var zu=Tb(),Ji=function(){},fs=m.forwardRef(function(e,t){var n=m.useRef(null),r=m.useState({onScrollCapture:Ji,onWheelCapture:Ji,onTouchMoveCapture:Ji}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,v=e.noIsolation,g=e.inert,y=e.allowPinchZoom,x=e.as,b=x===void 0?"div":x,C=e.gapMode,k=$u(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),T=p,S=wb([n,t]),I=xn(xn({},k),o);return m.createElement(m.Fragment,null,d&&m.createElement(T,{sideCar:zu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:v,inert:g,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:C}),i?m.cloneElement(m.Children.only(a),xn(xn({},I),{ref:S})):m.createElement(b,xn({},I,{className:l,ref:S}),a))});fs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},fs.classNames={fullWidth:ds,zeroRight:us};var Ib=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Eb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Ib();return t&&e.setAttribute("nonce",t),e}function Nb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ab(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var jb=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Eb())&&(Nb(t,n),Ab(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},_b=function(){var e=jb();return function(t,n){m.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Uu=function(){var e=_b(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Mb={left:0,top:0,right:0,gap:0},Zi=function(e){return parseInt(e||"",10)||0},Rb=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Zi(n),Zi(r),Zi(o)]},Pb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Mb;var t=Rb(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Ob=Uu(),Cr="data-scroll-locked",Db=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
39
+ .`.concat(xb,` {
40
40
  overflow: hidden `).concat(r,`;
41
41
  padding-right: `).concat(a,"px ").concat(r,`;
42
42
  }
43
- body[`).concat(wr,`] {
43
+ body[`).concat(Cr,`] {
44
44
  overflow: hidden `).concat(r,`;
45
45
  overscroll-behavior: contain;
46
46
  `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
@@ -53,29 +53,29 @@ React keys must be passed directly to JSX without using spread:
53
53
  `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
54
54
  }
55
55
 
56
- .`).concat(es,` {
56
+ .`).concat(us,` {
57
57
  right: `).concat(a,"px ").concat(r,`;
58
58
  }
59
59
 
60
- .`).concat(ts,` {
60
+ .`).concat(ds,` {
61
61
  margin-right: `).concat(a,"px ").concat(r,`;
62
62
  }
63
63
 
64
- .`).concat(es," .").concat(es,` {
64
+ .`).concat(us," .").concat(us,` {
65
65
  right: 0 `).concat(r,`;
66
66
  }
67
67
 
68
- .`).concat(ts," .").concat(ts,` {
68
+ .`).concat(ds," .").concat(ds,` {
69
69
  margin-right: 0 `).concat(r,`;
70
70
  }
71
71
 
72
- body[`).concat(wr,`] {
73
- `).concat(Bv,": ").concat(a,`px;
72
+ body[`).concat(Cr,`] {
73
+ `).concat(yb,": ").concat(a,`px;
74
74
  }
75
- `)},Tu=function(){var e=parseInt(document.body.getAttribute(wr)||"0",10);return isFinite(e)?e:0},sw=function(){v.useEffect(function(){return document.body.setAttribute(wr,(Tu()+1).toString()),function(){var e=Tu()-1;e<=0?document.body.removeAttribute(wr):document.body.setAttribute(wr,e.toString())}},[])},iw=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;sw();var s=v.useMemo(function(){return nw(o)},[o]);return v.createElement(rw,{styles:ow(s,!t,o,n?"":"!important")})},Vi=!1;if(typeof window<"u")try{var rs=Object.defineProperty({},"passive",{get:function(){return Vi=!0,!0}});window.addEventListener("test",rs,rs),window.removeEventListener("test",rs,rs)}catch{Vi=!1}var br=Vi?{passive:!1}:!1,aw=function(e){return e.tagName==="TEXTAREA"},ku=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!aw(e)&&n[t]==="visible")},lw=function(e){return ku(e,"overflowY")},cw=function(e){return ku(e,"overflowX")},Iu=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=Eu(e,r);if(o){var s=Nu(e,r),i=s[1],a=s[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},uw=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},dw=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},Eu=function(e,t){return e==="v"?lw(t):cw(t)},Nu=function(e,t){return e==="v"?uw(t):dw(t)},fw=function(e,t){return e==="h"&&t==="rtl"?-1:1},hw=function(e,t,n,r,o){var s=fw(e,window.getComputedStyle(t).direction),i=s*r,a=n.target,l=t.contains(a),c=!1,d=i>0,f=0,h=0;do{if(!a)break;var p=Nu(e,a),y=p[0],m=p[1],x=p[2],g=m-x-s*y;(y||g)&&Eu(e,a)&&(f+=g,h+=y);var w=a.parentNode;a=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!l&&a!==document.body||l&&(t.contains(a)||t===a));return(d&&Math.abs(f)<1||!d&&Math.abs(h)<1)&&(c=!0),c},os=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Au=function(e){return[e.deltaX,e.deltaY]},ju=function(e){return e&&"current"in e?e.current:e},pw=function(e,t){return e[0]===t[0]&&e[1]===t[1]},mw=function(e){return`
75
+ `)},Hu=function(){var e=parseInt(document.body.getAttribute(Cr)||"0",10);return isFinite(e)?e:0},Lb=function(){m.useEffect(function(){return document.body.setAttribute(Cr,(Hu()+1).toString()),function(){var e=Hu()-1;e<=0?document.body.removeAttribute(Cr):document.body.setAttribute(Cr,e.toString())}},[])},$b=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Lb();var s=m.useMemo(function(){return Pb(o)},[o]);return m.createElement(Ob,{styles:Db(s,!t,o,n?"":"!important")})},Qi=!1;if(typeof window<"u")try{var ps=Object.defineProperty({},"passive",{get:function(){return Qi=!0,!0}});window.addEventListener("test",ps,ps),window.removeEventListener("test",ps,ps)}catch{Qi=!1}var Tr=Qi?{passive:!1}:!1,Fb=function(e){return e.tagName==="TEXTAREA"},Wu=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Fb(e)&&n[t]==="visible")},Bb=function(e){return Wu(e,"overflowY")},zb=function(e){return Wu(e,"overflowX")},Vu=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=Ku(e,r);if(o){var s=qu(e,r),i=s[1],a=s[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Ub=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Hb=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},Ku=function(e,t){return e==="v"?Bb(t):zb(t)},qu=function(e,t){return e==="v"?Ub(t):Hb(t)},Wb=function(e,t){return e==="h"&&t==="rtl"?-1:1},Vb=function(e,t,n,r,o){var s=Wb(e,window.getComputedStyle(t).direction),i=s*r,a=n.target,l=t.contains(a),c=!1,d=i>0,f=0,p=0;do{if(!a)break;var h=qu(e,a),v=h[0],g=h[1],y=h[2],x=g-y-s*v;(v||x)&&Ku(e,a)&&(f+=x,p+=v);var b=a.parentNode;a=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!l&&a!==document.body||l&&(t.contains(a)||t===a));return(d&&Math.abs(f)<1||!d&&Math.abs(p)<1)&&(c=!0),c},hs=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Gu=function(e){return[e.deltaX,e.deltaY]},Yu=function(e){return e&&"current"in e?e.current:e},Kb=function(e,t){return e[0]===t[0]&&e[1]===t[1]},qb=function(e){return`
76
76
  .block-interactivity-`.concat(e,` {pointer-events: none;}
77
77
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
78
- `)},gw=0,Sr=[];function xw(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),o=v.useState(gw++)[0],s=v.useState(Cu)[0],i=v.useRef(e);v.useEffect(function(){i.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var m=$v([e.lockRef.current],(e.shards||[]).map(ju),!0).filter(Boolean);return m.forEach(function(x){return x.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=v.useCallback(function(m,x){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!i.current.allowPinchZoom;var g=os(m),w=n.current,S="deltaX"in m?m.deltaX:w[0]-g[0],k="deltaY"in m?m.deltaY:w[1]-g[1],C,T=m.target,I=Math.abs(S)>Math.abs(k)?"h":"v";if("touches"in m&&I==="h"&&T.type==="range")return!1;var j=Iu(I,T);if(!j)return!0;if(j?C=I:(C=I==="v"?"h":"v",j=Iu(I,T)),!j)return!1;if(!r.current&&"changedTouches"in m&&(S||k)&&(r.current=C),!C)return!0;var _=r.current||C;return hw(_,x,m,_==="h"?S:k)},[]),l=v.useCallback(function(m){var x=m;if(!(!Sr.length||Sr[Sr.length-1]!==s)){var g="deltaY"in x?Au(x):os(x),w=t.current.filter(function(C){return C.name===x.type&&(C.target===x.target||x.target===C.shadowParent)&&pw(C.delta,g)})[0];if(w&&w.should){x.cancelable&&x.preventDefault();return}if(!w){var S=(i.current.shards||[]).map(ju).filter(Boolean).filter(function(C){return C.contains(x.target)}),k=S.length>0?a(x,S[0]):!i.current.noIsolation;k&&x.cancelable&&x.preventDefault()}}},[]),c=v.useCallback(function(m,x,g,w){var S={name:m,delta:x,target:g,should:w,shadowParent:yw(g)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(k){return k!==S})},1)},[]),d=v.useCallback(function(m){n.current=os(m),r.current=void 0},[]),f=v.useCallback(function(m){c(m.type,Au(m),m.target,a(m,e.lockRef.current))},[]),h=v.useCallback(function(m){c(m.type,os(m),m.target,a(m,e.lockRef.current))},[]);v.useEffect(function(){return Sr.push(s),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:h}),document.addEventListener("wheel",l,br),document.addEventListener("touchmove",l,br),document.addEventListener("touchstart",d,br),function(){Sr=Sr.filter(function(m){return m!==s}),document.removeEventListener("wheel",l,br),document.removeEventListener("touchmove",l,br),document.removeEventListener("touchstart",d,br)}},[]);var p=e.removeScrollBar,y=e.inert;return v.createElement(v.Fragment,null,y?v.createElement(s,{styles:mw(o)}):null,p?v.createElement(iw,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function yw(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const vw=qv(Su,xw);var ss=v.forwardRef(function(e,t){return v.createElement(ns,mn({},e,{ref:t,sideCar:vw}))});ss.classNames=ns.classNames;var Ki=["Enter"," "],ww=["ArrowDown","PageUp","Home"],_u=["ArrowUp","PageDown","End"],bw=[...ww,..._u],Sw={ltr:[...Ki,"ArrowRight"],rtl:[...Ki,"ArrowLeft"]},Cw={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Hr="Menu",[Wr,Tw,kw]=vi(Hr),[Yn,Mu]=bn(Hr,[kw,Yo,hu]),is=Yo(),Pu=hu(),[Iw,Xn]=Yn(Hr),[Ew,Vr]=Yn(Hr),Ru=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=is(t),[l,c]=v.useState(null),d=v.useRef(!1),f=It(s),h=Do(o);return v.useEffect(()=>{const p=()=>{d.current=!0,document.addEventListener("pointerdown",y,{capture:!0,once:!0}),document.addEventListener("pointermove",y,{capture:!0,once:!0})},y=()=>d.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",y,{capture:!0}),document.removeEventListener("pointermove",y,{capture:!0})}},[]),u.jsx(lu,{...a,children:u.jsx(Iw,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:c,children:u.jsx(Ew,{scope:t,onClose:v.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:h,modal:i,children:r})})})};Ru.displayName=Hr;var Nw="MenuAnchor",qi=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=is(n);return u.jsx(cu,{...o,...r,ref:t})});qi.displayName=Nw;var Gi="MenuPortal",[Aw,Ou]=Yn(Gi,{forceMount:void 0}),Du=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Xn(Gi,t);return u.jsx(Aw,{scope:t,forceMount:n,children:u.jsx(Gt,{present:n||s.open,children:u.jsx(Xo,{asChild:!0,container:o,children:r})})})};Du.displayName=Gi;var Yt="MenuContent",[jw,Yi]=Yn(Yt),Lu=v.forwardRef((e,t)=>{const n=Ou(Yt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Xn(Yt,e.__scopeMenu),i=Vr(Yt,e.__scopeMenu);return u.jsx(Wr.Provider,{scope:e.__scopeMenu,children:u.jsx(Gt,{present:r||s.open,children:u.jsx(Wr.Slot,{scope:e.__scopeMenu,children:i.modal?u.jsx(_w,{...o,ref:t}):u.jsx(Mw,{...o,ref:t})})})})}),_w=v.forwardRef((e,t)=>{const n=Xn(Yt,e.__scopeMenu),r=v.useRef(null),o=Ue(t,r);return v.useEffect(()=>{const s=r.current;if(s)return zi(s)},[]),u.jsx(Xi,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Mw=v.forwardRef((e,t)=>{const n=Xn(Yt,e.__scopeMenu);return u.jsx(Xi,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Pw=Wn.createSlot("MenuContent.ScrollLock"),Xi=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,disableOutsideScroll:y,...m}=e,x=Xn(Yt,n),g=Vr(Yt,n),w=is(n),S=Pu(n),k=Tw(n),[C,T]=v.useState(null),I=v.useRef(null),j=Ue(t,I,x.onContentChange),_=v.useRef(0),O=v.useRef(""),B=v.useRef(0),K=v.useRef(null),V=v.useRef("right"),P=v.useRef(0),M=y?ss:v.Fragment,N=y?{as:Pw,allowPinchZoom:!0}:void 0,z=R=>{var te,F;const W=O.current+R,Y=k().filter(X=>!X.disabled),ne=document.activeElement,pe=(te=Y.find(X=>X.ref.current===ne))==null?void 0:te.textValue,be=Y.map(X=>X.textValue),Ie=Vw(be,W,pe),ve=(F=Y.find(X=>X.textValue===Ie))==null?void 0:F.ref.current;(function X(A){O.current=A,window.clearTimeout(_.current),A!==""&&(_.current=window.setTimeout(()=>X(""),1e3))})(W),ve&&setTimeout(()=>ve.focus())};v.useEffect(()=>()=>window.clearTimeout(_.current),[]),Si();const L=v.useCallback(R=>{var Y,ne;return V.current===((Y=K.current)==null?void 0:Y.side)&&qw(R,(ne=K.current)==null?void 0:ne.area)},[]);return u.jsx(jw,{scope:n,searchRef:O,onItemEnter:v.useCallback(R=>{L(R)&&R.preventDefault()},[L]),onItemLeave:v.useCallback(R=>{var W;L(R)||((W=I.current)==null||W.focus(),T(null))},[L]),onTriggerLeave:v.useCallback(R=>{L(R)&&R.preventDefault()},[L]),pointerGraceTimerRef:B,onPointerGraceIntentChange:v.useCallback(R=>{K.current=R},[]),children:u.jsx(M,{...N,children:u.jsx($o,{asChild:!0,trapped:o,onMountAutoFocus:ue(s,R=>{var W;R.preventDefault(),(W=I.current)==null||W.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:u.jsx(Lo,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:u.jsx(Pv,{asChild:!0,...S,dir:g.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:T,onEntryFocus:ue(l,R=>{g.isUsingKeyboardRef.current||R.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(uu,{role:"menu","aria-orientation":"vertical","data-state":ed(x.open),"data-radix-menu-content":"",dir:g.dir,...w,...m,ref:j,style:{outline:"none",...m.style},onKeyDown:ue(m.onKeyDown,R=>{const Y=R.target.closest("[data-radix-menu-content]")===R.currentTarget,ne=R.ctrlKey||R.altKey||R.metaKey,pe=R.key.length===1;Y&&(R.key==="Tab"&&R.preventDefault(),!ne&&pe&&z(R.key));const be=I.current;if(R.target!==be||!bw.includes(R.key))return;R.preventDefault();const ve=k().filter(te=>!te.disabled).map(te=>te.ref.current);_u.includes(R.key)&&ve.reverse(),Hw(ve)}),onBlur:ue(e.onBlur,R=>{R.currentTarget.contains(R.target)||(window.clearTimeout(_.current),O.current="")}),onPointerMove:ue(e.onPointerMove,qr(R=>{const W=R.target,Y=P.current!==R.clientX;if(R.currentTarget.contains(W)&&Y){const ne=R.clientX>P.current?"right":"left";V.current=ne,P.current=R.clientX}}))})})})})})})});Lu.displayName=Yt;var Rw="MenuGroup",Ji=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(_e.div,{role:"group",...r,ref:t})});Ji.displayName=Rw;var Ow="MenuLabel",$u=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(_e.div,{...r,ref:t})});$u.displayName=Ow;var as="MenuItem",Fu="menu.itemSelect",ls=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=v.useRef(null),i=Vr(as,e.__scopeMenu),a=Yi(as,e.__scopeMenu),l=Ue(t,s),c=v.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(Fu,{bubbles:!0,cancelable:!0});f.addEventListener(Fu,p=>r==null?void 0:r(p),{once:!0}),yc(f,h),h.defaultPrevented?c.current=!1:i.onClose()}};return u.jsx(Bu,{...o,ref:l,disabled:n,onClick:ue(e.onClick,d),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),c.current=!0},onPointerUp:ue(e.onPointerUp,f=>{var h;c.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:ue(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||Ki.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});ls.displayName=as;var Bu=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=Yi(as,n),a=Pu(n),l=v.useRef(null),c=Ue(t,l),[d,f]=v.useState(!1),[h,p]=v.useState("");return v.useEffect(()=>{const y=l.current;y&&p((y.textContent??"").trim())},[s.children]),u.jsx(Wr.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:u.jsx(Rv,{asChild:!0,...a,focusable:!r,children:u.jsx(_e.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:ue(e.onPointerMove,qr(y=>{r?i.onItemLeave(y):(i.onItemEnter(y),y.defaultPrevented||y.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ue(e.onPointerLeave,qr(y=>i.onItemLeave(y))),onFocus:ue(e.onFocus,()=>f(!0)),onBlur:ue(e.onBlur,()=>f(!1))})})})}),Dw="MenuCheckboxItem",zu=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return u.jsx(Ku,{scope:e.__scopeMenu,checked:n,children:u.jsx(ls,{role:"menuitemcheckbox","aria-checked":cs(n)?"mixed":n,...o,ref:t,"data-state":Qi(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(cs(n)?!0:!n),{checkForDefaultPrevented:!1})})})});zu.displayName=Dw;var Uu="MenuRadioGroup",[Lw,$w]=Yn(Uu,{value:void 0,onValueChange:()=>{}}),Hu=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=It(r);return u.jsx(Lw,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(Ji,{...o,ref:t})})});Hu.displayName=Uu;var Wu="MenuRadioItem",Vu=v.forwardRef((e,t)=>{const{value:n,...r}=e,o=$w(Wu,e.__scopeMenu),s=n===o.value;return u.jsx(Ku,{scope:e.__scopeMenu,checked:s,children:u.jsx(ls,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":Qi(s),onSelect:ue(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Vu.displayName=Wu;var Zi="MenuItemIndicator",[Ku,Fw]=Yn(Zi,{checked:!1}),qu=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=Fw(Zi,n);return u.jsx(Gt,{present:r||cs(s.checked)||s.checked===!0,children:u.jsx(_e.span,{...o,ref:t,"data-state":Qi(s.checked)})})});qu.displayName=Zi;var Bw="MenuSeparator",Gu=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(_e.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Gu.displayName=Bw;var zw="MenuArrow",Yu=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=is(n);return u.jsx(du,{...o,...r,ref:t})});Yu.displayName=zw;var Uw="MenuSub",[ck,Xu]=Yn(Uw),Kr="MenuSubTrigger",Ju=v.forwardRef((e,t)=>{const n=Xn(Kr,e.__scopeMenu),r=Vr(Kr,e.__scopeMenu),o=Xu(Kr,e.__scopeMenu),s=Yi(Kr,e.__scopeMenu),i=v.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,c={__scopeMenu:e.__scopeMenu},d=v.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return v.useEffect(()=>d,[d]),v.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),l(null)}},[a,l]),u.jsx(qi,{asChild:!0,...c,children:u.jsx(Bu,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":ed(n.open),...e,ref:yi(t,o.onTriggerChange),onClick:f=>{var h;(h=e.onClick)==null||h.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,qr(f=>{s.onItemEnter(f),!f.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:ue(e.onPointerLeave,qr(f=>{var p,y;d();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const m=(y=n.content)==null?void 0:y.dataset.side,x=m==="right",g=x?-5:5,w=h[x?"left":"right"],S=h[x?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+g,y:f.clientY},{x:w,y:h.top},{x:S,y:h.top},{x:S,y:h.bottom},{x:w,y:h.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||Sw[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});Ju.displayName=Kr;var Zu="MenuSubContent",Qu=v.forwardRef((e,t)=>{const n=Ou(Yt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Xn(Yt,e.__scopeMenu),i=Vr(Yt,e.__scopeMenu),a=Xu(Zu,e.__scopeMenu),l=v.useRef(null),c=Ue(t,l);return u.jsx(Wr.Provider,{scope:e.__scopeMenu,children:u.jsx(Gt,{present:r||s.open,children:u.jsx(Wr.Slot,{scope:e.__scopeMenu,children:u.jsx(Xi,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var f;i.isUsingKeyboardRef.current&&((f=l.current)==null||f.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:ue(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:ue(e.onKeyDown,d=>{var p;const f=d.currentTarget.contains(d.target),h=Cw[i.dir].includes(d.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),d.preventDefault())})})})})})});Qu.displayName=Zu;function ed(e){return e?"open":"closed"}function cs(e){return e==="indeterminate"}function Qi(e){return cs(e)?"indeterminate":e?"checked":"unchecked"}function Hw(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Ww(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Vw(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=Ww(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function Kw(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],l=t[i],c=a.x,d=a.y,f=l.x,h=l.y;d>r!=h>r&&n<(f-c)*(r-d)/(h-d)+c&&(o=!o)}return o}function qw(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Kw(n,t)}function qr(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Gw=Ru,Yw=qi,Xw=Du,Jw=Lu,Zw=Ji,Qw=$u,eb=ls,tb=zu,nb=Hu,rb=Vu,ob=qu,sb=Gu,ib=Yu,ab=Ju,lb=Qu,us="DropdownMenu",[cb,uk]=bn(us,[Mu]),Dt=Mu(),[ub,td]=cb(us),nd=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=Dt(t),c=v.useRef(null),[d,f]=pr({prop:o,defaultProp:s??!1,onChange:i,caller:us});return u.jsx(ub,{scope:t,triggerId:Sn(),triggerRef:c,contentId:Sn(),open:d,onOpenChange:f,onOpenToggle:v.useCallback(()=>f(h=>!h),[f]),modal:a,children:u.jsx(Gw,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};nd.displayName=us;var rd="DropdownMenuTrigger",od=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=td(rd,n),i=Dt(n);return u.jsx(Yw,{asChild:!0,...i,children:u.jsx(_e.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:yi(t,s.triggerRef),onPointerDown:ue(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:ue(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});od.displayName=rd;var db="DropdownMenuPortal",sd=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Dt(t);return u.jsx(Xw,{...r,...n})};sd.displayName=db;var id="DropdownMenuContent",ad=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=td(id,n),s=Dt(n),i=v.useRef(!1);return u.jsx(Jw,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;(!o.modal||d)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});ad.displayName=id;var fb="DropdownMenuGroup",hb=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(Zw,{...o,...r,ref:t})});hb.displayName=fb;var pb="DropdownMenuLabel",ld=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(Qw,{...o,...r,ref:t})});ld.displayName=pb;var mb="DropdownMenuItem",cd=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(eb,{...o,...r,ref:t})});cd.displayName=mb;var gb="DropdownMenuCheckboxItem",ud=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(tb,{...o,...r,ref:t})});ud.displayName=gb;var xb="DropdownMenuRadioGroup",yb=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(nb,{...o,...r,ref:t})});yb.displayName=xb;var vb="DropdownMenuRadioItem",dd=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(rb,{...o,...r,ref:t})});dd.displayName=vb;var wb="DropdownMenuItemIndicator",fd=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(ob,{...o,...r,ref:t})});fd.displayName=wb;var bb="DropdownMenuSeparator",hd=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(sb,{...o,...r,ref:t})});hd.displayName=bb;var Sb="DropdownMenuArrow",Cb=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(ib,{...o,...r,ref:t})});Cb.displayName=Sb;var Tb="DropdownMenuSubTrigger",pd=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(ab,{...o,...r,ref:t})});pd.displayName=Tb;var kb="DropdownMenuSubContent",md=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Dt(n);return u.jsx(lb,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});md.displayName=kb;var Ib=nd,Eb=od,Nb=sd,gd=ad,xd=ld,yd=cd,vd=ud,wd=dd,bd=fd,Sd=hd,Cd=pd,Td=md;const kd=Ib,Id=Eb,Ab=v.forwardRef(({className:e,inset:t,children:n,...r},o)=>u.jsxs(Cd,{ref:o,className:ee("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,u.jsx(oe.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Ab.displayName=Cd.displayName;const jb=v.forwardRef(({className:e,...t},n)=>u.jsx(Td,{ref:n,className:ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));jb.displayName=Td.displayName;const ea=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(Nb,{children:u.jsx(gd,{ref:r,sideOffset:t,className:ee("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));ea.displayName=gd.displayName;const Cr=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(yd,{ref:r,className:ee("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));Cr.displayName=yd.displayName;const _b=v.forwardRef(({className:e,children:t,checked:n,...r},o)=>u.jsxs(vd,{ref:o,className:ee("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(bd,{children:u.jsx(oe.Check,{className:"h-4 w-4"})})}),t]}));_b.displayName=vd.displayName;const Mb=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(wd,{ref:r,className:ee("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(bd,{children:u.jsx(oe.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Mb.displayName=wd.displayName;const Pb=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(xd,{ref:r,className:ee("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));Pb.displayName=xd.displayName;const Rb=v.forwardRef(({className:e,...t},n)=>u.jsx(Sd,{ref:n,className:ee("-mx-1 my-1 h-px bg-muted",e),...t}));Rb.displayName=Sd.displayName;function Ob(e){const t=new Map;for(const n of e){const o=[...n.messages??[]].reverse().find(s=>s.role==="user");if(o!=null&&o.id){const s=t.get(o.id)??[];s.push(n),t.set(o.id,s)}}return t}function Db(e){const t=new Map,n=Ob(e),r=Array.from(n.entries());for(const[o,s]of r)if(s.length===1){const i=s[0];i.checkpointId&&t.set(i.checkpointId,{attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:o})}else{const i=[...s].sort((a,l)=>Date.parse(l.createdAt??"0")-Date.parse(a.createdAt??"0"));i.forEach((a,l)=>{a.checkpointId&&t.set(a.checkpointId,{attemptIndex:l,attemptCount:i.length,isLatestAttempt:l===i.length-1,baseUserMessageId:o})})}return t}function Lb(e){const t=new Map;for(const[n,r]of e.entries())if(r.baseUserMessageId&&r.attemptCount>1){const o=t.get(r.baseUserMessageId)??[];o.push({checkpointId:n,attemptIndex:r.attemptIndex,attemptCount:r.attemptCount,isLatestAttempt:r.isLatestAttempt}),t.set(r.baseUserMessageId,o)}return t}function ds(e,t){if(!e||typeof e!="object")return null;const n=e[t];return typeof n=="number"?n:null}function $b(e,t){if(!e||typeof e!="object")return null;const n=e[t];return typeof n=="string"&&n.trim()?n:null}function Fb(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Bb(e){const t=Array.isArray(e)?e.map(r=>{const o=Fb(r.next);return o?{...r,metadata:{...r.metadata??{},next:o}}:r}):[];return t.some(r=>ds(r.metadata,"step")!==null)&&t.sort((r,o)=>{const s=ds(r.metadata,"step"),i=ds(o.metadata,"step");if(s!==null||i!==null)return(i??Number.NEGATIVE_INFINITY)-(s??Number.NEGATIVE_INFINITY);const a=Date.parse(r.createdAt??""),l=Date.parse(o.createdAt??"");return Number.isNaN(a)||Number.isNaN(l)?0:l-a}),t}function zb(e){const t=b.useMemo(()=>Bb(e),[e]),{checkpointMetaById:n,checkpointIndexByKey:r,attemptMetaById:o,userMessageIdToAttempts:s}=b.useMemo(()=>{const i=new Map,a=new Map,l=new Map;for(const f of t){const h=f.checkpointId??null;if(!h)continue;const p=ds(f.metadata,"step"),y=$b(f.metadata,"source"),m={id:h,step:p,source:y,createdAt:f.createdAt??null,namespace:f.checkpointNs??null,parentId:f.parentId??null};if(i.set(h,m),p!==null&&y){const x=`${p}:${y}`,g=a.get(x)??[];g.push(m),a.set(x,g)}}const c=Db(t);for(const[f,h]of i.entries()){const p=c.get(f);p?l.set(f,{...h,attemptIndex:p.attemptIndex,attemptCount:p.attemptCount,isLatestAttempt:p.isLatestAttempt,baseUserMessageId:p.baseUserMessageId??null}):l.set(f,{...h,attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:null})}const d=Lb(l);return{checkpointMetaById:i,checkpointIndexByKey:a,attemptMetaById:l,userMessageIdToAttempts:d}},[t]);return{checkpointMetaById:n,checkpointIndexByKey:r,attemptMetaById:o,userMessageIdToAttempts:s}}const fs=1e4;function Ub(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=e;for(const o of t)n=n.replace(o,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
78
+ `)},Gb=0,kr=[];function Yb(e){var t=m.useRef([]),n=m.useRef([0,0]),r=m.useRef(),o=m.useState(Gb++)[0],s=m.useState(Uu)[0],i=m.useRef(e);m.useEffect(function(){i.current=e},[e]),m.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var g=gb([e.lockRef.current],(e.shards||[]).map(Yu),!0).filter(Boolean);return g.forEach(function(y){return y.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),g.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=m.useCallback(function(g,y){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!i.current.allowPinchZoom;var x=hs(g),b=n.current,C="deltaX"in g?g.deltaX:b[0]-x[0],k="deltaY"in g?g.deltaY:b[1]-x[1],T,S=g.target,I=Math.abs(C)>Math.abs(k)?"h":"v";if("touches"in g&&I==="h"&&S.type==="range")return!1;var A=Vu(I,S);if(!A)return!0;if(A?T=I:(T=I==="v"?"h":"v",A=Vu(I,S)),!A)return!1;if(!r.current&&"changedTouches"in g&&(C||k)&&(r.current=T),!T)return!0;var R=r.current||T;return Vb(R,y,g,R==="h"?C:k)},[]),l=m.useCallback(function(g){var y=g;if(!(!kr.length||kr[kr.length-1]!==s)){var x="deltaY"in y?Gu(y):hs(y),b=t.current.filter(function(T){return T.name===y.type&&(T.target===y.target||y.target===T.shadowParent)&&Kb(T.delta,x)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var C=(i.current.shards||[]).map(Yu).filter(Boolean).filter(function(T){return T.contains(y.target)}),k=C.length>0?a(y,C[0]):!i.current.noIsolation;k&&y.cancelable&&y.preventDefault()}}},[]),c=m.useCallback(function(g,y,x,b){var C={name:g,delta:y,target:x,should:b,shadowParent:Xb(x)};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(k){return k!==C})},1)},[]),d=m.useCallback(function(g){n.current=hs(g),r.current=void 0},[]),f=m.useCallback(function(g){c(g.type,Gu(g),g.target,a(g,e.lockRef.current))},[]),p=m.useCallback(function(g){c(g.type,hs(g),g.target,a(g,e.lockRef.current))},[]);m.useEffect(function(){return kr.push(s),e.setCallbacks({onScrollCapture:f,onWheelCapture:f,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Tr),document.addEventListener("touchmove",l,Tr),document.addEventListener("touchstart",d,Tr),function(){kr=kr.filter(function(g){return g!==s}),document.removeEventListener("wheel",l,Tr),document.removeEventListener("touchmove",l,Tr),document.removeEventListener("touchstart",d,Tr)}},[]);var h=e.removeScrollBar,v=e.inert;return m.createElement(m.Fragment,null,v?m.createElement(s,{styles:qb(o)}):null,h?m.createElement($b,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Xb(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Jb=kb(zu,Yb);var ms=m.forwardRef(function(e,t){return m.createElement(fs,xn({},e,{ref:t,sideCar:Jb}))});ms.classNames=fs.classNames;var ea=["Enter"," "],Zb=["ArrowDown","PageUp","Home"],Xu=["ArrowUp","PageDown","End"],Qb=[...Zb,...Xu],ew={ltr:[...ea,"ArrowRight"],rtl:[...ea,"ArrowLeft"]},tw={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Xr="Menu",[Jr,nw,rw]=Ei(Xr),[Jn,Ju]=kn(Xr,[rw,ss,Mu]),gs=ss(),Zu=Mu(),[ow,Zn]=Jn(Xr),[sw,Zr]=Jn(Xr),Qu=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=gs(t),[l,c]=m.useState(null),d=m.useRef(!1),f=kt(s),p=Ko(o);return m.useEffect(()=>{const h=()=>{d.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},v=()=>d.current=!1;return document.addEventListener("keydown",h,{capture:!0}),()=>{document.removeEventListener("keydown",h,{capture:!0}),document.removeEventListener("pointerdown",v,{capture:!0}),document.removeEventListener("pointermove",v,{capture:!0})}},[]),u.jsx(Eu,{...a,children:u.jsx(ow,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:c,children:u.jsx(sw,{scope:t,onClose:m.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:p,modal:i,children:r})})})};Qu.displayName=Xr;var iw="MenuAnchor",ta=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gs(n);return u.jsx(Nu,{...o,...r,ref:t})});ta.displayName=iw;var na="MenuPortal",[aw,ed]=Jn(na,{forceMount:void 0}),td=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Zn(na,t);return u.jsx(aw,{scope:t,forceMount:n,children:u.jsx(Xt,{present:n||s.open,children:u.jsx(is,{asChild:!0,container:o,children:r})})})};td.displayName=na;var Jt="MenuContent",[lw,ra]=Jn(Jt),nd=m.forwardRef((e,t)=>{const n=ed(Jt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Zn(Jt,e.__scopeMenu),i=Zr(Jt,e.__scopeMenu);return u.jsx(Jr.Provider,{scope:e.__scopeMenu,children:u.jsx(Xt,{present:r||s.open,children:u.jsx(Jr.Slot,{scope:e.__scopeMenu,children:i.modal?u.jsx(cw,{...o,ref:t}):u.jsx(uw,{...o,ref:t})})})})}),cw=m.forwardRef((e,t)=>{const n=Zn(Jt,e.__scopeMenu),r=m.useRef(null),o=He(t,r);return m.useEffect(()=>{const s=r.current;if(s)return Yi(s)},[]),u.jsx(oa,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:me(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),uw=m.forwardRef((e,t)=>{const n=Zn(Jt,e.__scopeMenu);return u.jsx(oa,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),dw=Kn.createSlot("MenuContent.ScrollLock"),oa=m.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:p,onDismiss:h,disableOutsideScroll:v,...g}=e,y=Zn(Jt,n),x=Zr(Jt,n),b=gs(n),C=Zu(n),k=nw(n),[T,S]=m.useState(null),I=m.useRef(null),A=He(t,I,y.onContentChange),R=m.useRef(0),D=m.useRef(""),F=m.useRef(0),q=m.useRef(null),W=m.useRef("right"),_=m.useRef(0),j=v?ms:m.Fragment,N=v?{as:dw,allowPinchZoom:!0}:void 0,z=P=>{var G,O;const V=D.current+P,ne=k().filter(K=>!K.disabled),M=document.activeElement,Y=(G=ne.find(K=>K.ref.current===M))==null?void 0:G.textValue,ae=ne.map(K=>K.textValue),Q=Cw(ae,V,Y),ce=(O=ne.find(K=>K.textValue===Q))==null?void 0:O.ref.current;(function K(B){D.current=B,window.clearTimeout(R.current),B!==""&&(R.current=window.setTimeout(()=>K(""),1e3))})(V),ce&&setTimeout(()=>ce.focus())};m.useEffect(()=>()=>window.clearTimeout(R.current),[]),ji();const L=m.useCallback(P=>{var ne,M;return W.current===((ne=q.current)==null?void 0:ne.side)&&kw(P,(M=q.current)==null?void 0:M.area)},[]);return u.jsx(lw,{scope:n,searchRef:D,onItemEnter:m.useCallback(P=>{L(P)&&P.preventDefault()},[L]),onItemLeave:m.useCallback(P=>{var V;L(P)||((V=I.current)==null||V.focus(),S(null))},[L]),onTriggerLeave:m.useCallback(P=>{L(P)&&P.preventDefault()},[L]),pointerGraceTimerRef:F,onPointerGraceIntentChange:m.useCallback(P=>{q.current=P},[]),children:u.jsx(j,{...N,children:u.jsx(Go,{asChild:!0,trapped:o,onMountAutoFocus:me(s,P=>{var V;P.preventDefault(),(V=I.current)==null||V.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:u.jsx(qo,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:p,onDismiss:h,children:u.jsx(db,{asChild:!0,...C,dir:x.dir,orientation:"vertical",loop:r,currentTabStopId:T,onCurrentTabStopIdChange:S,onEntryFocus:me(l,P=>{x.isUsingKeyboardRef.current||P.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(Au,{role:"menu","aria-orientation":"vertical","data-state":vd(y.open),"data-radix-menu-content":"",dir:x.dir,...b,...g,ref:A,style:{outline:"none",...g.style},onKeyDown:me(g.onKeyDown,P=>{const ne=P.target.closest("[data-radix-menu-content]")===P.currentTarget,M=P.ctrlKey||P.altKey||P.metaKey,Y=P.key.length===1;ne&&(P.key==="Tab"&&P.preventDefault(),!M&&Y&&z(P.key));const ae=I.current;if(P.target!==ae||!Qb.includes(P.key))return;P.preventDefault();const ce=k().filter(G=>!G.disabled).map(G=>G.ref.current);Xu.includes(P.key)&&ce.reverse(),ww(ce)}),onBlur:me(e.onBlur,P=>{P.currentTarget.contains(P.target)||(window.clearTimeout(R.current),D.current="")}),onPointerMove:me(e.onPointerMove,eo(P=>{const V=P.target,ne=_.current!==P.clientX;if(P.currentTarget.contains(V)&&ne){const M=P.clientX>_.current?"right":"left";W.current=M,_.current=P.clientX}}))})})})})})})});nd.displayName=Jt;var fw="MenuGroup",sa=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ie.div,{role:"group",...r,ref:t})});sa.displayName=fw;var pw="MenuLabel",rd=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ie.div,{...r,ref:t})});rd.displayName=pw;var xs="MenuItem",od="menu.itemSelect",ys=m.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=m.useRef(null),i=Zr(xs,e.__scopeMenu),a=ra(xs,e.__scopeMenu),l=He(t,s),c=m.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const p=new CustomEvent(od,{bubbles:!0,cancelable:!0});f.addEventListener(od,h=>r==null?void 0:r(h),{once:!0}),Lc(f,p),p.defaultPrevented?c.current=!1:i.onClose()}};return u.jsx(sd,{...o,ref:l,disabled:n,onClick:me(e.onClick,d),onPointerDown:f=>{var p;(p=e.onPointerDown)==null||p.call(e,f),c.current=!0},onPointerUp:me(e.onPointerUp,f=>{var p;c.current||(p=f.currentTarget)==null||p.click()}),onKeyDown:me(e.onKeyDown,f=>{const p=a.searchRef.current!=="";n||p&&f.key===" "||ea.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});ys.displayName=xs;var sd=m.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=ra(xs,n),a=Zu(n),l=m.useRef(null),c=He(t,l),[d,f]=m.useState(!1),[p,h]=m.useState("");return m.useEffect(()=>{const v=l.current;v&&h((v.textContent??"").trim())},[s.children]),u.jsx(Jr.ItemSlot,{scope:n,disabled:r,textValue:o??p,children:u.jsx(fb,{asChild:!0,...a,focusable:!r,children:u.jsx(Ie.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:me(e.onPointerMove,eo(v=>{r?i.onItemLeave(v):(i.onItemEnter(v),v.defaultPrevented||v.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:me(e.onPointerLeave,eo(v=>i.onItemLeave(v))),onFocus:me(e.onFocus,()=>f(!0)),onBlur:me(e.onBlur,()=>f(!1))})})})}),hw="MenuCheckboxItem",id=m.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return u.jsx(dd,{scope:e.__scopeMenu,checked:n,children:u.jsx(ys,{role:"menuitemcheckbox","aria-checked":vs(n)?"mixed":n,...o,ref:t,"data-state":aa(n),onSelect:me(o.onSelect,()=>r==null?void 0:r(vs(n)?!0:!n),{checkForDefaultPrevented:!1})})})});id.displayName=hw;var ad="MenuRadioGroup",[mw,gw]=Jn(ad,{value:void 0,onValueChange:()=>{}}),ld=m.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=kt(r);return u.jsx(mw,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(sa,{...o,ref:t})})});ld.displayName=ad;var cd="MenuRadioItem",ud=m.forwardRef((e,t)=>{const{value:n,...r}=e,o=gw(cd,e.__scopeMenu),s=n===o.value;return u.jsx(dd,{scope:e.__scopeMenu,checked:s,children:u.jsx(ys,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":aa(s),onSelect:me(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});ud.displayName=cd;var ia="MenuItemIndicator",[dd,xw]=Jn(ia,{checked:!1}),fd=m.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=xw(ia,n);return u.jsx(Xt,{present:r||vs(s.checked)||s.checked===!0,children:u.jsx(Ie.span,{...o,ref:t,"data-state":aa(s.checked)})})});fd.displayName=ia;var yw="MenuSeparator",pd=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(Ie.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});pd.displayName=yw;var vw="MenuArrow",hd=m.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gs(n);return u.jsx(ju,{...o,...r,ref:t})});hd.displayName=vw;var bw="MenuSub",[dI,md]=Jn(bw),Qr="MenuSubTrigger",gd=m.forwardRef((e,t)=>{const n=Zn(Qr,e.__scopeMenu),r=Zr(Qr,e.__scopeMenu),o=md(Qr,e.__scopeMenu),s=ra(Qr,e.__scopeMenu),i=m.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,c={__scopeMenu:e.__scopeMenu},d=m.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return m.useEffect(()=>d,[d]),m.useEffect(()=>{const f=a.current;return()=>{window.clearTimeout(f),l(null)}},[a,l]),u.jsx(ta,{asChild:!0,...c,children:u.jsx(sd,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":vd(n.open),...e,ref:_n(t,o.onTriggerChange),onClick:f=>{var p;(p=e.onClick)==null||p.call(e,f),!(e.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:me(e.onPointerMove,eo(f=>{s.onItemEnter(f),!f.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:me(e.onPointerLeave,eo(f=>{var h,v;d();const p=(h=n.content)==null?void 0:h.getBoundingClientRect();if(p){const g=(v=n.content)==null?void 0:v.dataset.side,y=g==="right",x=y?-5:5,b=p[y?"left":"right"],C=p[y?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+x,y:f.clientY},{x:b,y:p.top},{x:C,y:p.top},{x:C,y:p.bottom},{x:b,y:p.bottom}],side:g}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:me(e.onKeyDown,f=>{var h;const p=s.searchRef.current!=="";e.disabled||p&&f.key===" "||ew[r.dir].includes(f.key)&&(n.onOpenChange(!0),(h=n.content)==null||h.focus(),f.preventDefault())})})})});gd.displayName=Qr;var xd="MenuSubContent",yd=m.forwardRef((e,t)=>{const n=ed(Jt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Zn(Jt,e.__scopeMenu),i=Zr(Jt,e.__scopeMenu),a=md(xd,e.__scopeMenu),l=m.useRef(null),c=He(t,l);return u.jsx(Jr.Provider,{scope:e.__scopeMenu,children:u.jsx(Xt,{present:r||s.open,children:u.jsx(Jr.Slot,{scope:e.__scopeMenu,children:u.jsx(oa,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var f;i.isUsingKeyboardRef.current&&((f=l.current)==null||f.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:me(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:me(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:me(e.onKeyDown,d=>{var h;const f=d.currentTarget.contains(d.target),p=tw[i.dir].includes(d.key);f&&p&&(s.onOpenChange(!1),(h=a.trigger)==null||h.focus(),d.preventDefault())})})})})})});yd.displayName=xd;function vd(e){return e?"open":"closed"}function vs(e){return e==="indeterminate"}function aa(e){return vs(e)?"indeterminate":e?"checked":"unchecked"}function ww(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Sw(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Cw(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=Sw(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function Tw(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],l=t[i],c=a.x,d=a.y,f=l.x,p=l.y;d>r!=p>r&&n<(f-c)*(r-d)/(p-d)+c&&(o=!o)}return o}function kw(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Tw(n,t)}function eo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Iw=Qu,Ew=ta,Nw=td,Aw=nd,jw=sa,_w=rd,Mw=ys,Rw=id,Pw=ld,Ow=ud,Dw=fd,Lw=pd,$w=hd,Fw=gd,Bw=yd,bs="DropdownMenu",[zw,fI]=kn(bs,[Ju]),Lt=Ju(),[Uw,bd]=zw(bs),wd=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=Lt(t),c=m.useRef(null),[d,f]=xr({prop:o,defaultProp:s??!1,onChange:i,caller:bs});return u.jsx(Uw,{scope:t,triggerId:Dt(),triggerRef:c,contentId:Dt(),open:d,onOpenChange:f,onOpenToggle:m.useCallback(()=>f(p=>!p),[f]),modal:a,children:u.jsx(Iw,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};wd.displayName=bs;var Sd="DropdownMenuTrigger",Cd=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=bd(Sd,n),i=Lt(n);return u.jsx(Ew,{asChild:!0,...i,children:u.jsx(Ie.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:_n(t,s.triggerRef),onPointerDown:me(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:me(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Cd.displayName=Sd;var Hw="DropdownMenuPortal",Td=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Lt(t);return u.jsx(Nw,{...r,...n})};Td.displayName=Hw;var kd="DropdownMenuContent",Id=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=bd(kd,n),s=Lt(n),i=m.useRef(!1);return u.jsx(Aw,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:me(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:me(e.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;(!o.modal||d)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Id.displayName=kd;var Ww="DropdownMenuGroup",Vw=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(jw,{...o,...r,ref:t})});Vw.displayName=Ww;var Kw="DropdownMenuLabel",Ed=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(_w,{...o,...r,ref:t})});Ed.displayName=Kw;var qw="DropdownMenuItem",Nd=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Mw,{...o,...r,ref:t})});Nd.displayName=qw;var Gw="DropdownMenuCheckboxItem",Ad=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Rw,{...o,...r,ref:t})});Ad.displayName=Gw;var Yw="DropdownMenuRadioGroup",Xw=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Pw,{...o,...r,ref:t})});Xw.displayName=Yw;var Jw="DropdownMenuRadioItem",jd=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Ow,{...o,...r,ref:t})});jd.displayName=Jw;var Zw="DropdownMenuItemIndicator",_d=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Dw,{...o,...r,ref:t})});_d.displayName=Zw;var Qw="DropdownMenuSeparator",Md=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Lw,{...o,...r,ref:t})});Md.displayName=Qw;var e0="DropdownMenuArrow",t0=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx($w,{...o,...r,ref:t})});t0.displayName=e0;var n0="DropdownMenuSubTrigger",Rd=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Fw,{...o,...r,ref:t})});Rd.displayName=n0;var r0="DropdownMenuSubContent",Pd=m.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Lt(n);return u.jsx(Bw,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Pd.displayName=r0;var o0=wd,s0=Cd,i0=Td,Od=Id,Dd=Ed,Ld=Nd,$d=Ad,Fd=jd,Bd=_d,zd=Md,Ud=Rd,Hd=Pd;const Wd=o0,Vd=s0,a0=m.forwardRef(({className:e,inset:t,children:n,...r},o)=>u.jsxs(Ud,{ref:o,className:se("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,u.jsx(ue.ChevronRight,{className:"ml-auto h-4 w-4"})]}));a0.displayName=Ud.displayName;const l0=m.forwardRef(({className:e,...t},n)=>u.jsx(Hd,{ref:n,className:se("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));l0.displayName=Hd.displayName;const la=m.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(i0,{children:u.jsx(Od,{ref:r,sideOffset:t,className:se("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})}));la.displayName=Od.displayName;const Ir=m.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(Ld,{ref:r,className:se("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));Ir.displayName=Ld.displayName;const c0=m.forwardRef(({className:e,children:t,checked:n,...r},o)=>u.jsxs($d,{ref:o,className:se("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(Bd,{children:u.jsx(ue.Check,{className:"h-4 w-4"})})}),t]}));c0.displayName=$d.displayName;const u0=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Fd,{ref:r,className:se("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(Bd,{children:u.jsx(ue.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));u0.displayName=Fd.displayName;const d0=m.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(Dd,{ref:r,className:se("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));d0.displayName=Dd.displayName;const f0=m.forwardRef(({className:e,...t},n)=>u.jsx(zd,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));f0.displayName=zd.displayName;function p0(e){const t=new Map;for(const n of e){const o=[...n.messages??[]].reverse().find(s=>s.role==="user");if(o!=null&&o.id){const s=t.get(o.id)??[];s.push(n),t.set(o.id,s)}}return t}function h0(e){const t=new Map,n=p0(e),r=Array.from(n.entries());for(const[o,s]of r)if(s.length===1){const i=s[0];i.checkpointId&&t.set(i.checkpointId,{attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:o})}else{const i=[...s].sort((a,l)=>Date.parse(l.createdAt??"0")-Date.parse(a.createdAt??"0"));i.forEach((a,l)=>{a.checkpointId&&t.set(a.checkpointId,{attemptIndex:l,attemptCount:i.length,isLatestAttempt:l===i.length-1,baseUserMessageId:o})})}return t}function m0(e){const t=new Map;for(const[n,r]of e.entries())if(r.baseUserMessageId&&r.attemptCount>1){const o=t.get(r.baseUserMessageId)??[];o.push({checkpointId:n,attemptIndex:r.attemptIndex,attemptCount:r.attemptCount,isLatestAttempt:r.isLatestAttempt}),t.set(r.baseUserMessageId,o)}return t}function ws(e,t){if(!e||typeof e!="object")return null;const n=e[t];return typeof n=="number"?n:null}function g0(e,t){if(!e||typeof e!="object")return null;const n=e[t];return typeof n=="string"&&n.trim()?n:null}function x0(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function y0(e){const t=Array.isArray(e)?e.map(r=>{const o=x0(r.next);return o?{...r,metadata:{...r.metadata??{},next:o}}:r}):[];return t.some(r=>ws(r.metadata,"step")!==null)&&t.sort((r,o)=>{const s=ws(r.metadata,"step"),i=ws(o.metadata,"step");if(s!==null||i!==null)return(i??Number.NEGATIVE_INFINITY)-(s??Number.NEGATIVE_INFINITY);const a=Date.parse(r.createdAt??""),l=Date.parse(o.createdAt??"");return Number.isNaN(a)||Number.isNaN(l)?0:l-a}),t}function v0(e){const t=w.useMemo(()=>y0(e),[e]),{checkpointMetaById:n,checkpointIndexByKey:r,attemptMetaById:o,userMessageIdToAttempts:s}=w.useMemo(()=>{const i=new Map,a=new Map,l=new Map;for(const f of t){const p=f.checkpointId??null;if(!p)continue;const h=ws(f.metadata,"step"),v=g0(f.metadata,"source"),g={id:p,step:h,source:v,createdAt:f.createdAt??null,namespace:f.checkpointNs??null,parentId:f.parentId??null};if(i.set(p,g),h!==null&&v){const y=`${h}:${v}`,x=a.get(y)??[];x.push(g),a.set(y,x)}}const c=h0(t);for(const[f,p]of i.entries()){const h=c.get(f);h?l.set(f,{...p,attemptIndex:h.attemptIndex,attemptCount:h.attemptCount,isLatestAttempt:h.isLatestAttempt,baseUserMessageId:h.baseUserMessageId??null}):l.set(f,{...p,attemptIndex:0,attemptCount:1,isLatestAttempt:!0,baseUserMessageId:null})}const d=m0(l);return{checkpointMetaById:i,checkpointIndexByKey:a,attemptMetaById:l,userMessageIdToAttempts:d}},[t]);return{checkpointMetaById:n,checkpointIndexByKey:r,attemptMetaById:o,userMessageIdToAttempts:s}}const Ss=1e4;function b0(e){if(typeof e!="string")return String(e);const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>.*?<\/embed>/gi,/<form[^>]*>.*?<\/form>/gi];let n=e;for(const o of t)n=n.replace(o,"");return/<[^>]+>/.test(n)&&!/<(?!\/?(?:code|strong|em|b|i|br|p|ul|ol|li|h[1-6])\b)[^>]+>/i.test(n)?n.replace(/<code>(.*?)<\/code>/gi,"`$1`").replace(/<strong>(.*?)<\/strong>/gi,"**$1**").replace(/<b>(.*?)<\/b>/gi,"**$1**").replace(/<em>(.*?)<\/em>/gi,"*$1*").replace(/<i>(.*?)<\/i>/gi,"*$1*").replace(/<br\s*\/?>/gi,`
79
79
  `).replace(/<p>(.*?)<\/p>/gi,`$1
80
80
 
81
81
  `).replace(/<h([1-6])>(.*?)<\/h[1-6]>/gi,(o,s,i)=>`${"#".repeat(parseInt(s))} ${i}
@@ -83,25 +83,25 @@ React keys must be passed directly to JSX without using spread:
83
83
  `).replace(/<ul>/gi,"").replace(/<\/ul>/gi,`
84
84
  `).replace(/<ol>/gi,"").replace(/<\/ol>/gi,`
85
85
  `).replace(/<li>(.*?)<\/li>/gi,`- $1
86
- `).trim():n.replace(/</g,"&lt;").replace(/>/g,"&gt;").trim()}function Hb(e,t=fs){if(!e||typeof e!="string")throw new Error("Invalid content: must be a non-empty string");if(e.length>t)throw new Error(`Message exceeds maximum length of ${t} characters`);return e}function Wb(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),Hb(t),Ub(t)}const hs=0,Mn=1,Tr=2,Ed=4;function Nd(e){return()=>e}function Vb(e){e()}function Ad(e,t){return n=>e(t(n))}function jd(e,t){return()=>e(t)}function Kb(e,t){return n=>e(t,n)}function ta(e){return e!==void 0}function qb(...e){return()=>{e.map(Vb)}}function kr(){}function ps(e,t){return t(e),e}function Gb(e,t){return t(e)}function at(...e){return e}function Ze(e,t){return e(Mn,t)}function Pe(e,t){e(hs,t)}function na(e){e(Tr)}function yt(e){return e(Ed)}function he(e,t){return Ze(e,Kb(t,hs))}function on(e,t){const n=e(Mn,r=>{n(),t(r)});return n}function _d(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Md(e,t){return e===t}function lt(e=Md){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Ne(e){return t=>n=>{e(n)&&t(n)}}function ie(e){return t=>Ad(t,e)}function gn(e){return t=>()=>{t(e)}}function q(e,...t){const n=Yb(...t);return(r,o)=>{switch(r){case Tr:na(e);return;case Mn:return Ze(e,n(o))}}}function xn(e,t){return n=>r=>{n(t=e(t,r))}}function Jn(e){return t=>n=>{e>0?e--:t(n)}}function kn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Oe(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);Ze(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function Yb(...e){return t=>e.reduceRight(Gb,t)}function Xb(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Mn:return s?n===s?void 0:(r(),n=s,t=Ze(e,s),t):(r(),kr);case Tr:r(),n=null;return}}}function Q(e){let t=e;const n=He();return(r,o)=>{switch(r){case hs:t=o;break;case Mn:{o(t);break}case Ed:return t}return n(r,o)}}function At(e,t){return ps(Q(t),n=>he(e,n))}function He(){const e=[];return(t,n)=>{switch(t){case hs:e.slice().forEach(r=>{r(n)});return;case Tr:e.splice(0,e.length);return;case Mn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function Vt(e){return ps(He(),t=>he(e,t))}function Ge(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:Jb(),singleton:n}}const Jb=()=>Symbol();function Zb(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function vt(...e){const t=He(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);Ze(s,l=>{n[i]=l,r=r|a,r===o&&Pe(t,n)})}),function(s,i){switch(s){case Tr:{na(t);return}case Mn:return r===o&&i(n),Ze(t,i)}}}function ke(e,t=Md){return q(e,lt(t))}function ra(...e){return function(t,n){switch(t){case Tr:return;case Mn:return qb(...e.map(r=>Ze(r,n)))}}}var zt=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(zt||{});const Qb={0:"debug",3:"error",1:"log",2:"warn"},e0=()=>typeof globalThis>"u"?window:globalThis,Pn=Ge(()=>{const e=Q(3);return{log:Q((t,n,r=1)=>{var o;const s=(o=e0().VIRTUOSO_LOG_LEVEL)!=null?o:yt(e);r>=s&&console[Qb[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function Zn(e,t,n){return oa(e,t,n).callbackRef}function oa(e,t,n){const r=b.useRef(null);let o=i=>{};const s=b.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function t0(e,t,n,r,o,s,i,a,l){const c=b.useCallback(d=>{const f=n0(d.children,t,a?"offsetWidth":"offsetHeight",o);let h=d.parentElement;for(;!h.dataset.virtuosoScroller;)h=h.parentElement;const p=h.lastElementChild.dataset.viewportType==="window";let y;p&&(y=h.ownerDocument.defaultView);const m=i?a?i.scrollLeft:i.scrollTop:p?a?y.scrollX||y.document.documentElement.scrollLeft:y.scrollY||y.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,x=i?a?i.scrollWidth:i.scrollHeight:p?a?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,g=i?a?i.offsetWidth:i.offsetHeight:p?a?y.innerWidth:y.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:x,scrollTop:Math.max(m,0),viewportHeight:g}),s==null||s(a?Pd("column-gap",getComputedStyle(d).columnGap,o):Pd("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return oa(c,n,l)}function n0(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},zt.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function Pd(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,zt.WARN),t==="normal"?0:parseInt(t??"0",10)}function Rd(e,t,n){const r=b.useRef(null),o=b.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,h;if(t){const p=t.getBoundingClientRect(),y=c.top-p.top;h=p.height-Math.max(0,y),f=y+t.scrollTop}else{const p=i.current.ownerDocument.defaultView;h=p.innerHeight-Math.max(0,c.top),f=c.top+p.scrollY}r.current={offsetTop:f,visibleHeight:h,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=oa(o,!0,n),a=b.useCallback(()=>{o(i.current)},[o,i]);return b.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const Lt=Ge(()=>{const e=He(),t=He(),n=Q(0),r=He(),o=Q(0),s=He(),i=He(),a=Q(0),l=Q(0),c=Q(0),d=Q(0),f=He(),h=He(),p=Q(!1),y=Q(!1),m=Q(!1);return he(q(e,ie(({scrollTop:x})=>x)),t),he(q(e,ie(({scrollHeight:x})=>x)),i),he(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:y,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:m,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),Gr={lvl:0};function Od(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function ot(e){return e===Gr}function Yr(e,t){if(!ot(e))return t===e.k?e.v:t<e.k?Yr(e.l,t):Yr(e.r,t)}function sn(e,t,n="k"){if(ot(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=sn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return sn(e.l,t,n)}function Kt(e,t,n){return ot(e)?$d(t,n,1):t===e.k?St(e,{k:t,v:n}):t<e.k?Fd(St(e,{l:Kt(e.l,t,n)})):Fd(St(e,{r:Kt(e.r,t,n)}))}function Ir(){return Gr}function ms(e,t,n){if(ot(e))return[];const r=sn(e,t)[0];return r0(ia(e,r,n))}function sa(e,t){if(ot(e))return Gr;const{k:n,l:r,r:o}=e;if(t===n){if(ot(r))return o;if(ot(o))return r;{const[s,i]=Ld(r);return gs(St(e,{k:s,l:Dd(r),v:i}))}}else return t<n?gs(St(e,{l:sa(r,t)})):gs(St(e,{r:sa(o,t)}))}function Qn(e){return ot(e)?[]:[...Qn(e.l),{k:e.k,v:e.v},...Qn(e.r)]}function ia(e,t,n){if(ot(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(ia(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(ia(s,t,n))),a}function gs(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(aa(t))return Bd(St(e,{lvl:n-1}));if(!ot(t)&&!ot(t.r))return St(t.r,{l:St(t,{r:t.r.l}),lvl:n,r:St(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(aa(e))return la(St(e,{lvl:n-1}));if(!ot(r)&&!ot(r.l)){const o=r.l,s=aa(o)?r.lvl-1:r.lvl;return St(o,{l:St(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:la(St(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function St(e,t){return $d(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function Dd(e){return ot(e.r)?e.l:gs(St(e,{r:Dd(e.r)}))}function aa(e){return ot(e)||e.lvl>e.r.lvl}function Ld(e){return ot(e.r)?[e.k,e.v]:Ld(e.r)}function $d(e,t,n,r=Gr,o=Gr){return{k:e,l:r,lvl:n,r:o,v:t}}function Fd(e){return la(Bd(e))}function Bd(e){const{l:t}=e;return!ot(t)&&t.lvl===e.lvl?St(t,{r:St(e,{l:t.r})}):e}function la(e){const{lvl:t,r:n}=e;return!ot(n)&&!ot(n.r)&&n.lvl===t&&n.r.lvl===t?St(n,{l:St(e,{r:n.l}),lvl:t+1}):e}function r0(e){return Od(e,({k:t,v:n})=>({index:t,value:n}))}function zd(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Xr(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const ca=Ge(()=>({recalcInProgress:Q(!1)}),[],{singleton:!0});function Ud(e,t,n){return e[xs(e,t,n)]}function xs(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function o0(e,t,n,r){const o=xs(e,t,r),s=xs(e,n,r,o);return e.slice(o,s+1)}function Rn(e,t){return Math.round(e.getBoundingClientRect()[t])}function ys(e){return!ot(e.groupOffsetTree)}function ua({index:e},t){return t===e?0:t<e?-1:1}function s0(){return{groupIndices:[],groupOffsetTree:Ir(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Ir()}}function i0(e,t){let n=ot(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),ot(e)){e=Kt(e,0,s);continue}const a=ms(e,i-1,o+1);if(a.some(h0(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=sa(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=Kt(e,o+1,h));c&&(e=Kt(e,i,s))}return[e,n]}function a0(e){return typeof e.groupIndex<"u"}function l0({offset:e},t){return t===e?0:t<e?-1:1}function Jr(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=Ud(t,e,ua),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function Hd(e,t){if(!ys(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function Wd(e,t,n){if(a0(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=Hd(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function c0(e,t,n,r=0){return r>0&&(t=Math.max(t,Ud(e,r,ua).offset)),Od(o0(e,t,n,l0),f0)}function u0(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,zt.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&ot(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((y,m)=>Kt(Kt(y,m,h),m+1,p),i)}else[i,a]=i0(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=da(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>Kt(h,p,Jr(p,f,o)),Ir()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function d0(e){return Qn(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function Vd(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function da(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=xs(o,t-1,ua),a=o[l].offset;const c=sn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===sn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of ms(n,t,1/0)){const f=c-s,h=f*i+a+f*r;o.push({index:c,offset:h,size:d}),s=c,a=h,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function f0(e){return{index:e.index,value:e}}function h0(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const p0={offsetHeight:"height",offsetWidth:"width"},yn=Ge(([{log:e},{recalcInProgress:t}])=>{const n=He(),r=He(),o=At(r,0),s=He(),i=He(),a=Q(0),l=Q([]),c=Q(void 0),d=Q(void 0),f=Q((C,T)=>Rn(C,p0[T])),h=Q(void 0),p=Q(0),y=s0(),m=At(q(n,Oe(l,e,p),xn(u0,y),lt()),y),x=At(q(l,lt(),xn((C,T)=>({current:T,prev:C.current}),{current:[],prev:[]}),ie(({prev:C})=>C)),[]);he(q(l,Ne(C=>C.length>0),Oe(m,p),ie(([C,T,I])=>{const j=C.reduce((_,O,B)=>Kt(_,O,Jr(O,T.offsetTree,I)||B),Ir());return{...T,groupIndices:C,groupOffsetTree:j}})),m),he(q(r,Oe(m),Ne(([C,{lastIndex:T}])=>C<T),ie(([C,{lastIndex:T,lastSize:I}])=>[{endIndex:T,size:I,startIndex:C}])),n),he(c,d);const g=At(q(c,ie(C=>C===void 0)),!0);he(q(d,Ne(C=>C!==void 0&&ot(yt(m).sizeTree)),ie(C=>[{endIndex:0,size:C,startIndex:0}])),n);const w=Vt(q(n,Oe(m),xn(({sizes:C},[T,I])=>({changed:I!==C,sizes:I}),{changed:!1,sizes:y}),ie(C=>C.changed)));Ze(q(a,xn((C,T)=>({diff:C.prev-T,prev:T}),{diff:0,prev:0}),ie(C=>C.diff)),C=>{const{groupIndices:T}=yt(m);if(C>0)Pe(t,!0),Pe(s,C+Vd(C,T));else if(C<0){const I=yt(x);I.length>0&&(C-=Vd(-C,I)),Pe(i,C)}}),Ze(q(a,Oe(e)),([C,T])=>{C<0&&T("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},zt.ERROR)});const S=Vt(s);he(q(s,Oe(m),ie(([C,T])=>{const I=T.groupIndices.length>0,j=[],_=T.lastSize;if(I){const O=Yr(T.sizeTree,0);let B=0,K=0;for(;B<C;){const P=T.groupIndices[K],M=T.groupIndices.length===K+1?1/0:T.groupIndices[K+1]-P-1;j.push({endIndex:P,size:O,startIndex:P}),j.push({endIndex:P+1+M-1,size:_,startIndex:P+1}),K++,B+=M+1}const V=Qn(T.sizeTree);return B!==C&&V.shift(),V.reduce((P,{k:M,v:N})=>{let z=P.ranges;return P.prevSize!==0&&(z=[...P.ranges,{endIndex:M+C-1,size:P.prevSize,startIndex:P.prevIndex}]),{prevIndex:M+C,prevSize:N,ranges:z}},{prevIndex:C,prevSize:0,ranges:j}).ranges}return Qn(T.sizeTree).reduce((O,{k:B,v:K})=>({prevIndex:B+C,prevSize:K,ranges:[...O.ranges,{endIndex:B+C-1,size:O.prevSize,startIndex:O.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const k=Vt(q(i,Oe(m,p),ie(([C,{offsetTree:T},I])=>{const j=-C;return Jr(j,T,I)})));return he(q(i,Oe(m,p),ie(([C,T,I])=>{if(T.groupIndices.length>0){if(ot(T.sizeTree))return T;let j=Ir();const _=yt(x);let O=0,B=0,K=0;for(;O<-C;){K=_[B];const V=_[B+1]-K-1;B++,O+=V+1}if(j=Qn(T.sizeTree).reduce((V,{k:P,v:M})=>Kt(V,Math.max(0,P+C),M),j),O!==-C){const V=Yr(T.sizeTree,K);j=Kt(j,0,V);const P=sn(T.sizeTree,-C+1)[1];j=Kt(j,1,P)}return{...T,sizeTree:j,...da(T.offsetTree,0,j,I)}}else{const j=Qn(T.sizeTree).reduce((_,{k:O,v:B})=>Kt(_,Math.max(0,O+C),B),Ir());return{...T,sizeTree:j,...da(T.offsetTree,0,j,I)}}})),m),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:w,shiftWith:i,shiftWithOffset:k,sizeRanges:n,sizes:m,statefulTotalCount:o,totalCount:r,trackItemSizes:g,unshiftWith:s}},at(Pn,ca),{singleton:!0});function m0(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Kd=Ge(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=He(),i=He(),a=Vt(q(s,ie(m0)));return he(q(a,ie(l=>l.totalCount)),n),he(q(a,ie(l=>l.groupIndices)),e),he(q(vt(o,t,r),Ne(([l,c])=>ys(c)),ie(([l,c,d])=>sn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),lt(),ie(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},at(yn,Lt)),On=Ge(([{log:e}])=>{const t=Q(!1),n=Vt(q(t,Ne(r=>r),lt()));return Ze(t,r=>{r&&yt(e)("props updated",{},zt.DEBUG)}),{didMount:n,propsReady:t}},at(Pn),{singleton:!0}),g0=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function qd(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!g0)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Zr=Ge(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:h}])=>{const p=He(),y=He(),m=Q(0);let x=null,g=null,w=null;function S(){x&&(x(),x=null),w&&(w(),w=null),g&&(clearTimeout(g),g=null),Pe(l,!1)}return he(q(p,Oe(n,f,r,m,a,i,h),Oe(e,s,o),ie(([[k,C,T,I,j,_,O,B],K,V,P])=>{const M=qd(k),{align:N,behavior:z,offset:L}=M,R=I-1,W=Wd(M,C,R);let Y=Jr(W,C.offsetTree,K)+_;N==="end"?(Y+=V+sn(C.sizeTree,W)[1]-T+P,W===R&&(Y+=O)):N==="center"?Y+=(V+sn(C.sizeTree,W)[1]-T+P)/2:Y-=j,L&&(Y+=L);const ne=pe=>{S(),pe?(B("retrying to scroll to",{location:k},zt.DEBUG),Pe(p,k)):(Pe(y,!0),B("list did not change, scroll successful",{},zt.DEBUG))};if(S(),z==="smooth"){let pe=!1;w=Ze(t,be=>{pe=pe||be}),x=on(d,()=>{ne(pe)})}else x=on(q(t,x0(150)),ne);return g=setTimeout(()=>{S()},1200),Pe(l,!0),B("scrolling from index to",{behavior:z,index:W,top:Y},zt.DEBUG),{behavior:z,top:Y}})),c),{scrollTargetReached:y,scrollToIndex:p,topListHeight:m}},at(yn,Lt,Pn),{singleton:!0});function x0(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function fa(e,t){e==0?t():requestAnimationFrame(()=>{fa(e-1,t)})}function ha(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const Qr=Ge(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=Q(!0),l=Q(0),c=Q(!0);return he(q(i,Oe(l),Ne(([d,f])=>!!f),gn(!1)),a),he(q(i,Oe(l),Ne(([d,f])=>!!f),gn(!1)),c),Ze(q(vt(t,i),Oe(a,n,e,c),Ne(([[,d],f,{sizeTree:h},p,y])=>d&&(!ot(h)||ta(p))&&!f&&!y),Oe(l)),([,d])=>{on(o,()=>{Pe(c,!0)}),fa(4,()=>{on(r,()=>{Pe(a,!0)}),Pe(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},at(yn,Lt,Zr,On),{singleton:!0});function Gd(e,t){return Math.abs(e-t)<1.01}const eo="up",to="down",y0="none",v0={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},w0=0,no=Ge(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=Q(!1),a=Q(!0),l=He(),c=He(),d=Q(4),f=Q(w0),h=At(q(ra(q(ke(o),Jn(1),gn(!0)),q(ke(o),Jn(1),gn(!1),_d(100))),lt()),!1),p=At(q(ra(q(n,gn(!0)),q(n,gn(!1),_d(200))),lt()),!1);he(q(vt(ke(o),ke(f)),ie(([w,S])=>w<=S),lt()),a),he(q(a,kn(50)),c);const y=Vt(q(vt(r,ke(s),ke(t),ke(e),ke(d)),xn((w,[{scrollHeight:S,scrollTop:k},C,T,I,j])=>{const _=k+C-S>-j,O={scrollHeight:S,scrollTop:k,viewportHeight:C};if(_){let K,V;return k>w.state.scrollTop?(K="SCROLLED_DOWN",V=w.state.scrollTop-k):(K="SIZE_DECREASED",V=w.state.scrollTop-k||w.scrollTopDelta),{atBottom:!0,atBottomBecause:K,scrollTopDelta:V,state:O}}let B;return O.scrollHeight>w.state.scrollHeight?B="SIZE_INCREASED":C<w.state.viewportHeight?B="VIEWPORT_HEIGHT_DECREASING":k<w.state.scrollTop?B="SCROLLING_UPWARDS":B="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:B,state:O}},v0),lt((w,S)=>w&&w.atBottom===S.atBottom))),m=At(q(r,xn((w,{scrollHeight:S,scrollTop:k,viewportHeight:C})=>{if(Gd(w.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:k};{const T=S-(k+C)<1;return w.scrollTop!==k&&T?{changed:!0,jump:w.scrollTop-k,scrollHeight:S,scrollTop:k}:{changed:!0,jump:0,scrollHeight:S,scrollTop:k}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ne(w=>w.changed),ie(w=>w.jump)),0);he(q(y,ie(w=>w.atBottom)),i),he(q(i,kn(50)),l);const x=Q(to);he(q(r,ie(({scrollTop:w})=>w),lt(),xn((w,S)=>yt(p)?{direction:w.direction,prevScrollTop:S}:{direction:S<w.prevScrollTop?eo:to,prevScrollTop:S},{direction:to,prevScrollTop:0}),ie(w=>w.direction)),x),he(q(r,kn(50),gn(y0)),x);const g=Q(0);return he(q(h,Ne(w=>!w),gn(0)),g),he(q(o,kn(100),Oe(h),Ne(([w,S])=>!!S),xn(([w,S],[k])=>[S,k],[0,0]),ie(([w,S])=>S-w)),g),{atBottomState:y,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:m,scrollDirection:x,scrollVelocity:g}},at(Lt)),vs="top",ws="bottom",Yd="none";function Xd(e,t,n){return typeof e=="number"?n===eo&&t===vs||n===to&&t===ws?e:0:n===eo?t===vs?e.main:e.reverse:t===ws?e.main:e.reverse}function Jd(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const pa=Ge(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=He(),i=Q(0),a=Q(0),l=Q(0),c=At(q(vt(ke(r),ke(o),ke(n),ke(s,Xr),ke(l),ke(i),ke(t),ke(e),ke(a)),ie(([d,f,h,[p,y],m,x,g,w,S])=>{const k=d-w,C=x+g,T=Math.max(h-k,0);let I=Yd;const j=Jd(S,vs),_=Jd(S,ws);return p-=w,p+=h+g,y+=h+g,y-=w,p>d+C-j&&(I=eo),y<d-T+f+_&&(I=to),I!==Yd?[Math.max(k-h-Xd(m,vs,I)-j,0),k-T-g+f+Xd(m,ws,I)+_]:null}),Ne(d=>d!=null),lt(Xr)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},at(Lt),{singleton:!0});function b0(e,t,n){if(ys(t)){const r=Hd(e,t);return[{index:sn(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const ma={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function bs(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const m=e[e.length-1];d=m.offset+m.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,y=h-d;return{bottom:d,firstItemIndex:s,items:Qd(e,o,s),offsetBottom:y,offsetTop:c,top:p,topItems:Qd(t,o,s),topListHeight:t.reduce((m,x)=>x.size+m,0),totalCount:n}}function Zd(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=ha(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return bs(c,[],a,o,n,r)}function Qd(e,t,n){if(e.length===0)return[];if(!ys(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=ms(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const er=Ge(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},h,{didMount:p},{recalcInProgress:y}])=>{const m=Q([]),x=Q(0),g=He();he(s.topItemsIndexes,m);const w=At(q(vt(p,y,ke(l,Xr),ke(o),ke(r),ke(c),d,ke(m),ke(t),ke(n),e),Ne(([T,I,,j,,,,,,,_])=>{const O=_&&_.length!==j;return T&&!I&&!O}),ie(([,,[T,I],j,_,O,B,K,V,P,M])=>{const N=_,{offsetTree:z,sizeTree:L}=N,R=yt(x);if(j===0)return{...ma,totalCount:j};if(T===0&&I===0)return R===0?{...ma,totalCount:j}:Zd(R,O,_,V,P,M||[]);if(ot(L))return R>0?null:bs(b0(ha(O,j),N,M),[],j,P,N,V);const W=[];if(K.length>0){const Ie=K[0],ve=K[K.length-1];let te=0;for(const F of ms(L,Ie,ve)){const X=F.value,A=Math.max(F.start,Ie),$=Math.min(F.end,ve);for(let H=A;H<=$;H++)W.push({data:M==null?void 0:M[H],index:H,offset:te,size:X}),te+=X}}if(!B)return bs([],W,j,P,N,V);const Y=K.length>0?K[K.length-1]+1:0,ne=c0(z,T,I,Y);if(ne.length===0)return null;const pe=j-1,be=ps([],Ie=>{for(const ve of ne){const te=ve.value;let F=te.offset,X=ve.start;const A=te.size;if(te.offset<T){X+=Math.floor((T-te.offset+P)/(A+P));const H=X-ve.start;F+=H*A+H*P}X<Y&&(F+=(Y-X)*A,X=Y);const $=Math.min(ve.end,pe);for(let H=X;H<=$&&!(F>=I);H++)Ie.push({data:M==null?void 0:M[H],index:H,offset:F,size:A}),F+=A+P}});return bs(be,W,j,P,N,V)}),Ne(T=>T!==null),lt()),ma);he(q(e,Ne(ta),ie(T=>T==null?void 0:T.length)),o),he(q(w,ie(T=>T.topListHeight)),f),he(f,a),he(q(w,ie(T=>[T.top,T.bottom])),i),he(q(w,ie(T=>T.items)),g);const S=Vt(q(w,Ne(({items:T})=>T.length>0),Oe(o,e),Ne(([{items:T},I])=>T[T.length-1].originalIndex===I-1),ie(([,T,I])=>[T-1,I]),lt(Xr),ie(([T])=>T))),k=Vt(q(w,kn(200),Ne(({items:T,topItems:I})=>T.length>0&&T[0].originalIndex===I.length),ie(({items:T})=>T[0].index),lt())),C=Vt(q(w,Ne(({items:T})=>T.length>0),ie(({items:T})=>{let I=0,j=T.length-1;for(;T[I].type==="group"&&I<j;)I++;for(;T[j].type==="group"&&j>I;)j--;return{endIndex:T[j].index,startIndex:T[I].index}}),lt(zd)));return{endReached:S,initialItemCount:x,itemsRendered:g,listState:w,rangeChanged:C,startReached:k,topItemsIndexes:m,...h}},at(yn,Kd,pa,Qr,Zr,no,On,ca),{singleton:!0}),ef=Ge(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=He(),i=At(q(vt(n,e,r,t,o),ie(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return he(ke(i),s),{totalListHeight:i,totalListHeightChanged:s}},at(Lt,er),{singleton:!0}),S0=Ge(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Q(!1),r=At(q(vt(n,e,t),Ne(([o])=>o),ie(([,o,s])=>Math.max(0,o-s)),kn(0),lt()),0);return{alignToBottom:n,paddingTopAddition:r}},at(Lt,ef),{singleton:!0}),tf=Ge(()=>({context:Q(null)})),C0=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,nf=Ge(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=He();return he(q(d,Oe(t,l,n,s,o,r,a),Oe(e),ie(([[f,h,p,y,m,x,g,w],S])=>{const{align:k,behavior:C,calculateViewLocation:T=C0,done:I,...j}=f,_=Wd(f,h,y-1),O=Jr(_,h.offsetTree,S)+m+x,B=O+sn(h.sizeTree,_)[1],K=w+x,V=w+p-g,P=T({itemBottom:B,itemTop:O,locationParams:{align:k,behavior:C,...j},viewportBottom:V,viewportTop:K});return P?I&&on(q(i,Ne(M=>!M),Jn(yt(i)?1:2)),I):I&&I(),P}),Ne(f=>f!==null)),c),{scrollIntoView:d}},at(yn,Lt,Zr,er,Pn),{singleton:!0});function rf(e){return e?e==="smooth"?"smooth":"auto":!1}const T0=(e,t)=>typeof e=="function"?rf(e(t)):t&&rf(e),k0=Ge(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:h},{scrollIntoView:p}])=>{const y=Q(!1),m=He();let x=null;function g(C){Pe(i,{align:"end",behavior:C,index:"LAST"})}Ze(q(vt(q(ke(t),Jn(1)),l),Oe(ke(y),s,a,f),ie(([[C,T],I,j,_,O])=>{let B=T&&_,K="auto";return B&&(K=T0(I,j||O),B=B&&!!K),{followOutputBehavior:K,shouldFollow:B,totalCount:C}}),Ne(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:T})=>{x&&(x(),x=null),yt(n)?requestAnimationFrame(()=>{yt(d)("following output to ",{totalCount:T},zt.DEBUG),g(C)}):x=on(e,()=>{yt(d)("following output to ",{totalCount:T},zt.DEBUG),g(C),x=null})});function w(C){const T=on(o,I=>{C&&!I.atBottom&&I.notAtBottomBecause==="SIZE_INCREASED"&&!x&&(yt(d)("scrolling to bottom due to increased size",{},zt.DEBUG),g("auto"))});setTimeout(T,100)}Ze(q(vt(ke(y),t,c),Ne(([C,,T])=>C&&T),xn(({value:C},[,T])=>({refreshed:C===T,value:T}),{refreshed:!1,value:0}),Ne(({refreshed:C})=>C),Oe(y,t)),([,C])=>{yt(a)&&w(C!==!1)}),Ze(m,()=>{w(yt(y)!==!1)}),Ze(vt(ke(y),o),([C,T])=>{C&&!T.atBottom&&T.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&g("auto")});const S=Q(null),k=He();return he(ra(q(ke(r),ie(C=>{var T;return(T=C==null?void 0:C.length)!=null?T:0})),q(ke(t))),k),Ze(q(vt(q(k,Jn(1)),l),Oe(ke(S),a,f,h),ie(([[C,T],I,j,_,O])=>T&&j&&(I==null?void 0:I({context:O,totalCount:C,scrollingInProgress:_}))),Ne(C=>!!C),kn(0)),C=>{x&&(x(),x=null),yt(n)?requestAnimationFrame(()=>{yt(d)("scrolling into view",{}),Pe(p,C)}):x=on(e,()=>{yt(d)("scrolling into view",{}),Pe(p,C),x=null})}),{autoscrollToBottom:m,followOutput:y,scrollIntoViewOnChange:S}},at(yn,no,Zr,Qr,On,Pn,Lt,tf,nf)),I0=Ge(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(he(q(a,Oe(s),Ne(([,l])=>l!==0),Oe(o,r,t,n,e),ie(([[,l],c,d,f,h,p=[]])=>Zd(l,c,d,f,h,p))),i),{}),at(yn,Qr,er,On),{singleton:!0}),E0=Ge(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=Q(0);return Ze(q(e,Oe(r),Ne(([,o])=>o!==0),ie(([,o])=>({top:o}))),o=>{on(q(n,Jn(1),Ne(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Pe(t,o)})})}),{initialScrollTop:r}},at(On,Lt,er),{singleton:!0}),of=Ge(([{scrollVelocity:e}])=>{const t=Q(!1),n=He(),r=Q(!1);return he(q(e,Oe(r,t,n),Ne(([o,s])=>!!s),ie(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),lt()),t),Ze(q(vt(t,e,n),Oe(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},at(no),{singleton:!0}),ga=Ge(([{scrollContainerState:e,scrollTo:t}])=>{const n=He(),r=He(),o=He(),s=Q(!1),i=Q(void 0);return he(q(vt(n,r),ie(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),he(q(t,Oe(r),ie(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},at(Lt)),N0=Ge(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=He(),d=Q(void 0),f=Q(null),h=Q(null);return he(a,f),he(l,h),Ze(q(c,Oe(t,r,i,f,h,n)),([p,y,m,x,g,w,S])=>{const k=d0(y.sizeTree);x&&g!==null&&w!==null&&(m=g.scrollTop-w.offsetTop),m-=S,p({ranges:k,scrollTop:m})}),he(q(d,Ne(ta),ie(A0)),o),he(q(s,Oe(d),Ne(([,p])=>p!==void 0),lt(),ie(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},at(yn,Lt,Qr,On,ga));function A0(e){return{align:"start",index:0,offset:e.scrollTop}}const j0=Ge(([{topItemsIndexes:e}])=>{const t=Q(0);return he(q(t,Ne(n=>n>=0),ie(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},at(er));function sf(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const _0=sf(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),M0=Ge(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:h},{log:p},{recalcInProgress:y}])=>{const m=Vt(q(l,Oe(i),xn(([,g,w,S],[{bottom:k,items:C,offsetBottom:T,totalCount:I},j])=>{const _=k+T;let O=0;return w===I&&g.length>0&&C.length>0&&(C[0].originalIndex===0&&g[0].originalIndex===0||(O=_-S,O!==0&&(O+=j))),[O,C,I,_]},[0,[],0,0]),Ne(([g])=>g!==0),Oe(r,a,n,o,p,y),Ne(([,g,w,S,,,k])=>!k&&!S&&g!==0&&w===eo),ie(([[g],,,,,w])=>(w("Upward scrolling compensation",{amount:g},zt.DEBUG),g))));function x(g){g>0?(Pe(t,{behavior:"auto",top:-g}),Pe(e,0)):(Pe(e,0),Pe(t,{behavior:"auto",top:-g}))}return Ze(q(m,Oe(e,s)),([g,w,S])=>{S&&_0()?Pe(e,w-g):x(-g)}),Ze(q(vt(At(s,!1),e,y),Ne(([g,w,S])=>!g&&!S&&w!==0),ie(([g,w])=>w),kn(1)),x),he(q(f,ie(g=>({top:-g}))),t),Ze(q(c,Oe(h,d),ie(([g,{groupIndices:w,lastSize:S,sizeTree:k},C])=>{function T(I){return I*(S+C)}if(w.length===0)return T(g);{let I=0;const j=Yr(k,0);let _=0,O=0;for(;_<g;){_++,I+=j;let B=w.length===O+1?1/0:w[O+1]-w[O]-1;_+B>g&&(I-=j,B=g-_+1),_+=B,I+=T(B),O++}return I}})),g=>{Pe(e,g),requestAnimationFrame(()=>{Pe(t,{top:g}),requestAnimationFrame(()=>{Pe(e,0),Pe(y,!1)})})}),{deviation:e}},at(Lt,no,er,yn,Pn,ca)),P0=Ge(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),at(pa,I0,On,of,ef,E0,S0,ga,nf,Pn,tf)),af=Ge(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:y},m,x,g,{listState:w,topItemsIndexes:S,...k},{scrollToIndex:C},T,{topItemCount:I},{groupCounts:j},_])=>(he(k.rangeChanged,_.scrollSeekRangeChanged),he(q(_.windowViewportRect,ie(O=>O.visibleHeight)),m.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:j,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:y,sizeRanges:a,topItemCount:I,topItemsIndexes:S,totalCount:d,...g,groupIndices:s,itemSize:i,listState:w,scrollToIndex:C,statefulTotalCount:c,trackItemSizes:f,...k,..._,...m,sizes:l,...x}),at(yn,Qr,Lt,N0,k0,er,Zr,M0,j0,Kd,P0));function R0(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const Ss=typeof document<"u"?b.useLayoutEffect:b.useEffect;function lf(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=b.createContext({});function l(x,g){x.propsReady&&Pe(x.propsReady,!1);for(const w of r){const S=x[t.required[w]];Pe(S,g[w])}for(const w of o)if(w in g){const S=x[t.optional[w]];Pe(S,g[w])}x.propsReady&&Pe(x.propsReady,!0)}function c(x){return s.reduce((g,w)=>(g[w]=S=>{const k=x[t.methods[w]];Pe(k,S)},g),{})}function d(x){return i.reduce((g,w)=>(g[w]=Xb(x[t.events[w]]),g),{})}const f=b.forwardRef((x,g)=>{const{children:w,...S}=x,[k]=b.useState(()=>ps(Zb(e),I=>{l(I,S)})),[C]=b.useState(jd(d,k));Ss(()=>{for(const I of i)I in S&&Ze(C[I],S[I]);return()=>{Object.values(C).map(na)}},[S,C,k]),Ss(()=>{l(k,S)}),b.useImperativeHandle(g,Nd(c(k)));const T=n;return u.jsx(a.Provider,{value:k,children:n?u.jsx(T,{...R0([...r,...o,...i],S),children:w}):w})}),h=x=>{const g=b.useContext(a);return b.useCallback(w=>{Pe(g[x],w)},[g,x])},p=x=>{const g=b.useContext(a)[x],w=b.useCallback(S=>Ze(g,S),[g]);return b.useSyncExternalStore(w,()=>yt(g),()=>yt(g))},y=x=>{const g=b.useContext(a)[x],[w,S]=b.useState(jd(yt,g));return Ss(()=>Ze(g,k=>{k!==w&&S(Nd(k))}),[g,w]),w},m=b.version.startsWith("18")?p:y;return{Component:f,useEmitter:(x,g)=>{const w=b.useContext(a)[x];Ss(()=>Ze(w,g),[g,w])},useEmitterValue:m,usePublisher:h}}const cf=b.createContext(void 0),uf=b.createContext(void 0),df=typeof document<"u"?b.useLayoutEffect:b.useEffect;function xa(e){return"self"in e}function O0(e){return"body"in e}function ff(e,t,n,r=kr,o,s){const i=b.useRef(null),a=b.useRef(null),l=b.useRef(null),c=b.useCallback(h=>{let p,y,m;const x=h.target;if(O0(x)||xa(x)){const w=xa(x)?x:x.defaultView;m=s?w.scrollX:w.scrollY,p=s?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,y=s?w.innerWidth:w.innerHeight}else m=s?x.scrollLeft:x.scrollTop,p=s?x.scrollWidth:x.scrollHeight,y=s?x.offsetWidth:x.offsetHeight;const g=()=>{e({scrollHeight:p,scrollTop:Math.max(m,0),viewportHeight:y})};h.suppressFlushSync?g():Js.flushSync(g),a.current!==null&&(m===a.current||m<=0||m===p-y)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);b.useEffect(()=>{const h=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:h}),h.addEventListener("scroll",c,{passive:!0}),()=>{r(null),h.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(h){const p=i.current;if(!p||(s?"offsetWidth"in p&&p.offsetWidth===0:"offsetHeight"in p&&p.offsetHeight===0))return;const y=h.behavior==="smooth";let m,x,g;xa(p)?(x=Math.max(Rn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),m=s?p.innerWidth:p.innerHeight,g=s?window.scrollX:window.scrollY):(x=p[s?"scrollWidth":"scrollHeight"],m=Rn(p,s?"width":"height"),g=p[s?"scrollLeft":"scrollTop"]);const w=x-m;if(h.top=Math.ceil(Math.max(Math.min(w,h.top),0)),Gd(m,x)||h.top===g){e({scrollHeight:x,scrollTop:g,viewportHeight:m}),y&&t(!0);return}y?(a.current=h.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(h={behavior:h.behavior,left:h.top}),p.scrollTo(h)}function f(h){s&&(h={behavior:h.behavior,left:h.top}),i.current.scrollBy(h)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const ya="-webkit-sticky",hf="sticky",va=sf(()=>{if(typeof document>"u")return hf;const e=document.createElement("div");return e.style.position=ya,e.style.position===ya?ya:hf});function wa(e){return e}const D0=Ge(()=>{const e=Q(a=>`Item ${a}`),t=Q(a=>`Group ${a}`),n=Q({}),r=Q(wa),o=Q("div"),s=Q(kr),i=(a,l=null)=>At(q(n,ie(c=>c[a]),lt()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),L0=Ge(([e,t])=>({...e,...t}),at(af,D0)),$0=({height:e})=>u.jsx("div",{style:{height:e}}),F0={overflowAnchor:"none",position:va(),zIndex:1},pf={overflowAnchor:"none"},B0={...pf,display:"inline-block",height:"100%"},mf=b.memo(function({showTopList:e=!1}){const t=je("listState"),n=Xt("sizeRanges"),r=je("useWindowScroll"),o=je("customScrollParent"),s=Xt("windowScrollContainerState"),i=Xt("scrollContainerState"),a=o||r?s:i,l=je("itemContent"),c=je("context"),d=je("groupContent"),f=je("trackItemSizes"),h=je("itemSize"),p=je("log"),y=Xt("gap"),m=je("horizontalDirection"),{callbackRef:x}=t0(n,h,f,e?kr:a,p,y,o,m,je("skipAnimationFrameInResizeObserver")),[g,w]=b.useState(0);ba("deviation",P=>{g!==P&&w(P)});const S=je("EmptyPlaceholder"),k=je("ScrollSeekPlaceholder")||$0,C=je("ListComponent"),T=je("ItemComponent"),I=je("GroupComponent"),j=je("computeItemKey"),_=je("isSeeking"),O=je("groupIndices").length>0,B=je("alignToBottom"),K=je("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...m?{display:"inline-block",height:"100%",marginLeft:g!==0?g:B?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:g!==0?g:B?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...K?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...jt(S,c)}):u.jsx(C,{...jt(C,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:x,style:V,children:(e?t.topItems:t.items).map(P=>{const M=P.originalIndex,N=j(M+t.firstItemIndex,P.data,c);return _?b.createElement(k,{...jt(k,c),height:P.size,index:P.index,key:N,type:P.type||"item",...P.type==="group"?{}:{groupIndex:P.groupIndex}}):P.type==="group"?b.createElement(I,{...jt(I,c),"data-index":M,"data-item-index":P.index,"data-known-size":P.size,key:N,style:F0},d(P.index,c)):b.createElement(T,{...jt(T,c),...W0(T,P.data),"data-index":M,"data-item-group-index":P.groupIndex,"data-item-index":P.index,"data-known-size":P.size,key:N,style:m?B0:pf},O?l(P.index,P.groupIndex,P.data,c):l(P.index,P.data,c))})})}),z0={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},U0={outline:"none",overflowX:"auto",position:"relative"},Cs=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),H0={position:va(),top:0,width:"100%",zIndex:1};function jt(e,t){if(typeof e!="string")return{context:t}}function W0(e,t){return{item:typeof e=="string"?void 0:t}}const V0=b.memo(function(){const e=je("HeaderComponent"),t=Xt("headerHeight"),n=je("HeaderFooterTag"),r=Zn(b.useMemo(()=>s=>{t(Rn(s,"height"))},[t]),!0,je("skipAnimationFrameInResizeObserver")),o=je("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null}),K0=b.memo(function(){const e=je("FooterComponent"),t=Xt("footerHeight"),n=je("HeaderFooterTag"),r=Zn(b.useMemo(()=>s=>{t(Rn(s,"height"))},[t]),!0,je("skipAnimationFrameInResizeObserver")),o=je("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null});function gf({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:p,scrollToCallback:y}=ff(a,c,l,d,void 0,f);return e("scrollTo",y),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?U0:z0,...o},tabIndex:0,...i,...jt(l,s),children:r})})}function xf({useEmitter:e,useEmitterValue:t,usePublisher:n}){return b.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),h=t("customScrollParent"),p=b.useRef(null),y=t("scrollerRef"),{scrollByCallback:m,scrollerRef:x,scrollToCallback:g}=ff(a,c,l,y,h);return df(()=>{var w;return x.current=h||((w=p.current)==null?void 0:w.ownerDocument.defaultView),()=>{x.current=null}},[x,h]),e("windowScrollTo",g),e("scrollBy",m),u.jsx(l,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...jt(l,s),children:r})})}const q0=({children:e})=>{const t=b.useContext(cf),n=Xt("viewportHeight"),r=Xt("fixedItemHeight"),o=je("alignToBottom"),s=je("horizontalDirection"),i=b.useMemo(()=>Ad(n,l=>Rn(l,s?"width":"height")),[n,s]),a=Zn(i,!0,je("skipAnimationFrameInResizeObserver"));return b.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:Cs(o),children:e})},G0=({children:e})=>{const t=b.useContext(cf),n=Xt("windowViewportRect"),r=Xt("fixedItemHeight"),o=je("customScrollParent"),s=Rd(n,o,je("skipAnimationFrameInResizeObserver")),i=je("alignToBottom");return b.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:Cs(i),children:e})},Y0=({children:e})=>{const t=je("TopItemListComponent")||"div",n=je("headerHeight"),r={...H0,marginTop:`${n}px`},o=je("context");return u.jsx(t,{style:r,...jt(t,o),children:e})},X0=b.memo(function(e){const t=je("useWindowScroll"),n=je("topItemsIndexes").length>0,r=je("customScrollParent"),o=je("context");return u.jsxs(r||t?Q0:Z0,{...e,context:o,children:[n&&u.jsx(Y0,{children:u.jsx(mf,{showTopList:!0})}),u.jsxs(r||t?G0:q0,{children:[u.jsx(V0,{}),u.jsx(mf,{}),u.jsx(K0,{})]})]})}),{Component:J0,useEmitter:ba,useEmitterValue:je,usePublisher:Xt}=lf(L0,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},X0),Z0=gf({useEmitter:ba,useEmitterValue:je,usePublisher:Xt}),Q0=xf({useEmitter:ba,useEmitterValue:je,usePublisher:Xt}),eS=J0;at(af,Ge(()=>{const e=Q(c=>u.jsxs("td",{children:["Item $",c]})),t=Q(null),n=Q(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=Q(null),o=Q(null),s=Q({}),i=Q(wa),a=Q(kr),l=(c,d=null)=>At(q(s,ie(f=>f[c]),lt()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),va();const yf={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},tS={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:vf,floor:Ts,max:ro,min:Sa,round:wf}=Math;function bf(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function nS(e){return{...tS,items:e}}function ks(e,t){return e&&e.width===t.width&&e.height===t.height}function rS(e,t){return e&&e.column===t.column&&e.row===t.row}const oS=Ge(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},h,p,{didMount:y,propsReady:m},{customScrollParent:x,useWindowScroll:g,windowScrollContainerState:w,windowScrollTo:S,windowViewportRect:k},C])=>{const T=Q(0),I=Q(0),j=Q(yf),_=Q({height:0,width:0}),O=Q({height:0,width:0}),B=He(),K=He(),V=Q(0),P=Q(null),M=Q({column:0,row:0}),N=He(),z=He(),L=Q(!1),R=Q(0),W=Q(!0),Y=Q(!1),ne=Q(!1);Ze(q(y,Oe(R),Ne(([F,X])=>!!X)),()=>{Pe(W,!1)}),Ze(q(vt(y,W,O,_,R,Y),Ne(([F,X,A,$,,H])=>F&&!X&&A.height!==0&&$.height!==0&&!H)),([,,,,F])=>{Pe(Y,!0),fa(1,()=>{Pe(B,F)}),on(q(c),()=>{Pe(t,[0,0]),Pe(W,!0)})}),he(q(z,Ne(F=>F!=null&&F.scrollTop>0),gn(0)),I),Ze(q(y,Oe(z),Ne(([,F])=>F!=null)),([,F])=>{F&&(Pe(_,F.viewport),Pe(O,F.item),Pe(M,F.gap),F.scrollTop>0&&(Pe(L,!0),on(q(c,Jn(1)),X=>{Pe(L,!1)}),Pe(l,{top:F.scrollTop})))}),he(q(_,ie(({height:F})=>F)),f),he(q(vt(ke(_,ks),ke(O,ks),ke(M,(F,X)=>F&&F.column===X.column&&F.row===X.row),ke(c)),ie(([F,X,A,$])=>({gap:A,item:X,scrollTop:$,viewport:F}))),N),he(q(vt(ke(T),r,ke(M,rS),ke(O,ks),ke(_,ks),ke(P),ke(I),ke(L),ke(W),ke(R)),Ne(([,,,,,,,F])=>!F),ie(([F,[X,A],$,H,fe,re,Z,,ce,me])=>{const{column:$e,row:Re}=$,{height:Be,width:Xe}=H,{width:Qe}=fe;if(Z===0&&(F===0||Qe===0))return yf;if(Xe===0){const Pt=ha(me,F),$t=Pt+Math.max(Z-1,0);return nS(bf(Pt,$t,re))}const Je=Sf(Qe,Xe,$e);let et,it;ce?X===0&&A===0&&Z>0?(et=0,it=Z-1):(et=Je*Ts((X+Re)/(Be+Re)),it=Je*vf((A+Re)/(Be+Re))-1,it=Sa(F-1,ro(it,Je-1)),et=Sa(it,ro(0,et))):(et=0,it=-1);const Mt=bf(et,it,re),{bottom:pt,top:Ct}=Cf(fe,$,H,Mt),mt=vf(F/Je),wt=mt*Be+(mt-1)*Re-pt;return{bottom:pt,itemHeight:Be,items:Mt,itemWidth:Xe,offsetBottom:wt,offsetTop:Ct,top:Ct}})),j),he(q(P,Ne(F=>F!==null),ie(F=>F.length)),T),he(q(vt(_,O,j,M),Ne(([F,X,{items:A}])=>A.length>0&&X.height!==0&&F.height!==0),ie(([F,X,{items:A},$])=>{const{bottom:H,top:fe}=Cf(F,$,X,A);return[fe,H]}),lt(Xr)),t);const pe=Q(!1);he(q(c,Oe(pe),ie(([F,X])=>X||F!==0)),pe);const be=Vt(q(vt(j,T),Ne(([{items:F}])=>F.length>0),Oe(pe),Ne(([[F,X],A])=>{const $=F.items[F.items.length-1].index===X-1;return(A||F.bottom>0&&F.itemHeight>0&&F.offsetBottom===0&&F.items.length===X)&&$}),ie(([[,F]])=>F-1),lt())),Ie=Vt(q(ke(j),Ne(({items:F})=>F.length>0&&F[0].index===0),gn(0),lt())),ve=Vt(q(ke(j),Oe(L),Ne(([{items:F},X])=>F.length>0&&!X),ie(([{items:F}])=>({endIndex:F[F.length-1].index,startIndex:F[0].index})),lt(zd),kn(0)));he(ve,p.scrollSeekRangeChanged),he(q(B,Oe(_,O,T,M),ie(([F,X,A,$,H])=>{const fe=qd(F),{align:re,behavior:Z,offset:ce}=fe;let me=fe.index;me==="LAST"&&(me=$-1),me=ro(0,me,Sa($-1,me));let $e=Ca(X,H,A,me);return re==="end"?$e=wf($e-X.height+A.height):re==="center"&&($e=wf($e-X.height/2+A.height/2)),ce&&($e+=ce),{behavior:Z,top:$e}})),l);const te=At(q(j,ie(F=>F.offsetBottom+F.bottom)),0);return he(q(k,ie(F=>({height:F.visibleHeight,width:F.visibleWidth}))),_),{customScrollParent:x,data:P,deviation:V,footerHeight:o,gap:M,headerHeight:s,increaseViewportBy:e,initialItemCount:I,itemDimensions:O,overscan:n,restoreStateFrom:z,scrollBy:i,scrollContainerState:a,scrollHeight:K,scrollTo:l,scrollToIndex:B,scrollTop:c,smoothScrollTargetReached:d,totalCount:T,useWindowScroll:g,viewportDimensions:_,windowScrollContainerState:w,windowScrollTo:S,windowViewportRect:k,...p,gridState:j,horizontalDirection:ne,initialTopMostItemIndex:R,totalListHeight:te,...h,endReached:be,propsReady:m,rangeChanged:ve,startReached:Ie,stateChanged:N,stateRestoreInProgress:L,...C}},at(pa,Lt,no,of,On,ga,Pn));function Sf(e,t,n){return ro(1,Ts((e+n)/(Ts(t)+n)))}function Cf(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Ca(e,t,n,r[0].index);return{bottom:Ca(e,t,n,r[r.length-1].index)+o,top:s}}function Ca(e,t,n,r){const o=Sf(e.width,n.width,t.column),s=Ts(r/o),i=s*n.height+ro(0,s-1)*t.row;return i>0?i+t.row:i}const sS=Ge(()=>{const e=Q(f=>`Item ${f}`),t=Q({}),n=Q(null),r=Q("virtuoso-grid-item"),o=Q("virtuoso-grid-list"),s=Q(wa),i=Q("div"),a=Q(kr),l=(f,h=null)=>At(q(t,ie(p=>p[f]),lt()),h),c=Q(!1),d=Q(!1);return he(ke(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),iS=Ge(([e,t])=>({...e,...t}),at(oS,sS)),aS=b.memo(function(){const e=dt("gridState"),t=dt("listClassName"),n=dt("itemClassName"),r=dt("itemContent"),o=dt("computeItemKey"),s=dt("isSeeking"),i=Jt("scrollHeight"),a=dt("ItemComponent"),l=dt("ListComponent"),c=dt("ScrollSeekPlaceholder"),d=dt("context"),f=Jt("itemDimensions"),h=Jt("gap"),p=dt("log"),y=dt("stateRestoreInProgress"),m=Jt("reportReadyState"),x=Zn(b.useMemo(()=>g=>{const w=g.parentElement.parentElement.scrollHeight;i(w);const S=g.firstChild;if(S){const{height:k,width:C}=S.getBoundingClientRect();f({height:k,width:C})}h({column:kf("column-gap",getComputedStyle(g).columnGap,p),row:kf("row-gap",getComputedStyle(g).rowGap,p)})},[i,f,h,p]),!0,!1);return df(()=>{e.itemHeight>0&&e.itemWidth>0&&m(!0)},[e]),y?null:u.jsx(l,{className:t,ref:x,...jt(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(g=>{const w=o(g.index,g.data,d);return s?u.jsx(c,{...jt(c,d),height:e.itemHeight,index:g.index,width:e.itemWidth},w):b.createElement(a,{...jt(a,d),className:n,"data-index":g.index,key:w},r(g.index,g.data,d))})})}),lS=b.memo(function(){const e=dt("HeaderComponent"),t=Jt("headerHeight"),n=dt("headerFooterTag"),r=Zn(b.useMemo(()=>s=>{t(Rn(s,"height"))},[t]),!0,!1),o=dt("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null}),cS=b.memo(function(){const e=dt("FooterComponent"),t=Jt("footerHeight"),n=dt("headerFooterTag"),r=Zn(b.useMemo(()=>s=>{t(Rn(s,"height"))},[t]),!0,!1),o=dt("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null}),uS=({children:e})=>{const t=b.useContext(uf),n=Jt("itemDimensions"),r=Jt("viewportDimensions"),o=Zn(b.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return b.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:Cs(!1),children:e})},dS=({children:e})=>{const t=b.useContext(uf),n=Jt("windowViewportRect"),r=Jt("itemDimensions"),o=dt("customScrollParent"),s=Rd(n,o,!1);return b.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:Cs(!1),children:e})},fS=b.memo(function({...e}){const t=dt("useWindowScroll"),n=dt("customScrollParent"),r=n||t?pS:hS,o=n||t?dS:uS,s=dt("context");return u.jsx(r,{...e,...jt(r,s),children:u.jsxs(o,{children:[u.jsx(lS,{}),u.jsx(aS,{}),u.jsx(cS,{})]})})}),{useEmitter:Tf,useEmitterValue:dt,usePublisher:Jt}=lf(iS,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},fS),hS=gf({useEmitter:Tf,useEmitterValue:dt,usePublisher:Jt}),pS=xf({useEmitter:Tf,useEmitterValue:dt,usePublisher:Jt});function kf(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,zt.WARN),t==="normal"?0:parseInt(t??"0",10)}const mS=mo.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function If({className:e,variant:t,...n}){return u.jsx("div",{className:ee(mS({variant:t}),e),...n})}function Ta(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function Ef(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function oo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(oo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(Ef(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=oo(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function so(e){if(typeof e=="string")return e;if(Ef(e))return"";try{const t=oo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function gS(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function xS(e){const t=so(e);return typeof e=="string"&&gS(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Is(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ta(t);if(n!==null)return Is(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Is(e.content):e}function yS(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Nf(e){const t=e.content.find(s=>s.type==="tool_call"),n=e.additionalKwargs??{},r=typeof(t==null?void 0:t.id)=="string"&&t.id||typeof n.toolCallId=="string"&&n.toolCallId||(e.id.startsWith("tool-")?e.id.slice(5):void 0);return{name:(typeof(t==null?void 0:t.name)=="string"&&t.name||typeof n.toolName=="string"&&n.toolName||e.name&&String(e.name))??void 0,toolCallId:r??void 0}}function Es(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function vS(e){const t=r=>{try{const o=oo(r);return typeof o=="string"?o:JSON.stringify(o??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
87
- `)):t(e)}function wS(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function Af(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function bS(e){if(!e)return"image/png";const t=e.trim();return t?t.includes("/")?t:`image/${t}`:"image/png"}function SS(e){const t=[],n=r=>{r&&r.trim()&&t.push(r.trim())};return e&&(n(e.plotId),n(e.artifactId)),t}function CS({base64:e,url:t,formatHint:n,extras:r}){const o=typeof e=="string"&&e.length>0,s=bS(n),i=o?`data:${s};base64,${e}`:t,a=SS(r),l=a.length?a.join(" / "):void 0,c=l?`${l} artifact`:"artifact image";return{src:i,alt:c,label:l}}function TS(e){var o,s;const t=((o=e.content_base64)==null?void 0:o.trim())||void 0,n=((s=e.url)==null?void 0:s.trim())||void 0,r=e.format||e.mimeType||e.mime_type;return CS({base64:t,url:n,formatHint:r,extras:{plotId:e.plotId,artifactId:e.artifactId}})}async function jf(e,t){return await Ut(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function _f(e,t){return await(await jf(`/files/${e}/view`,t)).text()}async function kS(e,t){const n=await jf(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await Ut(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function IS(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await Ut("/files",{params:r})}var Ns="Dialog",[Mf,fk]=bn(Ns),[ES,an]=Mf(Ns),Pf=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=v.useRef(null),l=v.useRef(null),[c,d]=pr({prop:r,defaultProp:o??!1,onChange:s,caller:Ns});return u.jsx(ES,{scope:t,triggerRef:a,contentRef:l,contentId:Sn(),titleId:Sn(),descriptionId:Sn(),open:c,onOpenChange:d,onOpenToggle:v.useCallback(()=>d(f=>!f),[d]),modal:i,children:n})};Pf.displayName=Ns;var Rf="DialogTrigger",Of=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=an(Rf,n),s=Ue(t,o.triggerRef);return u.jsx(_e.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ea(o.open),...r,ref:s,onClick:ue(e.onClick,o.onOpenToggle)})});Of.displayName=Rf;var ka="DialogPortal",[NS,Df]=Mf(ka,{forceMount:void 0}),Lf=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=an(ka,t);return u.jsx(NS,{scope:t,forceMount:n,children:v.Children.map(r,i=>u.jsx(Gt,{present:n||s.open,children:u.jsx(Xo,{asChild:!0,container:o,children:i})}))})};Lf.displayName=ka;var As="DialogOverlay",$f=v.forwardRef((e,t)=>{const n=Df(As,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=an(As,e.__scopeDialog);return s.modal?u.jsx(Gt,{present:r||s.open,children:u.jsx(jS,{...o,ref:t})}):null});$f.displayName=As;var AS=Wn.createSlot("DialogOverlay.RemoveScroll"),jS=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=an(As,n);return u.jsx(ss,{as:AS,allowPinchZoom:!0,shards:[o.contentRef],children:u.jsx(_e.div,{"data-state":Ea(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),tr="DialogContent",Ff=v.forwardRef((e,t)=>{const n=Df(tr,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=an(tr,e.__scopeDialog);return u.jsx(Gt,{present:r||s.open,children:s.modal?u.jsx(_S,{...o,ref:t}):u.jsx(MS,{...o,ref:t})})});Ff.displayName=tr;var _S=v.forwardRef((e,t)=>{const n=an(tr,e.__scopeDialog),r=v.useRef(null),o=Ue(t,n.contentRef,r);return v.useEffect(()=>{const s=r.current;if(s)return zi(s)},[]),u.jsx(Bf,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault())})}),MS=v.forwardRef((e,t)=>{const n=an(tr,e.__scopeDialog),r=v.useRef(!1),o=v.useRef(!1);return u.jsx(Bf,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),Bf=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=an(tr,n),l=v.useRef(null),c=Ue(t,l);return Si(),u.jsxs(u.Fragment,{children:[u.jsx($o,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:u.jsx(Lo,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Ea(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(PS,{titleId:a.titleId}),u.jsx(OS,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Ia="DialogTitle",zf=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=an(Ia,n);return u.jsx(_e.h2,{id:o.titleId,...r,ref:t})});zf.displayName=Ia;var Uf="DialogDescription",Hf=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=an(Uf,n);return u.jsx(_e.p,{id:o.descriptionId,...r,ref:t})});Hf.displayName=Uf;var Wf="DialogClose",Vf=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=an(Wf,n);return u.jsx(_e.button,{type:"button",...r,ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))})});Vf.displayName=Wf;function Ea(e){return e?"open":"closed"}var Kf="DialogTitleWarning",[hk,qf]=_x(Kf,{contentName:tr,titleName:Ia,docsSlug:"dialog"}),PS=({titleId:e})=>{const t=qf(Kf),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
86
+ `).trim():n.replace(/</g,"&lt;").replace(/>/g,"&gt;").trim()}function w0(e,t=Ss){if(!e||typeof e!="string")throw new Error("Invalid content: must be a non-empty string");if(e.length>t)throw new Error(`Message exceeds maximum length of ${t} characters`);return e}function S0(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),w0(t),b0(t)}const Cs=0,On=1,Er=2,Kd=4;function qd(e){return()=>e}function C0(e){e()}function Gd(e,t){return n=>e(t(n))}function Yd(e,t){return()=>e(t)}function T0(e,t){return n=>e(t,n)}function ca(e){return e!==void 0}function k0(...e){return()=>{e.map(C0)}}function Nr(){}function Ts(e,t){return t(e),e}function I0(e,t){return t(e)}function it(...e){return e}function et(e,t){return e(On,t)}function Le(e,t){e(Cs,t)}function ua(e){e(Er)}function xt(e){return e(Kd)}function ve(e,t){return et(e,T0(t,Cs))}function ln(e,t){const n=e(On,r=>{n(),t(r)});return n}function Xd(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Jd(e,t){return e===t}function at(e=Jd){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function Me(e){return t=>n=>{e(n)&&t(n)}}function pe(e){return t=>Gd(t,e)}function yn(e){return t=>()=>{t(e)}}function ee(e,...t){const n=E0(...t);return(r,o)=>{switch(r){case Er:ua(e);return;case On:return et(e,n(o))}}}function vn(e,t){return n=>r=>{n(t=e(t,r))}}function Qn(e){return t=>n=>{e>0?e--:t(n)}}function Nn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function Fe(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);et(s,l=>{const c=n;n=n|a,t[i]=l,c!==o&&n===o&&r&&(r(),r=null)})}),s=>i=>{const a=()=>{s([i].concat(t))};n===o?a():r=a}}function E0(...e){return t=>e.reduceRight(I0,t)}function N0(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case On:return s?n===s?void 0:(r(),n=s,t=et(e,s),t):(r(),Nr);case Er:r(),n=null;return}}}function ie(e){let t=e;const n=We();return(r,o)=>{switch(r){case Cs:t=o;break;case On:{o(t);break}case Kd:return t}return n(r,o)}}function At(e,t){return Ts(ie(t),n=>ve(e,n))}function We(){const e=[];return(t,n)=>{switch(t){case Cs:e.slice().forEach(r=>{r(n)});return;case Er:e.splice(0,e.length);return;case On:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function qt(e){return Ts(We(),t=>ve(e,t))}function Xe(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:A0(),singleton:n}}const A0=()=>Symbol();function j0(e){const t=new Map,n=({constructor:r,dependencies:o,id:s,singleton:i})=>{if(i&&t.has(s))return t.get(s);const a=r(o.map(l=>n(l)));return i&&t.set(s,a),a};return n(e)}function vt(...e){const t=We(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,i)=>{const a=Math.pow(2,i);et(s,l=>{n[i]=l,r=r|a,r===o&&Le(t,n)})}),function(s,i){switch(s){case Er:{ua(t);return}case On:return r===o&&i(n),et(t,i)}}}function je(e,t=Jd){return ee(e,at(t))}function da(...e){return function(t,n){switch(t){case Er:return;case On:return k0(...e.map(r=>et(r,n)))}}}var Ut=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Ut||{});const _0={0:"debug",3:"error",1:"log",2:"warn"},M0=()=>typeof globalThis>"u"?window:globalThis,Dn=Xe(()=>{const e=ie(3);return{log:ie((t,n,r=1)=>{var o;const s=(o=M0().VIRTUOSO_LOG_LEVEL)!=null?o:xt(e);r>=s&&console[_0[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function er(e,t,n){return fa(e,t,n).callbackRef}function fa(e,t,n){const r=w.useRef(null);let o=i=>{};const s=w.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(i=>{const a=()=>{const l=i[0].target;l.offsetParent!==null&&e(l)};n?a():requestAnimationFrame(a)}):null,[e,n]);return o=i=>{i&&t?(s==null||s.observe(i),r.current=i):(r.current&&(s==null||s.unobserve(r.current)),r.current=null)},{callbackRef:o,ref:r}}function R0(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=P0(d.children,t,a?"offsetWidth":"offsetHeight",o);let p=d.parentElement;for(;!p.dataset.virtuosoScroller;)p=p.parentElement;const h=p.lastElementChild.dataset.viewportType==="window";let v;h&&(v=p.ownerDocument.defaultView);const g=i?a?i.scrollLeft:i.scrollTop:h?a?v.scrollX||v.document.documentElement.scrollLeft:v.scrollY||v.document.documentElement.scrollTop:a?p.scrollLeft:p.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:h?a?v.document.documentElement.scrollWidth:v.document.documentElement.scrollHeight:a?p.scrollWidth:p.scrollHeight,x=i?a?i.offsetWidth:i.offsetHeight:h?a?v.innerWidth:v.innerHeight:a?p.offsetWidth:p.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(g,0),viewportHeight:x}),s==null||s(a?Zd("column-gap",getComputedStyle(d).columnGap,o):Zd("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return fa(c,n,l)}function P0(e,t,n,r){const o=e.length;if(o===0)return null;const s=[];for(let i=0;i<o;i++){const a=e.item(i);if(a.dataset.index===void 0)continue;const l=parseInt(a.dataset.index),c=parseFloat(a.dataset.knownSize),d=t(a,n);if(d===0&&r("Zero-sized element, this should not happen",{child:a},Ut.ERROR),d===c)continue;const f=s[s.length-1];s.length===0||f.size!==d||f.endIndex!==l-1?s.push({endIndex:l,size:d,startIndex:l}):s[s.length-1].endIndex++}return s}function Zd(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ut.WARN),t==="normal"?0:parseInt(t??"0",10)}function Qd(e,t,n){const r=w.useRef(null),o=w.useCallback(l=>{if(!(l!=null&&l.offsetParent))return;const c=l.getBoundingClientRect(),d=c.width;let f,p;if(t){const h=t.getBoundingClientRect(),v=c.top-h.top;p=h.height-Math.max(0,v),f=v+t.scrollTop}else{const h=i.current.ownerDocument.defaultView;p=h.innerHeight-Math.max(0,c.top),f=c.top+h.scrollY}r.current={offsetTop:f,visibleHeight:p,visibleWidth:d},e(r.current)},[e,t]),{callbackRef:s,ref:i}=fa(o,!0,n),a=w.useCallback(()=>{o(i.current)},[o,i]);return w.useEffect(()=>{var l;if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(()=>{requestAnimationFrame(a)});return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else{const c=(l=i.current)==null?void 0:l.ownerDocument.defaultView;return c==null||c.addEventListener("scroll",a),c==null||c.addEventListener("resize",a),()=>{c==null||c.removeEventListener("scroll",a),c==null||c.removeEventListener("resize",a)}}},[a,t,i]),s}const $t=Xe(()=>{const e=We(),t=We(),n=ie(0),r=We(),o=ie(0),s=We(),i=We(),a=ie(0),l=ie(0),c=ie(0),d=ie(0),f=We(),p=We(),h=ie(!1),v=ie(!1),g=ie(!1);return ve(ee(e,pe(({scrollTop:y})=>y)),t),ve(ee(e,pe(({scrollHeight:y})=>y)),i),ve(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:v,scrollBy:p,scrollContainerState:e,scrollHeight:i,scrollingInProgress:h,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),to={lvl:0};function ef(e,t){const n=e.length;if(n===0)return[];let{index:r,value:o}=t(e[0]);const s=[];for(let i=1;i<n;i++){const{index:a,value:l}=t(e[i]);s.push({end:a-1,start:r,value:o}),r=a,o=l}return s.push({end:1/0,start:r,value:o}),s}function ot(e){return e===to}function no(e,t){if(!ot(e))return t===e.k?e.v:t<e.k?no(e.l,t):no(e.r,t)}function cn(e,t,n="k"){if(ot(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=cn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return cn(e.l,t,n)}function Gt(e,t,n){return ot(e)?rf(t,n,1):t===e.k?bt(e,{k:t,v:n}):t<e.k?of(bt(e,{l:Gt(e.l,t,n)})):of(bt(e,{r:Gt(e.r,t,n)}))}function Ar(){return to}function ks(e,t,n){if(ot(e))return[];const r=cn(e,t)[0];return O0(ha(e,r,n))}function pa(e,t){if(ot(e))return to;const{k:n,l:r,r:o}=e;if(t===n){if(ot(r))return o;if(ot(o))return r;{const[s,i]=nf(r);return Is(bt(e,{k:s,l:tf(r),v:i}))}}else return t<n?Is(bt(e,{l:pa(r,t)})):Is(bt(e,{r:pa(o,t)}))}function tr(e){return ot(e)?[]:[...tr(e.l),{k:e.k,v:e.v},...tr(e.r)]}function ha(e,t,n){if(ot(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(ha(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(ha(s,t,n))),a}function Is(e){const{l:t,lvl:n,r}=e;if(r.lvl>=n-1&&t.lvl>=n-1)return e;if(n>r.lvl+1){if(ma(t))return sf(bt(e,{lvl:n-1}));if(!ot(t)&&!ot(t.r))return bt(t.r,{l:bt(t,{r:t.r.l}),lvl:n,r:bt(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(ma(e))return ga(bt(e,{lvl:n-1}));if(!ot(r)&&!ot(r.l)){const o=r.l,s=ma(o)?r.lvl-1:r.lvl;return bt(o,{l:bt(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:ga(bt(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function bt(e,t){return rf(t.k!==void 0?t.k:e.k,t.v!==void 0?t.v:e.v,t.lvl!==void 0?t.lvl:e.lvl,t.l!==void 0?t.l:e.l,t.r!==void 0?t.r:e.r)}function tf(e){return ot(e.r)?e.l:Is(bt(e,{r:tf(e.r)}))}function ma(e){return ot(e)||e.lvl>e.r.lvl}function nf(e){return ot(e.r)?[e.k,e.v]:nf(e.r)}function rf(e,t,n,r=to,o=to){return{k:e,l:r,lvl:n,r:o,v:t}}function of(e){return ga(sf(e))}function sf(e){const{l:t}=e;return!ot(t)&&t.lvl===e.lvl?bt(t,{r:bt(e,{l:t.r})}):e}function ga(e){const{lvl:t,r:n}=e;return!ot(n)&&!ot(n.r)&&n.lvl===t&&n.r.lvl===t?bt(n,{l:bt(e,{r:n.l}),lvl:t+1}):e}function O0(e){return ef(e,({k:t,v:n})=>({index:t,value:n}))}function af(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function ro(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const xa=Xe(()=>({recalcInProgress:ie(!1)}),[],{singleton:!0});function lf(e,t,n){return e[Es(e,t,n)]}function Es(e,t,n,r=0){let o=e.length-1;for(;r<=o;){const s=Math.floor((r+o)/2),i=e[s],a=n(i,t);if(a===0)return s;if(a===-1){if(o-r<2)return s-1;o=s-1}else{if(o===r)return s;r=s+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function D0(e,t,n,r){const o=Es(e,t,r),s=Es(e,n,r,o);return e.slice(o,s+1)}function Ln(e,t){return Math.round(e.getBoundingClientRect()[t])}function Ns(e){return!ot(e.groupOffsetTree)}function ya({index:e},t){return t===e?0:t<e?-1:1}function L0(){return{groupIndices:[],groupOffsetTree:Ar(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Ar()}}function $0(e,t){let n=ot(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),ot(e)){e=Gt(e,0,s);continue}const a=ks(e,i-1,o+1);if(a.some(V0(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:p}of a)l?(o>=f||s===p)&&(e=pa(e,f)):(c=p!==s,l=!0),d>o&&o>=f&&p!==s&&(e=Gt(e,o+1,p));c&&(e=Gt(e,i,s))}return[e,n]}function F0(e){return typeof e.groupIndex<"u"}function B0({offset:e},t){return t===e?0:t<e?-1:1}function oo(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=lf(t,e,ya),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function cf(e,t){if(!Ns(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function uf(e,t,n){if(F0(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=cf(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function z0(e,t,n,r=0){return r>0&&(t=Math.max(t,lf(e,r,ya).offset)),ef(D0(e,t,n,B0),W0)}function U0(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,Ut.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&ot(s)&&t.length===2){const p=t[0].size,h=t[1].size;i=n.reduce((v,g)=>Gt(Gt(v,g,p),g+1,h),i)}else[i,a]=$0(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=va(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,h)=>Gt(p,h,oo(h,f,o)),Ar()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function H0(e){return tr(e).map(({k:t,v:n},r,o)=>{const s=o[r+1];return{endIndex:s?s.k-1:1/0,size:n,startIndex:t}})}function df(e,t){let n=0,r=0;for(;n<e;)n+=t[r+1]-t[r]-1,r++;return r-(n===e?0:1)}function va(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=Es(o,t-1,ya),a=o[l].offset;const c=cn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===cn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of ks(n,t,1/0)){const f=c-s,p=f*i+a+f*r;o.push({index:c,offset:p,size:d}),s=c,a=p,i=d}return{lastIndex:s,lastOffset:a,lastSize:i,offsetTree:o}}function W0(e){return{index:e.index,value:e}}function V0(e){const{endIndex:t,size:n,startIndex:r}=e;return o=>o.start===r&&(o.end===t||o.end===1/0)&&o.value===n}const K0={offsetHeight:"height",offsetWidth:"width"},bn=Xe(([{log:e},{recalcInProgress:t}])=>{const n=We(),r=We(),o=At(r,0),s=We(),i=We(),a=ie(0),l=ie([]),c=ie(void 0),d=ie(void 0),f=ie((T,S)=>Ln(T,K0[S])),p=ie(void 0),h=ie(0),v=L0(),g=At(ee(n,Fe(l,e,h),vn(U0,v),at()),v),y=At(ee(l,at(),vn((T,S)=>({current:S,prev:T.current}),{current:[],prev:[]}),pe(({prev:T})=>T)),[]);ve(ee(l,Me(T=>T.length>0),Fe(g,h),pe(([T,S,I])=>{const A=T.reduce((R,D,F)=>Gt(R,D,oo(D,S.offsetTree,I)||F),Ar());return{...S,groupIndices:T,groupOffsetTree:A}})),g),ve(ee(r,Fe(g),Me(([T,{lastIndex:S}])=>T<S),pe(([T,{lastIndex:S,lastSize:I}])=>[{endIndex:S,size:I,startIndex:T}])),n),ve(c,d);const x=At(ee(c,pe(T=>T===void 0)),!0);ve(ee(d,Me(T=>T!==void 0&&ot(xt(g).sizeTree)),pe(T=>[{endIndex:0,size:T,startIndex:0}])),n);const b=qt(ee(n,Fe(g),vn(({sizes:T},[S,I])=>({changed:I!==T,sizes:I}),{changed:!1,sizes:v}),pe(T=>T.changed)));et(ee(a,vn((T,S)=>({diff:T.prev-S,prev:S}),{diff:0,prev:0}),pe(T=>T.diff)),T=>{const{groupIndices:S}=xt(g);if(T>0)Le(t,!0),Le(s,T+df(T,S));else if(T<0){const I=xt(y);I.length>0&&(T-=df(-T,I)),Le(i,T)}}),et(ee(a,Fe(e)),([T,S])=>{T<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},Ut.ERROR)});const C=qt(s);ve(ee(s,Fe(g),pe(([T,S])=>{const I=S.groupIndices.length>0,A=[],R=S.lastSize;if(I){const D=no(S.sizeTree,0);let F=0,q=0;for(;F<T;){const _=S.groupIndices[q],j=S.groupIndices.length===q+1?1/0:S.groupIndices[q+1]-_-1;A.push({endIndex:_,size:D,startIndex:_}),A.push({endIndex:_+1+j-1,size:R,startIndex:_+1}),q++,F+=j+1}const W=tr(S.sizeTree);return F!==T&&W.shift(),W.reduce((_,{k:j,v:N})=>{let z=_.ranges;return _.prevSize!==0&&(z=[..._.ranges,{endIndex:j+T-1,size:_.prevSize,startIndex:_.prevIndex}]),{prevIndex:j+T,prevSize:N,ranges:z}},{prevIndex:T,prevSize:0,ranges:A}).ranges}return tr(S.sizeTree).reduce((D,{k:F,v:q})=>({prevIndex:F+T,prevSize:q,ranges:[...D.ranges,{endIndex:F+T-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:R,ranges:[]}).ranges})),n);const k=qt(ee(i,Fe(g,h),pe(([T,{offsetTree:S},I])=>{const A=-T;return oo(A,S,I)})));return ve(ee(i,Fe(g,h),pe(([T,S,I])=>{if(S.groupIndices.length>0){if(ot(S.sizeTree))return S;let A=Ar();const R=xt(y);let D=0,F=0,q=0;for(;D<-T;){q=R[F];const W=R[F+1]-q-1;F++,D+=W+1}if(A=tr(S.sizeTree).reduce((W,{k:_,v:j})=>Gt(W,Math.max(0,_+T),j),A),D!==-T){const W=no(S.sizeTree,q);A=Gt(A,0,W);const _=cn(S.sizeTree,-T+1)[1];A=Gt(A,1,_)}return{...S,sizeTree:A,...va(S.offsetTree,0,A,I)}}else{const A=tr(S.sizeTree).reduce((R,{k:D,v:F})=>Gt(R,Math.max(0,D+T),F),Ar());return{...S,sizeTree:A,...va(S.offsetTree,0,A,I)}}})),g),{beforeUnshiftWith:C,data:p,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:h,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:k,sizeRanges:n,sizes:g,statefulTotalCount:o,totalCount:r,trackItemSizes:x,unshiftWith:s}},it(Dn,xa),{singleton:!0});function q0(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const ff=Xe(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=We(),i=We(),a=qt(ee(s,pe(q0)));return ve(ee(a,pe(l=>l.totalCount)),n),ve(ee(a,pe(l=>l.groupIndices)),e),ve(ee(vt(o,t,r),Me(([l,c])=>Ns(c)),pe(([l,c,d])=>cn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),at(),pe(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},it(bn,$t)),$n=Xe(([{log:e}])=>{const t=ie(!1),n=qt(ee(t,Me(r=>r),at()));return et(t,r=>{r&&xt(e)("props updated",{},Ut.DEBUG)}),{didMount:n,propsReady:t}},it(Dn),{singleton:!0}),G0=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function pf(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!G0)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const so=Xe(([{gap:e,listRefresh:t,sizes:n,totalCount:r},{fixedFooterHeight:o,fixedHeaderHeight:s,footerHeight:i,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:f},{log:p}])=>{const h=We(),v=We(),g=ie(0);let y=null,x=null,b=null;function C(){y&&(y(),y=null),b&&(b(),b=null),x&&(clearTimeout(x),x=null),Le(l,!1)}return ve(ee(h,Fe(n,f,r,g,a,i,p),Fe(e,s,o),pe(([[k,T,S,I,A,R,D,F],q,W,_])=>{const j=pf(k),{align:N,behavior:z,offset:L}=j,P=I-1,V=uf(j,T,P);let ne=oo(V,T.offsetTree,q)+R;N==="end"?(ne+=W+cn(T.sizeTree,V)[1]-S+_,V===P&&(ne+=D)):N==="center"?ne+=(W+cn(T.sizeTree,V)[1]-S+_)/2:ne-=A,L&&(ne+=L);const M=Y=>{C(),Y?(F("retrying to scroll to",{location:k},Ut.DEBUG),Le(h,k)):(Le(v,!0),F("list did not change, scroll successful",{},Ut.DEBUG))};if(C(),z==="smooth"){let Y=!1;b=et(t,ae=>{Y=Y||ae}),y=ln(d,()=>{M(Y)})}else y=ln(ee(t,Y0(150)),M);return x=setTimeout(()=>{C()},1200),Le(l,!0),F("scrolling from index to",{behavior:z,index:V,top:ne},Ut.DEBUG),{behavior:z,top:ne}})),c),{scrollTargetReached:v,scrollToIndex:h,topListHeight:g}},it(bn,$t,Dn),{singleton:!0});function Y0(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function ba(e,t){e==0?t():requestAnimationFrame(()=>{ba(e-1,t)})}function wa(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const io=Xe(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=ie(!0),l=ie(0),c=ie(!0);return ve(ee(i,Fe(l),Me(([d,f])=>!!f),yn(!1)),a),ve(ee(i,Fe(l),Me(([d,f])=>!!f),yn(!1)),c),et(ee(vt(t,i),Fe(a,n,e,c),Me(([[,d],f,{sizeTree:p},h,v])=>d&&(!ot(p)||ca(h))&&!f&&!v),Fe(l)),([,d])=>{ln(o,()=>{Le(c,!0)}),ba(4,()=>{ln(r,()=>{Le(a,!0)}),Le(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},it(bn,$t,so,$n),{singleton:!0});function hf(e,t){return Math.abs(e-t)<1.01}const ao="up",lo="down",X0="none",J0={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},Z0=0,co=Xe(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=ie(!1),a=ie(!0),l=We(),c=We(),d=ie(4),f=ie(Z0),p=At(ee(da(ee(je(o),Qn(1),yn(!0)),ee(je(o),Qn(1),yn(!1),Xd(100))),at()),!1),h=At(ee(da(ee(n,yn(!0)),ee(n,yn(!1),Xd(200))),at()),!1);ve(ee(vt(je(o),je(f)),pe(([b,C])=>b<=C),at()),a),ve(ee(a,Nn(50)),c);const v=qt(ee(vt(r,je(s),je(t),je(e),je(d)),vn((b,[{scrollHeight:C,scrollTop:k},T,S,I,A])=>{const R=k+T-C>-A,D={scrollHeight:C,scrollTop:k,viewportHeight:T};if(R){let q,W;return k>b.state.scrollTop?(q="SCROLLED_DOWN",W=b.state.scrollTop-k):(q="SIZE_DECREASED",W=b.state.scrollTop-k||b.scrollTopDelta),{atBottom:!0,atBottomBecause:q,scrollTopDelta:W,state:D}}let F;return D.scrollHeight>b.state.scrollHeight?F="SIZE_INCREASED":T<b.state.viewportHeight?F="VIEWPORT_HEIGHT_DECREASING":k<b.state.scrollTop?F="SCROLLING_UPWARDS":F="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:F,state:D}},J0),at((b,C)=>b&&b.atBottom===C.atBottom))),g=At(ee(r,vn((b,{scrollHeight:C,scrollTop:k,viewportHeight:T})=>{if(hf(b.scrollHeight,C))return{changed:!1,jump:0,scrollHeight:C,scrollTop:k};{const S=C-(k+T)<1;return b.scrollTop!==k&&S?{changed:!0,jump:b.scrollTop-k,scrollHeight:C,scrollTop:k}:{changed:!0,jump:0,scrollHeight:C,scrollTop:k}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Me(b=>b.changed),pe(b=>b.jump)),0);ve(ee(v,pe(b=>b.atBottom)),i),ve(ee(i,Nn(50)),l);const y=ie(lo);ve(ee(r,pe(({scrollTop:b})=>b),at(),vn((b,C)=>xt(h)?{direction:b.direction,prevScrollTop:C}:{direction:C<b.prevScrollTop?ao:lo,prevScrollTop:C},{direction:lo,prevScrollTop:0}),pe(b=>b.direction)),y),ve(ee(r,Nn(50),yn(X0)),y);const x=ie(0);return ve(ee(p,Me(b=>!b),yn(0)),x),ve(ee(o,Nn(100),Fe(p),Me(([b,C])=>!!C),vn(([b,C],[k])=>[C,k],[0,0]),pe(([b,C])=>C-b)),x),{atBottomState:v,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:p,lastJumpDueToItemResize:g,scrollDirection:y,scrollVelocity:x}},it($t)),As="top",js="bottom",mf="none";function gf(e,t,n){return typeof e=="number"?n===ao&&t===As||n===lo&&t===js?e:0:n===ao?t===As?e.main:e.reverse:t===js?e.main:e.reverse}function xf(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const Sa=Xe(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=We(),i=ie(0),a=ie(0),l=ie(0),c=At(ee(vt(je(r),je(o),je(n),je(s,ro),je(l),je(i),je(t),je(e),je(a)),pe(([d,f,p,[h,v],g,y,x,b,C])=>{const k=d-b,T=y+x,S=Math.max(p-k,0);let I=mf;const A=xf(C,As),R=xf(C,js);return h-=b,h+=p+x,v+=p+x,v-=b,h>d+T-A&&(I=ao),v<d-S+f+R&&(I=lo),I!==mf?[Math.max(k-p-gf(g,As,I)-A,0),k-S-x+f+gf(g,js,I)+R]:null}),Me(d=>d!=null),at(ro)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},it($t),{singleton:!0});function Q0(e,t,n){if(Ns(t)){const r=cf(e,t);return[{index:cn(t.groupOffsetTree,r)[0],offset:0,size:0},{data:n==null?void 0:n[0],index:r,offset:0,size:0}]}return[{data:n==null?void 0:n[0],index:e,offset:0,size:0}]}const Ca={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function _s(e,t,n,r,o,s){const{lastIndex:i,lastOffset:a,lastSize:l}=o;let c=0,d=0;if(e.length>0){c=e[0].offset;const g=e[e.length-1];d=g.offset+g.size}const f=n-i,p=a+f*l+(f-1)*r,h=c,v=p-d;return{bottom:d,firstItemIndex:s,items:vf(e,o,s),offsetBottom:v,offsetTop:c,top:h,topItems:vf(t,o,s),topListHeight:t.reduce((g,y)=>y.size+g,0),totalCount:n}}function yf(e,t,n,r,o,s){let i=0;if(n.groupIndices.length>0)for(const d of n.groupIndices){if(d-i>=e)break;i++}const a=e+i,l=wa(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return _s(c,[],a,o,n,r)}function vf(e,t,n){if(e.length===0)return[];if(!Ns(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const r=e[0].index,o=e[e.length-1].index,s=[],i=ks(t.groupOffsetTree,r,o);let a,l=0;for(const c of e){(!a||a.end<c.index)&&(a=i.shift(),l=t.groupIndices.indexOf(a.start));let d;c.index===a.start?d={index:l,type:"group"}:d={groupIndex:l,index:c.index-(l+1)+n},s.push({...d,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return s}const nr=Xe(([{data:e,firstItemIndex:t,gap:n,sizes:r,totalCount:o},s,{listBoundary:i,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:f},p,{didMount:h},{recalcInProgress:v}])=>{const g=ie([]),y=ie(0),x=We();ve(s.topItemsIndexes,g);const b=At(ee(vt(h,v,je(l,ro),je(o),je(r),je(c),d,je(g),je(t),je(n),e),Me(([S,I,,A,,,,,,,R])=>{const D=R&&R.length!==A;return S&&!I&&!D}),pe(([,,[S,I],A,R,D,F,q,W,_,j])=>{const N=R,{offsetTree:z,sizeTree:L}=N,P=xt(y);if(A===0)return{...Ca,totalCount:A};if(S===0&&I===0)return P===0?{...Ca,totalCount:A}:yf(P,D,R,W,_,j||[]);if(ot(L))return P>0?null:_s(Q0(wa(D,A),N,j),[],A,_,N,W);const V=[];if(q.length>0){const Q=q[0],ce=q[q.length-1];let G=0;for(const O of ks(L,Q,ce)){const K=O.value,B=Math.max(O.start,Q),te=Math.min(O.end,ce);for(let Z=B;Z<=te;Z++)V.push({data:j==null?void 0:j[Z],index:Z,offset:G,size:K}),G+=K}}if(!F)return _s([],V,A,_,N,W);const ne=q.length>0?q[q.length-1]+1:0,M=z0(z,S,I,ne);if(M.length===0)return null;const Y=A-1,ae=Ts([],Q=>{for(const ce of M){const G=ce.value;let O=G.offset,K=ce.start;const B=G.size;if(G.offset<S){K+=Math.floor((S-G.offset+_)/(B+_));const Z=K-ce.start;O+=Z*B+Z*_}K<ne&&(O+=(ne-K)*B,K=ne);const te=Math.min(ce.end,Y);for(let Z=K;Z<=te&&!(O>=I);Z++)Q.push({data:j==null?void 0:j[Z],index:Z,offset:O,size:B}),O+=B+_}});return _s(ae,V,A,_,N,W)}),Me(S=>S!==null),at()),Ca);ve(ee(e,Me(ca),pe(S=>S==null?void 0:S.length)),o),ve(ee(b,pe(S=>S.topListHeight)),f),ve(f,a),ve(ee(b,pe(S=>[S.top,S.bottom])),i),ve(ee(b,pe(S=>S.items)),x);const C=qt(ee(b,Me(({items:S})=>S.length>0),Fe(o,e),Me(([{items:S},I])=>S[S.length-1].originalIndex===I-1),pe(([,S,I])=>[S-1,I]),at(ro),pe(([S])=>S))),k=qt(ee(b,Nn(200),Me(({items:S,topItems:I})=>S.length>0&&S[0].originalIndex===I.length),pe(({items:S})=>S[0].index),at())),T=qt(ee(b,Me(({items:S})=>S.length>0),pe(({items:S})=>{let I=0,A=S.length-1;for(;S[I].type==="group"&&I<A;)I++;for(;S[A].type==="group"&&A>I;)A--;return{endIndex:S[A].index,startIndex:S[I].index}}),at(af)));return{endReached:C,initialItemCount:y,itemsRendered:x,listState:b,rangeChanged:T,startReached:k,topItemsIndexes:g,...p}},it(bn,ff,Sa,io,so,co,$n,xa),{singleton:!0}),bf=Xe(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=We(),i=At(ee(vt(n,e,r,t,o),pe(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return ve(je(i),s),{totalListHeight:i,totalListHeightChanged:s}},it($t,nr),{singleton:!0}),eS=Xe(([{viewportHeight:e},{totalListHeight:t}])=>{const n=ie(!1),r=At(ee(vt(n,e,t),Me(([o])=>o),pe(([,o,s])=>Math.max(0,o-s)),Nn(0),at()),0);return{alignToBottom:n,paddingTopAddition:r}},it($t,bf),{singleton:!0}),wf=Xe(()=>({context:ie(null)})),tS=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:r,...o},viewportBottom:s,viewportTop:i})=>t<i?{...o,align:n??"start",behavior:r}:e>s?{...o,align:n??"end",behavior:r}:null,Sf=Xe(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=We();return ve(ee(d,Fe(t,l,n,s,o,r,a),Fe(e),pe(([[f,p,h,v,g,y,x,b],C])=>{const{align:k,behavior:T,calculateViewLocation:S=tS,done:I,...A}=f,R=uf(f,p,v-1),D=oo(R,p.offsetTree,C)+g+y,F=D+cn(p.sizeTree,R)[1],q=b+y,W=b+h-x,_=S({itemBottom:F,itemTop:D,locationParams:{align:k,behavior:T,...A},viewportBottom:W,viewportTop:q});return _?I&&ln(ee(i,Me(j=>!j),Qn(xt(i)?1:2)),I):I&&I(),_}),Me(f=>f!==null)),c),{scrollIntoView:d}},it(bn,$t,so,nr,Dn),{singleton:!0});function Cf(e){return e?e==="smooth"?"smooth":"auto":!1}const nS=(e,t)=>typeof e=="function"?Cf(e(t)):t&&Cf(e),rS=Xe(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:r},{atBottomState:o,isAtBottom:s},{scrollToIndex:i},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:f},{context:p},{scrollIntoView:h}])=>{const v=ie(!1),g=We();let y=null;function x(T){Le(i,{align:"end",behavior:T,index:"LAST"})}et(ee(vt(ee(je(t),Qn(1)),l),Fe(je(v),s,a,f),pe(([[T,S],I,A,R,D])=>{let F=S&&R,q="auto";return F&&(q=nS(I,A||D),F=F&&!!q),{followOutputBehavior:q,shouldFollow:F,totalCount:T}}),Me(({shouldFollow:T})=>T)),({followOutputBehavior:T,totalCount:S})=>{y&&(y(),y=null),xt(n)?requestAnimationFrame(()=>{xt(d)("following output to ",{totalCount:S},Ut.DEBUG),x(T)}):y=ln(e,()=>{xt(d)("following output to ",{totalCount:S},Ut.DEBUG),x(T),y=null})});function b(T){const S=ln(o,I=>{T&&!I.atBottom&&I.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(xt(d)("scrolling to bottom due to increased size",{},Ut.DEBUG),x("auto"))});setTimeout(S,100)}et(ee(vt(je(v),t,c),Me(([T,,S])=>T&&S),vn(({value:T},[,S])=>({refreshed:T===S,value:S}),{refreshed:!1,value:0}),Me(({refreshed:T})=>T),Fe(v,t)),([,T])=>{xt(a)&&b(T!==!1)}),et(g,()=>{b(xt(v)!==!1)}),et(vt(je(v),o),([T,S])=>{T&&!S.atBottom&&S.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&x("auto")});const C=ie(null),k=We();return ve(da(ee(je(r),pe(T=>{var S;return(S=T==null?void 0:T.length)!=null?S:0})),ee(je(t))),k),et(ee(vt(ee(k,Qn(1)),l),Fe(je(C),a,f,p),pe(([[T,S],I,A,R,D])=>S&&A&&(I==null?void 0:I({context:D,totalCount:T,scrollingInProgress:R}))),Me(T=>!!T),Nn(0)),T=>{y&&(y(),y=null),xt(n)?requestAnimationFrame(()=>{xt(d)("scrolling into view",{}),Le(h,T)}):y=ln(e,()=>{xt(d)("scrolling into view",{}),Le(h,T),y=null})}),{autoscrollToBottom:g,followOutput:v,scrollIntoViewOnChange:C}},it(bn,co,so,io,$n,Dn,$t,wf,Sf)),oS=Xe(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(ve(ee(a,Fe(s),Me(([,l])=>l!==0),Fe(o,r,t,n,e),pe(([[,l],c,d,f,p,h=[]])=>yf(l,c,d,f,p,h))),i),{}),it(bn,io,nr,$n),{singleton:!0}),sS=Xe(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=ie(0);return et(ee(e,Fe(r),Me(([,o])=>o!==0),pe(([,o])=>({top:o}))),o=>{ln(ee(n,Qn(1),Me(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{Le(t,o)})})}),{initialScrollTop:r}},it($n,$t,nr),{singleton:!0}),Tf=Xe(([{scrollVelocity:e}])=>{const t=ie(!1),n=We(),r=ie(!1);return ve(ee(e,Fe(r,t,n),Me(([o,s])=>!!s),pe(([o,s,i,a])=>{const{enter:l,exit:c}=s;if(i){if(c(o,a))return!1}else if(l(o,a))return!0;return i}),at()),t),et(ee(vt(t,e,n),Fe(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},it(co),{singleton:!0}),Ta=Xe(([{scrollContainerState:e,scrollTo:t}])=>{const n=We(),r=We(),o=We(),s=ie(!1),i=ie(void 0);return ve(ee(vt(n,r),pe(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),ve(ee(t,Fe(r),pe(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},it($t)),iS=Xe(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=We(),d=ie(void 0),f=ie(null),p=ie(null);return ve(a,f),ve(l,p),et(ee(c,Fe(t,r,i,f,p,n)),([h,v,g,y,x,b,C])=>{const k=H0(v.sizeTree);y&&x!==null&&b!==null&&(g=x.scrollTop-b.offsetTop),g-=C,h({ranges:k,scrollTop:g})}),ve(ee(d,Me(ca),pe(aS)),o),ve(ee(s,Fe(d),Me(([,h])=>h!==void 0),at(),pe(([,h])=>h.ranges)),e),{getState:c,restoreStateFrom:d}},it(bn,$t,io,$n,Ta));function aS(e){return{align:"start",index:0,offset:e.scrollTop}}const lS=Xe(([{topItemsIndexes:e}])=>{const t=ie(0);return ve(ee(t,Me(n=>n>=0),pe(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},it(nr));function kf(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const cS=kf(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),uS=Xe(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:r},{isAtBottom:o,isScrolling:s,lastJumpDueToItemResize:i,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:f,sizes:p},{log:h},{recalcInProgress:v}])=>{const g=qt(ee(l,Fe(i),vn(([,x,b,C],[{bottom:k,items:T,offsetBottom:S,totalCount:I},A])=>{const R=k+S;let D=0;return b===I&&x.length>0&&T.length>0&&(T[0].originalIndex===0&&x[0].originalIndex===0||(D=R-C,D!==0&&(D+=A))),[D,T,I,R]},[0,[],0,0]),Me(([x])=>x!==0),Fe(r,a,n,o,h,v),Me(([,x,b,C,,,k])=>!k&&!C&&x!==0&&b===ao),pe(([[x],,,,,b])=>(b("Upward scrolling compensation",{amount:x},Ut.DEBUG),x))));function y(x){x>0?(Le(t,{behavior:"auto",top:-x}),Le(e,0)):(Le(e,0),Le(t,{behavior:"auto",top:-x}))}return et(ee(g,Fe(e,s)),([x,b,C])=>{C&&cS()?Le(e,b-x):y(-x)}),et(ee(vt(At(s,!1),e,v),Me(([x,b,C])=>!x&&!C&&b!==0),pe(([x,b])=>b),Nn(1)),y),ve(ee(f,pe(x=>({top:-x}))),t),et(ee(c,Fe(p,d),pe(([x,{groupIndices:b,lastSize:C,sizeTree:k},T])=>{function S(I){return I*(C+T)}if(b.length===0)return S(x);{let I=0;const A=no(k,0);let R=0,D=0;for(;R<x;){R++,I+=A;let F=b.length===D+1?1/0:b[D+1]-b[D]-1;R+F>x&&(I-=A,F=x-R+1),R+=F,I+=S(F),D++}return I}})),x=>{Le(e,x),requestAnimationFrame(()=>{Le(t,{top:x}),requestAnimationFrame(()=>{Le(e,0),Le(v,!1)})})}),{deviation:e}},it($t,co,nr,bn,Dn,xa)),dS=Xe(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),it(Sa,oS,$n,Tf,bf,sS,eS,Ta,Sf,Dn,wf)),If=Xe(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:r,gap:o,groupIndices:s,itemSize:i,sizeRanges:a,sizes:l,statefulTotalCount:c,totalCount:d,trackItemSizes:f},{initialItemFinalLocationReached:p,initialTopMostItemIndex:h,scrolledToInitialItem:v},g,y,x,{listState:b,topItemsIndexes:C,...k},{scrollToIndex:T},S,{topItemCount:I},{groupCounts:A},R])=>(ve(k.rangeChanged,R.scrollSeekRangeChanged),ve(ee(R.windowViewportRect,pe(D=>D.visibleHeight)),g.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:A,initialItemFinalLocationReached:p,initialTopMostItemIndex:h,scrolledToInitialItem:v,sizeRanges:a,topItemCount:I,topItemsIndexes:C,totalCount:d,...x,groupIndices:s,itemSize:i,listState:b,scrollToIndex:T,statefulTotalCount:c,trackItemSizes:f,...k,...R,...g,sizes:l,...y}),it(bn,io,$t,iS,rS,nr,so,uS,lS,ff,dS));function fS(e,t){const n={},r={};let o=0;const s=e.length;for(;o<s;)r[e[o]]=1,o+=1;for(const i in t)Object.hasOwn(r,i)||(n[i]=t[i]);return n}const Ms=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Ef(e,t,n){const r=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),s=Object.keys(t.methods||{}),i=Object.keys(t.events||{}),a=w.createContext({});function l(y,x){y.propsReady&&Le(y.propsReady,!1);for(const b of r){const C=y[t.required[b]];Le(C,x[b])}for(const b of o)if(b in x){const C=y[t.optional[b]];Le(C,x[b])}y.propsReady&&Le(y.propsReady,!0)}function c(y){return s.reduce((x,b)=>(x[b]=C=>{const k=y[t.methods[b]];Le(k,C)},x),{})}function d(y){return i.reduce((x,b)=>(x[b]=N0(y[t.events[b]]),x),{})}const f=w.forwardRef((y,x)=>{const{children:b,...C}=y,[k]=w.useState(()=>Ts(j0(e),I=>{l(I,C)})),[T]=w.useState(Yd(d,k));Ms(()=>{for(const I of i)I in C&&et(T[I],C[I]);return()=>{Object.values(T).map(ua)}},[C,T,k]),Ms(()=>{l(k,C)}),w.useImperativeHandle(x,qd(c(k)));const S=n;return u.jsx(a.Provider,{value:k,children:n?u.jsx(S,{...fS([...r,...o,...i],C),children:b}):b})}),p=y=>{const x=w.useContext(a);return w.useCallback(b=>{Le(x[y],b)},[x,y])},h=y=>{const x=w.useContext(a)[y],b=w.useCallback(C=>et(x,C),[x]);return w.useSyncExternalStore(b,()=>xt(x),()=>xt(x))},v=y=>{const x=w.useContext(a)[y],[b,C]=w.useState(Yd(xt,x));return Ms(()=>et(x,k=>{k!==b&&C(qd(k))}),[x,b]),b},g=w.version.startsWith("18")?h:v;return{Component:f,useEmitter:(y,x)=>{const b=w.useContext(a)[y];Ms(()=>et(b,x),[x,b])},useEmitterValue:g,usePublisher:p}}const Nf=w.createContext(void 0),Af=w.createContext(void 0),jf=typeof document<"u"?w.useLayoutEffect:w.useEffect;function ka(e){return"self"in e}function pS(e){return"body"in e}function _f(e,t,n,r=Nr,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(p=>{let h,v,g;const y=p.target;if(pS(y)||ka(y)){const b=ka(y)?y:y.defaultView;g=s?b.scrollX:b.scrollY,h=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,v=s?b.innerWidth:b.innerHeight}else g=s?y.scrollLeft:y.scrollTop,h=s?y.scrollWidth:y.scrollHeight,v=s?y.offsetWidth:y.offsetHeight;const x=()=>{e({scrollHeight:h,scrollTop:Math.max(g,0),viewportHeight:v})};p.suppressFlushSync?x():ii.flushSync(x),a.current!==null&&(g===a.current||g<=0||g===h-v)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.useEffect(()=>{const p=o||i.current;return r(o||i.current),c({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",c,{passive:!0}),()=>{r(null),p.removeEventListener("scroll",c)}},[i,c,n,r,o]);function d(p){const h=i.current;if(!h||(s?"offsetWidth"in h&&h.offsetWidth===0:"offsetHeight"in h&&h.offsetHeight===0))return;const v=p.behavior==="smooth";let g,y,x;ka(h)?(y=Math.max(Ln(h.document.documentElement,s?"width":"height"),s?h.document.documentElement.scrollWidth:h.document.documentElement.scrollHeight),g=s?h.innerWidth:h.innerHeight,x=s?window.scrollX:window.scrollY):(y=h[s?"scrollWidth":"scrollHeight"],g=Ln(h,s?"width":"height"),x=h[s?"scrollLeft":"scrollTop"]);const b=y-g;if(p.top=Math.ceil(Math.max(Math.min(b,p.top),0)),hf(g,y)||p.top===x){e({scrollHeight:y,scrollTop:x,viewportHeight:g}),v&&t(!0);return}v?(a.current=p.top,l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{l.current=null,a.current=null,t(!0)},1e3)):a.current=null,s&&(p={behavior:p.behavior,left:p.top}),h.scrollTo(p)}function f(p){s&&(p={behavior:p.behavior,left:p.top}),i.current.scrollBy(p)}return{scrollByCallback:f,scrollerRef:i,scrollToCallback:d}}const Ia="-webkit-sticky",Mf="sticky",Ea=kf(()=>{if(typeof document>"u")return Mf;const e=document.createElement("div");return e.style.position=Ia,e.style.position===Ia?Ia:Mf});function Na(e){return e}const hS=Xe(()=>{const e=ie(a=>`Item ${a}`),t=ie(a=>`Group ${a}`),n=ie({}),r=ie(Na),o=ie("div"),s=ie(Nr),i=(a,l=null)=>At(ee(n,pe(c=>c[a]),at()),l);return{components:n,computeItemKey:r,EmptyPlaceholder:i("EmptyPlaceholder"),FooterComponent:i("Footer"),GroupComponent:i("Group","div"),groupContent:t,HeaderComponent:i("Header"),HeaderFooterTag:o,ItemComponent:i("Item","div"),itemContent:e,ListComponent:i("List","div"),ScrollerComponent:i("Scroller","div"),scrollerRef:s,ScrollSeekPlaceholder:i("ScrollSeekPlaceholder"),TopItemListComponent:i("TopItemList")}}),mS=Xe(([e,t])=>({...e,...t}),it(If,hS)),gS=({height:e})=>u.jsx("div",{style:{height:e}}),xS={overflowAnchor:"none",position:Ea(),zIndex:1},Rf={overflowAnchor:"none"},yS={...Rf,display:"inline-block",height:"100%"},Pf=w.memo(function({showTopList:e=!1}){const t=Oe("listState"),n=Zt("sizeRanges"),r=Oe("useWindowScroll"),o=Oe("customScrollParent"),s=Zt("windowScrollContainerState"),i=Zt("scrollContainerState"),a=o||r?s:i,l=Oe("itemContent"),c=Oe("context"),d=Oe("groupContent"),f=Oe("trackItemSizes"),p=Oe("itemSize"),h=Oe("log"),v=Zt("gap"),g=Oe("horizontalDirection"),{callbackRef:y}=R0(n,p,f,e?Nr:a,h,v,o,g,Oe("skipAnimationFrameInResizeObserver")),[x,b]=w.useState(0);Aa("deviation",_=>{x!==_&&b(_)});const C=Oe("EmptyPlaceholder"),k=Oe("ScrollSeekPlaceholder")||gS,T=Oe("ListComponent"),S=Oe("ItemComponent"),I=Oe("GroupComponent"),A=Oe("computeItemKey"),R=Oe("isSeeking"),D=Oe("groupIndices").length>0,F=Oe("alignToBottom"),q=Oe("initialItemFinalLocationReached"),W=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginLeft:x!==0?x:F?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:x!==0?x:F?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...q?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&C?u.jsx(C,{...jt(C,c)}):u.jsx(T,{...jt(T,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:W,children:(e?t.topItems:t.items).map(_=>{const j=_.originalIndex,N=A(j+t.firstItemIndex,_.data,c);return R?w.createElement(k,{...jt(k,c),height:_.size,index:_.index,key:N,type:_.type||"item",..._.type==="group"?{}:{groupIndex:_.groupIndex}}):_.type==="group"?w.createElement(I,{...jt(I,c),"data-index":j,"data-item-index":_.index,"data-known-size":_.size,key:N,style:xS},d(_.index,c)):w.createElement(S,{...jt(S,c),...SS(S,_.data),"data-index":j,"data-item-group-index":_.groupIndex,"data-item-index":_.index,"data-known-size":_.size,key:N,style:g?yS:Rf},D?l(_.index,_.groupIndex,_.data,c):l(_.index,_.data,c))})})}),vS={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},bS={outline:"none",overflowX:"auto",position:"relative"},Rs=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),wS={position:Ea(),top:0,width:"100%",zIndex:1};function jt(e,t){if(typeof e!="string")return{context:t}}function SS(e,t){return{item:typeof e=="string"?void 0:t}}const CS=w.memo(function(){const e=Oe("HeaderComponent"),t=Zt("headerHeight"),n=Oe("HeaderFooterTag"),r=er(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null}),TS=w.memo(function(){const e=Oe("FooterComponent"),t=Zt("footerHeight"),n=Oe("HeaderFooterTag"),r=er(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,Oe("skipAnimationFrameInResizeObserver")),o=Oe("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null});function Of({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("scrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("scrollerRef"),f=t("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:h,scrollToCallback:v}=_f(a,c,l,d,void 0,f);return e("scrollTo",v),e("scrollBy",p),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:h,style:{...f?bS:vS,...o},tabIndex:0,...i,...jt(l,s),children:r})})}function Df({useEmitter:e,useEmitterValue:t,usePublisher:n}){return w.memo(function({children:r,style:o,context:s,...i}){const a=n("windowScrollContainerState"),l=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),d=t("totalListHeight"),f=t("deviation"),p=t("customScrollParent"),h=w.useRef(null),v=t("scrollerRef"),{scrollByCallback:g,scrollerRef:y,scrollToCallback:x}=_f(a,c,l,v,p);return jf(()=>{var b;return y.current=p||((b=h.current)==null?void 0:b.ownerDocument.defaultView),()=>{y.current=null}},[y,p]),e("windowScrollTo",x),e("scrollBy",g),u.jsx(l,{ref:h,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...d!==0?{height:d+f}:{}},...i,...jt(l,s),children:r})})}const kS=({children:e})=>{const t=w.useContext(Nf),n=Zt("viewportHeight"),r=Zt("fixedItemHeight"),o=Oe("alignToBottom"),s=Oe("horizontalDirection"),i=w.useMemo(()=>Gd(n,l=>Ln(l,s?"width":"height")),[n,s]),a=er(i,!0,Oe("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:Rs(o),children:e})},IS=({children:e})=>{const t=w.useContext(Nf),n=Zt("windowViewportRect"),r=Zt("fixedItemHeight"),o=Oe("customScrollParent"),s=Qd(n,o,Oe("skipAnimationFrameInResizeObserver")),i=Oe("alignToBottom");return w.useEffect(()=>{t&&(r(t.itemHeight),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,r]),u.jsx("div",{"data-viewport-type":"window",ref:s,style:Rs(i),children:e})},ES=({children:e})=>{const t=Oe("TopItemListComponent")||"div",n=Oe("headerHeight"),r={...wS,marginTop:`${n}px`},o=Oe("context");return u.jsx(t,{style:r,...jt(t,o),children:e})},NS=w.memo(function(e){const t=Oe("useWindowScroll"),n=Oe("topItemsIndexes").length>0,r=Oe("customScrollParent"),o=Oe("context");return u.jsxs(r||t?_S:jS,{...e,context:o,children:[n&&u.jsx(ES,{children:u.jsx(Pf,{showTopList:!0})}),u.jsxs(r||t?IS:kS,{children:[u.jsx(CS,{}),u.jsx(Pf,{}),u.jsx(TS,{})]})]})}),{Component:AS,useEmitter:Aa,useEmitterValue:Oe,usePublisher:Zt}=Ef(mS,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedItemHeight:"fixedItemHeight",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},NS),jS=Of({useEmitter:Aa,useEmitterValue:Oe,usePublisher:Zt}),_S=Df({useEmitter:Aa,useEmitterValue:Oe,usePublisher:Zt}),MS=AS;it(If,Xe(()=>{const e=ie(c=>u.jsxs("td",{children:["Item $",c]})),t=ie(null),n=ie(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=ie(null),o=ie(null),s=ie({}),i=ie(Na),a=ie(Nr),l=(c,d=null)=>At(ee(s,pe(f=>f[c]),at()),d);return{components:s,computeItemKey:i,context:t,EmptyPlaceholder:l("EmptyPlaceholder"),FillerRow:l("FillerRow"),fixedFooterContent:o,fixedHeaderContent:r,itemContent:e,groupContent:n,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder"),TableBodyComponent:l("TableBody","tbody"),TableComponent:l("Table","table"),TableFooterComponent:l("TableFoot","tfoot"),TableHeadComponent:l("TableHead","thead"),TableRowComponent:l("TableRow","tr"),GroupComponent:l("Group","tr")}})),Ea();const Lf={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},RS={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:$f,floor:Ps,max:uo,min:ja,round:Ff}=Math;function Bf(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function PS(e){return{...RS,items:e}}function Os(e,t){return e&&e.width===t.width&&e.height===t.height}function OS(e,t){return e&&e.column===t.column&&e.row===t.row}const DS=Xe(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:r},{footerHeight:o,headerHeight:s,scrollBy:i,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:f},p,h,{didMount:v,propsReady:g},{customScrollParent:y,useWindowScroll:x,windowScrollContainerState:b,windowScrollTo:C,windowViewportRect:k},T])=>{const S=ie(0),I=ie(0),A=ie(Lf),R=ie({height:0,width:0}),D=ie({height:0,width:0}),F=We(),q=We(),W=ie(0),_=ie(null),j=ie({column:0,row:0}),N=We(),z=We(),L=ie(!1),P=ie(0),V=ie(!0),ne=ie(!1),M=ie(!1);et(ee(v,Fe(P),Me(([O,K])=>!!K)),()=>{Le(V,!1)}),et(ee(vt(v,V,D,R,P,ne),Me(([O,K,B,te,,Z])=>O&&!K&&B.height!==0&&te.height!==0&&!Z)),([,,,,O])=>{Le(ne,!0),ba(1,()=>{Le(F,O)}),ln(ee(c),()=>{Le(t,[0,0]),Le(V,!0)})}),ve(ee(z,Me(O=>O!=null&&O.scrollTop>0),yn(0)),I),et(ee(v,Fe(z),Me(([,O])=>O!=null)),([,O])=>{O&&(Le(R,O.viewport),Le(D,O.item),Le(j,O.gap),O.scrollTop>0&&(Le(L,!0),ln(ee(c,Qn(1)),K=>{Le(L,!1)}),Le(l,{top:O.scrollTop})))}),ve(ee(R,pe(({height:O})=>O)),f),ve(ee(vt(je(R,Os),je(D,Os),je(j,(O,K)=>O&&O.column===K.column&&O.row===K.row),je(c)),pe(([O,K,B,te])=>({gap:B,item:K,scrollTop:te,viewport:O}))),N),ve(ee(vt(je(S),r,je(j,OS),je(D,Os),je(R,Os),je(_),je(I),je(L),je(V),je(P)),Me(([,,,,,,,O])=>!O),pe(([O,[K,B],te,Z,ye,fe,oe,,xe,Se])=>{const{column:$e,row:_e}=te,{height:Ue,width:U}=Z,{width:le}=ye;if(oe===0&&(O===0||le===0))return Lf;if(U===0){const Mt=wa(Se,O),Wt=Mt+Math.max(oe-1,0);return PS(Bf(Mt,Wt,fe))}const ke=zf(le,U,$e);let Ke,tt;xe?K===0&&B===0&&oe>0?(Ke=0,tt=oe-1):(Ke=ke*Ps((K+_e)/(Ue+_e)),tt=ke*$f((B+_e)/(Ue+_e))-1,tt=ja(O-1,uo(tt,ke-1)),Ke=ja(tt,uo(0,Ke))):(Ke=0,tt=-1);const St=Bf(Ke,tt,fe),{bottom:ut,top:yt}=Uf(ye,te,Z,St),pt=$f(O/ke),wt=pt*Ue+(pt-1)*_e-ut;return{bottom:ut,itemHeight:Ue,items:St,itemWidth:U,offsetBottom:wt,offsetTop:yt,top:yt}})),A),ve(ee(_,Me(O=>O!==null),pe(O=>O.length)),S),ve(ee(vt(R,D,A,j),Me(([O,K,{items:B}])=>B.length>0&&K.height!==0&&O.height!==0),pe(([O,K,{items:B},te])=>{const{bottom:Z,top:ye}=Uf(O,te,K,B);return[ye,Z]}),at(ro)),t);const Y=ie(!1);ve(ee(c,Fe(Y),pe(([O,K])=>K||O!==0)),Y);const ae=qt(ee(vt(A,S),Me(([{items:O}])=>O.length>0),Fe(Y),Me(([[O,K],B])=>{const te=O.items[O.items.length-1].index===K-1;return(B||O.bottom>0&&O.itemHeight>0&&O.offsetBottom===0&&O.items.length===K)&&te}),pe(([[,O]])=>O-1),at())),Q=qt(ee(je(A),Me(({items:O})=>O.length>0&&O[0].index===0),yn(0),at())),ce=qt(ee(je(A),Fe(L),Me(([{items:O},K])=>O.length>0&&!K),pe(([{items:O}])=>({endIndex:O[O.length-1].index,startIndex:O[0].index})),at(af),Nn(0)));ve(ce,h.scrollSeekRangeChanged),ve(ee(F,Fe(R,D,S,j),pe(([O,K,B,te,Z])=>{const ye=pf(O),{align:fe,behavior:oe,offset:xe}=ye;let Se=ye.index;Se==="LAST"&&(Se=te-1),Se=uo(0,Se,ja(te-1,Se));let $e=_a(K,Z,B,Se);return fe==="end"?$e=Ff($e-K.height+B.height):fe==="center"&&($e=Ff($e-K.height/2+B.height/2)),xe&&($e+=xe),{behavior:oe,top:$e}})),l);const G=At(ee(A,pe(O=>O.offsetBottom+O.bottom)),0);return ve(ee(k,pe(O=>({height:O.visibleHeight,width:O.visibleWidth}))),R),{customScrollParent:y,data:_,deviation:W,footerHeight:o,gap:j,headerHeight:s,increaseViewportBy:e,initialItemCount:I,itemDimensions:D,overscan:n,restoreStateFrom:z,scrollBy:i,scrollContainerState:a,scrollHeight:q,scrollTo:l,scrollToIndex:F,scrollTop:c,smoothScrollTargetReached:d,totalCount:S,useWindowScroll:x,viewportDimensions:R,windowScrollContainerState:b,windowScrollTo:C,windowViewportRect:k,...h,gridState:A,horizontalDirection:M,initialTopMostItemIndex:P,totalListHeight:G,...p,endReached:ae,propsReady:g,rangeChanged:ce,startReached:Q,stateChanged:N,stateRestoreInProgress:L,...T}},it(Sa,$t,co,Tf,$n,Ta,Dn));function zf(e,t,n){return uo(1,Ps((e+n)/(Ps(t)+n)))}function Uf(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=_a(e,t,n,r[0].index);return{bottom:_a(e,t,n,r[r.length-1].index)+o,top:s}}function _a(e,t,n,r){const o=zf(e.width,n.width,t.column),s=Ps(r/o),i=s*n.height+uo(0,s-1)*t.row;return i>0?i+t.row:i}const LS=Xe(()=>{const e=ie(f=>`Item ${f}`),t=ie({}),n=ie(null),r=ie("virtuoso-grid-item"),o=ie("virtuoso-grid-list"),s=ie(Na),i=ie("div"),a=ie(Nr),l=(f,p=null)=>At(ee(t,pe(h=>h[f]),at()),p),c=ie(!1),d=ie(!1);return ve(je(d),c),{components:t,computeItemKey:s,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:i,itemClassName:r,ItemComponent:l("Item","div"),itemContent:e,listClassName:o,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}),$S=Xe(([e,t])=>({...e,...t}),it(DS,LS)),FS=w.memo(function(){const e=ct("gridState"),t=ct("listClassName"),n=ct("itemClassName"),r=ct("itemContent"),o=ct("computeItemKey"),s=ct("isSeeking"),i=Qt("scrollHeight"),a=ct("ItemComponent"),l=ct("ListComponent"),c=ct("ScrollSeekPlaceholder"),d=ct("context"),f=Qt("itemDimensions"),p=Qt("gap"),h=ct("log"),v=ct("stateRestoreInProgress"),g=Qt("reportReadyState"),y=er(w.useMemo(()=>x=>{const b=x.parentElement.parentElement.scrollHeight;i(b);const C=x.firstChild;if(C){const{height:k,width:T}=C.getBoundingClientRect();f({height:k,width:T})}p({column:Wf("column-gap",getComputedStyle(x).columnGap,h),row:Wf("row-gap",getComputedStyle(x).rowGap,h)})},[i,f,p,h]),!0,!1);return jf(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),v?null:u.jsx(l,{className:t,ref:y,...jt(l,d),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(x=>{const b=o(x.index,x.data,d);return s?u.jsx(c,{...jt(c,d),height:e.itemHeight,index:x.index,width:e.itemWidth},b):w.createElement(a,{...jt(a,d),className:n,"data-index":x.index,key:b},r(x.index,x.data,d))})})}),BS=w.memo(function(){const e=ct("HeaderComponent"),t=Qt("headerHeight"),n=ct("headerFooterTag"),r=er(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,!1),o=ct("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null}),zS=w.memo(function(){const e=ct("FooterComponent"),t=Qt("footerHeight"),n=ct("headerFooterTag"),r=er(w.useMemo(()=>s=>{t(Ln(s,"height"))},[t]),!0,!1),o=ct("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...jt(e,o)})}):null}),US=({children:e})=>{const t=w.useContext(Af),n=Qt("itemDimensions"),r=Qt("viewportDimensions"),o=er(w.useMemo(()=>s=>{r(s.getBoundingClientRect())},[r]),!0,!1);return w.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),u.jsx("div",{ref:o,style:Rs(!1),children:e})},HS=({children:e})=>{const t=w.useContext(Af),n=Qt("windowViewportRect"),r=Qt("itemDimensions"),o=ct("customScrollParent"),s=Qd(n,o,!1);return w.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),u.jsx("div",{ref:s,style:Rs(!1),children:e})},WS=w.memo(function({...e}){const t=ct("useWindowScroll"),n=ct("customScrollParent"),r=n||t?KS:VS,o=n||t?HS:US,s=ct("context");return u.jsx(r,{...e,...jt(r,s),children:u.jsxs(o,{children:[u.jsx(BS,{}),u.jsx(FS,{}),u.jsx(zS,{})]})})}),{useEmitter:Hf,useEmitterValue:ct,usePublisher:Qt}=Ef($S,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},WS),VS=Of({useEmitter:Hf,useEmitterValue:ct,usePublisher:Qt}),KS=Df({useEmitter:Hf,useEmitterValue:ct,usePublisher:Qt});function Wf(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Ut.WARN),t==="normal"?0:parseInt(t??"0",10)}const qS=ko.cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Vf({className:e,variant:t,...n}){return u.jsx("div",{className:se(qS({variant:t}),e),...n})}function Ma(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function Kf(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function fo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(fo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(Kf(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=fo(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function po(e){if(typeof e=="string")return e;if(Kf(e))return"";try{const t=fo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function GS(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function YS(e){const t=po(e);return typeof e=="string"&&GS(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Ds(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ma(t);if(n!==null)return Ds(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Ds(e.content):e}function XS(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function qf(e){const t=e.content.find(s=>s.type==="tool_call"),n=e.additionalKwargs??{},r=typeof(t==null?void 0:t.id)=="string"&&t.id||typeof n.toolCallId=="string"&&n.toolCallId||(e.id.startsWith("tool-")?e.id.slice(5):void 0);return{name:(typeof(t==null?void 0:t.name)=="string"&&t.name||typeof n.toolName=="string"&&n.toolName||e.name&&String(e.name))??void 0,toolCallId:r??void 0}}function Ls(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function JS(e){const t=r=>{try{const o=fo(r);return typeof o=="string"?o:JSON.stringify(o??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
87
+ `)):t(e)}function ZS(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function Gf(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function QS(e){if(!e)return"image/png";const t=e.trim();return t?t.includes("/")?t:`image/${t}`:"image/png"}function eC(e){const t=[],n=r=>{r&&r.trim()&&t.push(r.trim())};return e&&(n(e.plotId),n(e.artifactId)),t}function tC({base64:e,url:t,formatHint:n,extras:r}){const o=typeof e=="string"&&e.length>0,s=QS(n),i=o?`data:${s};base64,${e}`:t,a=eC(r),l=a.length?a.join(" / "):void 0,c=l?`${l} artifact`:"artifact image";return{src:i,alt:c,label:l}}function nC(e){var o,s;const t=((o=e.content_base64)==null?void 0:o.trim())||void 0,n=((s=e.url)==null?void 0:s.trim())||void 0,r=e.format||e.mimeType||e.mime_type;return tC({base64:t,url:n,formatHint:r,extras:{plotId:e.plotId,artifactId:e.artifactId}})}async function Yf(e,t){return await zt(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function Xf(e,t){return await(await Yf(`/files/${e}/view`,t)).text()}async function rC(e,t){const n=await Yf(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await zt(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function oC(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await zt("/files",{params:r})}var $s="Dialog",[Jf,hI]=kn($s),[sC,un]=Jf($s),Zf=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,a=m.useRef(null),l=m.useRef(null),[c,d]=xr({prop:r,defaultProp:o??!1,onChange:s,caller:$s});return u.jsx(sC,{scope:t,triggerRef:a,contentRef:l,contentId:Dt(),titleId:Dt(),descriptionId:Dt(),open:c,onOpenChange:d,onOpenToggle:m.useCallback(()=>d(f=>!f),[d]),modal:i,children:n})};Zf.displayName=$s;var Qf="DialogTrigger",ep=m.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=un(Qf,n),s=He(t,o.triggerRef);return u.jsx(Ie.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Oa(o.open),...r,ref:s,onClick:me(e.onClick,o.onOpenToggle)})});ep.displayName=Qf;var Ra="DialogPortal",[iC,tp]=Jf(Ra,{forceMount:void 0}),np=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=un(Ra,t);return u.jsx(iC,{scope:t,forceMount:n,children:m.Children.map(r,i=>u.jsx(Xt,{present:n||s.open,children:u.jsx(is,{asChild:!0,container:o,children:i})}))})};np.displayName=Ra;var Fs="DialogOverlay",rp=m.forwardRef((e,t)=>{const n=tp(Fs,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=un(Fs,e.__scopeDialog);return s.modal?u.jsx(Xt,{present:r||s.open,children:u.jsx(lC,{...o,ref:t})}):null});rp.displayName=Fs;var aC=Kn.createSlot("DialogOverlay.RemoveScroll"),lC=m.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=un(Fs,n);return u.jsx(ms,{as:aC,allowPinchZoom:!0,shards:[o.contentRef],children:u.jsx(Ie.div,{"data-state":Oa(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),rr="DialogContent",op=m.forwardRef((e,t)=>{const n=tp(rr,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=un(rr,e.__scopeDialog);return u.jsx(Xt,{present:r||s.open,children:s.modal?u.jsx(cC,{...o,ref:t}):u.jsx(uC,{...o,ref:t})})});op.displayName=rr;var cC=m.forwardRef((e,t)=>{const n=un(rr,e.__scopeDialog),r=m.useRef(null),o=He(t,n.contentRef,r);return m.useEffect(()=>{const s=r.current;if(s)return Yi(s)},[]),u.jsx(sp,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:me(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:me(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&s.preventDefault()}),onFocusOutside:me(e.onFocusOutside,s=>s.preventDefault())})}),uC=m.forwardRef((e,t)=>{const n=un(rr,e.__scopeDialog),r=m.useRef(!1),o=m.useRef(!1);return u.jsx(sp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var l,c;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),sp=m.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,a=un(rr,n),l=m.useRef(null),c=He(t,l);return ji(),u.jsxs(u.Fragment,{children:[u.jsx(Go,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:u.jsx(qo,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Oa(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),u.jsxs(u.Fragment,{children:[u.jsx(dC,{titleId:a.titleId}),u.jsx(pC,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Pa="DialogTitle",ip=m.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=un(Pa,n);return u.jsx(Ie.h2,{id:o.titleId,...r,ref:t})});ip.displayName=Pa;var ap="DialogDescription",lp=m.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=un(ap,n);return u.jsx(Ie.p,{id:o.descriptionId,...r,ref:t})});lp.displayName=ap;var cp="DialogClose",up=m.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=un(cp,n);return u.jsx(Ie.button,{type:"button",...r,ref:t,onClick:me(e.onClick,()=>o.onOpenChange(!1))})});up.displayName=cp;function Oa(e){return e?"open":"closed"}var dp="DialogTitleWarning",[mI,fp]=cy(dp,{contentName:rr,titleName:Pa,docsSlug:"dialog"}),dC=({titleId:e})=>{const t=fp(dp),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
88
88
 
89
89
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
90
90
 
91
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return v.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},RS="DialogDescriptionWarning",OS=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${qf(RS).contentName}}.`;return v.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},Gf=Pf,DS=Of,Yf=Lf,js=$f,_s=Ff,nr=zf,Ms=Hf,Xf=Vf;const LS=Gf,$S=Yf,Jf=v.forwardRef(({className:e,...t},n)=>u.jsx(js,{ref:n,className:ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));Jf.displayName=js.displayName;const Zf=v.forwardRef(({className:e,children:t,...n},r)=>{const o=v.useMemo(()=>{let s=!1;function i(a){v.Children.forEach(a,l=>{if(s||!v.isValidElement(l))return;const c=l.type;if(c===nr||(c==null?void 0:c.displayName)===nr.displayName||(c==null?void 0:c.name)==="DialogTitle"){s=!0;return}l.props&&l.props.children&&i(l.props.children)})}return i(t),s},[t]);return u.jsxs($S,{children:[u.jsx(Jf,{}),u.jsxs(_s,{ref:r,className:ee("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[!o&&u.jsx(nr,{className:"sr-only",children:"Dialog"}),t,u.jsxs(Xf,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(oe.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Zf.displayName=_s.displayName;const Qf=({className:e,...t})=>u.jsx("div",{className:ee("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Qf.displayName="DialogHeader";const eh=v.forwardRef(({className:e,...t},n)=>u.jsx(nr,{ref:n,className:ee("text-lg font-semibold leading-none tracking-tight",e),...t}));eh.displayName=nr.displayName;const FS=v.forwardRef(({className:e,...t},n)=>u.jsx(Ms,{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));FS.displayName=Ms.displayName;const BS=1,zS=1e6;let Na=0;function US(){return Na=(Na+1)%Number.MAX_SAFE_INTEGER,Na.toString()}const Aa=new Map,th=e=>{if(Aa.has(e))return;const t=setTimeout(()=>{Aa.delete(e),io({type:"REMOVE_TOAST",toastId:e})},zS);Aa.set(e,t)},HS=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,BS)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?th(n):e.toasts.forEach(r=>{th(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Ps=[];let Rs={toasts:[]};function io(e){Rs=HS(Rs,e),Ps.forEach(t=>{t(Rs)})}function WS({...e}){const t=US(),n=o=>io({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>io({type:"DISMISS_TOAST",toastId:t});return io({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function ja(){const[e,t]=v.useState(Rs);return v.useEffect(()=>(Ps.push(t),()=>{const n=Ps.indexOf(t);n>-1&&Ps.splice(n,1)}),[e]),{...e,toast:WS,dismiss:n=>io({type:"DISMISS_TOAST",toastId:n})}}function VS({isOpen:e,onClose:t,fileId:n,fileName:r,mimeType:o}){const[s,i]=b.useState(!1),[a,l]=b.useState(null),[c,d]=b.useState(null),{toast:f}=ja(),h=b.useCallback(async()=>{if(n){i(!0),d(null),l(null);try{const g=await _f(n);l(g)}catch(g){console.error("Failed to load file:",g),d(g instanceof Error?g.message:"Failed to load file")}finally{i(!1)}}},[n]);b.useEffect(()=>{e&&n&&h()},[e,n,h]);const p=async()=>{if(n)try{await kS(n),f({title:"Download started",description:`Downloading ${r}`})}catch(g){console.error("Failed to download file:",g),f({title:"Download failed",description:String(g),variant:"destructive"})}},y=async()=>{if(n)try{const g=await _f(n),w=new Blob([g],{type:o}),S=URL.createObjectURL(w);window.open(S,"_blank"),URL.revokeObjectURL(S)}catch(g){console.error("Failed to open file externally:",g),f({title:"Failed to open file",description:String(g),variant:"destructive"})}},m=()=>s?u.jsxs("div",{className:"flex items-center justify-center py-12",children:[u.jsx(oe.Loader,{className:"h-8 w-8 animate-spin mr-3"}),u.jsx("span",{children:"Loading file..."})]}):c?u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u.jsx("div",{className:"text-red-500 mb-4",children:"⚠️"}),u.jsx("p",{className:"text-red-600 mb-4",children:c}),u.jsx(tt,{onClick:h,variant:"outline",children:"Try Again"})]}):a?o.startsWith("image/")?u.jsx("div",{className:"flex justify-center",children:u.jsx("img",{src:`data:${o};base64,${a}`,alt:r,className:"max-w-full max-h-[70vh] object-contain rounded-lg"})}):o==="application/pdf"?u.jsx("div",{className:"w-full h-[70vh] border rounded-lg overflow-hidden",children:u.jsx("iframe",{src:`data:application/pdf;base64,${a}`,className:"w-full h-full",title:r})}):o.startsWith("text/")||o.includes("json")||o.includes("xml")?u.jsx("div",{className:"bg-gray-50 dark:bg-gray-900 rounded-lg p-4 max-h-[70vh] overflow-auto",children:u.jsx("pre",{className:"whitespace-pre-wrap font-mono text-sm",children:a})}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u.jsx(oe.FileText,{className:"h-16 w-16 text-gray-400 mb-4"}),u.jsx("p",{className:"text-lg font-medium mb-2",children:r}),u.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:[o," • ",a.length," bytes"]}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"This file type cannot be previewed. Use download or external view."})]}):u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("p",{className:"text-muted-foreground",children:"No content to display"})}),x=()=>o.startsWith("image/")?u.jsx(oe.Image,{className:"h-5 w-5"}):u.jsx(oe.FileText,{className:"h-5 w-5"});return u.jsx(LS,{open:e,onOpenChange:t,children:u.jsxs(Zf,{className:"max-w-4xl max-h-[90vh] overflow-hidden",children:[u.jsx(Qf,{children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[x(),u.jsxs("div",{children:[u.jsx(eh,{className:"text-left",children:r}),u.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[o," • Click download or external view for full access"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs(tt,{variant:"outline",size:"sm",onClick:y,className:"flex items-center gap-2",children:[u.jsx(oe.ExternalLink,{className:"h-4 w-4"}),"External"]}),u.jsxs(tt,{variant:"outline",size:"sm",onClick:p,className:"flex items-center gap-2",children:[u.jsx(oe.Download,{className:"h-4 w-4"}),"Download"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-hidden",children:m()})]})})}function nh(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let rr=nh();function KS(e){rr=e}const rh=/[&<>"']/,qS=new RegExp(rh.source,"g"),oh=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,GS=new RegExp(oh.source,"g"),YS={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},sh=e=>YS[e];function _t(e,t){if(t){if(rh.test(e))return e.replace(qS,sh)}else if(oh.test(e))return e.replace(GS,sh);return e}const XS=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function ih(e){return e.replace(XS,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const JS=/(^|[^\[])\^/g;function st(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(JS,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const ZS=/[^\w:]/g,QS=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function ah(e,t,n){if(e){let r;try{r=decodeURIComponent(ih(n)).replace(ZS,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!QS.test(n)&&(n=rC(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const Os={},eC=/^[^:]+:\/*[^/]*$/,tC=/^([^:]+:)[\s\S]*$/,nC=/^([^:]+:\/*[^/]*)[\s\S]*$/;function rC(e,t){Os[" "+e]||(eC.test(e)?Os[" "+e]=e+"/":Os[" "+e]=Ls(e,"/",!0)),e=Os[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(tC,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(nC,"$1")+t:e+t}const Ds={exec:function(){}};function lh(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let l=!1,c=i;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function Ls(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function oC(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function sC(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function ch(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function uh(e,t,n,r){const o=t.href,s=t.title?_t(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:_t(i)}}function iC(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
91
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return m.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},fC="DialogDescriptionWarning",pC=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${fp(fC).contentName}}.`;return m.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},Da=Zf,hC=ep,La=np,ho=rp,mo=op,or=ip,Bs=lp,pp=up;const hp=Da,mC=La,mp=m.forwardRef(({className:e,...t},n)=>u.jsx(ho,{ref:n,className:se("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));mp.displayName=ho.displayName;const $a=m.forwardRef(({className:e,children:t,...n},r)=>{const o=m.useMemo(()=>{let s=!1;function i(a){m.Children.forEach(a,l=>{if(s||!m.isValidElement(l))return;const c=l.type;if(c===or||(c==null?void 0:c.displayName)===or.displayName||(c==null?void 0:c.name)==="DialogTitle"){s=!0;return}l.props&&l.props.children&&i(l.props.children)})}return i(t),s},[t]);return u.jsxs(mC,{children:[u.jsx(mp,{}),u.jsxs(mo,{ref:r,className:se("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n,children:[!o&&u.jsx(or,{className:"sr-only",children:"Dialog"}),t,u.jsxs(pp,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(ue.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});$a.displayName=mo.displayName;const Fa=({className:e,...t})=>u.jsx("div",{className:se("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});Fa.displayName="DialogHeader";const Ba=m.forwardRef(({className:e,...t},n)=>u.jsx(or,{ref:n,className:se("text-lg font-semibold leading-none tracking-tight",e),...t}));Ba.displayName=or.displayName;const gC=m.forwardRef(({className:e,...t},n)=>u.jsx(Bs,{ref:n,className:se("text-sm text-muted-foreground",e),...t}));gC.displayName=Bs.displayName;const xC=1,yC=1e6;let za=0;function vC(){return za=(za+1)%Number.MAX_SAFE_INTEGER,za.toString()}const Ua=new Map,gp=e=>{if(Ua.has(e))return;const t=setTimeout(()=>{Ua.delete(e),go({type:"REMOVE_TOAST",toastId:e})},yC);Ua.set(e,t)},bC=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,xC)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?gp(n):e.toasts.forEach(r=>{gp(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},zs=[];let Us={toasts:[]};function go(e){Us=bC(Us,e),zs.forEach(t=>{t(Us)})}function wC({...e}){const t=vC(),n=o=>go({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>go({type:"DISMISS_TOAST",toastId:t});return go({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Ha(){const[e,t]=m.useState(Us);return m.useEffect(()=>(zs.push(t),()=>{const n=zs.indexOf(t);n>-1&&zs.splice(n,1)}),[e]),{...e,toast:wC,dismiss:n=>go({type:"DISMISS_TOAST",toastId:n})}}function SC({isOpen:e,onClose:t,fileId:n,fileName:r,mimeType:o}){const[s,i]=w.useState(!1),[a,l]=w.useState(null),[c,d]=w.useState(null),{toast:f}=Ha(),p=w.useCallback(async()=>{if(n){i(!0),d(null),l(null);try{const x=await Xf(n);l(x)}catch(x){console.error("Failed to load file:",x),d(x instanceof Error?x.message:"Failed to load file")}finally{i(!1)}}},[n]);w.useEffect(()=>{e&&n&&p()},[e,n,p]);const h=async()=>{if(n)try{await rC(n),f({title:"Download started",description:`Downloading ${r}`})}catch(x){console.error("Failed to download file:",x),f({title:"Download failed",description:String(x),variant:"destructive"})}},v=async()=>{if(n)try{const x=await Xf(n),b=new Blob([x],{type:o}),C=URL.createObjectURL(b);window.open(C,"_blank"),URL.revokeObjectURL(C)}catch(x){console.error("Failed to open file externally:",x),f({title:"Failed to open file",description:String(x),variant:"destructive"})}},g=()=>s?u.jsxs("div",{className:"flex items-center justify-center py-12",children:[u.jsx(ue.Loader,{className:"h-8 w-8 animate-spin mr-3"}),u.jsx("span",{children:"Loading file..."})]}):c?u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u.jsx("div",{className:"text-red-500 mb-4",children:"⚠️"}),u.jsx("p",{className:"text-red-600 mb-4",children:c}),u.jsx(rt,{onClick:p,variant:"outline",children:"Try Again"})]}):a?o.startsWith("image/")?u.jsx("div",{className:"flex justify-center",children:u.jsx("img",{src:`data:${o};base64,${a}`,alt:r,className:"max-w-full max-h-[70vh] object-contain rounded-lg"})}):o==="application/pdf"?u.jsx("div",{className:"w-full h-[70vh] border rounded-lg overflow-hidden",children:u.jsx("iframe",{src:`data:application/pdf;base64,${a}`,className:"w-full h-full",title:r})}):o.startsWith("text/")||o.includes("json")||o.includes("xml")?u.jsx("div",{className:"bg-gray-50 dark:bg-gray-900 rounded-lg p-4 max-h-[70vh] overflow-auto",children:u.jsx("pre",{className:"whitespace-pre-wrap font-mono text-sm",children:a})}):u.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u.jsx(ue.FileText,{className:"h-16 w-16 text-gray-400 mb-4"}),u.jsx("p",{className:"text-lg font-medium mb-2",children:r}),u.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:[o," • ",a.length," bytes"]}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"This file type cannot be previewed. Use download or external view."})]}):u.jsx("div",{className:"flex items-center justify-center py-12",children:u.jsx("p",{className:"text-muted-foreground",children:"No content to display"})}),y=()=>o.startsWith("image/")?u.jsx(ue.Image,{className:"h-5 w-5"}):u.jsx(ue.FileText,{className:"h-5 w-5"});return u.jsx(hp,{open:e,onOpenChange:t,children:u.jsxs($a,{className:"max-w-4xl max-h-[90vh] overflow-hidden",children:[u.jsx(Fa,{children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[y(),u.jsxs("div",{children:[u.jsx(Ba,{className:"text-left",children:r}),u.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[o," • Click download or external view for full access"]})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs(rt,{variant:"outline",size:"sm",onClick:v,className:"flex items-center gap-2",children:[u.jsx(ue.ExternalLink,{className:"h-4 w-4"}),"External"]}),u.jsxs(rt,{variant:"outline",size:"sm",onClick:h,className:"flex items-center gap-2",children:[u.jsx(ue.Download,{className:"h-4 w-4"}),"Download"]})]})]})}),u.jsx("div",{className:"flex-1 overflow-hidden",children:g()})]})})}function xp(){return{async:!1,baseUrl:null,breaks:!1,extensions:null,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,hooks:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:null,sanitize:!1,sanitizer:null,silent:!1,smartypants:!1,tokenizer:null,walkTokens:null,xhtml:!1}}let sr=xp();function CC(e){sr=e}const yp=/[&<>"']/,TC=new RegExp(yp.source,"g"),vp=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,kC=new RegExp(vp.source,"g"),IC={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},bp=e=>IC[e];function _t(e,t){if(t){if(yp.test(e))return e.replace(TC,bp)}else if(vp.test(e))return e.replace(kC,bp);return e}const EC=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function wp(e){return e.replace(EC,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const NC=/(^|[^\[])\^/g;function st(e,t){e=typeof e=="string"?e:e.source,t=t||"";const n={replace:(r,o)=>(o=o.source||o,o=o.replace(NC,"$1"),e=e.replace(r,o),n),getRegex:()=>new RegExp(e,t)};return n}const AC=/[^\w:]/g,jC=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function Sp(e,t,n){if(e){let r;try{r=decodeURIComponent(wp(n)).replace(AC,"").toLowerCase()}catch{return null}if(r.indexOf("javascript:")===0||r.indexOf("vbscript:")===0||r.indexOf("data:")===0)return null}t&&!jC.test(n)&&(n=PC(t,n));try{n=encodeURI(n).replace(/%25/g,"%")}catch{return null}return n}const Hs={},_C=/^[^:]+:\/*[^/]*$/,MC=/^([^:]+:)[\s\S]*$/,RC=/^([^:]+:\/*[^/]*)[\s\S]*$/;function PC(e,t){Hs[" "+e]||(_C.test(e)?Hs[" "+e]=e+"/":Hs[" "+e]=Vs(e,"/",!0)),e=Hs[" "+e];const n=e.indexOf(":")===-1;return t.substring(0,2)==="//"?n?t:e.replace(MC,"$1")+t:t.charAt(0)==="/"?n?t:e.replace(RC,"$1")+t:e+t}const Ws={exec:function(){}};function Cp(e,t){const n=e.replace(/\|/g,(s,i,a)=>{let l=!1,c=i;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(/ \|/);let o=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(/\\\|/g,"|");return r}function Vs(e,t,n){const r=e.length;if(r===0)return"";let o=0;for(;o<r;){const s=e.charAt(r-o-1);if(s===t&&!n)o++;else if(s!==t&&n)o++;else break}return e.slice(0,r-o)}function OC(e,t){if(e.indexOf(t[1])===-1)return-1;const n=e.length;let r=0,o=0;for(;o<n;o++)if(e[o]==="\\")o++;else if(e[o]===t[0])r++;else if(e[o]===t[1]&&(r--,r<0))return o;return-1}function DC(e){e&&e.sanitize&&!e.silent&&console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options")}function Tp(e,t){if(t<1)return"";let n="";for(;t>1;)t&1&&(n+=e),t>>=1,e+=e;return n+e}function kp(e,t,n,r){const o=t.href,s=t.title?_t(t.title):null,i=e[1].replace(/\\([\[\]])/g,"$1");if(e[0].charAt(0)!=="!"){r.state.inLink=!0;const a={type:"link",raw:n,href:o,title:s,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,a}return{type:"image",raw:n,href:o,title:s,text:_t(i)}}function LC(e,t){const n=e.match(/^(\s+)(?:```)/);if(n===null)return t;const r=n[1];return t.split(`
92
92
  `).map(o=>{const s=o.match(/^\s+/);if(s===null)return o;const[i]=s;return i.length>=r.length?o.slice(r.length):o}).join(`
93
- `)}class _a{constructor(t){this.options=t||rr}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:Ls(r,`
94
- `)}}}fences(t){const n=this.rules.block.fences.exec(t);if(n){const r=n[0],o=iC(r,n[3]||"");return{type:"code",raw:r,lang:n[2]?n[2].trim().replace(this.rules.inline._escapes,"$1"):n[2],text:o}}}heading(t){const n=this.rules.block.heading.exec(t);if(n){let r=n[2].trim();if(/#$/.test(r)){const o=Ls(r,"#");(this.options.pedantic||!o||/ $/.test(o))&&(r=o.trim())}return{type:"heading",raw:n[0],depth:n[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){const n=this.rules.block.hr.exec(t);if(n)return{type:"hr",raw:n[0]}}blockquote(t){const n=this.rules.block.blockquote.exec(t);if(n){const r=n[0].replace(/^ *>[ \t]?/gm,""),o=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(r);return this.lexer.state.top=o,{type:"blockquote",raw:n[0],tokens:s,text:r}}}list(t){let n=this.rules.block.list.exec(t);if(n){let r,o,s,i,a,l,c,d,f,h,p,y,m=n[1].trim();const x=m.length>1,g={type:"list",raw:"",ordered:x,start:x?+m.slice(0,-1):"",loose:!1,items:[]};m=x?`\\d{1,9}\\${m.slice(-1)}`:`\\${m}`,this.options.pedantic&&(m=x?m:"[*+-]");const w=new RegExp(`^( {0,3}${m})((?:[ ][^\\n]*)?(?:\\n|$))`);for(;t&&(y=!1,!(!(n=w.exec(t))||this.rules.block.hr.test(t)));){if(r=n[0],t=t.substring(r.length),d=n[2].split(`
93
+ `)}class Wa{constructor(t){this.options=t||sr}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:Vs(r,`
94
+ `)}}}fences(t){const n=this.rules.block.fences.exec(t);if(n){const r=n[0],o=LC(r,n[3]||"");return{type:"code",raw:r,lang:n[2]?n[2].trim().replace(this.rules.inline._escapes,"$1"):n[2],text:o}}}heading(t){const n=this.rules.block.heading.exec(t);if(n){let r=n[2].trim();if(/#$/.test(r)){const o=Vs(r,"#");(this.options.pedantic||!o||/ $/.test(o))&&(r=o.trim())}return{type:"heading",raw:n[0],depth:n[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){const n=this.rules.block.hr.exec(t);if(n)return{type:"hr",raw:n[0]}}blockquote(t){const n=this.rules.block.blockquote.exec(t);if(n){const r=n[0].replace(/^ *>[ \t]?/gm,""),o=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(r);return this.lexer.state.top=o,{type:"blockquote",raw:n[0],tokens:s,text:r}}}list(t){let n=this.rules.block.list.exec(t);if(n){let r,o,s,i,a,l,c,d,f,p,h,v,g=n[1].trim();const y=g.length>1,x={type:"list",raw:"",ordered:y,start:y?+g.slice(0,-1):"",loose:!1,items:[]};g=y?`\\d{1,9}\\${g.slice(-1)}`:`\\${g}`,this.options.pedantic&&(g=y?g:"[*+-]");const b=new RegExp(`^( {0,3}${g})((?:[ ][^\\n]*)?(?:\\n|$))`);for(;t&&(v=!1,!(!(n=b.exec(t))||this.rules.block.hr.test(t)));){if(r=n[0],t=t.substring(r.length),d=n[2].split(`
95
95
  `,1)[0].replace(/^\t+/,k=>" ".repeat(3*k.length)),f=t.split(`
96
- `,1)[0],this.options.pedantic?(i=2,p=d.trimLeft()):(i=n[2].search(/[^ ]/),i=i>4?1:i,p=d.slice(i),i+=n[1].length),l=!1,!d&&/^ *$/.test(f)&&(r+=f+`
97
- `,t=t.substring(f.length+1),y=!0),!y){const k=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),C=new RegExp(`^ {0,${Math.min(3,i-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),T=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:\`\`\`|~~~)`),I=new RegExp(`^ {0,${Math.min(3,i-1)}}#`);for(;t&&(h=t.split(`
98
- `,1)[0],f=h,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(T.test(f)||I.test(f)||k.test(f)||C.test(t)));){if(f.search(/[^ ]/)>=i||!f.trim())p+=`
99
- `+f.slice(i);else{if(l||d.search(/[^ ]/)>=4||T.test(d)||I.test(d)||C.test(d))break;p+=`
100
- `+f}!l&&!f.trim()&&(l=!0),r+=h+`
101
- `,t=t.substring(h.length+1),d=f.slice(i)}}g.loose||(c?g.loose=!0:/\n *\n *$/.test(r)&&(c=!0)),this.options.gfm&&(o=/^\[[ xX]\] /.exec(p),o&&(s=o[0]!=="[ ] ",p=p.replace(/^\[[ xX]\] +/,""))),g.items.push({type:"list_item",raw:r,task:!!o,checked:s,loose:!1,text:p}),g.raw+=r}g.items[g.items.length-1].raw=r.trimRight(),g.items[g.items.length-1].text=p.trimRight(),g.raw=g.raw.trimRight();const S=g.items.length;for(a=0;a<S;a++)if(this.lexer.state.top=!1,g.items[a].tokens=this.lexer.blockTokens(g.items[a].text,[]),!g.loose){const k=g.items[a].tokens.filter(T=>T.type==="space"),C=k.length>0&&k.some(T=>/\n.*\n/.test(T.raw));g.loose=C}if(g.loose)for(a=0;a<S;a++)g.items[a].loose=!0;return g}}html(t){const n=this.rules.block.html.exec(t);if(n){const r={type:"html",raw:n[0],pre:!this.options.sanitizer&&(n[1]==="pre"||n[1]==="script"||n[1]==="style"),text:n[0]};if(this.options.sanitize){const o=this.options.sanitizer?this.options.sanitizer(n[0]):_t(n[0]);r.type="paragraph",r.text=o,r.tokens=this.lexer.inline(o)}return r}}def(t){const n=this.rules.block.def.exec(t);if(n){const r=n[1].toLowerCase().replace(/\s+/g," "),o=n[2]?n[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline._escapes,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:o,title:s}}}table(t){const n=this.rules.block.table.exec(t);if(n){const r={type:"table",header:lh(n[1]).map(o=>({text:o})),align:n[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:n[3]&&n[3].trim()?n[3].replace(/\n[ \t]*$/,"").split(`
102
- `):[]};if(r.header.length===r.align.length){r.raw=n[0];let o=r.align.length,s,i,a,l;for(s=0;s<o;s++)/^ *-+: *$/.test(r.align[s])?r.align[s]="right":/^ *:-+: *$/.test(r.align[s])?r.align[s]="center":/^ *:-+ *$/.test(r.align[s])?r.align[s]="left":r.align[s]=null;for(o=r.rows.length,s=0;s<o;s++)r.rows[s]=lh(r.rows[s],r.header.length).map(c=>({text:c}));for(o=r.header.length,i=0;i<o;i++)r.header[i].tokens=this.lexer.inline(r.header[i].text);for(o=r.rows.length,i=0;i<o;i++)for(l=r.rows[i],a=0;a<l.length;a++)l[a].tokens=this.lexer.inline(l[a].text);return r}}}lheading(t){const n=this.rules.block.lheading.exec(t);if(n)return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:n[1],tokens:this.lexer.inline(n[1])}}paragraph(t){const n=this.rules.block.paragraph.exec(t);if(n){const r=n[1].charAt(n[1].length-1)===`
103
- `?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){const n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){const n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:_t(n[1])}}tag(t){const n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&/^<a /i.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):_t(n[0]):n[0]}}link(t){const n=this.rules.inline.link.exec(t);if(n){const r=n[2].trim();if(!this.options.pedantic&&/^</.test(r)){if(!/>$/.test(r))return;const i=Ls(r.slice(0,-1),"\\");if((r.length-i.length)%2===0)return}else{const i=oC(n[2],"()");if(i>-1){const l=(n[0].indexOf("!")===0?5:4)+n[1].length+i;n[2]=n[2].substring(0,i),n[0]=n[0].substring(0,l).trim(),n[3]=""}}let o=n[2],s="";if(this.options.pedantic){const i=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);i&&(o=i[1],s=i[3])}else s=n[3]?n[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(r)?o=o.slice(1):o=o.slice(1,-1)),uh(n,{href:o&&o.replace(this.rules.inline._escapes,"$1"),title:s&&s.replace(this.rules.inline._escapes,"$1")},n[0],this.lexer)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let o=(r[2]||r[1]).replace(/\s+/g," ");if(o=n[o.toLowerCase()],!o){const s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return uh(r,o,r[0],this.lexer)}}emStrong(t,n,r=""){let o=this.rules.inline.emStrong.lDelim.exec(t);if(!o||o[3]&&r.match(/[\p{L}\p{N}]/u))return;const s=o[1]||o[2]||"";if(!s||s&&(r===""||this.rules.inline.punctuation.exec(r))){const i=o[0].length-1;let a,l,c=i,d=0;const f=o[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,n=n.slice(-1*t.length+i);(o=f.exec(n))!=null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(l=a.length,o[3]||o[4]){c+=l;continue}else if((o[5]||o[6])&&i%3&&!((i+l)%3)){d+=l;continue}if(c-=l,c>0)continue;l=Math.min(l,l+c+d);const h=t.slice(0,i+o.index+(o[0].length-a.length)+l);if(Math.min(i,l)%2){const y=h.slice(1,-1);return{type:"em",raw:h,text:y,tokens:this.lexer.inlineTokens(y)}}const p=h.slice(2,-2);return{type:"strong",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(t){const n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(/\n/g," ");const o=/[^ ]/.test(r),s=/^ /.test(r)&&/ $/.test(r);return o&&s&&(r=r.substring(1,r.length-1)),r=_t(r,!0),{type:"codespan",raw:n[0],text:r}}}br(t){const n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t){const n=this.rules.inline.del.exec(t);if(n)return{type:"del",raw:n[0],text:n[2],tokens:this.lexer.inlineTokens(n[2])}}autolink(t,n){const r=this.rules.inline.autolink.exec(t);if(r){let o,s;return r[2]==="@"?(o=_t(this.options.mangle?n(r[1]):r[1]),s="mailto:"+o):(o=_t(r[1]),s=o),{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}url(t,n){let r;if(r=this.rules.inline.url.exec(t)){let o,s;if(r[2]==="@")o=_t(this.options.mangle?n(r[0]):r[0]),s="mailto:"+o;else{let i;do i=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(i!==r[0]);o=_t(r[0]),r[1]==="www."?s="http://"+r[0]:s=r[0]}return{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}inlineText(t,n){const r=this.rules.inline.text.exec(t);if(r){let o;return this.lexer.state.inRawBlock?o=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):_t(r[0]):r[0]:o=_t(this.options.smartypants?n(r[0]):r[0]),{type:"text",raw:r[0],text:o}}}}const we={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:Ds,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};we._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/,we._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,we.def=st(we.def).replace("label",we._label).replace("title",we._title).getRegex(),we.bullet=/(?:[*+-]|\d{1,9}[.)])/,we.listItemStart=st(/^( *)(bull) */).replace("bull",we.bullet).getRegex(),we.list=st(we.list).replace(/bull/g,we.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+we.def.source+")").getRegex(),we._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",we._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,we.html=st(we.html,"i").replace("comment",we._comment).replace("tag",we._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),we.paragraph=st(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.blockquote=st(we.blockquote).replace("paragraph",we.paragraph).getRegex(),we.normal={...we},we.gfm={...we.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},we.gfm.table=st(we.gfm.table).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.gfm.paragraph=st(we._paragraph).replace("hr",we.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",we.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",we._tag).getRegex(),we.pedantic={...we.normal,html:st(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",we._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ds,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:st(we.normal._paragraph).replace("hr",we.hr).replace("heading",` *#{1,6} *[^
104
- ]`).replace("lheading",we.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const ae={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:Ds,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:Ds,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};ae._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",ae.punctuation=st(ae.punctuation).replace(/punctuation/g,ae._punctuation).getRegex(),ae.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,ae.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,ae._comment=st(we._comment).replace("(?:-->|$)","-->").getRegex(),ae.emStrong.lDelim=st(ae.emStrong.lDelim).replace(/punct/g,ae._punctuation).getRegex(),ae.emStrong.rDelimAst=st(ae.emStrong.rDelimAst,"g").replace(/punct/g,ae._punctuation).getRegex(),ae.emStrong.rDelimUnd=st(ae.emStrong.rDelimUnd,"g").replace(/punct/g,ae._punctuation).getRegex(),ae._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,ae._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,ae._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,ae.autolink=st(ae.autolink).replace("scheme",ae._scheme).replace("email",ae._email).getRegex(),ae._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,ae.tag=st(ae.tag).replace("comment",ae._comment).replace("attribute",ae._attribute).getRegex(),ae._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,ae._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,ae._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,ae.link=st(ae.link).replace("label",ae._label).replace("href",ae._href).replace("title",ae._title).getRegex(),ae.reflink=st(ae.reflink).replace("label",ae._label).replace("ref",we._label).getRegex(),ae.nolink=st(ae.nolink).replace("ref",we._label).getRegex(),ae.reflinkSearch=st(ae.reflinkSearch,"g").replace("reflink",ae.reflink).replace("nolink",ae.nolink).getRegex(),ae.normal={...ae},ae.pedantic={...ae.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:st(/^!?\[(label)\]\((.*?)\)/).replace("label",ae._label).getRegex(),reflink:st(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ae._label).getRegex()},ae.gfm={...ae.normal,escape:st(ae.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},ae.gfm.url=st(ae.gfm.url,"i").replace("email",ae.gfm._extended_email).getRegex(),ae.breaks={...ae.gfm,br:st(ae.br).replace("{2,}","*").getRegex(),text:st(ae.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};function aC(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function dh(e){let t="",n,r;const o=e.length;for(n=0;n<o;n++)r=e.charCodeAt(n),Math.random()>.5&&(r="x"+r.toString(16)),t+="&#"+r+";";return t}class Dn{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||rr,this.options.tokenizer=this.options.tokenizer||new _a,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:we.normal,inline:ae.normal};this.options.pedantic?(n.block=we.pedantic,n.inline=ae.pedantic):this.options.gfm&&(n.block=we.gfm,this.options.breaks?n.inline=ae.breaks:n.inline=ae.gfm),this.tokenizer.rules=n}static get rules(){return{block:we,inline:ae}}static lex(t,n){return new Dn(n).lex(t)}static lexInline(t,n){return new Dn(n).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
96
+ `,1)[0],this.options.pedantic?(i=2,h=d.trimLeft()):(i=n[2].search(/[^ ]/),i=i>4?1:i,h=d.slice(i),i+=n[1].length),l=!1,!d&&/^ *$/.test(f)&&(r+=f+`
97
+ `,t=t.substring(f.length+1),v=!0),!v){const k=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),T=new RegExp(`^ {0,${Math.min(3,i-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),S=new RegExp(`^ {0,${Math.min(3,i-1)}}(?:\`\`\`|~~~)`),I=new RegExp(`^ {0,${Math.min(3,i-1)}}#`);for(;t&&(p=t.split(`
98
+ `,1)[0],f=p,this.options.pedantic&&(f=f.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),!(S.test(f)||I.test(f)||k.test(f)||T.test(t)));){if(f.search(/[^ ]/)>=i||!f.trim())h+=`
99
+ `+f.slice(i);else{if(l||d.search(/[^ ]/)>=4||S.test(d)||I.test(d)||T.test(d))break;h+=`
100
+ `+f}!l&&!f.trim()&&(l=!0),r+=p+`
101
+ `,t=t.substring(p.length+1),d=f.slice(i)}}x.loose||(c?x.loose=!0:/\n *\n *$/.test(r)&&(c=!0)),this.options.gfm&&(o=/^\[[ xX]\] /.exec(h),o&&(s=o[0]!=="[ ] ",h=h.replace(/^\[[ xX]\] +/,""))),x.items.push({type:"list_item",raw:r,task:!!o,checked:s,loose:!1,text:h}),x.raw+=r}x.items[x.items.length-1].raw=r.trimRight(),x.items[x.items.length-1].text=h.trimRight(),x.raw=x.raw.trimRight();const C=x.items.length;for(a=0;a<C;a++)if(this.lexer.state.top=!1,x.items[a].tokens=this.lexer.blockTokens(x.items[a].text,[]),!x.loose){const k=x.items[a].tokens.filter(S=>S.type==="space"),T=k.length>0&&k.some(S=>/\n.*\n/.test(S.raw));x.loose=T}if(x.loose)for(a=0;a<C;a++)x.items[a].loose=!0;return x}}html(t){const n=this.rules.block.html.exec(t);if(n){const r={type:"html",raw:n[0],pre:!this.options.sanitizer&&(n[1]==="pre"||n[1]==="script"||n[1]==="style"),text:n[0]};if(this.options.sanitize){const o=this.options.sanitizer?this.options.sanitizer(n[0]):_t(n[0]);r.type="paragraph",r.text=o,r.tokens=this.lexer.inline(o)}return r}}def(t){const n=this.rules.block.def.exec(t);if(n){const r=n[1].toLowerCase().replace(/\s+/g," "),o=n[2]?n[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline._escapes,"$1"):"",s=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline._escapes,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:o,title:s}}}table(t){const n=this.rules.block.table.exec(t);if(n){const r={type:"table",header:Cp(n[1]).map(o=>({text:o})),align:n[2].replace(/^ *|\| *$/g,"").split(/ *\| */),rows:n[3]&&n[3].trim()?n[3].replace(/\n[ \t]*$/,"").split(`
102
+ `):[]};if(r.header.length===r.align.length){r.raw=n[0];let o=r.align.length,s,i,a,l;for(s=0;s<o;s++)/^ *-+: *$/.test(r.align[s])?r.align[s]="right":/^ *:-+: *$/.test(r.align[s])?r.align[s]="center":/^ *:-+ *$/.test(r.align[s])?r.align[s]="left":r.align[s]=null;for(o=r.rows.length,s=0;s<o;s++)r.rows[s]=Cp(r.rows[s],r.header.length).map(c=>({text:c}));for(o=r.header.length,i=0;i<o;i++)r.header[i].tokens=this.lexer.inline(r.header[i].text);for(o=r.rows.length,i=0;i<o;i++)for(l=r.rows[i],a=0;a<l.length;a++)l[a].tokens=this.lexer.inline(l[a].text);return r}}}lheading(t){const n=this.rules.block.lheading.exec(t);if(n)return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:n[1],tokens:this.lexer.inline(n[1])}}paragraph(t){const n=this.rules.block.paragraph.exec(t);if(n){const r=n[1].charAt(n[1].length-1)===`
103
+ `?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){const n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){const n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:_t(n[1])}}tag(t){const n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&/^<a /i.test(n[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:this.options.sanitize?"text":"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,text:this.options.sanitize?this.options.sanitizer?this.options.sanitizer(n[0]):_t(n[0]):n[0]}}link(t){const n=this.rules.inline.link.exec(t);if(n){const r=n[2].trim();if(!this.options.pedantic&&/^</.test(r)){if(!/>$/.test(r))return;const i=Vs(r.slice(0,-1),"\\");if((r.length-i.length)%2===0)return}else{const i=OC(n[2],"()");if(i>-1){const l=(n[0].indexOf("!")===0?5:4)+n[1].length+i;n[2]=n[2].substring(0,i),n[0]=n[0].substring(0,l).trim(),n[3]=""}}let o=n[2],s="";if(this.options.pedantic){const i=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(o);i&&(o=i[1],s=i[3])}else s=n[3]?n[3].slice(1,-1):"";return o=o.trim(),/^</.test(o)&&(this.options.pedantic&&!/>$/.test(r)?o=o.slice(1):o=o.slice(1,-1)),kp(n,{href:o&&o.replace(this.rules.inline._escapes,"$1"),title:s&&s.replace(this.rules.inline._escapes,"$1")},n[0],this.lexer)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let o=(r[2]||r[1]).replace(/\s+/g," ");if(o=n[o.toLowerCase()],!o){const s=r[0].charAt(0);return{type:"text",raw:s,text:s}}return kp(r,o,r[0],this.lexer)}}emStrong(t,n,r=""){let o=this.rules.inline.emStrong.lDelim.exec(t);if(!o||o[3]&&r.match(/[\p{L}\p{N}]/u))return;const s=o[1]||o[2]||"";if(!s||s&&(r===""||this.rules.inline.punctuation.exec(r))){const i=o[0].length-1;let a,l,c=i,d=0;const f=o[0][0]==="*"?this.rules.inline.emStrong.rDelimAst:this.rules.inline.emStrong.rDelimUnd;for(f.lastIndex=0,n=n.slice(-1*t.length+i);(o=f.exec(n))!=null;){if(a=o[1]||o[2]||o[3]||o[4]||o[5]||o[6],!a)continue;if(l=a.length,o[3]||o[4]){c+=l;continue}else if((o[5]||o[6])&&i%3&&!((i+l)%3)){d+=l;continue}if(c-=l,c>0)continue;l=Math.min(l,l+c+d);const p=t.slice(0,i+o.index+(o[0].length-a.length)+l);if(Math.min(i,l)%2){const v=p.slice(1,-1);return{type:"em",raw:p,text:v,tokens:this.lexer.inlineTokens(v)}}const h=p.slice(2,-2);return{type:"strong",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(t){const n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(/\n/g," ");const o=/[^ ]/.test(r),s=/^ /.test(r)&&/ $/.test(r);return o&&s&&(r=r.substring(1,r.length-1)),r=_t(r,!0),{type:"codespan",raw:n[0],text:r}}}br(t){const n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t){const n=this.rules.inline.del.exec(t);if(n)return{type:"del",raw:n[0],text:n[2],tokens:this.lexer.inlineTokens(n[2])}}autolink(t,n){const r=this.rules.inline.autolink.exec(t);if(r){let o,s;return r[2]==="@"?(o=_t(this.options.mangle?n(r[1]):r[1]),s="mailto:"+o):(o=_t(r[1]),s=o),{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}url(t,n){let r;if(r=this.rules.inline.url.exec(t)){let o,s;if(r[2]==="@")o=_t(this.options.mangle?n(r[0]):r[0]),s="mailto:"+o;else{let i;do i=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])[0];while(i!==r[0]);o=_t(r[0]),r[1]==="www."?s="http://"+r[0]:s=r[0]}return{type:"link",raw:r[0],text:o,href:s,tokens:[{type:"text",raw:o,text:o}]}}}inlineText(t,n){const r=this.rules.inline.text.exec(t);if(r){let o;return this.lexer.state.inRawBlock?o=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(r[0]):_t(r[0]):r[0]:o=_t(this.options.smartypants?n(r[0]):r[0]),{type:"text",raw:r[0],text:o}}}}const Te={newline:/^(?: *(?:\n|$))+/,code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr:/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,html:"^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",def:/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,table:Ws,lheading:/^((?:.|\n(?!\n))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,text:/^[^\n]+/};Te._label=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Te._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,Te.def=st(Te.def).replace("label",Te._label).replace("title",Te._title).getRegex(),Te.bullet=/(?:[*+-]|\d{1,9}[.)])/,Te.listItemStart=st(/^( *)(bull) */).replace("bull",Te.bullet).getRegex(),Te.list=st(Te.list).replace(/bull/g,Te.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+Te.def.source+")").getRegex(),Te._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Te._comment=/<!--(?!-?>)[\s\S]*?(?:-->|$)/,Te.html=st(Te.html,"i").replace("comment",Te._comment).replace("tag",Te._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Te.paragraph=st(Te._paragraph).replace("hr",Te.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Te._tag).getRegex(),Te.blockquote=st(Te.blockquote).replace("paragraph",Te.paragraph).getRegex(),Te.normal={...Te},Te.gfm={...Te.normal,table:"^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"},Te.gfm.table=st(Te.gfm.table).replace("hr",Te.hr).replace("heading"," {0,3}#{1,6} ").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Te._tag).getRegex(),Te.gfm.paragraph=st(Te._paragraph).replace("hr",Te.hr).replace("heading"," {0,3}#{1,6} ").replace("|lheading","").replace("table",Te.gfm.table).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Te._tag).getRegex(),Te.pedantic={...Te.normal,html:st(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Te._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ws,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:st(Te.normal._paragraph).replace("hr",Te.hr).replace("heading",` *#{1,6} *[^
104
+ ]`).replace("lheading",Te.lheading).replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").getRegex()};const he={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:Ws,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(ref)\]/,nolink:/^!?\[(ref)\](?:\[\])?/,reflinkSearch:"reflink|nolink(?!\\()",emStrong:{lDelim:/^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,rDelimAst:/^(?:[^_*\\]|\\.)*?\_\_(?:[^_*\\]|\\.)*?\*(?:[^_*\\]|\\.)*?(?=\_\_)|(?:[^*\\]|\\.)+(?=[^*])|[punct_](\*+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|(?:[^punct*_\s\\]|\\.)(\*+)(?=[^punct*_\s])/,rDelimUnd:/^(?:[^_*\\]|\\.)*?\*\*(?:[^_*\\]|\\.)*?\_(?:[^_*\\]|\\.)*?(?=\*\*)|(?:[^_\\]|\\.)+(?=[^_])|[punct*](\_+)(?=[\s]|$)|(?:[^punct*_\s\\]|\\.)(\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/},code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:Ws,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,punctuation:/^([\spunctuation])/};he._punctuation="!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~",he.punctuation=st(he.punctuation).replace(/punctuation/g,he._punctuation).getRegex(),he.blockSkip=/\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g,he.escapedEmSt=/(?:^|[^\\])(?:\\\\)*\\[*_]/g,he._comment=st(Te._comment).replace("(?:-->|$)","-->").getRegex(),he.emStrong.lDelim=st(he.emStrong.lDelim).replace(/punct/g,he._punctuation).getRegex(),he.emStrong.rDelimAst=st(he.emStrong.rDelimAst,"g").replace(/punct/g,he._punctuation).getRegex(),he.emStrong.rDelimUnd=st(he.emStrong.rDelimUnd,"g").replace(/punct/g,he._punctuation).getRegex(),he._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,he._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,he._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,he.autolink=st(he.autolink).replace("scheme",he._scheme).replace("email",he._email).getRegex(),he._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,he.tag=st(he.tag).replace("comment",he._comment).replace("attribute",he._attribute).getRegex(),he._label=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,he._href=/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/,he._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,he.link=st(he.link).replace("label",he._label).replace("href",he._href).replace("title",he._title).getRegex(),he.reflink=st(he.reflink).replace("label",he._label).replace("ref",Te._label).getRegex(),he.nolink=st(he.nolink).replace("ref",Te._label).getRegex(),he.reflinkSearch=st(he.reflinkSearch,"g").replace("reflink",he.reflink).replace("nolink",he.nolink).getRegex(),he.normal={...he},he.pedantic={...he.normal,strong:{start:/^__|\*\*/,middle:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,endAst:/\*\*(?!\*)/g,endUnd:/__(?!_)/g},em:{start:/^_|\*/,middle:/^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,endAst:/\*(?!\*)/g,endUnd:/_(?!_)/g},link:st(/^!?\[(label)\]\((.*?)\)/).replace("label",he._label).getRegex(),reflink:st(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",he._label).getRegex()},he.gfm={...he.normal,escape:st(he.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},he.gfm.url=st(he.gfm.url,"i").replace("email",he.gfm._extended_email).getRegex(),he.breaks={...he.gfm,br:st(he.br).replace("{2,}","*").getRegex(),text:st(he.gfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()};function $C(e){return e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")}function Ip(e){let t="",n,r;const o=e.length;for(n=0;n<o;n++)r=e.charCodeAt(n),Math.random()>.5&&(r="x"+r.toString(16)),t+="&#"+r+";";return t}class Fn{constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||sr,this.options.tokenizer=this.options.tokenizer||new Wa,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:Te.normal,inline:he.normal};this.options.pedantic?(n.block=Te.pedantic,n.inline=he.pedantic):this.options.gfm&&(n.block=Te.gfm,this.options.breaks?n.inline=he.breaks:n.inline=he.gfm),this.tokenizer.rules=n}static get rules(){return{block:Te,inline:he}}static lex(t,n){return new Fn(n).lex(t)}static lexInline(t,n){return new Fn(n).inlineTokens(t)}lex(t){t=t.replace(/\r\n|\r/g,`
105
105
  `),this.blockTokens(t,this.tokens);let n;for(;n=this.inlineQueue.shift();)this.inlineTokens(n.src,n.tokens);return this.tokens}blockTokens(t,n=[]){this.options.pedantic?t=t.replace(/\t/g," ").replace(/^ +$/gm,""):t=t.replace(/^( *)(\t+)/gm,(a,l,c)=>l+" ".repeat(c.length));let r,o,s,i;for(;t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(a=>(r=a.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length),r.raw.length===1&&n.length>0?n[n.length-1].raw+=`
106
106
  `:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&(o.type==="paragraph"||o.type==="text")?(o.raw+=`
107
107
  `+r.raw,o.text+=`
@@ -111,7 +111,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
111
111
  `+r.raw,o.text+=`
112
112
  `+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):n.push(r),i=s.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&o.type==="text"?(o.raw+=`
113
113
  `+r.raw,o.text+=`
114
- `+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):n.push(r);continue}if(t){const a="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let r,o,s,i=t,a,l,c;if(this.tokens.links){const d=Object.keys(this.tokens.links);if(d.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)d.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,a.index)+"["+ch("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)i=i.slice(0,a.index)+"["+ch("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(i))!=null;)i=i.slice(0,a.index+a[0].length-2)+"++"+i.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;t;)if(l||(c=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(d=>(r=d.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.escape(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.tag(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.link(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.emStrong(t,i,c)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.codespan(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.br(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.del(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.autolink(t,dh)){t=t.substring(r.raw.length),n.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(t,dh))){t=t.substring(r.raw.length),n.push(r);continue}if(s=t,this.options.extensions&&this.options.extensions.startInline){let d=1/0;const f=t.slice(1);let h;this.options.extensions.startInline.forEach(function(p){h=p.call({lexer:this},f),typeof h=="number"&&h>=0&&(d=Math.min(d,h))}),d<1/0&&d>=0&&(s=t.substring(0,d+1))}if(r=this.tokenizer.inlineText(s,aC)){t=t.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(c=r.raw.slice(-1)),l=!0,o=n[n.length-1],o&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(t){const d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}}class Ma{constructor(t){this.options=t||rr}code(t,n,r){const o=(n||"").match(/\S*/)[0];if(this.options.highlight){const s=this.options.highlight(t,o);s!=null&&s!==t&&(r=!0,t=s)}return t=t.replace(/\n$/,"")+`
114
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=o.text):n.push(r);continue}if(t){const a="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let r,o,s,i=t,a,l,c;if(this.tokens.links){const d=Object.keys(this.tokens.links);if(d.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)d.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,a.index)+"["+Tp("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)i=i.slice(0,a.index)+"["+Tp("a",a[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(a=this.tokenizer.rules.inline.escapedEmSt.exec(i))!=null;)i=i.slice(0,a.index+a[0].length-2)+"++"+i.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex),this.tokenizer.rules.inline.escapedEmSt.lastIndex--;for(;t;)if(l||(c=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(d=>(r=d.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.escape(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.tag(t)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.link(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(r.raw.length),o=n[n.length-1],o&&r.type==="text"&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(r=this.tokenizer.emStrong(t,i,c)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.codespan(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.br(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.del(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.autolink(t,Ip)){t=t.substring(r.raw.length),n.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(t,Ip))){t=t.substring(r.raw.length),n.push(r);continue}if(s=t,this.options.extensions&&this.options.extensions.startInline){let d=1/0;const f=t.slice(1);let p;this.options.extensions.startInline.forEach(function(h){p=h.call({lexer:this},f),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(s=t.substring(0,d+1))}if(r=this.tokenizer.inlineText(s,$C)){t=t.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(c=r.raw.slice(-1)),l=!0,o=n[n.length-1],o&&o.type==="text"?(o.raw+=r.raw,o.text+=r.text):n.push(r);continue}if(t){const d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}}class Va{constructor(t){this.options=t||sr}code(t,n,r){const o=(n||"").match(/\S*/)[0];if(this.options.highlight){const s=this.options.highlight(t,o);s!=null&&s!==t&&(r=!0,t=s)}return t=t.replace(/\n$/,"")+`
115
115
  `,o?'<pre><code class="'+this.options.langPrefix+_t(o)+'">'+(r?t:_t(t,!0))+`</code></pre>
116
116
  `:"<pre><code>"+(r?t:_t(t,!0))+`</code></pre>
117
117
  `}blockquote(t){return`<blockquote>
@@ -131,7 +131,7 @@ ${t}</blockquote>
131
131
  `}tablerow(t){return`<tr>
132
132
  ${t}</tr>
133
133
  `}tablecell(t,n){const r=n.header?"th":"td";return(n.align?`<${r} align="${n.align}">`:`<${r}>`)+t+`</${r}>
134
- `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=ah(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=ah(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class fh{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class hh{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class Ln{constructor(t){this.options=t||rr,this.options.renderer=this.options.renderer||new Ma,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new fh,this.slugger=new hh}static parse(t,n){return new Ln(n).parse(t)}static parseInline(t,n){return new Ln(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,h,p,y,m,x,g,w,S,k,C,T;const I=t.length;for(o=0;o<I;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(T=this.options.extensions.renderers[p.type].call({parser:this},p),T!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=T||"";continue}switch(p.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(p.tokens),p.depth,ih(this.parseInline(p.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(p.text,p.lang,p.escaped);continue}case"table":{for(f="",d="",a=p.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(p.header[s].tokens),{header:!0,align:p.align[s]});for(f+=this.renderer.tablerow(d),h="",a=p.rows.length,s=0;s<a;s++){for(c=p.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:p.align[i]});h+=this.renderer.tablerow(d)}r+=this.renderer.table(f,h);continue}case"blockquote":{h=this.parse(p.tokens),r+=this.renderer.blockquote(h);continue}case"list":{for(y=p.ordered,m=p.start,x=p.loose,a=p.items.length,h="",s=0;s<a;s++)w=p.items[s],S=w.checked,k=w.task,g="",w.task&&(C=this.renderer.checkbox(S),x?w.tokens.length>0&&w.tokens[0].type==="paragraph"?(w.tokens[0].text=C+" "+w.tokens[0].text,w.tokens[0].tokens&&w.tokens[0].tokens.length>0&&w.tokens[0].tokens[0].type==="text"&&(w.tokens[0].tokens[0].text=C+" "+w.tokens[0].tokens[0].text)):w.tokens.unshift({type:"text",text:C}):g+=C),g+=this.parse(w.tokens,x),h+=this.renderer.listitem(g,k,S);r+=this.renderer.list(h,y,m);continue}case"html":{r+=this.renderer.html(p.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(p.tokens));continue}case"text":{for(h=p.tokens?this.parseInline(p.tokens):p.text;o+1<I&&t[o+1].type==="text";)p=t[++o],h+=`
135
- `+(p.tokens?this.parseInline(p.tokens):p.text);r+=n?this.renderer.paragraph(h):h;continue}default:{const j='Token with "'+p.type+'" type was not found.';if(this.options.silent){console.error(j);return}else throw new Error(j)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class $s{constructor(t){this.options=t||rr}preprocess(t){return t}postprocess(t){return t}}Yp($s,"passThroughHooks",new Set(["preprocess","postprocess"]));function lC(e,t,n){return r=>{if(r.message+=`
136
- Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+_t(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function ph(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...xe.defaults,...s};const i=lC(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(sC(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let h;if(!f)try{r.walkTokens&&xe.walkTokens(l,r.walkTokens),h=t(l,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;xe.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return c(h);p!=null&&p!==f.text&&(f.text=p,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(xe.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&xe.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function xe(e,t,n){return ph(Dn.lex,Ln.parse)(e,t,n)}xe.options=xe.setOptions=function(e){return xe.defaults={...xe.defaults,...e},KS(xe.defaults),xe},xe.getDefaults=nh,xe.defaults=rr,xe.use=function(...e){const t=xe.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=xe.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=xe.defaults.renderer||new Ma;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=xe.defaults.tokenizer||new _a;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=xe.defaults.hooks||new $s;for(const s in n.hooks){const i=o[s];$s.passThroughHooks.has(s)?o[s]=a=>{if(xe.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=xe.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}xe.setOptions(r)})},xe.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(xe,r)),r.type){case"table":{for(const o of r.header)n=n.concat(xe.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(xe.walkTokens(s.tokens,t));break}case"list":{n=n.concat(xe.walkTokens(r.items,t));break}default:xe.defaults.extensions&&xe.defaults.extensions.childTokens&&xe.defaults.extensions.childTokens[r.type]?xe.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(xe.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(xe.walkTokens(r.tokens,t)))}return n},xe.parseInline=ph(Dn.lexInline,Ln.parseInline),xe.Parser=Ln,xe.parser=Ln.parse,xe.Renderer=Ma,xe.TextRenderer=fh,xe.Lexer=Dn,xe.lexer=Dn.lex,xe.Tokenizer=_a,xe.Slugger=hh,xe.Hooks=$s,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,Ln.parse,Dn.lex;function ao({content:e,className:t="",allowHtml:n=!1,style:r}){const o=b.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof xe.parse=="function"?xe.parse(i):xe(i)}return typeof xe.parse=="function"?xe.parse(e):xe(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=b.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:ee("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const cC={MODE:"library"};function uC(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Zs&&Zs.tagName.toUpperCase()==="SCRIPT"&&Zs.src||new URL("index.umd.js",document.baseURI).href}<"u"?cC:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function dC(){return!uC()}function fC(){return typeof window>"u"?!1:window.__ARTIFACT_DEBUG__===!0}function hC(){return dC()||fC()}function pC({preview:e,idx:t}){return b.useEffect(()=>{hC()&&console.debug(`[MessageComponent] Preview ${t} mounted:`,{src:e.src.substring(0,100),alt:e.alt,label:e.label})},[t,e]),u.jsxs("div",{className:"space-y-2",children:[e.label&&u.jsxs("p",{className:"text-[0.65rem] uppercase tracking-wide text-muted-foreground",children:["Artifact: ",e.label]}),u.jsx("div",{className:"overflow-hidden rounded border border-border/60 bg-background/60 p-1 shadow-sm",children:u.jsx("img",{src:e.src,alt:e.alt,title:e.label,loading:"lazy",className:"h-auto max-h-[420px] w-full rounded object-contain",onLoad:()=>{},onError:n=>{console.error(`[MessageComponent] ❌ Image failed to load for artifact ${t}:`,{alt:e.alt,label:e.label,message:n.target.alt})}})})]})}const lo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));lo.displayName="Card";const co=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("flex flex-col space-y-1.5 p-6",e),...t}));co.displayName="CardHeader";const uo=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:ee("text-2xl font-semibold leading-none tracking-tight",e),...t}));uo.displayName="CardTitle";const mh=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));mh.displayName="CardDescription";const fo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("p-6 pt-0",e),...t}));fo.displayName="CardContent";const gh=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:ee("flex items-center p-6 pt-0",e),...t}));gh.displayName="CardFooter";function mC({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=so(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(lo,{className:ee("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(co,{className:"pb-3",children:[u.jsx(uo,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(mh,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(fo,{className:"pt-0 pb-3",children:a}),u.jsx(gh,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(tt,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(tt,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}const gC="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function xh({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:gC,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:so(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:so(e)})}function xC({message:e,isStreaming:t=!1}){const n=e.name??"tool",r=b.useMemo(()=>{const a=e.additionalKwargs??{};return Array.isArray(a.toolProgress)?[...a.toolProgress]:[]},[e]),s=r.some(a=>a.type==="tool.start"||a.type==="tool.call"||a.type==="message.start")?`Running ${n}…`:void 0;return t||r.length>0?u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[t&&u.jsx(oe.Loader,{className:"h-3 w-3 animate-spin"}),u.jsx("span",{children:s??`Running ${n}…`})]}),r.length>0&&u.jsx("div",{className:"space-y-2 text-xs text-muted-foreground",children:r.map((a,l)=>{var c;return u.jsxs("div",{className:"rounded border border-current/10 bg-muted/60 p-2 text-[11px] leading-snug",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between text-[8px] uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:((c=a.type)==null?void 0:c.replace(/\./g," "))??"progress"}),u.jsx("span",{children:a.idx??l+1})]}),a.content&&u.jsx("p",{className:"mt-1 text-[12px] text-foreground/90",children:a.content}),u.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[10px] opacity-70",children:[typeof a.factsFound=="number"&&u.jsxs("span",{children:["Facts found: ",a.factsFound]}),typeof a.isSufficient=="boolean"&&u.jsxs("span",{children:["Research ",a.isSufficient?"sufficient":"needs more data"]})]})]},`tool-progress-${n}-${l}`)})})]}):null}function yC({message:e,viewMode:t,isStreaming:n=!1}){const o=Nf(e).name||"tool",s=l=>{if(l==null)return null;const c=typeof l=="string"?Ta(l)??l:l;if(c&&typeof c=="object")return u.jsx(xh,{data:c});const d=typeof c=="string"?c:(()=>{try{return so(c)}catch{return String(c??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:d})},i=l=>{if(l==null)return null;const{content:c,isMarkdown:d}=xS(l);return d?u.jsx(ao,{content:c,className:"text-current"}):s(l)},a=()=>{const l=e.content.find(f=>f.type!=="tool_call");if(!l)return u.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:u.jsxs("span",{children:["Running ",o,"…"]})});if(l.type==="text"){const h=(l.text??"").trim();if(!h)return null;const p=Is(h);return i(p)}const c=oo(l),d=Is(c);return i(d)};return u.jsxs("div",{className:"space-y-2",children:[u.jsx(xC,{message:e,isStreaming:n}),t==="expanded"&&a()]})}function vC(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=ja(),[o,s]=b.useState({}),[i,a]=b.useState(null),[l,c]=b.useState(!1),d=b.useCallback(()=>{c(!1),a(null)},[]),f=b.useCallback(p=>{a(p),c(!0)},[]),h=b.useCallback(async(p,y,m)=>{var x,g;if(!t){p.preventDefault();return}if(o[m]){p.preventDefault();return}try{const w=String(y.url??""),S=w.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){p.preventDefault();const k=S[1],C=y.name||`file_${k}`,T=y.mimeType||"application/octet-stream";f({id:k,name:C,mimeType:T});return}if(w.startsWith("data:")){p.preventDefault(),s(C=>({...C,[m]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const C=await IS(n??void 0);if(!C||!Array.isArray(C))throw new Error("Invalid file list response");const T=C.find(I=>!I||typeof I!="object"||!((I.filename??"")===(y.name??""))?!1:typeof y.size=="number"&&typeof I.size=="number"?I.size===y.size:!0);if(!(T!=null&&T.id))throw new Error(`File "${y.name}" is not yet available on the server`);if(!T.id||!T.filename)throw new Error("Invalid file data received from server");f({id:T.id,name:y.name||T.filename||`file_${T.id}`,mimeType:y.mimeType||T.mime_type||"application/octet-stream"}),(x=k.update)==null||x.call(k,{id:k.id,title:"Success",description:`Opened ${y.name}`,open:!0})}catch(C){console.error("Failed to fetch server file:",C);const T=C instanceof Error?C.message:"Unknown error occurred";(g=k.update)==null||g.call(k,{id:k.id,title:"Failed",description:T}),r({title:"Failed to fetch file",description:T,open:!0})}finally{s(C=>({...C,[m]:!1}))}}}catch(w){console.error("File click error:",w),s(S=>({...S,[m]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function wC({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:ee("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(ao,{content:e,allowHtml:!1}):u.jsxs("pre",{className:ee("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(tt,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(oe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(oe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function bC({className:e}){const[t,n]=b.useState(0);return b.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:ee("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function yh(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}const Fs=b.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,showArtifactPreviews:h=!0,customStyles:p={},onEdit:y,onRegenerate:m,onCancelEdit:x,onCopy:g,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,checkpointCandidates:T=[],activeCheckpointId:I=null,onSelectCheckpoint:j,defaultCheckpointId:_=null,messageParentCheckpointId:O=null}){const[B,K]=b.useState(!1),[V,P]=b.useState("preview"),[M,N]=b.useState(!1),{currentThreadId:z}=Po(),{respondToInterrupt:L}=Ro(),R=l==="phone"||l==="half-screen",W=t.role,Y=W==="tool",ne=b.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),pe=!!ne,be=!(r&&W!=="user"),{uploadingFiles:Ie,handleFileClick:ve,fileViewerOpen:te,currentFileInfo:F,closeFileViewer:X}=vC({allowFileOpen:be,currentThreadId:z}),A=b.useMemo(()=>{switch(W){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[W]),$=b.useMemo(()=>{if(ne)return"";const U=t.content;return Array.isArray(U)?yS(U):""},[ne,t]),H=b.useMemo(()=>{if(ne)return{};const U=t.content;return Array.isArray(U)?Nf(t):{}},[ne,t]),fe=b.useMemo(()=>Y?!!(t.additionalKwargs??{}).toolStreaming:!1,[Y,t]),re=b.useMemo(()=>{if(ne)return[];const U=t.content;return Array.isArray(U)?U.filter(ge=>ge.type==="image_url"):[]},[ne,t]),Z=b.useMemo(()=>{if(ne)return[];const U=t.content;return Array.isArray(U)?U.filter(ge=>ge.type==="file"):[]},[ne,t]),ce=b.useMemo(()=>{if(ne)return[];const U=t.content;return Array.isArray(U)?U.filter(ge=>ge.type==="interrupt"):[]},[ne,t]),me=(w==null?void 0:w.id)??(w==null?void 0:w.interrupt_id),$e=Es(me),Re=w==null?void 0:w.value,Be=b.useMemo(()=>{if(ne)return"";const U=t.content;return Array.isArray(U)?vS(U):""},[ne,t]),Xe=b.useMemo(()=>{if(ne||!h)return[];const ge=t.artifact;if(!ge)return[];const ye=[],Ke=[...Array.isArray(ge.plots)?ge.plots:[]];for(const De of Ke){const ct=TS(De);ct&&ye.push(ct)}return ye},[ne,t,h]),Qe=b.useCallback(async()=>{const U=Y?Be:$;async function ge(ye){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ye);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Ke=new Blob([ye],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Ke})]);return}throw new Error("Clipboard API not supported in this context.")}try{await ge(U),K(!0),setTimeout(()=>K(!1),2e3),g==null||g(U)}catch(ye){console.error("Failed to copy:",ye)}},[Y,Be,$,g]),Je=b.useCallback(()=>{if(!y)return;const U=Y?Be:$,ge="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};y(t.id,U,ge)},[y,t.id,Y,Be,$,t]),et=b.useCallback(()=>{m==null||m(n)},[m,n]),it=b.useCallback(()=>{const ge=ee(R?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",A);switch(W){case"user":return u.jsx(oe.User,{className:ge});case"assistant":return u.jsx(oe.Bot,{className:ge});case"tool":return u.jsx(oe.Wrench,{className:ge});default:return u.jsx(oe.Bot,{className:ge})}},[R,A,W]),Mt=b.useCallback(()=>{const U="group relative mb-4 flex w-full";switch(W){case"user":return ee(U,"justify-end");case"assistant":case"tool":case"system":return ee(U,"justify-start");default:return U}},[W]),pt=b.useCallback(()=>{const U=ee("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",R&&"px-3 py-2 text-sm");if(pe)return ee(U,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(W){case"user":return ee(U,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return ee(U,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return ee(U,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return ee(U,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return ee(U,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[R,pe,W]),Ct=b.useCallback(async U=>{if(S)return;const ge=Es((U==null?void 0:U.id)??(U==null?void 0:U.interrupt_id));if(!ge){console.warn("Interrupt part missing id",U);return}try{k==null||k(),await L(ge,!0)}catch(ye){console.error("Failed to approve interrupt:",ye)}finally{C==null||C()}},[S,C,k,L]),mt=b.useCallback(async U=>{if(S)return;const ge=Es((U==null?void 0:U.id)??(U==null?void 0:U.interrupt_id));if(!ge){console.warn("Interrupt part missing id",U);return}try{k==null||k(),await L(ge,!1)}catch(ye){console.error("Failed to reject interrupt:",ye)}finally{C==null||C()}},[S,C,k,L]),wt=b.useCallback(({part:U,i:ge})=>{if(U.type==="text"){const ye=U.text??"",Ke=ye.trim(),De=Ta(Ke);return De&&W!=="tool"?u.jsx(xh,{data:De},ge):W==="user"&&c&&Ke.length>d?u.jsx(wC,{text:Ke,expanded:M,onExpandedChange:N,previewLength:d,isCompact:R},ge):u.jsx(ao,{content:ye,allowHtml:!1},ge)}if(U.type==="image_url"){const ye=U;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ye.url,alt:ye.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},ge)}if(U.type==="file"){const ye=U,Ke=ye.name||"file";return u.jsxs("a",{href:ye.url,onClick:De=>ve(De.nativeEvent,ye,ge),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
137
- dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[Ie[ge]?u.jsx(oe.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[Ke,Ie[ge]?" (processing)":""]})]},ge)}if(U.type==="interrupt"){const ye=U,Ke=Es((ye==null?void 0:ye.id)??(ye==null?void 0:ye.interrupt_id)),De=!!($e&&Ke&&Ke===$e),ct=De?Re??(ye==null?void 0:ye.value):ye==null?void 0:ye.value,Ve=Ke?{...ye,id:Ke,interrupt_id:Ke}:ye;return u.jsx(mC,{interruptPart:Ve,onApprove:Ct,onReject:mt,disabled:S,isActive:De,payload:ct},ge)}return null},[ve,Ie,Ct,mt,W,c,d,M,R,$e,Re,w,S,ce]),Pt=b.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(oe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),$t=b.useCallback(()=>{const U=$.trim().length>0||re.length>0||Z.length>0||ce.length>0;if(!Y&&Z.length>0&&!r)return Pt();if(!Y&&!U&&!r)return null;if(Y)return!f&&Xe.length>0?null:f?u.jsx(yC,{message:t,viewMode:V,isStreaming:fe},t.id):null;if(!Y&&!ne){const ge=t,ye=u.jsx("div",{className:"space-y-2",children:ge.content.map((Ke,De)=>u.jsx(wt,{part:Ke,i:De},De))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ye,u.jsx(bC,{className:A})]}):ye}},[$,re.length,Z.length,ce.length,r,Y,V,f,Xe.length,Pt,A]),cn=b.useMemo(()=>ne?"Assistant":wS(t),[ne,t]),We=b.useMemo(()=>ne?[]:Array.isArray(T)?T:[],[T,ne]),In=b.useMemo(()=>{var U;return We.length?_&&We.some(ge=>ge.id===_)?_:((U=We[0])==null?void 0:U.id)??null:null},[_,We]),J=b.useMemo(()=>!We.length||!I?null:We.some(U=>U.id===I)?I:null,[I,We])??In,le=W==="user"&&We.length>0&&typeof j=="function",ze=b.useCallback((U,ge=!1)=>{if(!j)return;const ye=(U==null?void 0:U.id)??null,Ke=(U==null?void 0:U.parentId)??O??null;j(ye,Ke,ge)},[O,j]),Se=b.useMemo(()=>J?We.findIndex(U=>U.id===J):-1,[J,We]),ft=b.useMemo(()=>Se<0?null:We[Se]??null,[Se,We]);return Y&&!f&&Xe.length===0?null:pe&&ne?u.jsx("div",{className:ee(Mt(),p.container),children:u.jsxs("div",{className:ee(pt(),p.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(oe.Bot,{className:ee("h-4 w-4",A)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(ao,{content:ne.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:ee(Mt(),p.container),children:u.jsxs("div",{className:ee(pt(),p.content),children:[(i||a||Y)&&u.jsxs("div",{className:ee("flex items-center justify-between mb-2 pb-2 border-b border-current/10",R&&"mb-1 pb-1",A,p.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[it(),a&&cn&&u.jsx("span",{className:ee("font-medium",R?"text-xs":"text-sm"),children:cn}),Y&&u.jsxs(If,{variant:"outline",className:ee("text-xs flex items-center gap-1 cursor-pointer select-none",A,"border border-current/40",R&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":V==="expanded",onClick:()=>P(U=>U==="expanded"?"preview":"expanded"),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),P(ge=>ge==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:H.name??"Tool Output"}),H.toolCallId&&u.jsx("span",{className:"opacity-70",children:H.toolCallId.slice(0,8)}),V==="expanded"?u.jsx(oe.ChevronUp,{className:"h-3 w-3"}):u.jsx(oe.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[le&&ft&&Se>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:ee("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Se<We.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Se>=We.length-1)return;const U=We[Se+1];U&&ze(U)},"aria-label":"Older checkpoint (back in time)",disabled:Se>=We.length-1,children:u.jsx(oe.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[We.length-Se," / ",We.length]})}),u.jsx("button",{type:"button",className:ee("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Se>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(Se<=0))if(Se===1)ze(null,!0);else{const U=We[Se-1];U&&ze(U,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:Se<=0,children:u.jsx(oe.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:ee("text-xs opacity-60",A,R&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:ee("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",p.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:ee("h-6 w-6 p-0 hover:bg-foreground/10",A,R&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(oe.Copy,{className:ee(B?"text-success":A,R?"h-3 w-3":"h-4 w-4")})})}),W==="user"&&y&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Je,className:ee("h-6 w-6 p-0 hover:bg-foreground/10",A,R&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(oe.Edit,{className:ee(A,R?"h-3 w-3":"h-4 w-4")})}),W==="assistant"&&m&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:et,className:ee("h-6 w-6 p-0 hover:bg-foreground/10",A,R&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(oe.RotateCcw,{className:ee(A,R?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[$t(),h&&Xe.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:Xe.map((U,ge)=>u.jsx(pC,{preview:U,idx:ge},`artifact-${ge}`))})]}),Y&&V==="expanded"&&(H.toolCallId||H.name)&&u.jsxs("div",{className:ee("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",R&&"text-xs"),children:[H.name&&u.jsxs("div",{children:["Function: ",H.name]}),H.toolCallId&&u.jsxs("div",{children:["Call ID: ",H.toolCallId]})]}),!(i||a||Y)&&s&&!o&&u.jsxs("div",{className:ee("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",p.actions),children:[u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(oe.Copy,{className:ee(B?"text-success":"text-current",R?"h-3 w-3":"h-4 w-4")})}),W==="user"&&y&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Je,className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(oe.Edit,{className:ee("text-current",R?"h-3 w-3":"h-4 w-4")})}),W==="assistant"&&m&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:et,className:ee("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(oe.RotateCcw,{className:ee("text-current",R?"h-3 w-3":"h-4 w-4")})})]})]})}),F&&u.jsx(VS,{isOpen:te,onClose:X,fileId:F.id,fileName:F.name,mimeType:F.mimeType})]})},(e,t)=>{var l,c,d,f,h,p,y,m;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&Af(e.message)===Af(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","attemptMeta"].every(x=>e[x]===t[x]),s=((l=e.customStyles)==null?void 0:l.container)===((c=t.customStyles)==null?void 0:c.container)&&((d=e.customStyles)==null?void 0:d.content)===((f=t.customStyles)==null?void 0:f.content)&&((h=e.customStyles)==null?void 0:h.actions)===((p=t.customStyles)==null?void 0:p.actions)&&((y=e.customStyles)==null?void 0:y.header)===((m=t.customStyles)==null?void 0:m.header);if(!o||!s)return!1;const i=yh(e.message),a=yh(t.message);return i.length===a.length});Fs.displayName="MessageComponent";function SC(e,t){return b.useMemo(()=>{var d,f,h,p,y;const n=e&&"type"in e&&e.type==="default_message";let r=[],o=null,s={},i={},a=null,l=null,c=null;if(!n&&e){const m=e,x=m.checkpointId??null;s=m.additionalKwargs??{},i=m.responseMetadata??{};const g=x&&t.checkpointMetaById?t.checkpointMetaById.get(x)??null:null;a=typeof s.step=="number"?s.step:typeof i.step=="number"?i.step:(g==null?void 0:g.step)??null;const w=typeof s.source=="string"?s.source:typeof i.source=="string"?i.source:(g==null?void 0:g.source)??null;l=w?String(w):null;const S=a!==null&&l?`${a}:${l}`:null;if(S&&((d=t.checkpointIndexByKey)!=null&&d.has(S))?r=t.checkpointIndexByKey.get(S)??[]:x&&g&&(r=[g]),o=x??((f=r[0])==null?void 0:f.id)??null,c=x?((h=t.attemptMetaById)==null?void 0:h.get(x))??null:null,!c&&(e==null?void 0:e.role)==="user"&&(e!=null&&e.id)&&t.userMessageIdToAttempts){const k=t.userMessageIdToAttempts.get(e.id);if(k&&k.length>0){const C=k[0].checkpointId;c=((p=t.attemptMetaById)==null?void 0:p.get(C))??null,c&&console.log(`[useMessageMetadata] Found attempt by user message ID "${e.id}":`,k.length,"versions")}}if(!c&&r.length>0&&t.attemptMetaById){const k=t.attemptMetaById.get(r[0].id);k&&(c=k)}if(c&&c.attemptCount>1&&t.attemptMetaById){const k=c.baseUserMessageId;if(k){const C=[];for(const[T,I]of t.attemptMetaById.entries())if(I.baseUserMessageId===k){const j=(y=t.checkpointMetaById)==null?void 0:y.get(T);j&&C.push(j)}C.length>0&&(r=C)}}if(c&&c.attemptCount>1&&t.checkpointMetaById&&t.attemptMetaById){const k=[];for(const[C,T]of t.checkpointMetaById.entries()){const I=t.attemptMetaById.get(C);I&&I.attemptCount===c.attemptCount&&I.baseUserMessageId===c.baseUserMessageId&&k.push(T)}k.sort((C,T)=>{const I=C.createdAt?Date.parse(C.createdAt):0;return(T.createdAt?Date.parse(T.createdAt):0)-I}),k.length>0&&(r=k,console.log("[useMessageMetadata] Populated checkpointCandidates with all attempts:",{messageId:e.id,attemptCount:c.attemptCount,candidateIds:r.map(C=>C.id)}))}}return{checkpointCandidates:r,defaultCheckpointId:o,attemptMeta:c,resolvedStep:a,resolvedSource:l}},[e,t.checkpointMetaById,t.checkpointIndexByKey,t.attemptMetaById,t.userMessageIdToAttempts])}const vh=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,wh=b.memo(function({message:t,index:n,isStreaming:r,streamingAssistantId:o,streamingDebounceMs:s,layoutSize:i,enableMessageEditing:a,editingMessageId:l,onEdit:c,onRegenerate:d,onCancelEdit:f,activeInterrupt:h,disableInterruptActions:p,onInterruptActionStart:y,onInterruptActionEnd:m,showToolMessages:x,showArtifactPreviews:g,checkpointMetaById:w,checkpointIndexByKey:S,attemptMetaById:k,userMessageIdToAttempts:C,activeCheckpointId:T,onSelectCheckpoint:I}){const j=vh(t,n),_="type"in t&&t.type==="default_message",{checkpointCandidates:O,defaultCheckpointId:B,attemptMeta:K}=SC(t,{checkpointMetaById:w,checkpointIndexByKey:S,attemptMetaById:k,userMessageIdToAttempts:C}),V=t&&!_?t.additionalKwargs??{}:{},P=t&&!_?t.responseMetadata??{}:{},M=(()=>{if(typeof V.parentCheckpointId=="string")return V.parentCheckpointId;if(typeof P.parentCheckpointId=="string")return P.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":j,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Fs,{message:t,messageIndex:n,isStreamingMessage:r&&o===t.id,streamingDebounceMs:s,isEditing:l===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:c,onRegenerate:()=>d(n),onCancelEdit:f,activeInterrupt:h,disableInterruptActions:p,onInterruptActionStart:y,onInterruptActionEnd:m,showToolMessages:x,showArtifactPreviews:g,checkpointCandidates:O,activeCheckpointId:T??null,onSelectCheckpoint:I,defaultCheckpointId:B,messageParentCheckpointId:M,attemptMeta:K})})});wh.displayName="MessageRow";const Pa=b.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:h,emptyMessage:p,followNewMessages:y=!0,isNavigatingCheckpoint:m=!1,onScrollAway:x,onAtBottom:g,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T=!0,showArtifactPreviews:I=!0,checkpointMetaById:j,checkpointIndexByKey:_,attemptMetaById:O,userMessageIdToAttempts:B,activeCheckpointId:K,onSelectCheckpoint:V,createSyntheticThinkingMessage:P=!1},M)=>{const N=b.useRef(null),z=b.useRef(null),L=b.useRef(!1),R=b.useRef(!1),[W,Y]=b.useState(!0),ne=b.useMemo(()=>w?e.some(Z=>"type"in Z&&Z.type==="default_message"?!1:Array.isArray(Z==null?void 0:Z.content)&&Z.content.some(ce=>ce&&ce.type==="interrupt"&&(ce.id??ce.interrupt_id)===w.id)):!1,[w,e]),pe=b.useMemo(()=>{if(!w||ne)return null;const Z=w.id&&String(w.id).trim()?String(w.id).trim():"pending-interrupt";let ce;const me=w.value;if(me&&typeof me=="object"&&!Array.isArray(me)){const $e=me.title;typeof $e=="string"&&$e.trim()&&(ce=$e.trim())}return{id:`interrupt-${Z}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:Z,value:me,title:ce}]}},[w,ne]),be=b.useMemo(()=>pe?[...e,pe]:e,[e,pe]),Ie=b.useMemo(()=>!P||!t?be:!be.some(ce=>ce.role==="assistant")&&be.length>0?[...be,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString()}]:be,[be,t,P]),ve=b.useMemo(()=>T?Ie:Ie.filter(Z=>(Z==null?void 0:Z.role)!=="tool"),[Ie,T]),te=b.useCallback(Z=>{Y(Z),x&&x(!Z),g&&g(Z)},[x,g]),F=b.useMemo(()=>{if(a)return async()=>{if(!L.current){L.current=!0;try{await a()}finally{L.current=!1}}}},[a]),X=b.useMemo(()=>!y||m?!1:W?"auto":!1,[W,y,m]),A=b.useMemo(()=>{if(typeof p!="string")return null;const Z=p.trim();return Z?{id:"default-message",role:"assistant",type:"default_message",content:Z,createdAt:new Date().toISOString()}:null},[p]),$=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),H=()=>A?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Fs,{message:A,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:I})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:p??"No messages yet. Start a conversation!"}),fe=ve.length,re=fe>0;return b.useEffect(()=>{var Z,ce;if(fe===0){R.current=!1;return}if(!R.current)if(R.current=!0,N.current&&ve.length>0){const me=ve.length-1;(ce=(Z=N.current).scrollToIndex)==null||ce.call(Z,{index:me,align:"end",behavior:"auto"})}else z.current&&(z.current.scrollTop=z.current.scrollHeight)},[fe,ve.length]),b.useImperativeHandle(M,()=>({scrollToLatest:()=>{var Z,ce;if(N.current&&ve.length>0){const me=ve.length-1;(ce=(Z=N.current).scrollToIndex)==null||ce.call(Z,{index:me,align:"end",behavior:"auto"})}else z.current&&(z.current.scrollTop=z.current.scrollHeight)},scrollToTop:()=>{var Z,ce;N.current&&ve.length>0?(ce=(Z=N.current).scrollToIndex)==null||ce.call(Z,{index:0,align:"start",behavior:"auto"}):z.current&&(z.current.scrollTop=0)}}),[ve]),u.jsx("div",{className:$,style:h,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:re?u.jsx(eS,{ref:Z=>{N.current=Z},scrollerRef:Z=>{z.current=Z instanceof HTMLDivElement?Z:null},data:ve,followOutput:X,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{F&&F()},atBottomStateChange:te,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(Z,ce)=>vh(ce,Z),itemContent:(Z,ce)=>u.jsx(wh,{message:ce,index:Z,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:w,disableInterruptActions:S,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T,showArtifactPreviews:I,checkpointMetaById:j,checkpointIndexByKey:_,attemptMetaById:O,userMessageIdToAttempts:B,activeCheckpointId:K,onSelectCheckpoint:V})}):H()})})});Pa.displayName="MessageList";const bh={value:""};function Bs({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,showArtifactPreviews:f=!0,customStyles:h={},onMessageSent:p,onExcelUploadSuccess:y,onError:m}){const{api:x}=hi(),{currentThreadId:g}=Po(),{threadId:w,messages:S,isHistoryLoading:k,isLoading:C,navigateToCheckpoint:T,returnToLatest:I,checkpoint:j,checkpoints:_,interrupt:O,metadata:B,timelineCheckpoints:K,messagePreviews:V}=Ro(),{isStreaming:P,error:M,connectionState:N,submit:z,stop:L}=pc(),R=w??g??null,W=(j==null?void 0:j.id)??null,Y=(j==null?void 0:j.namespace)??null,ne=(B==null?void 0:B.assemblingMessageId)??null,pe=O,[be,Ie]=b.useState(!1);b.useEffect(()=>{pe||Ie(!1)},[pe]);const ve=b.useCallback(()=>{Ie(!0)},[]),te=b.useCallback(()=>{Ie(!1)},[]),F=!!pe||be,[X,A]=b.useState(null),[$,H]=b.useState(""),[fe,re]=b.useState(null),[Z,ce]=b.useState(null),[me,$e]=b.useState([]),[Re,Be]=b.useState(0),[Xe,Qe]=b.useState(0),[Je,et]=b.useState(!1),[it,Mt]=b.useState(null),[pt,Ct]=b.useState(null),[mt,wt]=b.useState(!1),[Pt,$t]=b.useState(null),cn=b.useRef(!1),[We,In]=b.useState(()=>bh.value),rt=b.useRef(We),J=b.useRef(null),le=b.useCallback(de=>{bh.value=de,In(de)},[]),[ze,Se]=b.useState(!1),ft=b.useRef(null),{checkpointMetaById:U,checkpointIndexByKey:ge,attemptMetaById:ye,userMessageIdToAttempts:Ke}=zb(_),De=K??[],ct=b.useRef(null),Ve=b.useRef(null),bt=b.useCallback(()=>{ct.current&&(ct.current.value=""),Ve.current&&(Ve.current.value=""),Be(de=>de+1),Qe(de=>de+1)},[]),zn=b.useCallback(de=>{le(de)},[le]),ar=b.useRef(!1);b.useEffect(()=>{ar.current&&!P&&($e([]),bt()),ar.current=P},[P,bt]);const[En,jr]=b.useState("desktop");b.useEffect(()=>{const de=()=>{const Ce=window.innerWidth;jr(Ce<640?"phone":Ce<1024?"tablet":"desktop")};return de(),window.addEventListener("resize",de),()=>window.removeEventListener("resize",de)},[]),b.useEffect(()=>{cn.current=!1},[R]),b.useEffect(()=>{rt.current=We},[We]),b.useEffect(()=>{if(!X){J.current=null;return}J.current===null&&(J.current=rt.current),le($??"")},[$,X,le]),b.useEffect(()=>{(async()=>{if(!x.baseUrl){$t(null);return}try{const Ae=(await x.getAgent("default")).uiDefaultMessage||"";$t(Ae||null)}catch(Ce){console.warn("Failed to fetch default message:",Ce),$t(null)}})()},[x.baseUrl]),b.useEffect(()=>{M&&!mt&&(m==null||m(M))},[M,mt,m]);const Un=de=>{if(de.length>fs)return`Message too long (${de.length}/${fs} characters)`;try{return Wb(de),null}catch(Ce){return(Ce==null?void 0:Ce.message)||"Invalid message"}},po=async de=>{const Ce=de.trim();if(!(!Ce&&me.length===0)){if(Ce){const Ae=Un(Ce);if(Ae){ce(Ae);return}}try{const Ae=X?(fe==null?void 0:fe.checkpointId)??W??void 0:W??void 0,qe=X?(fe==null?void 0:fe.checkpointNs)??Y??void 0:Y??void 0;await z({text:Ce||"",attachments:me},{checkpointId:Ae,checkpointNs:qe,edit:!!X,originalMessageId:X??void 0}),p==null||p(Ce),le(""),ce(null),$e([]),bt(),A(null),H(""),re(null)}catch(Ae){const qe=(Ae==null?void 0:Ae.message)||"Failed to send message";ce(qe),m==null||m(qe)}}},lr=b.useCallback((de,Ce,Ae)=>{c&&(J.current=We,A(de),H(Ce),le(Ce),ce(null),re({checkpointId:(Ae==null?void 0:Ae.checkpointId)??null,checkpointNs:(Ae==null?void 0:Ae.checkpointNs)??null}))},[We,c,le]),E=b.useCallback(()=>{A(null),H(""),re(null),ce(null),le(J.current??We),J.current=null},[We,le]),G=b.useCallback((de,Ce,Ae)=>{lr(de,Ce,Ae)},[lr]),se=b.useCallback(de=>{let Ce=null;for(let en=de-1;en>=0;en--)if(S[en].role==="user"){Ce=S[en];break}if(!Ce)return;const Ae=Array.isArray(Ce.content)?Ce.content:[],Hn=Ae.filter(en=>(en==null?void 0:en.type)==="text").map(en=>en.text).join("")||(()=>{try{return JSON.stringify(Ae,null,2)}catch{return String(Ae)}})();Hn&&z({text:Hn},{checkpointId:W??void 0,checkpointNs:Y??void 0,edit:!0,originalMessageId:Ce.id})},[S,z,W,Y]),Ee=de=>{const Ce=Array.from(de.target.files||[]);$e(Ae=>[...Ae,...Ce]),de.target.value=""},Ye=de=>{$e(Ce=>{const Ae=Ce.filter((qe,Hn)=>de!==Hn);return Ae.length===0&&bt(),Ae})},nt=async de=>{const Ce=(de.target.files||[])[0];if(Ce){Mt(null),Ct(null),et(!0);try{await z({attachments:[Ce]},{checkpointId:W??void 0,checkpointNs:Y??void 0});const Ae=`Uploaded ${Ce.name} - processing through chat stream`;Ct(Ae)}catch(Ae){const qe=Ae instanceof Error?Ae.message:"Failed to upload Excel file";console.error("Excel upload failed",Ae),Mt(qe),m==null||m(qe)}finally{et(!1),de.target.value="",bt()}}},Fe=async de=>{if(g){Se(!0);try{if(!de){await I(),requestAnimationFrame(()=>{var qe;(qe=ft.current)==null||qe.scrollToLatest()});return}const Ce=_.find(qe=>qe.checkpointId===de),Ae=(Ce==null?void 0:Ce.checkpointNs)??null;await T(de,Ae),requestAnimationFrame(()=>{var qe;(qe=ft.current)==null||qe.scrollToTop()})}finally{Se(!1)}}},Le=b.useCallback(async(de,Ce,Ae)=>{await Fe(Ae?null:de)},[Fe]),Et=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${h.container||""}`,ht=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${h.messagesArea||""}`,gt=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${h.inputArea||""}`;return u.jsxs("div",{className:Et,children:[!!M&&!mt&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:M}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>wt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(oe.X,{size:16})})]}),u.jsxs("div",{className:`relative ${ht}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Pa,{ref:ft,className:"h-full",style:{height:"100%"},messages:S,isStreaming:P,streamingAssistantId:ne,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:En,enableMessageEditing:c,editingMessageId:X,onEdit:G,onRegenerate:se,onCancelEdit:E,emptyMessage:Pt??void 0,isNavigatingCheckpoint:ze,activeInterrupt:pe,disableInterruptActions:be,onInterruptActionStart:ve,onInterruptActionEnd:te,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:U,checkpointIndexByKey:ge,attemptMetaById:ye,userMessageIdToAttempts:Ke,activeCheckpointId:W,onSelectCheckpoint:Le,timelineCheckpoints:De,messagePreviews:V}),(N==="reconnecting"||N==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(oe.Loader2,{className:"h-3 w-3 animate-spin"}),N==="reconnecting"?"Reconnecting…":"Connecting…"]})}),N==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),C&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(oe.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||ze)&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(oe.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:gt,children:[X&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(oe.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:E,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(oe.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:ct,type:"file",multiple:!0,onChange:de=>Ee(de),className:"hidden"},Re),me.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:me.map((de,Ce)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(oe.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:de.name}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Ye(Ce),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${de.name}`,children:u.jsx(oe.X,{size:12})})]},Ce))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Ve,type:"file",accept:".xls,.xlsx,.xlsm",onChange:nt,className:"hidden"},Xe),Je&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(oe.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),pt&&!Je&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:pt}),it&&!Je&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:it})]})]}),Z&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:Z}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(kd,{children:[u.jsx(Id,{asChild:!0,children:u.jsx(tt,{type:"button",size:"icon",variant:"outline",disabled:P||F,title:"More input actions",className:h.moreButton||"",children:u.jsx(oe.Plus,{size:16})})}),u.jsxs(ea,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Cr,{onClick:()=>{var de;return(de=ct.current)==null?void 0:de.click()},className:"cursor-pointer",children:[u.jsx(oe.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Cr,{onClick:()=>{var de;Je||(de=Ve.current)==null||de.click()},className:`cursor-pointer ${Je?"opacity-60 pointer-events-none":""}`,children:[u.jsx(oe.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(jx,{initialValue:$,editingMessageId:X,value:We,onValueChange:zn,placeholder:X?"Edit your message...":t,isStreaming:P,disabled:F,maxLength:fs,onSend:po,onCancelEdit:E,onStop:L,allowEmptySend:me.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${X?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${Z?"border-red-400":""} ${h.textarea||""}`})})]})]})]})}const zs=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:ee("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));zs.displayName="Input";function Ra(e,[t,n]){return Math.min(n,Math.max(t,e))}function CC(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Oa="ScrollArea",[Sh,pk]=bn(Oa),[TC,Zt]=Sh(Oa),Ch=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=v.useState(null),[c,d]=v.useState(null),[f,h]=v.useState(null),[p,y]=v.useState(null),[m,x]=v.useState(null),[g,w]=v.useState(0),[S,k]=v.useState(0),[C,T]=v.useState(!1),[I,j]=v.useState(!1),_=Ue(t,B=>l(B)),O=Do(o);return u.jsx(TC,{scope:n,type:r,dir:O,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:y,scrollbarXEnabled:C,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:x,scrollbarYEnabled:I,onScrollbarYEnabledChange:j,onCornerWidthChange:w,onCornerHeightChange:k,children:u.jsx(_e.div,{dir:O,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});Ch.displayName=Oa;var Th="ScrollAreaViewport",kh=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=Zt(Th,n),a=v.useRef(null),l=Ue(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),u.jsx(_e.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});kh.displayName=Th;var vn="ScrollAreaScrollbar",Da=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(vn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return v.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(kC,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(IC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(Ih,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(La,{...r,ref:t}):null});Da.displayName=vn;var kC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(vn,e.__scopeScrollArea),[s,i]=v.useState(!1);return v.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Gt,{present:n||s,children:u.jsx(Ih,{"data-state":s?"visible":"hidden",...r,ref:t})})}),IC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Zt(vn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Vs(()=>l("SCROLL_END"),100),[a,l]=CC("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),v.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const h=()=>{const p=c[d];f!==p&&(l("SCROLL"),i()),f=p};return c.addEventListener("scroll",h),()=>c.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),u.jsx(Gt,{present:n||a!=="hidden",children:u.jsx(La,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:ue(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Ih=v.forwardRef((e,t)=>{const n=Zt(vn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=Vs(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Er(n.viewport,l),Er(n.content,l),u.jsx(Gt,{present:r||s,children:u.jsx(La,{"data-state":s?"visible":"hidden",...o,ref:t})})}),La=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=Zt(vn,e.__scopeScrollArea),s=v.useRef(null),i=v.useRef(0),[a,l]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=_h(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return MC(h,i.current,a,p)}return n==="horizontal"?u.jsx(EC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Mh(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?u.jsx(NC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Mh(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),EC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Zt(vn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ue(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Nh,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Ws(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Rh(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Hs(i.paddingLeft),paddingEnd:Hs(i.paddingRight)}})}})}),NC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=Zt(vn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ue(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Nh,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Ws(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Rh(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Hs(i.paddingTop),paddingEnd:Hs(i.paddingBottom)}})}})}),[AC,Eh]=Sh(vn),Nh=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...h}=e,p=Zt(vn,n),[y,m]=v.useState(null),x=Ue(t,_=>m(_)),g=v.useRef(null),w=v.useRef(""),S=p.viewport,k=r.content-r.viewport,C=It(d),T=It(l),I=Vs(f,10);function j(_){if(g.current){const O=_.clientX-g.current.left,B=_.clientY-g.current.top;c({x:O,y:B})}}return v.useEffect(()=>{const _=O=>{const B=O.target;(y==null?void 0:y.contains(B))&&C(O,k)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,y,k,C]),v.useEffect(T,[r,T]),Er(y,I),Er(p.content,I),u.jsx(AC,{scope:n,scrollbar:y,hasThumb:o,onThumbChange:It(s),onThumbPointerUp:It(i),onThumbPositionChange:T,onThumbPointerDown:It(a),children:u.jsx(_e.div,{...h,ref:x,style:{position:"absolute",...h.style},onPointerDown:ue(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),g.current=y.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),j(_))}),onPointerMove:ue(e.onPointerMove,j),onPointerUp:ue(e.onPointerUp,_=>{const O=_.target;O.hasPointerCapture(_.pointerId)&&O.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=w.current,p.viewport&&(p.viewport.style.scrollBehavior=""),g.current=null})})})}),Us="ScrollAreaThumb",Ah=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Eh(Us,e.__scopeScrollArea);return u.jsx(Gt,{present:n||o.hasThumb,children:u.jsx(jC,{ref:t,...r})})}),jC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=Zt(Us,n),i=Eh(Us,n),{onThumbPositionChange:a}=i,l=Ue(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=Vs(()=>{c.current&&(c.current(),c.current=void 0)},100);return v.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!c.current){const p=PC(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(_e.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),y=f.clientX-p.left,m=f.clientY-p.top;i.onThumbPointerDown({x:y,y:m})}),onPointerUp:ue(e.onPointerUp,i.onThumbPointerUp)})});Ah.displayName=Us;var $a="ScrollAreaCorner",jh=v.forwardRef((e,t)=>{const n=Zt($a,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(_C,{...e,ref:t}):null});jh.displayName=$a;var _C=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=Zt($a,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return Er(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Er(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(_e.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Hs(e){return e?parseInt(e,10):0}function _h(e,t){const n=e/t;return isNaN(n)?0:n}function Ws(e){const t=_h(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function MC(e,t,n,r="ltr"){const o=Ws(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Ph([l,c],f)(e)}function Mh(e,t,n="ltr"){const r=Ws(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],c=Ra(e,l);return Ph([0,i],[0,a])(c)}function Ph(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Rh(e,t){return e>0&&e<t}var PC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Vs(e,t){const n=It(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Er(e,t){const n=It(t);kt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Oh=Ch,RC=kh,OC=jh;const Dh=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Oh,{ref:r,className:ee("relative overflow-hidden",e),...n,children:[u.jsx(RC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Lh,{}),u.jsx(OC,{})]}));Dh.displayName=Oh.displayName;const Lh=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Da,{ref:r,orientation:t,className:ee("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(Ah,{className:"relative flex-1 rounded-full bg-border"})}));Lh.displayName=Da.displayName;const $h=25;function Fa({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,sharedThreads:h,currentThreadId:p,setCurrentThreadId:y,isLoading:m,isLoadingSharedThreads:x,actions:g}=Po(),{createThread:w,deleteThread:S,renameThread:k,shareThread:C}=g,{loadThread:T}=Ro(),I=i??p,[j,_]=b.useState(Array.isArray(f)?f:[]),O=b.useRef(j.length>0),B=b.useRef(null),K=b.useRef(0),[V,P]=b.useState(null),[M,N]=b.useState(""),[z,L]=b.useState(!1);b.useEffect(()=>{const A=Array.isArray(f)?f:[];if(A.length>0){O.current=!0,_(A);return}m||(O.current=!1,_(A))},[f,m]),b.useEffect(()=>{if(!B.current)return;const A=B.current.querySelector("[data-radix-scroll-area-viewport]");if(!A)return;let $=null,H=null;return $=requestAnimationFrame(()=>{H=requestAnimationFrame(()=>{A.scrollTop=K.current})}),()=>{$!==null&&cancelAnimationFrame($),H!==null&&cancelAnimationFrame(H)}},[j]);const R=async A=>{try{y(A),await T(A,void 0,{clearProgress:!0}),a==null||a(A),l==null||l(A)}catch($){console.error("Failed to select thread:",$)}},W=async()=>{try{L(!0);const A=await w();A&&(c==null||c(A),a==null||a(A))}catch(A){console.error("Failed to create thread:",A)}finally{L(!1)}},Y=async(A,$)=>{if($.stopPropagation(),!!confirm("Delete this thread?")){if(B.current){const H=B.current.querySelector("[data-radix-scroll-area-viewport]");H&&(K.current=H.scrollTop)}try{await S(A),d==null||d(A)}catch(H){console.error("Failed to delete thread:",H)}}},ne=async A=>{const $=window.prompt("Share this thread with (user id or email):");if($!=null&&$.trim())try{await C(A,$.trim())}catch(H){console.error("Failed to share thread:",H),alert(H instanceof Error?H.message:String(H))}},pe=(A,$)=>{$.stopPropagation(),P(A.threadId),N(A.title||`Thread ${A.threadId.slice(0,8)}`)},be=async A=>{if(M.trim())try{await k(A,M.trim()),P(null),N("")}catch($){console.error("Failed to update title:",$)}},Ie=()=>{P(null),N("")},ve=(A,$)=>{A.key==="Enter"?be($):A.key==="Escape"&&Ie()},te=A=>{if(!A)return"";try{const $=new Date(A),fe=new Date().getTime()-$.getTime(),re=Math.floor(fe/(1e3*60*60*24));return re===0?$.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):re===1?"Yesterday":re<7?`${re} days ago`:$.toLocaleDateString()}catch{return""}},F=A=>A.title||`Thread ${A.threadId.slice(0,8)}`,X=A=>{const $=F(A);return $.length<=$h?$:`${$.slice(0,$h)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:u.jsx(tt,{onClick:W,disabled:z||m,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:z?"Creating...":"New Chat",children:u.jsx(oe.MessageSquarePlus,{size:20})})}),u.jsx(Dh,{ref:B,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsxs("div",{className:"p-2 space-y-1 pb-4",children:[(h.length>0||x)&&u.jsxs("div",{className:"space-y-2 rounded-lg border border-slate-700 bg-slate-800/60 p-2",children:[u.jsxs("div",{className:"flex items-center justify-between text-xs uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:"Shared with you"}),x&&u.jsx(oe.Loader2,{className:"h-3 w-3 animate-spin"})]}),u.jsx("div",{className:"space-y-1",children:h.map(A=>u.jsx("button",{type:"button",onClick:()=>R(A.threadId),className:`w-full text-left rounded-lg px-3 py-2 transition-colors border ${I===A.threadId?"bg-slate-600 border-slate-500":"bg-slate-700/40 border-transparent hover:bg-slate-600"} text-gray-100`,children:u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:"font-medium text-sm truncate",children:X(A)}),u.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Shared by ",A.sharedByUserId," • ",te(A.sharedAt||A.updatedAt)]})]})},A.shareId))})]}),m?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(oe.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):j.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(oe.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):j.slice().sort((A,$)=>new Date($.updatedAt||$.createdAt||"").getTime()-new Date(A.updatedAt||A.createdAt||"").getTime()).map(A=>u.jsxs("div",{onClick:()=>R(A.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${I===A.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:V===A.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:$=>$.stopPropagation(),children:[u.jsx(zs,{value:M,onChange:$=>N($.target.value),onKeyDown:$=>ve($,A.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>be(A.threadId),className:"h-6 w-6 p-0",children:u.jsx(oe.Check,{size:12})}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ie,className:"h-6 w-6 p-0",children:u.jsx(oe.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:X(A)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(oe.Calendar,{size:10}),u.jsx("span",{children:te(A.updatedAt||A.createdAt)})]})]})}),u.jsx("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:u.jsxs(kd,{children:[u.jsx(Id,{asChild:!0,children:u.jsx(tt,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:u.jsx(oe.MoreHorizontal,{size:12})})}),u.jsxs(ea,{align:"end",sideOffset:6,className:"w-44",children:[u.jsxs(Cr,{onClick:$=>{$.preventDefault(),ne(A.threadId)},children:[u.jsx(oe.Share2,{className:"mr-2 h-4 w-4"}),"Share thread"]}),r&&V!==A.threadId&&u.jsxs(Cr,{onClick:$=>{$.preventDefault(),pe(A,$)},children:[u.jsx(oe.Edit3,{className:"mr-2 h-4 w-4"}),"Rename"]}),n&&u.jsxs(Cr,{className:"text-red-400 hover:text-red-300",onClick:$=>{$.preventDefault(),Y(A.threadId,$)},children:[u.jsx(oe.Trash2,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})})]}),i===A.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},A.threadId))]})})]})}const DC=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r,className:o,onHoverStart:s,onHoverEnd:i})=>{const a=e??[],l=a.length>0,c=b.useMemo(()=>l?[...a].reverse():[],[a,l]),d=t??(a.length?a[a.length-1].id:null);if(!l)return null;const h=["w-32 flex-shrink-0 flex-col border-r border-border/40 pr-2 flex bg-white text-gray-900 dark:bg-slate-900 dark:text-slate-100",o].filter(Boolean).join(" ");return u.jsxs("div",{className:h,onMouseEnter:s,onMouseLeave:i,children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-4 pb-2 pr-1",children:[u.jsx("div",{className:"absolute left-0 right-0 top-1 px-2 pb-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:u.jsx("span",{children:"Timeline"})}),u.jsx("div",{className:"pointer-events-none absolute left-3 top-0 bottom-0 w-px bg-border/40"}),u.jsx("div",{className:"flex flex-col gap-3 pt-6 pr-2",children:c.map(p=>{const y=d===p.id,m=(r==null?void 0:r.get(p.id))??null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(p.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${y?"text-primary":"text-muted-foreground"} ${n?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-3 w-3 items-center justify-center rounded-full border ${y?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${y?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:p.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[p.step!==null?`STEP ${p.step}`:"STEP —",p.next?` - ${p.next}`:""]}),m&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:m,children:m})]})]},p.id)})})]}),n&&u.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(null),className:"mt-auto mb-3 rounded-md border border-border/70 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]})};function Nr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function LC(e){if(typeof e!="string")return;const t=e.trim();if(t)return wn(t)}function Fh(){const e=[Nr("__API_BASE_URL__"),Nr("__CHAT_API_BASE_URL__"),Nr("__CHAT_API_URL__")];for(const t of e){const n=LC(t);if(n)return n}}function Bh(){const e=[Nr("__API_AUTH_TOKEN__"),Nr("__CHAT_API_KEY__"),Nr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function zh(...e){for(const t of e)if(typeof t=="string"&&t.trim())return wn(t);return wn()}function Uh(){const e={},t=Fh(),n=Bh();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Hh(){const e=Uh(),t=Nn.getAuthToken(),n=Fh();return{apiBaseUrl:zh(e.baseUrl,Nn.baseUrl,n),apiKey:t||e.apiKey||Bh()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Wh="chat-settings";function $C(){try{const e=localStorage.getItem(Wh);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function FC(e){try{const t={...e,apiBaseUrl:wn(e.apiBaseUrl)};localStorage.setItem(Wh,JSON.stringify(t)),t.apiKey&&Nn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function BC(){const e=Hh(),t=$C(),n=Nn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:zh(Nn.baseUrl,r,e.apiBaseUrl)}}function zC(e){Nn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),FC(e)}var UC="Label",Vh=v.forwardRef((e,t)=>u.jsx(_e.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Vh.displayName=UC;var Kh=Vh;const HC=mo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qt=v.forwardRef(({className:e,...t},n)=>u.jsx(Kh,{ref:n,className:ee(HC(),e),...t}));Qt.displayName=Kh.displayName;function qh(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Gh=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),WC="VisuallyHidden",VC=v.forwardRef((e,t)=>u.jsx(_e.span,{...e,ref:t,style:{...Gh,...e.style}}));VC.displayName=WC;var KC=[" ","Enter","ArrowUp","ArrowDown"],qC=[" ","Enter"],or="Select",[Ks,qs,GC]=vi(or),[Ar,mk]=bn(or,[GC,Yo]),Gs=Yo(),[YC,$n]=Ar(or),[XC,JC]=Ar(or),Yh=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:h,required:p,form:y}=e,m=Gs(t),[x,g]=v.useState(null),[w,S]=v.useState(null),[k,C]=v.useState(!1),T=Do(c),[I,j]=pr({prop:r,defaultProp:o??!1,onChange:s,caller:or}),[_,O]=pr({prop:i,defaultProp:a,onChange:l,caller:or}),B=v.useRef(null),K=x?y||!!x.closest("form"):!0,[V,P]=v.useState(new Set),M=Array.from(V).map(N=>N.props.value).join(";");return u.jsx(lu,{...m,children:u.jsxs(YC,{required:p,scope:t,trigger:x,onTriggerChange:g,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:k,onValueNodeHasChildrenChange:C,contentId:Sn(),value:_,onValueChange:O,open:I,onOpenChange:j,dir:T,triggerPointerDownPosRef:B,disabled:h,children:[u.jsx(Ks.Provider,{scope:t,children:u.jsx(XC,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(N=>{P(z=>new Set(z).add(N))},[]),onNativeOptionRemove:v.useCallback(N=>{P(z=>{const L=new Set(z);return L.delete(N),L})},[]),children:n})}),K?u.jsxs(vp,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:N=>O(N.target.value),disabled:h,form:y,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(V)]},M):null]})})};Yh.displayName=or;var Xh="SelectTrigger",Jh=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Gs(n),i=$n(Xh,n),a=i.disabled||r,l=Ue(t,i.onTriggerChange),c=qs(n),d=v.useRef("touch"),[f,h,p]=bp(m=>{const x=c().filter(S=>!S.disabled),g=x.find(S=>S.value===i.value),w=Sp(x,m,g);w!==void 0&&i.onValueChange(w.value)}),y=m=>{a||(i.onOpenChange(!0),p()),m&&(i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)})};return u.jsx(cu,{asChild:!0,...s,children:u.jsx(_e.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":wp(i.value)?"":void 0,...o,ref:l,onClick:ue(o.onClick,m=>{m.currentTarget.focus(),d.current!=="mouse"&&y(m)}),onPointerDown:ue(o.onPointerDown,m=>{d.current=m.pointerType;const x=m.target;x.hasPointerCapture(m.pointerId)&&x.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&m.pointerType==="mouse"&&(y(m),m.preventDefault())}),onKeyDown:ue(o.onKeyDown,m=>{const x=f.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&h(m.key),!(x&&m.key===" ")&&KC.includes(m.key)&&(y(),m.preventDefault())})})})});Jh.displayName=Xh;var Zh="SelectValue",Qh=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=$n(Zh,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ue(t,l.onValueNodeChange);return kt(()=>{c(d)},[c,d]),u.jsx(_e.span,{...a,ref:f,style:{pointerEvents:"none"},children:wp(l.value)?u.jsx(u.Fragment,{children:i}):s})});Qh.displayName=Zh;var ZC="SelectIcon",ep=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(_e.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});ep.displayName=ZC;var QC="SelectPortal",tp=e=>u.jsx(Xo,{asChild:!0,...e});tp.displayName=QC;var sr="SelectContent",np=v.forwardRef((e,t)=>{const n=$n(sr,e.__scopeSelect),[r,o]=v.useState();if(kt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?go.createPortal(u.jsx(rp,{scope:e.__scopeSelect,children:u.jsx(Ks.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(op,{...e,ref:t})});np.displayName=sr;var ln=10,[rp,Fn]=Ar(sr),eT="SelectContentImpl",tT=Wn.createSlot("SelectContent.RemoveScroll"),op=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:y,hideWhenDetached:m,avoidCollisions:x,...g}=e,w=$n(sr,n),[S,k]=v.useState(null),[C,T]=v.useState(null),I=Ue(t,te=>k(te)),[j,_]=v.useState(null),[O,B]=v.useState(null),K=qs(n),[V,P]=v.useState(!1),M=v.useRef(!1);v.useEffect(()=>{if(S)return zi(S)},[S]),Si();const N=v.useCallback(te=>{const[F,...X]=K().map(H=>H.ref.current),[A]=X.slice(-1),$=document.activeElement;for(const H of te)if(H===$||(H==null||H.scrollIntoView({block:"nearest"}),H===F&&C&&(C.scrollTop=0),H===A&&C&&(C.scrollTop=C.scrollHeight),H==null||H.focus(),document.activeElement!==$))return},[K,C]),z=v.useCallback(()=>N([j,S]),[N,j,S]);v.useEffect(()=>{V&&z()},[V,z]);const{onOpenChange:L,triggerPointerDownPosRef:R}=w;v.useEffect(()=>{if(S){let te={x:0,y:0};const F=A=>{var $,H;te={x:Math.abs(Math.round(A.pageX)-((($=R.current)==null?void 0:$.x)??0)),y:Math.abs(Math.round(A.pageY)-(((H=R.current)==null?void 0:H.y)??0))}},X=A=>{te.x<=10&&te.y<=10?A.preventDefault():S.contains(A.target)||L(!1),document.removeEventListener("pointermove",F),R.current=null};return R.current!==null&&(document.addEventListener("pointermove",F),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",F),document.removeEventListener("pointerup",X,{capture:!0})}}},[S,L,R]),v.useEffect(()=>{const te=()=>L(!1);return window.addEventListener("blur",te),window.addEventListener("resize",te),()=>{window.removeEventListener("blur",te),window.removeEventListener("resize",te)}},[L]);const[W,Y]=bp(te=>{const F=K().filter($=>!$.disabled),X=F.find($=>$.ref.current===document.activeElement),A=Sp(F,te,X);A&&setTimeout(()=>A.ref.current.focus())}),ne=v.useCallback((te,F,X)=>{const A=!M.current&&!X;(w.value!==void 0&&w.value===F||A)&&(_(te),A&&(M.current=!0))},[w.value]),pe=v.useCallback(()=>S==null?void 0:S.focus(),[S]),be=v.useCallback((te,F,X)=>{const A=!M.current&&!X;(w.value!==void 0&&w.value===F||A)&&B(te)},[w.value]),Ie=r==="popper"?Ba:sp,ve=Ie===Ba?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:y,hideWhenDetached:m,avoidCollisions:x}:{};return u.jsx(rp,{scope:n,content:S,viewport:C,onViewportChange:T,itemRefCallback:ne,selectedItem:j,onItemLeave:pe,itemTextRefCallback:be,focusSelectedItem:z,selectedItemText:O,position:r,isPositioned:V,searchRef:W,children:u.jsx(ss,{as:tT,allowPinchZoom:!0,children:u.jsx($o,{asChild:!0,trapped:w.open,onMountAutoFocus:te=>{te.preventDefault()},onUnmountAutoFocus:ue(o,te=>{var F;(F=w.trigger)==null||F.focus({preventScroll:!0}),te.preventDefault()}),children:u.jsx(Lo,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:te=>te.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:u.jsx(Ie,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:te=>te.preventDefault(),...g,...ve,onPlaced:()=>P(!0),ref:I,style:{display:"flex",flexDirection:"column",outline:"none",...g.style},onKeyDown:ue(g.onKeyDown,te=>{const F=te.ctrlKey||te.altKey||te.metaKey;if(te.key==="Tab"&&te.preventDefault(),!F&&te.key.length===1&&Y(te.key),["ArrowUp","ArrowDown","Home","End"].includes(te.key)){let A=K().filter($=>!$.disabled).map($=>$.ref.current);if(["ArrowUp","End"].includes(te.key)&&(A=A.slice().reverse()),["ArrowUp","ArrowDown"].includes(te.key)){const $=te.target,H=A.indexOf($);A=A.slice(H+1)}setTimeout(()=>N(A)),te.preventDefault()}})})})})})})});op.displayName=eT;var nT="SelectItemAlignedPosition",sp=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=$n(sr,n),i=Fn(sr,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=Ue(t,I=>d(I)),h=qs(n),p=v.useRef(!1),y=v.useRef(!0),{viewport:m,selectedItem:x,selectedItemText:g,focusSelectedItem:w}=i,S=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&m&&x&&g){const I=s.trigger.getBoundingClientRect(),j=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),O=g.getBoundingClientRect();if(s.dir!=="rtl"){const $=O.left-j.left,H=_.left-$,fe=I.left-H,re=I.width+fe,Z=Math.max(re,j.width),ce=window.innerWidth-ln,me=Ra(H,[ln,Math.max(ln,ce-Z)]);a.style.minWidth=re+"px",a.style.left=me+"px"}else{const $=j.right-O.right,H=window.innerWidth-_.right-$,fe=window.innerWidth-I.right-H,re=I.width+fe,Z=Math.max(re,j.width),ce=window.innerWidth-ln,me=Ra(H,[ln,Math.max(ln,ce-Z)]);a.style.minWidth=re+"px",a.style.right=me+"px"}const B=h(),K=window.innerHeight-ln*2,V=m.scrollHeight,P=window.getComputedStyle(c),M=parseInt(P.borderTopWidth,10),N=parseInt(P.paddingTop,10),z=parseInt(P.borderBottomWidth,10),L=parseInt(P.paddingBottom,10),R=M+N+V+L+z,W=Math.min(x.offsetHeight*5,R),Y=window.getComputedStyle(m),ne=parseInt(Y.paddingTop,10),pe=parseInt(Y.paddingBottom,10),be=I.top+I.height/2-ln,Ie=K-be,ve=x.offsetHeight/2,te=x.offsetTop+ve,F=M+N+te,X=R-F;if(F<=be){const $=B.length>0&&x===B[B.length-1].ref.current;a.style.bottom="0px";const H=c.clientHeight-m.offsetTop-m.offsetHeight,fe=Math.max(Ie,ve+($?pe:0)+H+z),re=F+fe;a.style.height=re+"px"}else{const $=B.length>0&&x===B[0].ref.current;a.style.top="0px";const fe=Math.max(be,M+m.offsetTop+($?ne:0)+ve)+X;a.style.height=fe+"px",m.scrollTop=F-be+m.offsetTop}a.style.margin=`${ln}px 0`,a.style.minHeight=W+"px",a.style.maxHeight=K+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,m,x,g,s.dir,r]);kt(()=>S(),[S]);const[k,C]=v.useState();kt(()=>{c&&C(window.getComputedStyle(c).zIndex)},[c]);const T=v.useCallback(I=>{I&&y.current===!0&&(S(),w==null||w(),y.current=!1)},[S,w]);return u.jsx(oT,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(_e.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});sp.displayName=nT;var rT="SelectPopperPosition",Ba=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ln,...s}=e,i=Gs(n);return u.jsx(uu,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Ba.displayName=rT;var[oT,za]=Ar(sr,{}),Ua="SelectViewport",ip=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Fn(Ua,n),i=za(Ua,n),a=Ue(t,s.onViewportChange),l=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(Ks.Slot,{scope:n,children:u.jsx(_e.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:ue(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const y=window.innerHeight-ln*2,m=parseFloat(f.style.minHeight),x=parseFloat(f.style.height),g=Math.max(m,x);if(g<y){const w=g+p,S=Math.min(y,w),k=w-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});ip.displayName=Ua;var ap="SelectGroup",[sT,iT]=Ar(ap),aT=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Sn();return u.jsx(sT,{scope:n,id:o,children:u.jsx(_e.div,{role:"group","aria-labelledby":o,...r,ref:t})})});aT.displayName=ap;var lp="SelectLabel",cp=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=iT(lp,n);return u.jsx(_e.div,{id:o.id,...r,ref:t})});cp.displayName=lp;var Ys="SelectItem",[lT,up]=Ar(Ys),dp=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=$n(Ys,n),l=Fn(Ys,n),c=a.value===r,[d,f]=v.useState(s??""),[h,p]=v.useState(!1),y=Ue(t,w=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,w,r,o)}),m=Sn(),x=v.useRef("touch"),g=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(lT,{scope:n,value:r,disabled:o,textId:m,isSelected:c,onItemTextChange:v.useCallback(w=>{f(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:u.jsx(Ks.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(_e.div,{role:"option","aria-labelledby":m,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:y,onFocus:ue(i.onFocus,()=>p(!0)),onBlur:ue(i.onBlur,()=>p(!1)),onClick:ue(i.onClick,()=>{x.current!=="mouse"&&g()}),onPointerUp:ue(i.onPointerUp,()=>{x.current==="mouse"&&g()}),onPointerDown:ue(i.onPointerDown,w=>{x.current=w.pointerType}),onPointerMove:ue(i.onPointerMove,w=>{var S;x.current=w.pointerType,o?(S=l.onItemLeave)==null||S.call(l):x.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(i.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:ue(i.onKeyDown,w=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&w.key===" "||(qC.includes(w.key)&&g(),w.key===" "&&w.preventDefault())})})})})});dp.displayName=Ys;var ho="SelectItemText",fp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=$n(ho,n),a=Fn(ho,n),l=up(ho,n),c=JC(ho,n),[d,f]=v.useState(null),h=Ue(t,g=>f(g),l.onItemTextChange,g=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,g,l.value,l.disabled)}),p=d==null?void 0:d.textContent,y=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:m,onNativeOptionRemove:x}=c;return kt(()=>(m(y),()=>x(y)),[m,x,y]),u.jsxs(u.Fragment,{children:[u.jsx(_e.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?go.createPortal(s.children,i.valueNode):null]})});fp.displayName=ho;var hp="SelectItemIndicator",pp=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return up(hp,n).isSelected?u.jsx(_e.span,{"aria-hidden":!0,...r,ref:t}):null});pp.displayName=hp;var Ha="SelectScrollUpButton",mp=v.forwardRef((e,t)=>{const n=Fn(Ha,e.__scopeSelect),r=za(Ha,e.__scopeSelect),[o,s]=v.useState(!1),i=Ue(t,r.onScrollButtonChange);return kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(xp,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});mp.displayName=Ha;var Wa="SelectScrollDownButton",gp=v.forwardRef((e,t)=>{const n=Fn(Wa,e.__scopeSelect),r=za(Wa,e.__scopeSelect),[o,s]=v.useState(!1),i=Ue(t,r.onScrollButtonChange);return kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(xp,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});gp.displayName=Wa;var xp=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Fn("SelectScrollButton",n),i=v.useRef(null),a=qs(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),kt(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(_e.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{l()})})}),cT="SelectSeparator",yp=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(_e.div,{"aria-hidden":!0,...r,ref:t})});yp.displayName=cT;var Va="SelectArrow",uT=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Gs(n),s=$n(Va,n),i=Fn(Va,n);return s.open&&i.position==="popper"?u.jsx(du,{...o,...r,ref:t}):null});uT.displayName=Va;var dT="SelectBubbleInput",vp=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=Ue(r,o),i=qh(t);return v.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(_e.select,{...n,style:{...Gh,...n.style},ref:s,defaultValue:t})});vp.displayName=dT;function wp(e){return e===""||e===void 0}function bp(e){const t=It(e),n=v.useRef(""),r=v.useRef(0),o=v.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function Sp(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=fT(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function fT(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var hT=Yh,Cp=Jh,pT=Qh,mT=ep,gT=tp,Tp=np,xT=ip,kp=cp,Ip=dp,yT=fp,vT=pp,Ep=mp,Np=gp,Ap=yp;const jp=hT,_p=pT,Ka=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Cp,{ref:r,className:ee("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(mT,{asChild:!0,children:u.jsx(oe.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ka.displayName=Cp.displayName;const Mp=v.forwardRef(({className:e,...t},n)=>u.jsx(Ep,{ref:n,className:ee("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(oe.ChevronUp,{className:"h-4 w-4"})}));Mp.displayName=Ep.displayName;const Pp=v.forwardRef(({className:e,...t},n)=>u.jsx(Np,{ref:n,className:ee("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(oe.ChevronDown,{className:"h-4 w-4"})}));Pp.displayName=Np.displayName;const qa=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(gT,{children:u.jsxs(Tp,{ref:o,className:ee("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(Mp,{}),u.jsx(xT,{className:ee("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(Pp,{})]})}));qa.displayName=Tp.displayName;const wT=v.forwardRef(({className:e,...t},n)=>u.jsx(kp,{ref:n,className:ee("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));wT.displayName=kp.displayName;const ir=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Ip,{ref:r,className:ee("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(vT,{children:u.jsx(oe.Check,{className:"h-4 w-4"})})}),u.jsx(yT,{children:t})]}));ir.displayName=Ip.displayName;const bT=v.forwardRef(({className:e,...t},n)=>u.jsx(Ap,{ref:n,className:ee("-mx-1 my-1 h-px bg-muted",e),...t}));bT.displayName=Ap.displayName;var ST="Separator",Rp="horizontal",CT=["horizontal","vertical"],Op=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Rp,...o}=e,s=TT(r)?r:Rp,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(_e.div,{"data-orientation":s,...a,...o,ref:t})});Op.displayName=ST;function TT(e){return CT.includes(e)}var Dp=Op;const Lp=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Dp,{ref:o,decorative:n,orientation:t,className:ee("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Lp.displayName=Dp.displayName;const kT=Gf,IT=DS,ET=Yf,$p=v.forwardRef(({className:e,...t},n)=>u.jsx(js,{className:ee("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));$p.displayName=js.displayName;const NT=mo.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Fp=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(ET,{children:[u.jsx($p,{}),u.jsxs(_s,{ref:o,className:ee(NT({side:e}),t),...r,children:[n,u.jsxs(Xf,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(oe.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fp.displayName=_s.displayName;const Bp=({className:e,...t})=>u.jsx("div",{className:ee("flex flex-col space-y-2 text-center sm:text-left",e),...t});Bp.displayName="SheetHeader";const zp=v.forwardRef(({className:e,...t},n)=>u.jsx(nr,{ref:n,className:ee("text-lg font-semibold text-foreground",e),...t}));zp.displayName=nr.displayName;const Up=v.forwardRef(({className:e,...t},n)=>u.jsx(Ms,{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));Up.displayName=Ms.displayName;var Xs="Switch",[AT,gk]=bn(Xs),[jT,_T]=AT(Xs),Hp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[h,p]=v.useState(null),y=Ue(t,S=>p(S)),m=v.useRef(!1),x=h?d||!!h.closest("form"):!0,[g,w]=pr({prop:o,defaultProp:s??!1,onChange:c,caller:Xs});return u.jsxs(jT,{scope:n,checked:g,disabled:a,children:[u.jsx(_e.button,{type:"button",role:"switch","aria-checked":g,"aria-required":i,"data-state":qp(g),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:y,onClick:ue(e.onClick,S=>{w(k=>!k),x&&(m.current=S.isPropagationStopped(),m.current||S.stopPropagation())})}),x&&u.jsx(Kp,{control:h,bubbles:!m.current,name:r,value:l,checked:g,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Hp.displayName=Xs;var Wp="SwitchThumb",Vp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_T(Wp,n);return u.jsx(_e.span,{"data-state":qp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Vp.displayName=Wp;var MT="SwitchBubbleInput",Kp=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=Ue(i,s),l=qh(n),c=Zc(t);return v.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const y=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(y)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Kp.displayName=MT;function qp(e){return e?"checked":"unchecked"}var Gp=Hp,PT=Vp;const Bn=v.forwardRef(({className:e,...t},n)=>u.jsx(Gp,{className:ee("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(PT,{className:ee("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Bn.displayName=Gp.displayName;const RT={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function OT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=b.useState(!1),[s,i]=b.useState(!1),[a,l]=b.useState(e),[c,d]=b.useState(!1),{toast:f}=ja();b.useEffect(()=>{const x=JSON.stringify(a)!==JSON.stringify(e);d(x)},[a,e]),b.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(RT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},y=()=>{l(e),d(!1),o(!1)},m=async()=>{try{const g=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${g.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(kT,{open:r,onOpenChange:o,children:[u.jsx(IT,{asChild:!0,children:u.jsxs(tt,{variant:"outline",size:"sm",className:n,children:[u.jsx(oe.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(If,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Fp,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(Bp,{children:[u.jsx(zp,{children:"Chat Settings"}),u.jsx(Up,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(lo,{children:[u.jsx(co,{className:"pb-3",children:u.jsxs(uo,{className:"text-lg flex items-center gap-2",children:[u.jsx(oe.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(fo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(Qt,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(zs,{id:"api-url",value:a.api.baseUrl,onChange:x=>l(g=>({...g,api:{...g.api,baseUrl:x.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(tt,{variant:"outline",onClick:m,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(Qt,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Bn,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:x=>l(g=>({...g,api:{...g.api,enableAuth:x}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(Qt,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(zs,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:x=>l(g=>({...g,api:{...g.api,authToken:x.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(tt,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(oe.EyeOff,{className:"h-4 w-4"}):u.jsx(oe.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(lo,{children:[u.jsx(co,{className:"pb-3",children:u.jsxs(uo,{className:"text-lg flex items-center gap-2",children:[u.jsx(oe.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(fo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(Qt,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(jp,{value:a.ui.layout,onValueChange:x=>l(g=>({...g,ui:{...g.ui,layout:x}})),children:[u.jsx(Ka,{children:u.jsx(_p,{})}),u.jsxs(qa,{children:[u.jsx(ir,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(ir,{value:"fullscreen",children:"Fullscreen"}),u.jsx(ir,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(Qt,{htmlFor:"theme",children:"Theme"}),u.jsxs(jp,{value:a.ui.theme,onValueChange:x=>l(g=>({...g,ui:{...g.ui,theme:x}})),children:[u.jsx(Ka,{children:u.jsx(_p,{})}),u.jsxs(qa,{children:[u.jsx(ir,{value:"light",children:"Light"}),u.jsx(ir,{value:"dark",children:"Dark"}),u.jsx(ir,{value:"system",children:"System"})]})]})]}),u.jsx(Lp,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(Qt,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Bn,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:x=>l(g=>({...g,ui:{...g.ui,showTimestamps:x}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(Qt,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Bn,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:x=>l(g=>({...g,ui:{...g.ui,showAgentNames:x}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(Qt,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Bn,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:x=>l(g=>({...g,ui:{...g.ui,compactMessages:x}}))})]})]})]})]}),u.jsxs(lo,{children:[u.jsx(co,{className:"pb-3",children:u.jsxs(uo,{className:"text-lg flex items-center gap-2",children:[u.jsx(oe.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(fo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(Qt,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(Bn,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:x=>l(g=>({...g,behavior:{...g.behavior,autoSave:x}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(Qt,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(Bn,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:x=>l(g=>({...g,behavior:{...g.behavior,enableStreaming:x}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(Qt,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(Bn,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:x=>l(g=>({...g,behavior:{...g.behavior,showTypingIndicator:x}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(tt,{variant:"outline",onClick:p,children:[u.jsx(oe.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(tt,{variant:"outline",onClick:y,children:"Cancel"}),u.jsxs(tt,{onClick:h,disabled:!c,children:[u.jsx(oe.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function DT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=b.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(Oo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(Bs,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(Oo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Fa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Bs,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(Oo,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Fa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Bs,{onError:s.onError,enableFileUpload:!0})})]})})}Te.ChatApi=zl,Te.ChatInput=gc,Te.ChatInterface=Bs,Te.ChatProviders=Oo,Te.ChatSettings=OT,Te.MarkdownContent=ao,Te.MessageComponent=Fs,Te.MessageList=Pa,Te.ThreadManager=Fa,Te.TimelineColumn=DC,Te.applySettings=zC,Te.buildMessagePreviewMap=Ag,Te.chatApiClient=Nn,Te.default=DT,Te.del=fi,Te.get=Ut,Te.getChatToken=$l,Te.getCurrentSettings=BC,Te.getDefaultApiConfig=Uh,Te.getDefaultChatSettings=Hh,Te.onChatTokenChanged=Fl,Te.post=Ao,Te.put=Bl,Te.setChatToken=No,Te.useApi=hi,Te.useChatStream=cc,Te.useMessagesReducer=ac,Te.useStream=pc,Te.useThreadState=Ro,Te.useThreads=Po,Object.defineProperties(Te,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
134
+ `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=Sp(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=Sp(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class Ep{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class Np{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class Bn{constructor(t){this.options=t||sr,this.options.renderer=this.options.renderer||new Va,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Ep,this.slugger=new Np}static parse(t,n){return new Bn(n).parse(t)}static parseInline(t,n){return new Bn(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,p,h,v,g,y,x,b,C,k,T,S;const I=t.length;for(o=0;o<I;o++){if(h=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[h.type]&&(S=this.options.extensions.renderers[h.type].call({parser:this},h),S!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(h.type))){r+=S||"";continue}switch(h.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(h.tokens),h.depth,wp(this.parseInline(h.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(h.text,h.lang,h.escaped);continue}case"table":{for(f="",d="",a=h.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(h.header[s].tokens),{header:!0,align:h.align[s]});for(f+=this.renderer.tablerow(d),p="",a=h.rows.length,s=0;s<a;s++){for(c=h.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:h.align[i]});p+=this.renderer.tablerow(d)}r+=this.renderer.table(f,p);continue}case"blockquote":{p=this.parse(h.tokens),r+=this.renderer.blockquote(p);continue}case"list":{for(v=h.ordered,g=h.start,y=h.loose,a=h.items.length,p="",s=0;s<a;s++)b=h.items[s],C=b.checked,k=b.task,x="",b.task&&(T=this.renderer.checkbox(C),y?b.tokens.length>0&&b.tokens[0].type==="paragraph"?(b.tokens[0].text=T+" "+b.tokens[0].text,b.tokens[0].tokens&&b.tokens[0].tokens.length>0&&b.tokens[0].tokens[0].type==="text"&&(b.tokens[0].tokens[0].text=T+" "+b.tokens[0].tokens[0].text)):b.tokens.unshift({type:"text",text:T}):x+=T),x+=this.parse(b.tokens,y),p+=this.renderer.listitem(x,k,C);r+=this.renderer.list(p,v,g);continue}case"html":{r+=this.renderer.html(h.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(h.tokens));continue}case"text":{for(p=h.tokens?this.parseInline(h.tokens):h.text;o+1<I&&t[o+1].type==="text";)h=t[++o],p+=`
135
+ `+(h.tokens?this.parseInline(h.tokens):h.text);r+=n?this.renderer.paragraph(p):p;continue}default:{const A='Token with "'+h.type+'" type was not found.';if(this.options.silent){console.error(A);return}else throw new Error(A)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class Ks{constructor(t){this.options=t||sr}preprocess(t){return t}postprocess(t){return t}}Em(Ks,"passThroughHooks",new Set(["preprocess","postprocess"]));function FC(e,t,n){return r=>{if(r.message+=`
136
+ Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+_t(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function Ap(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...be.defaults,...s};const i=FC(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(DC(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let p;if(!f)try{r.walkTokens&&be.walkTokens(l,r.walkTokens),p=t(l,r),r.hooks&&(p=r.hooks.postprocess(p))}catch(h){f=h}return r.highlight=a,f?i(f):o(null,p)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;be.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(p,h){if(p)return c(p);h!=null&&h!==f.text&&(f.text=h,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(be.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&be.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function be(e,t,n){return Ap(Fn.lex,Bn.parse)(e,t,n)}be.options=be.setOptions=function(e){return be.defaults={...be.defaults,...e},CC(be.defaults),be},be.getDefaults=xp,be.defaults=sr,be.use=function(...e){const t=be.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=be.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=be.defaults.renderer||new Va;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=be.defaults.tokenizer||new Wa;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=be.defaults.hooks||new Ks;for(const s in n.hooks){const i=o[s];Ks.passThroughHooks.has(s)?o[s]=a=>{if(be.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=be.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}be.setOptions(r)})},be.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(be,r)),r.type){case"table":{for(const o of r.header)n=n.concat(be.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(be.walkTokens(s.tokens,t));break}case"list":{n=n.concat(be.walkTokens(r.items,t));break}default:be.defaults.extensions&&be.defaults.extensions.childTokens&&be.defaults.extensions.childTokens[r.type]?be.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(be.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(be.walkTokens(r.tokens,t)))}return n},be.parseInline=Ap(Fn.lexInline,Bn.parseInline),be.Parser=Bn,be.parser=Bn.parse,be.Renderer=Va,be.TextRenderer=Ep,be.Lexer=Fn,be.lexer=Fn.lex,be.Tokenizer=Wa,be.Slugger=Np,be.Hooks=Ks,be.parse=be,be.options,be.setOptions,be.use,be.walkTokens,be.parseInline,Bn.parse,Fn.lex;function xo({content:e,className:t="",allowHtml:n=!1,style:r}){const o=w.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof be.parse=="function"?be.parse(i):be(i)}return typeof be.parse=="function"?be.parse(e):be(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=w.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:se("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const BC={MODE:"library"};function zC(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ai&&ai.tagName.toUpperCase()==="SCRIPT"&&ai.src||new URL("index.umd.js",document.baseURI).href}<"u"?BC:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function UC(){return!zC()}function HC(){return typeof window>"u"?!1:window.__ARTIFACT_DEBUG__===!0}function WC(){return UC()||HC()}function VC({preview:e,idx:t}){return w.useEffect(()=>{WC()&&console.debug(`[MessageComponent] Preview ${t} mounted:`,{src:e.src.substring(0,100),alt:e.alt,label:e.label})},[t,e]),u.jsxs("div",{className:"space-y-2",children:[e.label&&u.jsxs("p",{className:"text-[0.65rem] uppercase tracking-wide text-muted-foreground",children:["Artifact: ",e.label]}),u.jsx("div",{className:"overflow-hidden rounded border border-border/60 bg-background/60 p-1 shadow-sm",children:u.jsx("img",{src:e.src,alt:e.alt,title:e.label,loading:"lazy",className:"h-auto max-h-[420px] w-full rounded object-contain",onLoad:()=>{},onError:n=>{console.error(`[MessageComponent] ❌ Image failed to load for artifact ${t}:`,{alt:e.alt,label:e.label,message:n.target.alt})}})})]})}const yo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));yo.displayName="Card";const vo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex flex-col space-y-1.5 p-6",e),...t}));vo.displayName="CardHeader";const bo=m.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:se("text-2xl font-semibold leading-none tracking-tight",e),...t}));bo.displayName="CardTitle";const jp=m.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:se("text-sm text-muted-foreground",e),...t}));jp.displayName="CardDescription";const wo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("p-6 pt-0",e),...t}));wo.displayName="CardContent";const _p=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex items-center p-6 pt-0",e),...t}));_p.displayName="CardFooter";function KC({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=po(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(yo,{className:se("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(vo,{className:"pb-3",children:[u.jsx(bo,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(jp,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(wo,{className:"pt-0 pb-3",children:a}),u.jsx(_p,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(rt,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(rt,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}const qC="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Mp({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:qC,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:po(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:po(e)})}function GC({message:e,isStreaming:t=!1}){const n=e.name??"tool",r=w.useMemo(()=>{const a=e.additionalKwargs??{};return Array.isArray(a.toolProgress)?[...a.toolProgress]:[]},[e]),s=r.some(a=>a.type==="tool.start"||a.type==="tool.call"||a.type==="message.start")?`Running ${n}…`:void 0;return t||r.length>0?u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[t&&u.jsx(ue.Loader,{className:"h-3 w-3 animate-spin"}),u.jsx("span",{children:s??`Running ${n}…`})]}),r.length>0&&u.jsx("div",{className:"space-y-2 text-xs text-muted-foreground",children:r.map((a,l)=>{var c;return u.jsxs("div",{className:"rounded border border-current/10 bg-muted/60 p-2 text-[11px] leading-snug",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between text-[8px] uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:((c=a.type)==null?void 0:c.replace(/\./g," "))??"progress"}),u.jsx("span",{children:a.idx??l+1})]}),a.content&&u.jsx("p",{className:"mt-1 text-[12px] text-foreground/90",children:a.content}),u.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[10px] opacity-70",children:[typeof a.factsFound=="number"&&u.jsxs("span",{children:["Facts found: ",a.factsFound]}),typeof a.isSufficient=="boolean"&&u.jsxs("span",{children:["Research ",a.isSufficient?"sufficient":"needs more data"]})]})]},`tool-progress-${n}-${l}`)})})]}):null}function YC({message:e,viewMode:t,isStreaming:n=!1}){const o=qf(e).name||"tool",s=l=>{if(l==null)return null;const c=typeof l=="string"?Ma(l)??l:l;if(c&&typeof c=="object")return u.jsx(Mp,{data:c});const d=typeof c=="string"?c:(()=>{try{return po(c)}catch{return String(c??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:d})},i=l=>{if(l==null)return null;const{content:c,isMarkdown:d}=YS(l);return d?u.jsx(xo,{content:c,className:"text-current"}):s(l)},a=()=>{const l=e.content.find(f=>f.type!=="tool_call");if(!l)return u.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:u.jsxs("span",{children:["Running ",o,"…"]})});if(l.type==="text"){const p=(l.text??"").trim();if(!p)return null;const h=Ds(p);return i(h)}const c=fo(l),d=Ds(c);return i(d)};return u.jsxs("div",{className:"space-y-2",children:[u.jsx(GC,{message:e,isStreaming:n}),t==="expanded"&&a()]})}function XC(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=Ha(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(h=>{a(h),c(!0)},[]),p=w.useCallback(async(h,v,g)=>{var y,x;if(!t){h.preventDefault();return}if(o[g]){h.preventDefault();return}try{const b=String(v.url??""),C=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(C){h.preventDefault();const k=C[1],T=v.name||`file_${k}`,S=v.mimeType||"application/octet-stream";f({id:k,name:T,mimeType:S});return}if(b.startsWith("data:")){h.preventDefault(),s(T=>({...T,[g]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const T=await oC(n??void 0);if(!T||!Array.isArray(T))throw new Error("Invalid file list response");const S=T.find(I=>!I||typeof I!="object"||!((I.filename??"")===(v.name??""))?!1:typeof v.size=="number"&&typeof I.size=="number"?I.size===v.size:!0);if(!(S!=null&&S.id))throw new Error(`File "${v.name}" is not yet available on the server`);if(!S.id||!S.filename)throw new Error("Invalid file data received from server");f({id:S.id,name:v.name||S.filename||`file_${S.id}`,mimeType:v.mimeType||S.mime_type||"application/octet-stream"}),(y=k.update)==null||y.call(k,{id:k.id,title:"Success",description:`Opened ${v.name}`,open:!0})}catch(T){console.error("Failed to fetch server file:",T);const S=T instanceof Error?T.message:"Unknown error occurred";(x=k.update)==null||x.call(k,{id:k.id,title:"Failed",description:S}),r({title:"Failed to fetch file",description:S,open:!0})}finally{s(T=>({...T,[g]:!1}))}}}catch(b){console.error("File click error:",b),s(C=>({...C,[g]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:p,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function JC({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:se("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(xo,{content:e,allowHtml:!1}):u.jsxs("pre",{className:se("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(rt,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(ue.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(ue.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function ZC({className:e}){const[t,n]=w.useState(0);return w.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:se("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function Rp(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}const qs=w.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,showArtifactPreviews:p=!0,customStyles:h={},onEdit:v,onRegenerate:g,onCancelEdit:y,onCopy:x,activeInterrupt:b,disableInterruptActions:C=!1,onInterruptActionStart:k,onInterruptActionEnd:T,checkpointCandidates:S=[],activeCheckpointId:I=null,onSelectCheckpoint:A,defaultCheckpointId:R=null,messageParentCheckpointId:D=null}){const[F,q]=w.useState(!1),[W,_]=w.useState("preview"),[j,N]=w.useState(!1),{currentThreadId:z}=Ho(),{respondToInterrupt:L}=Wo(),P=l==="phone"||l==="half-screen",V=t.role,ne=V==="tool",M=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),Y=!!M,ae=!(r&&V!=="user"),{uploadingFiles:Q,handleFileClick:ce,fileViewerOpen:G,currentFileInfo:O,closeFileViewer:K}=XC({allowFileOpen:ae,currentThreadId:z}),B=w.useMemo(()=>{switch(V){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[V]),te=w.useMemo(()=>{if(M)return"";const X=t.content;return Array.isArray(X)?XS(X):""},[M,t]),Z=w.useMemo(()=>{if(M)return{};const X=t.content;return Array.isArray(X)?qf(t):{}},[M,t]),ye=w.useMemo(()=>ne?!!(t.additionalKwargs??{}).toolStreaming:!1,[ne,t]),fe=w.useMemo(()=>{if(M)return[];const X=t.content;return Array.isArray(X)?X.filter(H=>H.type==="image_url"):[]},[M,t]),oe=w.useMemo(()=>{if(M)return[];const X=t.content;return Array.isArray(X)?X.filter(H=>H.type==="file"):[]},[M,t]),xe=w.useMemo(()=>{if(M)return[];const X=t.content;return Array.isArray(X)?X.filter(H=>H.type==="interrupt"):[]},[M,t]),Se=(b==null?void 0:b.id)??(b==null?void 0:b.interrupt_id),$e=Ls(Se),_e=b==null?void 0:b.value,Ue=w.useMemo(()=>{if(M)return"";const X=t.content;return Array.isArray(X)?JS(X):""},[M,t]),U=w.useMemo(()=>{if(M||!p)return[];const H=t.artifact;if(!H)return[];const re=[],Ee=[...Array.isArray(H.plots)?H.plots:[]];for(const we of Ee){const Qe=nC(we);Qe&&re.push(Qe)}return re},[M,t,p]),le=w.useCallback(async()=>{const X=ne?Ue:te;async function H(re){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(re);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Ee=new Blob([re],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Ee})]);return}throw new Error("Clipboard API not supported in this context.")}try{await H(X),q(!0),setTimeout(()=>q(!1),2e3),x==null||x(X)}catch(re){console.error("Failed to copy:",re)}},[ne,Ue,te,x]),ke=w.useCallback(()=>{if(!v)return;const X=ne?Ue:te,H="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};v(t.id,X,H)},[v,t.id,ne,Ue,te,t]),Ke=w.useCallback(()=>{g==null||g(n)},[g,n]),tt=w.useCallback(()=>{const H=se(P?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",B);switch(V){case"user":return u.jsx(ue.User,{className:H});case"assistant":return u.jsx(ue.Bot,{className:H});case"tool":return u.jsx(ue.Wrench,{className:H});default:return u.jsx(ue.Bot,{className:H})}},[P,B,V]),St=w.useCallback(()=>{const X="group relative mb-4 flex w-full";switch(V){case"user":return se(X,"justify-end");case"assistant":case"tool":case"system":return se(X,"justify-start");default:return X}},[V]),ut=w.useCallback(()=>{const X=se("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",P&&"px-3 py-2 text-sm");if(Y)return se(X,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(V){case"user":return se(X,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return se(X,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return se(X,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return se(X,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return se(X,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[P,Y,V]),yt=w.useCallback(async X=>{if(C)return;const H=Ls((X==null?void 0:X.id)??(X==null?void 0:X.interrupt_id));if(!H){console.warn("Interrupt part missing id",X);return}try{k==null||k(),await L(H,!0)}catch(re){console.error("Failed to approve interrupt:",re)}finally{T==null||T()}},[C,T,k,L]),pt=w.useCallback(async X=>{if(C)return;const H=Ls((X==null?void 0:X.id)??(X==null?void 0:X.interrupt_id));if(!H){console.warn("Interrupt part missing id",X);return}try{k==null||k(),await L(H,!1)}catch(re){console.error("Failed to reject interrupt:",re)}finally{T==null||T()}},[C,T,k,L]),wt=w.useCallback(({part:X,i:H})=>{if(X.type==="text"){const re=X.text??"",Ee=re.trim(),we=Ma(Ee);return we&&V!=="tool"?u.jsx(Mp,{data:we},H):V==="user"&&c&&Ee.length>d?u.jsx(JC,{text:Ee,expanded:j,onExpandedChange:N,previewLength:d,isCompact:P},H):u.jsx(xo,{content:re,allowHtml:!1},H)}if(X.type==="image_url"){const re=X;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:re.url,alt:re.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},H)}if(X.type==="file"){const re=X,Ee=re.name||"file";return u.jsxs("a",{href:re.url,onClick:we=>ce(we.nativeEvent,re,H),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
137
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[Q[H]?u.jsx(ue.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[Ee,Q[H]?" (processing)":""]})]},H)}if(X.type==="interrupt"){const re=X,Ee=Ls((re==null?void 0:re.id)??(re==null?void 0:re.interrupt_id)),we=!!($e&&Ee&&Ee===$e),Qe=we?_e??(re==null?void 0:re.value):re==null?void 0:re.value,Pe=Ee?{...re,id:Ee,interrupt_id:Ee}:re;return u.jsx(KC,{interruptPart:Pe,onApprove:yt,onReject:pt,disabled:C,isActive:we,payload:Qe},H)}return null},[ce,Q,yt,pt,V,c,d,j,P,$e,_e,b,C,xe]),Mt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(ue.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),Wt=w.useCallback(()=>{const X=te.trim().length>0||fe.length>0||oe.length>0||xe.length>0;if(!ne&&oe.length>0&&!r)return Mt();if(!ne&&!X&&!r)return null;if(ne)return!f&&U.length>0?null:f?u.jsx(YC,{message:t,viewMode:W,isStreaming:ye},t.id):null;if(!ne&&!M){const H=t,re=u.jsx("div",{className:"space-y-2",children:H.content.map((Ee,we)=>u.jsx(wt,{part:Ee,i:we},we))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[re,u.jsx(ZC,{className:B})]}):re}},[te,fe.length,oe.length,xe.length,r,ne,W,f,U.length,Mt,B]),nn=w.useMemo(()=>M?"Assistant":ZS(t),[M,t]),Ve=w.useMemo(()=>M?[]:Array.isArray(S)?S:[],[S,M]),Sn=w.useMemo(()=>{var X;return Ve.length?R&&Ve.some(H=>H.id===R)?R:((X=Ve[0])==null?void 0:X.id)??null:null},[R,Ve]),Ge=w.useMemo(()=>!Ve.length||!I?null:Ve.some(X=>X.id===I)?I:null,[I,Ve])??Sn,dt=V==="user"&&Ve.length>0&&typeof A=="function",Rt=w.useCallback((X,H=!1)=>{if(!A)return;const re=(X==null?void 0:X.id)??null,Ee=(X==null?void 0:X.parentId)??D??null;A(re,Ee,H)},[D,A]),Je=w.useMemo(()=>Ge?Ve.findIndex(X=>X.id===Ge):-1,[Ge,Ve]),Pt=w.useMemo(()=>Je<0?null:Ve[Je]??null,[Je,Ve]);return ne&&!f&&U.length===0?null:Y&&M?u.jsx("div",{className:se(St(),h.container),children:u.jsxs("div",{className:se(ut(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(ue.Bot,{className:se("h-4 w-4",B)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(xo,{content:M.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:se(St(),h.container),children:u.jsxs("div",{className:se(ut(),h.content),children:[(i||a||ne)&&u.jsxs("div",{className:se("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",B,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[tt(),a&&nn&&u.jsx("span",{className:se("font-medium",P?"text-xs":"text-sm"),children:nn}),ne&&u.jsxs(Vf,{variant:"outline",className:se("text-xs flex items-center gap-1 cursor-pointer select-none",B,"border border-current/40",P&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":W==="expanded",onClick:()=>_(X=>X==="expanded"?"preview":"expanded"),onKeyDown:X=>{(X.key==="Enter"||X.key===" ")&&(X.preventDefault(),_(H=>H==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:Z.name??"Tool Output"}),Z.toolCallId&&u.jsx("span",{className:"opacity-70",children:Z.toolCallId.slice(0,8)}),W==="expanded"?u.jsx(ue.ChevronUp,{className:"h-3 w-3"}):u.jsx(ue.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[dt&&Pt&&Je>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Je<Ve.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Je>=Ve.length-1)return;const X=Ve[Je+1];X&&Rt(X)},"aria-label":"Older checkpoint (back in time)",disabled:Je>=Ve.length-1,children:u.jsx(ue.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[Ve.length-Je," / ",Ve.length]})}),u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Je>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(Je<=0))if(Je===1)Rt(null,!0);else{const X=Ve[Je-1];X&&Rt(X,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:Je<=0,children:u.jsx(ue.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:se("text-xs opacity-60",B,P&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:se("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(rt,{variant:"ghost",size:"sm",onClick:()=>le(),className:se("h-6 w-6 p-0 hover:bg-foreground/10",B,P&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(ue.Copy,{className:se(F?"text-success":B,P?"h-3 w-3":"h-4 w-4")})})}),V==="user"&&v&&u.jsx(rt,{variant:"ghost",size:"sm",onClick:ke,className:se("h-6 w-6 p-0 hover:bg-foreground/10",B,P&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(ue.Edit,{className:se(B,P?"h-3 w-3":"h-4 w-4")})}),V==="assistant"&&g&&u.jsx(rt,{variant:"ghost",size:"sm",onClick:Ke,className:se("h-6 w-6 p-0 hover:bg-foreground/10",B,P&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(ue.RotateCcw,{className:se(B,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[Wt(),p&&U.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:U.map((X,H)=>u.jsx(VC,{preview:X,idx:H},`artifact-${H}`))})]}),ne&&W==="expanded"&&(Z.toolCallId||Z.name)&&u.jsxs("div",{className:se("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[Z.name&&u.jsxs("div",{children:["Function: ",Z.name]}),Z.toolCallId&&u.jsxs("div",{children:["Call ID: ",Z.toolCallId]})]}),!(i||a||ne)&&s&&!o&&u.jsxs("div",{className:se("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(rt,{variant:"ghost",size:"sm",onClick:()=>le(),className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ue.Copy,{className:se(F?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),V==="user"&&v&&u.jsx(rt,{variant:"ghost",size:"sm",onClick:ke,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ue.Edit,{className:se("text-current",P?"h-3 w-3":"h-4 w-4")})}),V==="assistant"&&g&&u.jsx(rt,{variant:"ghost",size:"sm",onClick:Ke,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ue.RotateCcw,{className:se("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})}),O&&u.jsx(SC,{isOpen:G,onClose:K,fileId:O.id,fileName:O.name,mimeType:O.mimeType})]})},(e,t)=>{var l,c,d,f,p,h,v,g;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&Gf(e.message)===Gf(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","attemptMeta"].every(y=>e[y]===t[y]),s=((l=e.customStyles)==null?void 0:l.container)===((c=t.customStyles)==null?void 0:c.container)&&((d=e.customStyles)==null?void 0:d.content)===((f=t.customStyles)==null?void 0:f.content)&&((p=e.customStyles)==null?void 0:p.actions)===((h=t.customStyles)==null?void 0:h.actions)&&((v=e.customStyles)==null?void 0:v.header)===((g=t.customStyles)==null?void 0:g.header);if(!o||!s)return!1;const i=Rp(e.message),a=Rp(t.message);return i.length===a.length});qs.displayName="MessageComponent";function QC(e,t){return w.useMemo(()=>{var d,f,p,h,v;const n=e&&"type"in e&&e.type==="default_message";let r=[],o=null,s={},i={},a=null,l=null,c=null;if(!n&&e){const g=e,y=g.checkpointId??null;s=g.additionalKwargs??{},i=g.responseMetadata??{};const x=y&&t.checkpointMetaById?t.checkpointMetaById.get(y)??null:null;a=typeof s.step=="number"?s.step:typeof i.step=="number"?i.step:(x==null?void 0:x.step)??null;const b=typeof s.source=="string"?s.source:typeof i.source=="string"?i.source:(x==null?void 0:x.source)??null;l=b?String(b):null;const C=a!==null&&l?`${a}:${l}`:null;if(C&&((d=t.checkpointIndexByKey)!=null&&d.has(C))?r=t.checkpointIndexByKey.get(C)??[]:y&&x&&(r=[x]),o=y??((f=r[0])==null?void 0:f.id)??null,c=y?((p=t.attemptMetaById)==null?void 0:p.get(y))??null:null,!c&&(e==null?void 0:e.role)==="user"&&(e!=null&&e.id)&&t.userMessageIdToAttempts){const k=t.userMessageIdToAttempts.get(e.id);if(k&&k.length>0){const T=k[0].checkpointId;c=((h=t.attemptMetaById)==null?void 0:h.get(T))??null,c&&console.log(`[useMessageMetadata] Found attempt by user message ID "${e.id}":`,k.length,"versions")}}if(!c&&r.length>0&&t.attemptMetaById){const k=t.attemptMetaById.get(r[0].id);k&&(c=k)}if(c&&c.attemptCount>1&&t.attemptMetaById){const k=c.baseUserMessageId;if(k){const T=[];for(const[S,I]of t.attemptMetaById.entries())if(I.baseUserMessageId===k){const A=(v=t.checkpointMetaById)==null?void 0:v.get(S);A&&T.push(A)}T.length>0&&(r=T)}}if(c&&c.attemptCount>1&&t.checkpointMetaById&&t.attemptMetaById){const k=[];for(const[T,S]of t.checkpointMetaById.entries()){const I=t.attemptMetaById.get(T);I&&I.attemptCount===c.attemptCount&&I.baseUserMessageId===c.baseUserMessageId&&k.push(S)}k.sort((T,S)=>{const I=T.createdAt?Date.parse(T.createdAt):0;return(S.createdAt?Date.parse(S.createdAt):0)-I}),k.length>0&&(r=k,console.log("[useMessageMetadata] Populated checkpointCandidates with all attempts:",{messageId:e.id,attemptCount:c.attemptCount,candidateIds:r.map(T=>T.id)}))}}return{checkpointCandidates:r,defaultCheckpointId:o,attemptMeta:c,resolvedStep:a,resolvedSource:l}},[e,t.checkpointMetaById,t.checkpointIndexByKey,t.attemptMetaById,t.userMessageIdToAttempts])}const Pp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Op=w.memo(function({message:t,index:n,isStreaming:r,streamingAssistantId:o,streamingDebounceMs:s,layoutSize:i,enableMessageEditing:a,editingMessageId:l,onEdit:c,onRegenerate:d,onCancelEdit:f,activeInterrupt:p,disableInterruptActions:h,onInterruptActionStart:v,onInterruptActionEnd:g,showToolMessages:y,showArtifactPreviews:x,checkpointMetaById:b,checkpointIndexByKey:C,attemptMetaById:k,userMessageIdToAttempts:T,activeCheckpointId:S,onSelectCheckpoint:I}){const A=Pp(t,n),R="type"in t&&t.type==="default_message",{checkpointCandidates:D,defaultCheckpointId:F,attemptMeta:q}=QC(t,{checkpointMetaById:b,checkpointIndexByKey:C,attemptMetaById:k,userMessageIdToAttempts:T}),W=t&&!R?t.additionalKwargs??{}:{},_=t&&!R?t.responseMetadata??{}:{},j=(()=>{if(typeof W.parentCheckpointId=="string")return W.parentCheckpointId;if(typeof _.parentCheckpointId=="string")return _.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":A,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(qs,{message:t,messageIndex:n,isStreamingMessage:r&&o===t.id,streamingDebounceMs:s,isEditing:l===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:c,onRegenerate:()=>d(n),onCancelEdit:f,activeInterrupt:p,disableInterruptActions:h,onInterruptActionStart:v,onInterruptActionEnd:g,showToolMessages:y,showArtifactPreviews:x,checkpointCandidates:D,activeCheckpointId:S??null,onSelectCheckpoint:I,defaultCheckpointId:F,messageParentCheckpointId:j,attemptMeta:q})})});Op.displayName="MessageRow";const Ka=w.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:p,emptyMessage:h,followNewMessages:v=!0,isNavigatingCheckpoint:g=!1,onScrollAway:y,onAtBottom:x,activeInterrupt:b,disableInterruptActions:C=!1,onInterruptActionStart:k,onInterruptActionEnd:T,showToolMessages:S=!0,showArtifactPreviews:I=!0,checkpointMetaById:A,checkpointIndexByKey:R,attemptMetaById:D,userMessageIdToAttempts:F,activeCheckpointId:q,onSelectCheckpoint:W,createSyntheticThinkingMessage:_=!1},j)=>{const N=w.useRef(null),z=w.useRef(null),L=w.useRef(!1),P=w.useRef(!1),[V,ne]=w.useState(!0),M=w.useMemo(()=>b?e.some(oe=>"type"in oe&&oe.type==="default_message"?!1:Array.isArray(oe==null?void 0:oe.content)&&oe.content.some(xe=>xe&&xe.type==="interrupt"&&(xe.id??xe.interrupt_id)===b.id)):!1,[b,e]),Y=w.useMemo(()=>{if(!b||M)return null;const oe=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let xe;const Se=b.value;if(Se&&typeof Se=="object"&&!Array.isArray(Se)){const $e=Se.title;typeof $e=="string"&&$e.trim()&&(xe=$e.trim())}return{id:`interrupt-${oe}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:oe,value:Se,title:xe}]}},[b,M]),ae=w.useMemo(()=>Y?[...e,Y]:e,[e,Y]),Q=w.useMemo(()=>!_||!t?ae:!ae.some(xe=>xe.role==="assistant")&&ae.length>0?[...ae,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString()}]:ae,[ae,t,_]),ce=w.useMemo(()=>S?Q:Q.filter(oe=>(oe==null?void 0:oe.role)!=="tool"),[Q,S]),G=w.useCallback(oe=>{ne(oe),y&&y(!oe),x&&x(oe)},[y,x]),O=w.useMemo(()=>{if(a)return async()=>{if(!L.current){L.current=!0;try{await a()}finally{L.current=!1}}}},[a]),K=w.useMemo(()=>!v||g?!1:V?"auto":!1,[V,v,g]),B=w.useMemo(()=>{if(typeof h!="string")return null;const oe=h.trim();return oe?{id:"default-message",role:"assistant",type:"default_message",content:oe,createdAt:new Date().toISOString()}:null},[h]),te=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),Z=()=>B?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(qs,{message:B,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:I})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:h??"No messages yet. Start a conversation!"}),ye=ce.length,fe=ye>0;return w.useEffect(()=>{var oe,xe;if(ye===0){P.current=!1;return}if(!P.current)if(P.current=!0,N.current&&ce.length>0){const Se=ce.length-1;(xe=(oe=N.current).scrollToIndex)==null||xe.call(oe,{index:Se,align:"end",behavior:"auto"})}else z.current&&(z.current.scrollTop=z.current.scrollHeight)},[ye,ce.length]),w.useImperativeHandle(j,()=>({scrollToLatest:()=>{var oe,xe;if(N.current&&ce.length>0){const Se=ce.length-1;(xe=(oe=N.current).scrollToIndex)==null||xe.call(oe,{index:Se,align:"end",behavior:"auto"})}else z.current&&(z.current.scrollTop=z.current.scrollHeight)},scrollToTop:()=>{var oe,xe;N.current&&ce.length>0?(xe=(oe=N.current).scrollToIndex)==null||xe.call(oe,{index:0,align:"start",behavior:"auto"}):z.current&&(z.current.scrollTop=0)}}),[ce]),u.jsx("div",{className:te,style:p,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:fe?u.jsx(MS,{ref:oe=>{N.current=oe},scrollerRef:oe=>{z.current=oe instanceof HTMLDivElement?oe:null},data:ce,followOutput:K,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{O&&O()},atBottomStateChange:G,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(oe,xe)=>Pp(xe,oe),itemContent:(oe,xe)=>u.jsx(Op,{message:xe,index:oe,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:b,disableInterruptActions:C,onInterruptActionStart:k,onInterruptActionEnd:T,showToolMessages:S,showArtifactPreviews:I,checkpointMetaById:A,checkpointIndexByKey:R,attemptMetaById:D,userMessageIdToAttempts:F,activeCheckpointId:q,onSelectCheckpoint:W})}):Z()})})});Ka.displayName="MessageList";const Dp={value:""};function Gs({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,showArtifactPreviews:f=!0,customStyles:p={},onMessageSent:h,onExcelUploadSuccess:v,onError:g}){const{api:y}=Si(),{currentThreadId:x}=Ho(),{threadId:b,messages:C,isHistoryLoading:k,isLoading:T,navigateToCheckpoint:S,returnToLatest:I,checkpoint:A,checkpoints:R,interrupt:D,metadata:F,timelineCheckpoints:q,messagePreviews:W}=Wo(),{isStreaming:_,error:j,connectionState:N,submit:z,stop:L}=Rc(),P=b??x??null,V=(A==null?void 0:A.id)??null,ne=(A==null?void 0:A.namespace)??null,M=(F==null?void 0:F.assemblingMessageId)??null,Y=D,[ae,Q]=w.useState(!1);w.useEffect(()=>{Y||Q(!1)},[Y]);const ce=w.useCallback(()=>{Q(!0)},[]),G=w.useCallback(()=>{Q(!1)},[]),O=!!Y||ae,[K,B]=w.useState(null),[te,Z]=w.useState(""),[ye,fe]=w.useState(null),[oe,xe]=w.useState(null),[Se,$e]=w.useState([]),[_e,Ue]=w.useState(0),[U,le]=w.useState(0),[ke,Ke]=w.useState(!1),[tt,St]=w.useState(null),[ut,yt]=w.useState(null),[pt,wt]=w.useState(!1),[Mt,Wt]=w.useState(null),nn=w.useRef(!1),[Ve,Sn]=w.useState(()=>Dp.value),nt=w.useRef(Ve),Ge=w.useRef(null),dt=w.useCallback(ge=>{Dp.value=ge,Sn(ge)},[]),[Rt,Je]=w.useState(!1),Pt=w.useRef(null),{checkpointMetaById:X,checkpointIndexByKey:H,attemptMetaById:re,userMessageIdToAttempts:Ee}=v0(R),we=q??[],Qe=w.useRef(null),Pe=w.useRef(null),ht=w.useCallback(()=>{Qe.current&&(Qe.current.value=""),Pe.current&&(Pe.current.value=""),Ue(ge=>ge+1),le(ge=>ge+1)},[]),Cn=w.useCallback(ge=>{dt(ge)},[dt]),An=w.useRef(!1);w.useEffect(()=>{An.current&&!_&&($e([]),ht()),An.current=_},[_,ht]);const[Or,Dr]=w.useState("desktop");w.useEffect(()=>{const ge=()=>{const Ne=window.innerWidth;Dr(Ne<640?"phone":Ne<1024?"tablet":"desktop")};return ge(),window.addEventListener("resize",ge),()=>window.removeEventListener("resize",ge)},[]),w.useEffect(()=>{nn.current=!1},[P]),w.useEffect(()=>{nt.current=Ve},[Ve]),w.useEffect(()=>{if(!K){Ge.current=null;return}Ge.current===null&&(Ge.current=nt.current),dt(te??"")},[te,K,dt]),w.useEffect(()=>{(async()=>{if(!y.baseUrl){Wt(null);return}try{const Re=(await y.getAgent("default")).uiDefaultMessage||"";Wt(Re||null)}catch(Ne){console.warn("Failed to fetch default message:",Ne),Wt(null)}})()},[y.baseUrl]),w.useEffect(()=>{j&&!pt&&(g==null||g(j))},[j,pt,g]);const ur=ge=>{if(ge.length>Ss)return`Message too long (${ge.length}/${Ss} characters)`;try{return S0(ge),null}catch(Ne){return(Ne==null?void 0:Ne.message)||"Invalid message"}},Lr=async ge=>{const Ne=ge.trim();if(!(!Ne&&Se.length===0)){if(Ne){const Re=ur(Ne);if(Re){xe(Re);return}}try{const Re=K?(ye==null?void 0:ye.checkpointId)??V??void 0:V??void 0,Ye=K?(ye==null?void 0:ye.checkpointNs)??ne??void 0:ne??void 0;await z({text:Ne||"",attachments:Se},{checkpointId:Re,checkpointNs:Ye,edit:!!K,originalMessageId:K??void 0}),h==null||h(Ne),dt(""),xe(null),$e([]),ht(),B(null),Z(""),fe(null)}catch(Re){const Ye=(Re==null?void 0:Re.message)||"Failed to send message";xe(Ye),g==null||g(Ye)}}},dr=w.useCallback((ge,Ne,Re)=>{c&&(Ge.current=Ve,B(ge),Z(Ne),dt(Ne),xe(null),fe({checkpointId:(Re==null?void 0:Re.checkpointId)??null,checkpointNs:(Re==null?void 0:Re.checkpointNs)??null}))},[Ve,c,dt]),E=w.useCallback(()=>{B(null),Z(""),fe(null),xe(null),dt(Ge.current??Ve),Ge.current=null},[Ve,dt]),J=w.useCallback((ge,Ne,Re)=>{dr(ge,Ne,Re)},[dr]),de=w.useCallback(ge=>{let Ne=null;for(let rn=ge-1;rn>=0;rn--)if(C[rn].role==="user"){Ne=C[rn];break}if(!Ne)return;const Re=Array.isArray(Ne.content)?Ne.content:[],Vn=Re.filter(rn=>(rn==null?void 0:rn.type)==="text").map(rn=>rn.text).join("")||(()=>{try{return JSON.stringify(Re,null,2)}catch{return String(Re)}})();Vn&&z({text:Vn},{checkpointId:V??void 0,checkpointNs:ne??void 0,edit:!0,originalMessageId:Ne.id})},[C,z,V,ne]),Ce=ge=>{const Ne=Array.from(ge.target.files||[]);$e(Re=>[...Re,...Ne]),ge.target.value=""},qe=ge=>{$e(Ne=>{const Re=Ne.filter((Ye,Vn)=>ge!==Vn);return Re.length===0&&ht(),Re})},Ze=async ge=>{const Ne=(ge.target.files||[])[0];if(Ne){St(null),yt(null),Ke(!0);try{await z({attachments:[Ne]},{checkpointId:V??void 0,checkpointNs:ne??void 0});const Re=`Uploaded ${Ne.name} - processing through chat stream`;yt(Re)}catch(Re){const Ye=Re instanceof Error?Re.message:"Failed to upload Excel file";console.error("Excel upload failed",Re),St(Ye),g==null||g(Ye)}finally{Ke(!1),ge.target.value="",ht()}}},Be=async ge=>{if(x){Je(!0);try{if(!ge){await I(),requestAnimationFrame(()=>{var Ye;(Ye=Pt.current)==null||Ye.scrollToLatest()});return}const Ne=R.find(Ye=>Ye.checkpointId===ge),Re=(Ne==null?void 0:Ne.checkpointNs)??null;await S(ge,Re),requestAnimationFrame(()=>{var Ye;(Ye=Pt.current)==null||Ye.scrollToTop()})}finally{Je(!1)}}},ze=w.useCallback(async(ge,Ne,Re)=>{await Be(Re?null:ge)},[Be]),It=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,ft=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${p.messagesArea||""}`,mt=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return u.jsxs("div",{className:It,children:[!!j&&!pt&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:j}),u.jsx(rt,{variant:"ghost",size:"sm",onClick:()=>wt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(ue.X,{size:16})})]}),u.jsxs("div",{className:`relative ${ft}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Ka,{ref:Pt,className:"h-full",style:{height:"100%"},messages:C,isStreaming:_,streamingAssistantId:M,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Or,enableMessageEditing:c,editingMessageId:K,onEdit:J,onRegenerate:de,onCancelEdit:E,emptyMessage:Mt??void 0,isNavigatingCheckpoint:Rt,activeInterrupt:Y,disableInterruptActions:ae,onInterruptActionStart:ce,onInterruptActionEnd:G,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:X,checkpointIndexByKey:H,attemptMetaById:re,userMessageIdToAttempts:Ee,activeCheckpointId:V,onSelectCheckpoint:ze,timelineCheckpoints:we,messagePreviews:W}),(N==="reconnecting"||N==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(ue.Loader2,{className:"h-3 w-3 animate-spin"}),N==="reconnecting"?"Reconnecting…":"Connecting…"]})}),N==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),T&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(ue.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||Rt)&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(ue.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:mt,children:[K&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ue.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(rt,{variant:"ghost",size:"sm",onClick:E,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(ue.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Qe,type:"file",multiple:!0,onChange:ge=>Ce(ge),className:"hidden"},_e),Se.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:Se.map((ge,Ne)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(ue.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:ge.name}),u.jsx(rt,{variant:"ghost",size:"sm",onClick:()=>qe(Ne),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${ge.name}`,children:u.jsx(ue.X,{size:12})})]},Ne))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Pe,type:"file",accept:".xls,.xlsx,.xlsm",onChange:Ze,className:"hidden"},U),ke&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ue.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),ut&&!ke&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:ut}),tt&&!ke&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:tt})]})]}),oe&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:oe}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(Wd,{children:[u.jsx(Vd,{asChild:!0,children:u.jsx(rt,{type:"button",size:"icon",variant:"outline",disabled:_||O,title:"More input actions",className:p.moreButton||"",children:u.jsx(ue.Plus,{size:16})})}),u.jsxs(la,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Ir,{onClick:()=>{var ge;return(ge=Qe.current)==null?void 0:ge.click()},className:"cursor-pointer",children:[u.jsx(ue.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Ir,{onClick:()=>{var ge;ke||(ge=Pe.current)==null||ge.click()},className:`cursor-pointer ${ke?"opacity-60 pointer-events-none":""}`,children:[u.jsx(ue.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(ly,{initialValue:te,editingMessageId:K,value:Ve,onValueChange:Cn,placeholder:K?"Edit your message...":t,isStreaming:_,disabled:O,maxLength:Ss,onSend:Lr,onCancelEdit:E,onStop:L,allowEmptySend:Se.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${K?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${oe?"border-red-400":""} ${p.textarea||""}`})})]})]})]})}const Ys=m.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:se("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:r,...n}));Ys.displayName="Input";function qa(e,[t,n]){return Math.min(n,Math.max(t,e))}function eT(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Ga="ScrollArea",[Lp,gI]=kn(Ga),[tT,en]=Lp(Ga),$p=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=m.useState(null),[c,d]=m.useState(null),[f,p]=m.useState(null),[h,v]=m.useState(null),[g,y]=m.useState(null),[x,b]=m.useState(0),[C,k]=m.useState(0),[T,S]=m.useState(!1),[I,A]=m.useState(!1),R=He(t,F=>l(F)),D=Ko(o);return u.jsx(tT,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:p,scrollbarX:h,onScrollbarXChange:v,scrollbarXEnabled:T,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:y,scrollbarYEnabled:I,onScrollbarYEnabledChange:A,onCornerWidthChange:b,onCornerHeightChange:k,children:u.jsx(Ie.div,{dir:D,...i,ref:R,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})})});$p.displayName=Ga;var Fp="ScrollAreaViewport",Bp=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=en(Fp,n),a=m.useRef(null),l=He(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),u.jsx(Ie.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Bp.displayName=Fp;var wn="ScrollAreaScrollbar",Ya=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(wn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return m.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(nT,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(rT,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(zp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Xa,{...r,ref:t}):null});Ya.displayName=wn;var nT=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(wn,e.__scopeScrollArea),[s,i]=m.useState(!1);return m.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Xt,{present:n||s,children:u.jsx(zp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),rT=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(wn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Qs(()=>l("SCROLL_END"),100),[a,l]=eT("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return m.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),m.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const p=()=>{const h=c[d];f!==h&&(l("SCROLL"),i()),f=h};return c.addEventListener("scroll",p),()=>c.removeEventListener("scroll",p)}},[o.viewport,s,l,i]),u.jsx(Xt,{present:n||a!=="hidden",children:u.jsx(Xa,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:me(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:me(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),zp=m.forwardRef((e,t)=>{const n=en(wn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=m.useState(!1),a=e.orientation==="horizontal",l=Qs(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return jr(n.viewport,l),jr(n.content,l),u.jsx(Xt,{present:r||s,children:u.jsx(Xa,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Xa=m.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=en(wn,e.__scopeScrollArea),s=m.useRef(null),i=m.useRef(0),[a,l]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Kp(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,h){return cT(p,i.current,a,h)}return n==="horizontal"?u.jsx(oT,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,h=qp(p,a,o.dir);s.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):n==="vertical"?u.jsx(sT,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,h=qp(p,a);s.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),oT=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=en(wn,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),c=He(t,l,s.onScrollbarXChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Hp,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Zs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(p),Yp(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Js(i.paddingLeft),paddingEnd:Js(i.paddingRight)}})}})}),sT=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=en(wn,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),c=He(t,l,s.onScrollbarYChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Hp,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Zs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(p),Yp(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Js(i.paddingTop),paddingEnd:Js(i.paddingBottom)}})}})}),[iT,Up]=Lp(wn),Hp=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...p}=e,h=en(wn,n),[v,g]=m.useState(null),y=He(t,R=>g(R)),x=m.useRef(null),b=m.useRef(""),C=h.viewport,k=r.content-r.viewport,T=kt(d),S=kt(l),I=Qs(f,10);function A(R){if(x.current){const D=R.clientX-x.current.left,F=R.clientY-x.current.top;c({x:D,y:F})}}return m.useEffect(()=>{const R=D=>{const F=D.target;(v==null?void 0:v.contains(F))&&T(D,k)};return document.addEventListener("wheel",R,{passive:!1}),()=>document.removeEventListener("wheel",R,{passive:!1})},[C,v,k,T]),m.useEffect(S,[r,S]),jr(v,I),jr(h.content,I),u.jsx(iT,{scope:n,scrollbar:v,hasThumb:o,onThumbChange:kt(s),onThumbPointerUp:kt(i),onThumbPositionChange:S,onThumbPointerDown:kt(a),children:u.jsx(Ie.div,{...p,ref:y,style:{position:"absolute",...p.style},onPointerDown:me(e.onPointerDown,R=>{R.button===0&&(R.target.setPointerCapture(R.pointerId),x.current=v.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),A(R))}),onPointerMove:me(e.onPointerMove,A),onPointerUp:me(e.onPointerUp,R=>{const D=R.target;D.hasPointerCapture(R.pointerId)&&D.releasePointerCapture(R.pointerId),document.body.style.webkitUserSelect=b.current,h.viewport&&(h.viewport.style.scrollBehavior=""),x.current=null})})})}),Xs="ScrollAreaThumb",Wp=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Up(Xs,e.__scopeScrollArea);return u.jsx(Xt,{present:n||o.hasThumb,children:u.jsx(aT,{ref:t,...r})})}),aT=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=en(Xs,n),i=Up(Xs,n),{onThumbPositionChange:a}=i,l=He(t,f=>i.onThumbChange(f)),c=m.useRef(void 0),d=Qs(()=>{c.current&&(c.current(),c.current=void 0)},100);return m.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(d(),!c.current){const h=uT(f,a);c.current=h,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,d,a]),u.jsx(Ie.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:me(e.onPointerDownCapture,f=>{const h=f.target.getBoundingClientRect(),v=f.clientX-h.left,g=f.clientY-h.top;i.onThumbPointerDown({x:v,y:g})}),onPointerUp:me(e.onPointerUp,i.onThumbPointerUp)})});Wp.displayName=Xs;var Ja="ScrollAreaCorner",Vp=m.forwardRef((e,t)=>{const n=en(Ja,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(lT,{...e,ref:t}):null});Vp.displayName=Ja;var lT=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=en(Ja,n),[s,i]=m.useState(0),[a,l]=m.useState(0),c=!!(s&&a);return jr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),jr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Ie.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Js(e){return e?parseInt(e,10):0}function Kp(e,t){const n=e/t;return isNaN(n)?0:n}function Zs(e){const t=Kp(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function cT(e,t,n,r="ltr"){const o=Zs(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Gp([l,c],f)(e)}function qp(e,t,n="ltr"){const r=Zs(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],c=qa(e,l);return Gp([0,i],[0,a])(c)}function Gp(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Yp(e,t){return e>0&&e<t}var uT=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Qs(e,t){const n=kt(e),r=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),m.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function jr(e,t){const n=kt(t);Tt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Xp=$p,dT=Bp,fT=Vp;const Jp=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Xp,{ref:r,className:se("relative overflow-hidden",e),...n,children:[u.jsx(dT,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Zp,{}),u.jsx(fT,{})]}));Jp.displayName=Xp.displayName;const Zp=m.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Ya,{ref:r,orientation:t,className:se("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(Wp,{className:"relative flex-1 rounded-full bg-border"})}));Zp.displayName=Ya.displayName;var Qp=1,pT=.9,hT=.8,mT=.17,Za=.1,Qa=.999,gT=.9999,xT=.99,yT=/[\\\/_+.#"@\[\(\{&]/,vT=/[\\\/_+.#"@\[\(\{&]/g,bT=/[\s-]/,eh=/[\s-]/g;function el(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?Qp:xT;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(s),c=n.indexOf(l,o),d=0,f,p,h,v;c>=0;)f=el(e,t,n,r,c+1,s+1,i),f>d&&(c===o?f*=Qp:yT.test(e.charAt(c-1))?(f*=hT,h=e.slice(o,c-1).match(vT),h&&o>0&&(f*=Math.pow(Qa,h.length))):bT.test(e.charAt(c-1))?(f*=pT,v=e.slice(o,c-1).match(eh),v&&o>0&&(f*=Math.pow(Qa,v.length))):(f*=mT,o>0&&(f*=Math.pow(Qa,c-o))),e.charAt(c)!==t.charAt(s)&&(f*=gT)),(f<Za&&n.charAt(c-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(c-1)!==r.charAt(s))&&(p=el(e,t,n,r,c+1,s+2,i),p*Za>f&&(f=p*Za)),f>d&&(d=f),c=n.indexOf(l,c+1);return i[a]=d,d}function th(e){return e.toLowerCase().replace(eh," ")}function wT(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,el(e,t,th(e),th(t),0,0,{})}var So='[cmdk-group=""]',tl='[cmdk-group-items=""]',ST='[cmdk-group-heading=""]',nh='[cmdk-item=""]',rh=`${nh}:not([aria-disabled="true"])`,nl="cmdk-item-select",_r="data-value",CT=(e,t,n)=>wT(e,t,n),oh=m.createContext(void 0),Co=()=>m.useContext(oh),sh=m.createContext(void 0),rl=()=>m.useContext(sh),ih=m.createContext(void 0),ah=m.forwardRef((e,t)=>{let n=Mr(()=>{var M,Y;return{search:"",value:(Y=(M=e.value)!=null?M:e.defaultValue)!=null?Y:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Mr(()=>new Set),o=Mr(()=>new Map),s=Mr(()=>new Map),i=Mr(()=>new Set),a=lh(e),{label:l,children:c,value:d,onValueChange:f,filter:p,shouldFilter:h,loop:v,disablePointerSelection:g=!1,vimBindings:y=!0,...x}=e,b=Dt(),C=Dt(),k=Dt(),T=m.useRef(null),S=PT();ir(()=>{if(d!==void 0){let M=d.trim();n.current.value=M,I.emit()}},[d]),ir(()=>{S(6,W)},[]);let I=m.useMemo(()=>({subscribe:M=>(i.current.add(M),()=>i.current.delete(M)),snapshot:()=>n.current,setState:(M,Y,ae)=>{var Q,ce,G,O;if(!Object.is(n.current[M],Y)){if(n.current[M]=Y,M==="search")q(),D(),S(1,F);else if(M==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let K=document.getElementById(k);K?K.focus():(Q=document.getElementById(b))==null||Q.focus()}if(S(7,()=>{var K;n.current.selectedItemId=(K=_())==null?void 0:K.id,I.emit()}),ae||S(5,W),((ce=a.current)==null?void 0:ce.value)!==void 0){let K=Y??"";(O=(G=a.current).onValueChange)==null||O.call(G,K);return}}I.emit()}},emit:()=>{i.current.forEach(M=>M())}}),[]),A=m.useMemo(()=>({value:(M,Y,ae)=>{var Q;Y!==((Q=s.current.get(M))==null?void 0:Q.value)&&(s.current.set(M,{value:Y,keywords:ae}),n.current.filtered.items.set(M,R(Y,ae)),S(2,()=>{D(),I.emit()}))},item:(M,Y)=>(r.current.add(M),Y&&(o.current.has(Y)?o.current.get(Y).add(M):o.current.set(Y,new Set([M]))),S(3,()=>{q(),D(),n.current.value||F(),I.emit()}),()=>{s.current.delete(M),r.current.delete(M),n.current.filtered.items.delete(M);let ae=_();S(4,()=>{q(),(ae==null?void 0:ae.getAttribute("id"))===M&&F(),I.emit()})}),group:M=>(o.current.has(M)||o.current.set(M,new Set),()=>{s.current.delete(M),o.current.delete(M)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:b,inputId:k,labelId:C,listInnerRef:T}),[]);function R(M,Y){var ae,Q;let ce=(Q=(ae=a.current)==null?void 0:ae.filter)!=null?Q:CT;return M?ce(M,n.current.search,Y):0}function D(){if(!n.current.search||a.current.shouldFilter===!1)return;let M=n.current.filtered.items,Y=[];n.current.filtered.groups.forEach(Q=>{let ce=o.current.get(Q),G=0;ce.forEach(O=>{let K=M.get(O);G=Math.max(K,G)}),Y.push([Q,G])});let ae=T.current;j().sort((Q,ce)=>{var G,O;let K=Q.getAttribute("id"),B=ce.getAttribute("id");return((G=M.get(B))!=null?G:0)-((O=M.get(K))!=null?O:0)}).forEach(Q=>{let ce=Q.closest(tl);ce?ce.appendChild(Q.parentElement===ce?Q:Q.closest(`${tl} > *`)):ae.appendChild(Q.parentElement===ae?Q:Q.closest(`${tl} > *`))}),Y.sort((Q,ce)=>ce[1]-Q[1]).forEach(Q=>{var ce;let G=(ce=T.current)==null?void 0:ce.querySelector(`${So}[${_r}="${encodeURIComponent(Q[0])}"]`);G==null||G.parentElement.appendChild(G)})}function F(){let M=j().find(ae=>ae.getAttribute("aria-disabled")!=="true"),Y=M==null?void 0:M.getAttribute(_r);I.setState("value",Y||void 0)}function q(){var M,Y,ae,Q;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let ce=0;for(let G of r.current){let O=(Y=(M=s.current.get(G))==null?void 0:M.value)!=null?Y:"",K=(Q=(ae=s.current.get(G))==null?void 0:ae.keywords)!=null?Q:[],B=R(O,K);n.current.filtered.items.set(G,B),B>0&&ce++}for(let[G,O]of o.current)for(let K of O)if(n.current.filtered.items.get(K)>0){n.current.filtered.groups.add(G);break}n.current.filtered.count=ce}function W(){var M,Y,ae;let Q=_();Q&&(((M=Q.parentElement)==null?void 0:M.firstChild)===Q&&((ae=(Y=Q.closest(So))==null?void 0:Y.querySelector(ST))==null||ae.scrollIntoView({block:"nearest"})),Q.scrollIntoView({block:"nearest"}))}function _(){var M;return(M=T.current)==null?void 0:M.querySelector(`${nh}[aria-selected="true"]`)}function j(){var M;return Array.from(((M=T.current)==null?void 0:M.querySelectorAll(rh))||[])}function N(M){let Y=j()[M];Y&&I.setState("value",Y.getAttribute(_r))}function z(M){var Y;let ae=_(),Q=j(),ce=Q.findIndex(O=>O===ae),G=Q[ce+M];(Y=a.current)!=null&&Y.loop&&(G=ce+M<0?Q[Q.length-1]:ce+M===Q.length?Q[0]:Q[ce+M]),G&&I.setState("value",G.getAttribute(_r))}function L(M){let Y=_(),ae=Y==null?void 0:Y.closest(So),Q;for(;ae&&!Q;)ae=M>0?MT(ae,So):RT(ae,So),Q=ae==null?void 0:ae.querySelector(rh);Q?I.setState("value",Q.getAttribute(_r)):z(M)}let P=()=>N(j().length-1),V=M=>{M.preventDefault(),M.metaKey?P():M.altKey?L(1):z(1)},ne=M=>{M.preventDefault(),M.metaKey?N(0):M.altKey?L(-1):z(-1)};return m.createElement(Ie.div,{ref:t,tabIndex:-1,...x,"cmdk-root":"",onKeyDown:M=>{var Y;(Y=x.onKeyDown)==null||Y.call(x,M);let ae=M.nativeEvent.isComposing||M.keyCode===229;if(!(M.defaultPrevented||ae))switch(M.key){case"n":case"j":{y&&M.ctrlKey&&V(M);break}case"ArrowDown":{V(M);break}case"p":case"k":{y&&M.ctrlKey&&ne(M);break}case"ArrowUp":{ne(M);break}case"Home":{M.preventDefault(),N(0);break}case"End":{M.preventDefault(),P();break}case"Enter":{M.preventDefault();let Q=_();if(Q){let ce=new Event(nl);Q.dispatchEvent(ce)}}}}},m.createElement("label",{"cmdk-label":"",htmlFor:A.inputId,id:A.labelId,style:DT},l),ei(e,M=>m.createElement(sh.Provider,{value:I},m.createElement(oh.Provider,{value:A},M))))}),TT=m.forwardRef((e,t)=>{var n,r;let o=Dt(),s=m.useRef(null),i=m.useContext(ih),a=Co(),l=lh(e),c=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;ir(()=>{if(!c)return a.item(o,i==null?void 0:i.id)},[c]);let d=ch(o,s,[e.value,e.children,s],e.keywords),f=rl(),p=zn(S=>S.value&&S.value===d.current),h=zn(S=>c||a.filter()===!1?!0:S.search?S.filtered.items.get(o)>0:!0);m.useEffect(()=>{let S=s.current;if(!(!S||e.disabled))return S.addEventListener(nl,v),()=>S.removeEventListener(nl,v)},[h,e.onSelect,e.disabled]);function v(){var S,I;g(),(I=(S=l.current).onSelect)==null||I.call(S,d.current)}function g(){f.setState("value",d.current,!0)}if(!h)return null;let{disabled:y,value:x,onSelect:b,forceMount:C,keywords:k,...T}=e;return m.createElement(Ie.div,{ref:_n(s,t),...T,id:o,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!p,"data-disabled":!!y,"data-selected":!!p,onPointerMove:y||a.getDisablePointerSelection()?void 0:g,onClick:y?void 0:v},e.children)}),kT=m.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=Dt(),a=m.useRef(null),l=m.useRef(null),c=Dt(),d=Co(),f=zn(h=>o||d.filter()===!1?!0:h.search?h.filtered.groups.has(i):!0);ir(()=>d.group(i),[]),ch(i,a,[e.value,e.heading,l]);let p=m.useMemo(()=>({id:i,forceMount:o}),[o]);return m.createElement(Ie.div,{ref:_n(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&m.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),ei(e,h=>m.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},m.createElement(ih.Provider,{value:p},h))))}),IT=m.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=m.useRef(null),s=zn(i=>!i.search);return!n&&!s?null:m.createElement(Ie.div,{ref:_n(o,t),...r,"cmdk-separator":"",role:"separator"})}),ET=m.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=rl(),i=zn(c=>c.search),a=zn(c=>c.selectedItemId),l=Co();return m.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),m.createElement(Ie.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:o?e.value:i,onChange:c=>{o||s.setState("search",c.target.value),n==null||n(c.target.value)}})}),NT=m.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=m.useRef(null),i=m.useRef(null),a=zn(c=>c.selectedItemId),l=Co();return m.useEffect(()=>{if(i.current&&s.current){let c=i.current,d=s.current,f,p=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let h=c.offsetHeight;d.style.setProperty("--cmdk-list-height",h.toFixed(1)+"px")})});return p.observe(c),()=>{cancelAnimationFrame(f),p.unobserve(c)}}},[]),m.createElement(Ie.div,{ref:_n(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},ei(e,c=>m.createElement("div",{ref:_n(i,l.listInnerRef),"cmdk-list-sizer":""},c)))}),AT=m.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return m.createElement(Da,{open:n,onOpenChange:r},m.createElement(La,{container:i},m.createElement(ho,{"cmdk-overlay":"",className:o}),m.createElement(mo,{"aria-label":e.label,"cmdk-dialog":"",className:s},m.createElement(ah,{ref:t,...a}))))}),jT=m.forwardRef((e,t)=>zn(n=>n.filtered.count===0)?m.createElement(Ie.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),_T=m.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return m.createElement(Ie.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},ei(e,i=>m.createElement("div",{"aria-hidden":!0},i)))}),Ht=Object.assign(ah,{List:NT,Item:TT,Input:ET,Group:kT,Separator:IT,Dialog:AT,Empty:jT,Loading:_T});function MT(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function RT(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function lh(e){let t=m.useRef(e);return ir(()=>{t.current=e}),t}var ir=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Mr(e){let t=m.useRef();return t.current===void 0&&(t.current=e()),t}function zn(e){let t=rl(),n=()=>e(t.snapshot());return m.useSyncExternalStore(t.subscribe,n,n)}function ch(e,t,n,r=[]){let o=m.useRef(),s=Co();return ir(()=>{var i;let a=(()=>{var c;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(c=d.current.textContent)==null?void 0:c.trim():o.current}})(),l=r.map(c=>c.trim());s.value(e,a,l),(i=t.current)==null||i.setAttribute(_r,a),o.current=a}),o}var PT=()=>{let[e,t]=m.useState(),n=Mr(()=>new Map);return ir(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function OT(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function ei({asChild:e,children:t},n){return e&&m.isValidElement(t)?m.cloneElement(OT(t),{ref:t.ref},n(t.props.children)):n(t)}var DT={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const uh=m.forwardRef(({className:e,...t},n)=>u.jsx(Ht,{ref:n,className:se("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));uh.displayName=Ht.displayName;const dh=m.forwardRef(({className:e,...t},n)=>u.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[u.jsx(ue.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),u.jsx(Ht.Input,{ref:n,className:se("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));dh.displayName=Ht.Input.displayName;const fh=m.forwardRef(({className:e,...t},n)=>u.jsx(Ht.List,{ref:n,className:se("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));fh.displayName=Ht.List.displayName;const ph=m.forwardRef((e,t)=>u.jsx(Ht.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));ph.displayName=Ht.Empty.displayName;const hh=m.forwardRef(({className:e,...t},n)=>u.jsx(Ht.Group,{ref:n,className:se("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));hh.displayName=Ht.Group.displayName;const LT=m.forwardRef(({className:e,...t},n)=>u.jsx(Ht.Separator,{ref:n,className:se("-mx-1 h-px bg-border",e),...t}));LT.displayName=Ht.Separator.displayName;const mh=m.forwardRef(({className:e,...t},n)=>u.jsx(Ht.Item,{ref:n,className:se("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}));mh.displayName=Ht.Item.displayName;const gh=25;function ol({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,sharedThreads:p,currentThreadId:h,setCurrentThreadId:v,isLoading:g,isLoadingSharedThreads:y,smartOrgUsers:x,isLoadingSmartOrgUsers:b,actions:C}=Ho(),{createThread:k,deleteThread:T,renameThread:S,shareThread:I}=C,{loadThread:A}=Wo(),R=i??h,[D,F]=w.useState(Array.isArray(f)?f:[]),q=w.useRef(D.length>0),W=w.useRef(null),_=w.useRef(0),[j,N]=w.useState(null),[z,L]=w.useState(""),[P,V]=w.useState(!1),[ne,M]=w.useState(!1),[Y,ae]=w.useState(null),[Q,ce]=w.useState(""),G=U=>{ae(U),ce(""),M(!0)},O=()=>{M(!1),ae(null),ce("")},K=async U=>{if(!Y)return;const le=U.user_id??U.id??U.username??U.email;if(le)try{await I(Y,le),O()}catch(ke){console.error("Failed to share thread:",ke),alert(ke instanceof Error?ke.message:String(ke))}},B=w.useMemo(()=>{const U=Q.trim().toLowerCase();return U?x.filter(le=>`${le.username??""} ${le.user_id??""} ${le.email??""} ${le.name??""}`.toLowerCase().includes(U)):x},[x,Q]);w.useEffect(()=>{const U=Array.isArray(f)?f:[];if(U.length>0){q.current=!0,F(U);return}g||(q.current=!1,F(U))},[f,g]),w.useEffect(()=>{if(!W.current)return;const U=W.current.querySelector("[data-radix-scroll-area-viewport]");if(!U)return;let le=null,ke=null;return le=requestAnimationFrame(()=>{ke=requestAnimationFrame(()=>{U.scrollTop=_.current})}),()=>{le!==null&&cancelAnimationFrame(le),ke!==null&&cancelAnimationFrame(ke)}},[D]);const te=async U=>{try{v(U),await A(U,void 0,{clearProgress:!0}),a==null||a(U),l==null||l(U)}catch(le){console.error("Failed to select thread:",le)}},Z=async()=>{try{V(!0);const U=await k();U&&(c==null||c(U),a==null||a(U))}catch(U){console.error("Failed to create thread:",U)}finally{V(!1)}},ye=async(U,le)=>{if(le.stopPropagation(),!!confirm("Delete this thread?")){if(W.current){const ke=W.current.querySelector("[data-radix-scroll-area-viewport]");ke&&(_.current=ke.scrollTop)}try{await T(U),d==null||d(U)}catch(ke){console.error("Failed to delete thread:",ke)}}},fe=(U,le)=>{le.stopPropagation(),N(U.threadId),L(U.title||`Thread ${U.threadId.slice(0,8)}`)},oe=async U=>{if(z.trim())try{await S(U,z.trim()),N(null),L("")}catch(le){console.error("Failed to update title:",le)}},xe=()=>{N(null),L("")},Se=(U,le)=>{U.key==="Enter"?oe(le):U.key==="Escape"&&xe()},$e=U=>{if(!U)return"";try{const le=new Date(U),Ke=new Date().getTime()-le.getTime(),tt=Math.floor(Ke/(1e3*60*60*24));return tt===0?le.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):tt===1?"Yesterday":tt<7?`${tt} days ago`:le.toLocaleDateString()}catch{return""}},_e=U=>U.title||`Thread ${U.threadId.slice(0,8)}`,Ue=U=>{const le=_e(U);return le.length<=gh?le:`${le.slice(0,gh)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:u.jsx(rt,{onClick:Z,disabled:P||g,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:P?"Creating...":"New Chat",children:u.jsx(ue.MessageSquarePlus,{size:20})})}),u.jsx(Jp,{ref:W,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsxs("div",{className:"p-2 space-y-1 pb-4",children:[(p.length>0||y)&&u.jsxs("div",{className:"space-y-2 rounded-lg border border-slate-700 bg-slate-800/60 p-2",children:[u.jsxs("div",{className:"flex items-center justify-between text-xs uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:"Shared with you"}),y&&u.jsx(ue.Loader2,{className:"h-3 w-3 animate-spin"})]}),u.jsx("div",{className:"space-y-1",children:p.map(U=>u.jsx("button",{type:"button",onClick:()=>te(U.threadId),className:`w-full text-left rounded-lg px-3 py-2 transition-colors border ${R===U.threadId?"bg-slate-600 border-slate-500":"bg-slate-700/40 border-transparent hover:bg-slate-600"} text-gray-100`,children:u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:"font-medium text-sm truncate",children:Ue(U)}),u.jsxs("div",{className:"text-[11px] text-muted-foreground",children:["Shared by ",U.sharedByUserId," • ",$e(U.sharedAt||U.updatedAt)]})]})},U.shareId))})]}),g?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(ue.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):D.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(ue.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):D.slice().sort((U,le)=>new Date(le.updatedAt||le.createdAt||"").getTime()-new Date(U.updatedAt||U.createdAt||"").getTime()).map(U=>u.jsxs("div",{onClick:()=>te(U.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${R===U.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:j===U.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:le=>le.stopPropagation(),children:[u.jsx(Ys,{value:z,onChange:le=>L(le.target.value),onKeyDown:le=>Se(le,U.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(rt,{variant:"ghost",size:"sm",onClick:()=>oe(U.threadId),className:"h-6 w-6 p-0",children:u.jsx(ue.Check,{size:12})}),u.jsx(rt,{variant:"ghost",size:"sm",onClick:xe,className:"h-6 w-6 p-0",children:u.jsx(ue.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:Ue(U)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(ue.Calendar,{size:10}),u.jsx("span",{children:$e(U.updatedAt||U.createdAt)})]})]})}),u.jsx("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:u.jsxs(Wd,{children:[u.jsx(Vd,{asChild:!0,children:u.jsx(rt,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:u.jsx(ue.MoreHorizontal,{size:12})})}),u.jsxs(la,{align:"end",sideOffset:6,className:"w-44",children:[u.jsxs(Ir,{onClick:le=>{le.preventDefault(),G(U.threadId)},children:[u.jsx(ue.Share2,{className:"mr-2 h-4 w-4"}),"Share thread"]}),r&&j!==U.threadId&&u.jsxs(Ir,{onClick:le=>{le.preventDefault(),fe(U,le)},children:[u.jsx(ue.Edit3,{className:"mr-2 h-4 w-4"}),"Rename"]}),n&&u.jsxs(Ir,{className:"text-red-400 hover:text-red-300",onClick:le=>{le.preventDefault(),ye(U.threadId,le)},children:[u.jsx(ue.Trash2,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})})]}),R===U.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},U.threadId))]})}),u.jsx(hp,{open:ne,onOpenChange:U=>!U&&O(),children:u.jsxs($a,{className:"max-w-md p-0",children:[u.jsx(Fa,{children:u.jsx(Ba,{children:"Share thread"})}),u.jsxs(uh,{children:[u.jsx(dh,{autoFocus:!0,value:Q,onValueChange:U=>ce(U),placeholder:"Search for users (name, email, id)..."}),u.jsxs(fh,{children:[u.jsx(ph,{children:b?u.jsxs("span",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ue.Loader2,{className:"h-4 w-4 animate-spin"}),"Loading users…"]}):"No matching users found"}),u.jsx(hh,{heading:"Users",children:B.map(U=>{const le=U.username??U.user_id??U.email??"Unknown user",ke=[U.email,U.user_id].filter(Boolean).join(" • "),Ke=U.user_id??U.id??U.username??U.email??le;return u.jsx(mh,{onSelect:()=>K(U),children:u.jsxs("div",{className:"flex flex-col items-start text-sm",children:[u.jsx("span",{className:"font-medium",children:le}),ke&&u.jsx("span",{className:"text-xs text-muted-foreground",children:ke})]})},Ke)})})]})]})]})})]})}const $T=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r,className:o,onHoverStart:s,onHoverEnd:i})=>{const a=e??[],l=a.length>0,c=w.useMemo(()=>l?[...a].reverse():[],[a,l]),d=t??(a.length?a[a.length-1].id:null);if(!l)return null;const p=["w-32 flex-shrink-0 flex-col border-r border-border/40 pr-2 flex bg-white text-gray-900 dark:bg-slate-900 dark:text-slate-100",o].filter(Boolean).join(" ");return u.jsxs("div",{className:p,onMouseEnter:s,onMouseLeave:i,children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-4 pb-2 pr-1",children:[u.jsx("div",{className:"absolute left-0 right-0 top-1 px-2 pb-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:u.jsx("span",{children:"Timeline"})}),u.jsx("div",{className:"pointer-events-none absolute left-3 top-0 bottom-0 w-px bg-border/40"}),u.jsx("div",{className:"flex flex-col gap-3 pt-6 pr-2",children:c.map(h=>{const v=d===h.id,g=(r==null?void 0:r.get(h.id))??null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(h.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${v?"text-primary":"text-muted-foreground"} ${n?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-3 w-3 items-center justify-center rounded-full border ${v?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${v?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:h.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[h.step!==null?`STEP ${h.step}`:"STEP —",h.next?` - ${h.next}`:""]}),g&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:g,children:g})]})]},h.id)})})]}),n&&u.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(null),className:"mt-auto mb-3 rounded-md border border-border/70 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]})};function Rr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function FT(e){if(typeof e!="string")return;const t=e.trim();if(t)return Tn(t)}function xh(){const e=[Rr("__API_BASE_URL__"),Rr("__CHAT_API_BASE_URL__"),Rr("__CHAT_API_URL__")];for(const t of e){const n=FT(t);if(n)return n}}function yh(){const e=[Rr("__API_AUTH_TOKEN__"),Rr("__CHAT_API_KEY__"),Rr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function vh(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Tn(t);return Tn()}function bh(){const e={},t=xh(),n=yh();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function wh(){const e=bh(),t=jn.getAuthToken(),n=xh();return{apiBaseUrl:vh(e.baseUrl,jn.baseUrl,n),apiKey:t||e.apiKey||yh()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Sh="chat-settings";function BT(){try{const e=localStorage.getItem(Sh);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function zT(e){try{const t={...e,apiBaseUrl:Tn(e.apiBaseUrl)};localStorage.setItem(Sh,JSON.stringify(t)),t.apiKey&&jn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function UT(){const e=wh(),t=BT(),n=jn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:vh(jn.baseUrl,r,e.apiBaseUrl)}}function HT(e){jn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),zT(e)}var WT="Label",Ch=m.forwardRef((e,t)=>u.jsx(Ie.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Ch.displayName=WT;var Th=Ch;const VT=ko.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),tn=m.forwardRef(({className:e,...t},n)=>u.jsx(Th,{ref:n,className:se(VT(),e),...t}));tn.displayName=Th.displayName;function kh(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ih=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),KT="VisuallyHidden",qT=m.forwardRef((e,t)=>u.jsx(Ie.span,{...e,ref:t,style:{...Ih,...e.style}}));qT.displayName=KT;var GT=[" ","Enter","ArrowUp","ArrowDown"],YT=[" ","Enter"],ar="Select",[ti,ni,XT]=Ei(ar),[Pr,xI]=kn(ar,[XT,ss]),ri=ss(),[JT,Un]=Pr(ar),[ZT,QT]=Pr(ar),Eh=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:p,required:h,form:v}=e,g=ri(t),[y,x]=m.useState(null),[b,C]=m.useState(null),[k,T]=m.useState(!1),S=Ko(c),[I,A]=xr({prop:r,defaultProp:o??!1,onChange:s,caller:ar}),[R,D]=xr({prop:i,defaultProp:a,onChange:l,caller:ar}),F=m.useRef(null),q=y?v||!!y.closest("form"):!0,[W,_]=m.useState(new Set),j=Array.from(W).map(N=>N.props.value).join(";");return u.jsx(Eu,{...g,children:u.jsxs(JT,{required:h,scope:t,trigger:y,onTriggerChange:x,valueNode:b,onValueNodeChange:C,valueNodeHasChildren:k,onValueNodeHasChildrenChange:T,contentId:Dt(),value:R,onValueChange:D,open:I,onOpenChange:A,dir:S,triggerPointerDownPosRef:F,disabled:p,children:[u.jsx(ti.Provider,{scope:t,children:u.jsx(ZT,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(N=>{_(z=>new Set(z).add(N))},[]),onNativeOptionRemove:m.useCallback(N=>{_(z=>{const L=new Set(z);return L.delete(N),L})},[]),children:n})}),q?u.jsxs(Jh,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:R,onChange:N=>D(N.target.value),disabled:p,form:v,children:[R===void 0?u.jsx("option",{value:""}):null,Array.from(W)]},j):null]})})};Eh.displayName=ar;var Nh="SelectTrigger",Ah=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=ri(n),i=Un(Nh,n),a=i.disabled||r,l=He(t,i.onTriggerChange),c=ni(n),d=m.useRef("touch"),[f,p,h]=Qh(g=>{const y=c().filter(C=>!C.disabled),x=y.find(C=>C.value===i.value),b=em(y,g,x);b!==void 0&&i.onValueChange(b.value)}),v=g=>{a||(i.onOpenChange(!0),h()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return u.jsx(Nu,{asChild:!0,...s,children:u.jsx(Ie.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":Zh(i.value)?"":void 0,...o,ref:l,onClick:me(o.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&v(g)}),onPointerDown:me(o.onPointerDown,g=>{d.current=g.pointerType;const y=g.target;y.hasPointerCapture(g.pointerId)&&y.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(v(g),g.preventDefault())}),onKeyDown:me(o.onKeyDown,g=>{const y=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&p(g.key),!(y&&g.key===" ")&&GT.includes(g.key)&&(v(),g.preventDefault())})})})});Ah.displayName=Nh;var jh="SelectValue",_h=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Un(jh,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=He(t,l.onValueNodeChange);return Tt(()=>{c(d)},[c,d]),u.jsx(Ie.span,{...a,ref:f,style:{pointerEvents:"none"},children:Zh(l.value)?u.jsx(u.Fragment,{children:i}):s})});_h.displayName=jh;var ek="SelectIcon",Mh=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Ie.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Mh.displayName=ek;var tk="SelectPortal",Rh=e=>u.jsx(is,{asChild:!0,...e});Rh.displayName=tk;var lr="SelectContent",Ph=m.forwardRef((e,t)=>{const n=Un(lr,e.__scopeSelect),[r,o]=m.useState();if(Tt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Io.createPortal(u.jsx(Oh,{scope:e.__scopeSelect,children:u.jsx(ti.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(Dh,{...e,ref:t})});Ph.displayName=lr;var dn=10,[Oh,Hn]=Pr(lr),nk="SelectContentImpl",rk=Kn.createSlot("SelectContent.RemoveScroll"),Dh=m.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:v,hideWhenDetached:g,avoidCollisions:y,...x}=e,b=Un(lr,n),[C,k]=m.useState(null),[T,S]=m.useState(null),I=He(t,G=>k(G)),[A,R]=m.useState(null),[D,F]=m.useState(null),q=ni(n),[W,_]=m.useState(!1),j=m.useRef(!1);m.useEffect(()=>{if(C)return Yi(C)},[C]),ji();const N=m.useCallback(G=>{const[O,...K]=q().map(Z=>Z.ref.current),[B]=K.slice(-1),te=document.activeElement;for(const Z of G)if(Z===te||(Z==null||Z.scrollIntoView({block:"nearest"}),Z===O&&T&&(T.scrollTop=0),Z===B&&T&&(T.scrollTop=T.scrollHeight),Z==null||Z.focus(),document.activeElement!==te))return},[q,T]),z=m.useCallback(()=>N([A,C]),[N,A,C]);m.useEffect(()=>{W&&z()},[W,z]);const{onOpenChange:L,triggerPointerDownPosRef:P}=b;m.useEffect(()=>{if(C){let G={x:0,y:0};const O=B=>{var te,Z;G={x:Math.abs(Math.round(B.pageX)-(((te=P.current)==null?void 0:te.x)??0)),y:Math.abs(Math.round(B.pageY)-(((Z=P.current)==null?void 0:Z.y)??0))}},K=B=>{G.x<=10&&G.y<=10?B.preventDefault():C.contains(B.target)||L(!1),document.removeEventListener("pointermove",O),P.current=null};return P.current!==null&&(document.addEventListener("pointermove",O),document.addEventListener("pointerup",K,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",O),document.removeEventListener("pointerup",K,{capture:!0})}}},[C,L,P]),m.useEffect(()=>{const G=()=>L(!1);return window.addEventListener("blur",G),window.addEventListener("resize",G),()=>{window.removeEventListener("blur",G),window.removeEventListener("resize",G)}},[L]);const[V,ne]=Qh(G=>{const O=q().filter(te=>!te.disabled),K=O.find(te=>te.ref.current===document.activeElement),B=em(O,G,K);B&&setTimeout(()=>B.ref.current.focus())}),M=m.useCallback((G,O,K)=>{const B=!j.current&&!K;(b.value!==void 0&&b.value===O||B)&&(R(G),B&&(j.current=!0))},[b.value]),Y=m.useCallback(()=>C==null?void 0:C.focus(),[C]),ae=m.useCallback((G,O,K)=>{const B=!j.current&&!K;(b.value!==void 0&&b.value===O||B)&&F(G)},[b.value]),Q=r==="popper"?sl:Lh,ce=Q===sl?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:v,hideWhenDetached:g,avoidCollisions:y}:{};return u.jsx(Oh,{scope:n,content:C,viewport:T,onViewportChange:S,itemRefCallback:M,selectedItem:A,onItemLeave:Y,itemTextRefCallback:ae,focusSelectedItem:z,selectedItemText:D,position:r,isPositioned:W,searchRef:V,children:u.jsx(ms,{as:rk,allowPinchZoom:!0,children:u.jsx(Go,{asChild:!0,trapped:b.open,onMountAutoFocus:G=>{G.preventDefault()},onUnmountAutoFocus:me(o,G=>{var O;(O=b.trigger)==null||O.focus({preventScroll:!0}),G.preventDefault()}),children:u.jsx(qo,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:G=>G.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(Q,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:G=>G.preventDefault(),...x,...ce,onPlaced:()=>_(!0),ref:I,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:me(x.onKeyDown,G=>{const O=G.ctrlKey||G.altKey||G.metaKey;if(G.key==="Tab"&&G.preventDefault(),!O&&G.key.length===1&&ne(G.key),["ArrowUp","ArrowDown","Home","End"].includes(G.key)){let B=q().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(G.key)&&(B=B.slice().reverse()),["ArrowUp","ArrowDown"].includes(G.key)){const te=G.target,Z=B.indexOf(te);B=B.slice(Z+1)}setTimeout(()=>N(B)),G.preventDefault()}})})})})})})});Dh.displayName=nk;var ok="SelectItemAlignedPosition",Lh=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Un(lr,n),i=Hn(lr,n),[a,l]=m.useState(null),[c,d]=m.useState(null),f=He(t,I=>d(I)),p=ni(n),h=m.useRef(!1),v=m.useRef(!0),{viewport:g,selectedItem:y,selectedItemText:x,focusSelectedItem:b}=i,C=m.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&g&&y&&x){const I=s.trigger.getBoundingClientRect(),A=c.getBoundingClientRect(),R=s.valueNode.getBoundingClientRect(),D=x.getBoundingClientRect();if(s.dir!=="rtl"){const te=D.left-A.left,Z=R.left-te,ye=I.left-Z,fe=I.width+ye,oe=Math.max(fe,A.width),xe=window.innerWidth-dn,Se=qa(Z,[dn,Math.max(dn,xe-oe)]);a.style.minWidth=fe+"px",a.style.left=Se+"px"}else{const te=A.right-D.right,Z=window.innerWidth-R.right-te,ye=window.innerWidth-I.right-Z,fe=I.width+ye,oe=Math.max(fe,A.width),xe=window.innerWidth-dn,Se=qa(Z,[dn,Math.max(dn,xe-oe)]);a.style.minWidth=fe+"px",a.style.right=Se+"px"}const F=p(),q=window.innerHeight-dn*2,W=g.scrollHeight,_=window.getComputedStyle(c),j=parseInt(_.borderTopWidth,10),N=parseInt(_.paddingTop,10),z=parseInt(_.borderBottomWidth,10),L=parseInt(_.paddingBottom,10),P=j+N+W+L+z,V=Math.min(y.offsetHeight*5,P),ne=window.getComputedStyle(g),M=parseInt(ne.paddingTop,10),Y=parseInt(ne.paddingBottom,10),ae=I.top+I.height/2-dn,Q=q-ae,ce=y.offsetHeight/2,G=y.offsetTop+ce,O=j+N+G,K=P-O;if(O<=ae){const te=F.length>0&&y===F[F.length-1].ref.current;a.style.bottom="0px";const Z=c.clientHeight-g.offsetTop-g.offsetHeight,ye=Math.max(Q,ce+(te?Y:0)+Z+z),fe=O+ye;a.style.height=fe+"px"}else{const te=F.length>0&&y===F[0].ref.current;a.style.top="0px";const ye=Math.max(ae,j+g.offsetTop+(te?M:0)+ce)+K;a.style.height=ye+"px",g.scrollTop=O-ae+g.offsetTop}a.style.margin=`${dn}px 0`,a.style.minHeight=V+"px",a.style.maxHeight=q+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,s.trigger,s.valueNode,a,c,g,y,x,s.dir,r]);Tt(()=>C(),[C]);const[k,T]=m.useState();Tt(()=>{c&&T(window.getComputedStyle(c).zIndex)},[c]);const S=m.useCallback(I=>{I&&v.current===!0&&(C(),b==null||b(),v.current=!1)},[C,b]);return u.jsx(ik,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:h,onScrollButtonChange:S,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Ie.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});Lh.displayName=ok;var sk="SelectPopperPosition",sl=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=dn,...s}=e,i=ri(n);return u.jsx(Au,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});sl.displayName=sk;var[ik,il]=Pr(lr,{}),al="SelectViewport",$h=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Hn(al,n),i=il(al,n),a=He(t,s.onViewportChange),l=m.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(ti.Slot,{scope:n,children:u.jsx(Ie.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:me(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&f){const h=Math.abs(l.current-d.scrollTop);if(h>0){const v=window.innerHeight-dn*2,g=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),x=Math.max(g,y);if(x<v){const b=x+h,C=Math.min(v,b),k=b-C;f.style.height=C+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});$h.displayName=al;var Fh="SelectGroup",[ak,lk]=Pr(Fh),ck=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Dt();return u.jsx(ak,{scope:n,id:o,children:u.jsx(Ie.div,{role:"group","aria-labelledby":o,...r,ref:t})})});ck.displayName=Fh;var Bh="SelectLabel",zh=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=lk(Bh,n);return u.jsx(Ie.div,{id:o.id,...r,ref:t})});zh.displayName=Bh;var oi="SelectItem",[uk,Uh]=Pr(oi),Hh=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Un(oi,n),l=Hn(oi,n),c=a.value===r,[d,f]=m.useState(s??""),[p,h]=m.useState(!1),v=He(t,b=>{var C;return(C=l.itemRefCallback)==null?void 0:C.call(l,b,r,o)}),g=Dt(),y=m.useRef("touch"),x=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(uk,{scope:n,value:r,disabled:o,textId:g,isSelected:c,onItemTextChange:m.useCallback(b=>{f(C=>C||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(ti.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Ie.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":c&&p,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:v,onFocus:me(i.onFocus,()=>h(!0)),onBlur:me(i.onBlur,()=>h(!1)),onClick:me(i.onClick,()=>{y.current!=="mouse"&&x()}),onPointerUp:me(i.onPointerUp,()=>{y.current==="mouse"&&x()}),onPointerDown:me(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:me(i.onPointerMove,b=>{var C;y.current=b.pointerType,o?(C=l.onItemLeave)==null||C.call(l):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:me(i.onPointerLeave,b=>{var C;b.currentTarget===document.activeElement&&((C=l.onItemLeave)==null||C.call(l))}),onKeyDown:me(i.onKeyDown,b=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&b.key===" "||(YT.includes(b.key)&&x(),b.key===" "&&b.preventDefault())})})})})});Hh.displayName=oi;var To="SelectItemText",Wh=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Un(To,n),a=Hn(To,n),l=Uh(To,n),c=QT(To,n),[d,f]=m.useState(null),p=He(t,x=>f(x),l.onItemTextChange,x=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,x,l.value,l.disabled)}),h=d==null?void 0:d.textContent,v=m.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:y}=c;return Tt(()=>(g(v),()=>y(v)),[g,y,v]),u.jsxs(u.Fragment,{children:[u.jsx(Ie.span,{id:l.textId,...s,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Io.createPortal(s.children,i.valueNode):null]})});Wh.displayName=To;var Vh="SelectItemIndicator",Kh=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Uh(Vh,n).isSelected?u.jsx(Ie.span,{"aria-hidden":!0,...r,ref:t}):null});Kh.displayName=Vh;var ll="SelectScrollUpButton",qh=m.forwardRef((e,t)=>{const n=Hn(ll,e.__scopeSelect),r=il(ll,e.__scopeSelect),[o,s]=m.useState(!1),i=He(t,r.onScrollButtonChange);return Tt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(Yh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});qh.displayName=ll;var cl="SelectScrollDownButton",Gh=m.forwardRef((e,t)=>{const n=Hn(cl,e.__scopeSelect),r=il(cl,e.__scopeSelect),[o,s]=m.useState(!1),i=He(t,r.onScrollButtonChange);return Tt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(Yh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Gh.displayName=cl;var Yh=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Hn("SelectScrollButton",n),i=m.useRef(null),a=ni(n),l=m.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return m.useEffect(()=>()=>l(),[l]),Tt(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(Ie.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:me(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:me(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:me(o.onPointerLeave,()=>{l()})})}),dk="SelectSeparator",Xh=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Ie.div,{"aria-hidden":!0,...r,ref:t})});Xh.displayName=dk;var ul="SelectArrow",fk=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ri(n),s=Un(ul,n),i=Hn(ul,n);return s.open&&i.position==="popper"?u.jsx(ju,{...o,...r,ref:t}):null});fk.displayName=ul;var pk="SelectBubbleInput",Jh=m.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=m.useRef(null),s=He(r,o),i=kh(t);return m.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(Ie.select,{...n,style:{...Ih,...n.style},ref:s,defaultValue:t})});Jh.displayName=pk;function Zh(e){return e===""||e===void 0}function Qh(e){const t=kt(e),n=m.useRef(""),r=m.useRef(0),o=m.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function em(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=hk(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function hk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var mk=Eh,tm=Ah,gk=_h,xk=Mh,yk=Rh,nm=Ph,vk=$h,rm=zh,om=Hh,bk=Wh,wk=Kh,sm=qh,im=Gh,am=Xh;const lm=mk,cm=gk,dl=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(tm,{ref:r,className:se("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(xk,{asChild:!0,children:u.jsx(ue.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));dl.displayName=tm.displayName;const um=m.forwardRef(({className:e,...t},n)=>u.jsx(sm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ue.ChevronUp,{className:"h-4 w-4"})}));um.displayName=sm.displayName;const dm=m.forwardRef(({className:e,...t},n)=>u.jsx(im,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ue.ChevronDown,{className:"h-4 w-4"})}));dm.displayName=im.displayName;const fl=m.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(yk,{children:u.jsxs(nm,{ref:o,className:se("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(um,{}),u.jsx(vk,{className:se("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(dm,{})]})}));fl.displayName=nm.displayName;const Sk=m.forwardRef(({className:e,...t},n)=>u.jsx(rm,{ref:n,className:se("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Sk.displayName=rm.displayName;const cr=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(om,{ref:r,className:se("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(wk,{children:u.jsx(ue.Check,{className:"h-4 w-4"})})}),u.jsx(bk,{children:t})]}));cr.displayName=om.displayName;const Ck=m.forwardRef(({className:e,...t},n)=>u.jsx(am,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));Ck.displayName=am.displayName;var Tk="Separator",fm="horizontal",kk=["horizontal","vertical"],pm=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=fm,...o}=e,s=Ik(r)?r:fm,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Ie.div,{"data-orientation":s,...a,...o,ref:t})});pm.displayName=Tk;function Ik(e){return kk.includes(e)}var hm=pm;const mm=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(hm,{ref:o,decorative:n,orientation:t,className:se("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));mm.displayName=hm.displayName;const Ek=Da,Nk=hC,Ak=La,gm=m.forwardRef(({className:e,...t},n)=>u.jsx(ho,{className:se("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));gm.displayName=ho.displayName;const jk=ko.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),xm=m.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(Ak,{children:[u.jsx(gm,{}),u.jsxs(mo,{ref:o,className:se(jk({side:e}),t),...r,children:[n,u.jsxs(pp,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(ue.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));xm.displayName=mo.displayName;const ym=({className:e,...t})=>u.jsx("div",{className:se("flex flex-col space-y-2 text-center sm:text-left",e),...t});ym.displayName="SheetHeader";const vm=m.forwardRef(({className:e,...t},n)=>u.jsx(or,{ref:n,className:se("text-lg font-semibold text-foreground",e),...t}));vm.displayName=or.displayName;const bm=m.forwardRef(({className:e,...t},n)=>u.jsx(Bs,{ref:n,className:se("text-sm text-muted-foreground",e),...t}));bm.displayName=Bs.displayName;var si="Switch",[_k,yI]=kn(si),[Mk,Rk]=_k(si),wm=m.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[p,h]=m.useState(null),v=He(t,C=>h(C)),g=m.useRef(!1),y=p?d||!!p.closest("form"):!0,[x,b]=xr({prop:o,defaultProp:s??!1,onChange:c,caller:si});return u.jsxs(Mk,{scope:n,checked:x,disabled:a,children:[u.jsx(Ie.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":km(x),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:v,onClick:me(e.onClick,C=>{b(k=>!k),y&&(g.current=C.isPropagationStopped(),g.current||C.stopPropagation())})}),y&&u.jsx(Tm,{control:p,bubbles:!g.current,name:r,value:l,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});wm.displayName=si;var Sm="SwitchThumb",Cm=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=Rk(Sm,n);return u.jsx(Ie.span,{"data-state":km(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Cm.displayName=Sm;var Pk="SwitchBubbleInput",Tm=m.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=m.useRef(null),a=He(i,s),l=kh(n),c=xu(t);return m.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&h){const v=new Event("click",{bubbles:r});h.call(d,n),d.dispatchEvent(v)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Tm.displayName=Pk;function km(e){return e?"checked":"unchecked"}var Im=wm,Ok=Cm;const Wn=m.forwardRef(({className:e,...t},n)=>u.jsx(Im,{className:se("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(Ok,{className:se("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Wn.displayName=Im.displayName;const Dk={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function Lk({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(e),[c,d]=w.useState(!1),{toast:f}=Ha();w.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),w.useEffect(()=>{l(e)},[e]);const p=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},h=()=>{l(Dk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},v=()=>{l(e),d(!1),o(!1)},g=async()=>{try{const x=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${x.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(Ek,{open:r,onOpenChange:o,children:[u.jsx(Nk,{asChild:!0,children:u.jsxs(rt,{variant:"outline",size:"sm",className:n,children:[u.jsx(ue.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Vf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(xm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(ym,{children:[u.jsx(vm,{children:"Chat Settings"}),u.jsx(bm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(yo,{children:[u.jsx(vo,{className:"pb-3",children:u.jsxs(bo,{className:"text-lg flex items-center gap-2",children:[u.jsx(ue.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(wo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Ys,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(x=>({...x,api:{...x.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(rt,{variant:"outline",onClick:g,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Wn,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(x=>({...x,api:{...x.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Ys,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(x=>({...x,api:{...x.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(rt,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(ue.EyeOff,{className:"h-4 w-4"}):u.jsx(ue.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(yo,{children:[u.jsx(vo,{className:"pb-3",children:u.jsxs(bo,{className:"text-lg flex items-center gap-2",children:[u.jsx(ue.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(wo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(lm,{value:a.ui.layout,onValueChange:y=>l(x=>({...x,ui:{...x.ui,layout:y}})),children:[u.jsx(dl,{children:u.jsx(cm,{})}),u.jsxs(fl,{children:[u.jsx(cr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(cr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(cr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"theme",children:"Theme"}),u.jsxs(lm,{value:a.ui.theme,onValueChange:y=>l(x=>({...x,ui:{...x.ui,theme:y}})),children:[u.jsx(dl,{children:u.jsx(cm,{})}),u.jsxs(fl,{children:[u.jsx(cr,{value:"light",children:"Light"}),u.jsx(cr,{value:"dark",children:"Dark"}),u.jsx(cr,{value:"system",children:"System"})]})]})]}),u.jsx(mm,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Wn,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Wn,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Wn,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(yo,{children:[u.jsx(vo,{className:"pb-3",children:u.jsxs(bo,{className:"text-lg flex items-center gap-2",children:[u.jsx(ue.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(wo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(Wn,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(Wn,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(Wn,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(rt,{variant:"outline",onClick:h,children:[u.jsx(ue.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(rt,{variant:"outline",onClick:v,children:"Cancel"}),u.jsxs(rt,{onClick:p,disabled:!c,children:[u.jsx(ue.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function $k({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=w.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(Vo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(Gs,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(Vo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(ol,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Gs,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(Vo,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(ol,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(Gs,{onError:s.onError,enableFileUpload:!0})})]})})}Ae.ChatApi=ic,Ae.ChatInput=Oc,Ae.ChatInterface=Gs,Ae.ChatProviders=Vo,Ae.ChatSettings=Lk,Ae.MarkdownContent=xo,Ae.MessageComponent=qs,Ae.MessageList=Ka,Ae.ThreadManager=ol,Ae.TimelineColumn=$T,Ae.applySettings=HT,Ae.buildMessagePreviewMap=ax,Ae.chatApiClient=jn,Ae.default=$k,Ae.del=wi,Ae.get=zt,Ae.getChatToken=rc,Ae.getCurrentSettings=UT,Ae.getDefaultApiConfig=bh,Ae.getDefaultChatSettings=wh,Ae.onChatTokenChanged=oc,Ae.post=Fo,Ae.put=sc,Ae.setChatToken=$o,Ae.useApi=Si,Ae.useChatStream=Nc,Ae.useMessagesReducer=Ic,Ae.useStream=Rc,Ae.useThreadState=Wo,Ae.useThreads=Ho,Object.defineProperties(Ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});