teodor-new-chat-ui 4.3.113 → 4.3.114

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
@@ -15,14 +15,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
17
  */var $l;function Wm(){return $l||($l=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"),h=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),g=Symbol.iterator,x="@@iterator";function y(I){if(I===null||typeof I!="object")return null;var q=g&&I[g]||I[x];return typeof q=="function"?q:null}var m=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(I){{for(var q=arguments.length,ue=new Array(q>1?q-1:0),ke=1;ke<q;ke++)ue[ke-1]=arguments[ke];S("error",I,ue)}}function S(I,q,ue){{var ke=m.ReactDebugCurrentFrame,Xe=ke.getStackAddendum();Xe!==""&&(q+="%s",ue=ue.concat([Xe]));var at=ue.map(function(Ke){return String(Ke)});at.unshift("Warning: "+q),Function.prototype.apply.call(console[I],console,at)}}var T=!1,k=!1,C=!1,E=!1,R=!1,_;_=Symbol.for("react.module.reference");function j(I){return!!(typeof I=="string"||typeof I=="function"||I===r||I===s||R||I===o||I===c||I===d||E||I===p||T||k||C||typeof I=="object"&&I!==null&&(I.$$typeof===h||I.$$typeof===f||I.$$typeof===i||I.$$typeof===a||I.$$typeof===l||I.$$typeof===_||I.getModuleId!==void 0))}function L(I,q,ue){var ke=I.displayName;if(ke)return ke;var Xe=q.displayName||q.name||"";return Xe!==""?ue+"("+Xe+")":ue}function z(I){return I.displayName||"Context"}function V(I){if(I==null)return null;if(typeof I.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof I=="function")return I.displayName||I.name||null;if(typeof I=="string")return I;switch(I){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 I=="object")switch(I.$$typeof){case a:var q=I;return z(q)+".Consumer";case i:var ue=I;return z(ue._context)+".Provider";case l:return L(I,I.render,"ForwardRef");case f:var ke=I.displayName||null;return ke!==null?ke:V(I.type)||"Memo";case h:{var Xe=I,at=Xe._payload,Ke=Xe._init;try{return V(Ke(at))}catch{return null}}}return null}var O=Object.assign,H=0,P,W,F,$,ne,oe,we;function Ne(){}Ne.__reactDisabledLog=!0;function Z(){{if(H===0){P=console.log,W=console.info,F=console.warn,$=console.error,ne=console.group,oe=console.groupCollapsed,we=console.groupEnd;var I={configurable:!0,enumerable:!0,value:Ne,writable:!0};Object.defineProperties(console,{info:I,log:I,warn:I,error:I,group:I,groupCollapsed:I,groupEnd:I})}H++}}function ie(){{if(H--,H===0){var I={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:O({},I,{value:P}),info:O({},I,{value:W}),warn:O({},I,{value:F}),error:O({},I,{value:$}),group:O({},I,{value:ne}),groupCollapsed:O({},I,{value:oe}),groupEnd:O({},I,{value:we})})}H<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Te=m.ReactCurrentDispatcher,ee;function D(I,q,ue){{if(ee===void 0)try{throw Error()}catch(Xe){var ke=Xe.stack.trim().match(/\n( *(at )?)/);ee=ke&&ke[1]||""}return`
18
- `+ee+I}}var G=!1,ae;{var fe=typeof WeakMap=="function"?WeakMap:Map;ae=new fe}function B(I,q){if(!I||G)return"";{var ue=ae.get(I);if(ue!==void 0)return ue}var ke;G=!0;var Xe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var at;at=Te.current,Te.current=null,Z();try{if(q){var Ke=function(){throw Error()};if(Object.defineProperty(Ke.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ke,[])}catch(de){ke=de}Reflect.construct(I,[],Ke)}else{try{Ke.call()}catch(de){ke=de}I.call(Ke.prototype)}}else{try{throw Error()}catch(de){ke=de}I()}}catch(de){if(de&&ke&&typeof de.stack=="string"){for(var $e=de.stack.split(`
18
+ `+ee+I}}var X=!1,ae;{var fe=typeof WeakMap=="function"?WeakMap:Map;ae=new fe}function B(I,q){if(!I||X)return"";{var ue=ae.get(I);if(ue!==void 0)return ue}var ke;X=!0;var Xe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var at;at=Te.current,Te.current=null,Z();try{if(q){var Ke=function(){throw Error()};if(Object.defineProperty(Ke.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ke,[])}catch(de){ke=de}Reflect.construct(I,[],Ke)}else{try{Ke.call()}catch(de){ke=de}I.call(Ke.prototype)}}else{try{throw Error()}catch(de){ke=de}I()}}catch(de){if(de&&ke&&typeof de.stack=="string"){for(var $e=de.stack.split(`
19
19
  `),jt=ke.stack.split(`
20
20
  `),vt=$e.length-1,pt=jt.length-1;vt>=1&&pt>=0&&$e[vt]!==jt[pt];)pt--;for(;vt>=1&&pt>=0;vt--,pt--)if($e[vt]!==jt[pt]){if(vt!==1||pt!==1)do if(vt--,pt--,pt<0||$e[vt]!==jt[pt]){var qt=`
21
- `+$e[vt].replace(" at new "," at ");return I.displayName&&qt.includes("<anonymous>")&&(qt=qt.replace("<anonymous>",I.displayName)),typeof I=="function"&&ae.set(I,qt),qt}while(vt>=1&&pt>=0);break}}}finally{G=!1,Te.current=at,ie(),Error.prepareStackTrace=Xe}var Gt=I?I.displayName||I.name:"",J=Gt?D(Gt):"";return typeof I=="function"&&ae.set(I,J),J}function le(I,q,ue){return B(I,!1)}function Q(I){var q=I.prototype;return!!(q&&q.isReactComponent)}function Ae(I,q,ue){if(I==null)return"";if(typeof I=="function")return B(I,Q(I));if(typeof I=="string")return D(I);switch(I){case c:return D("Suspense");case d:return D("SuspenseList")}if(typeof I=="object")switch(I.$$typeof){case l:return le(I.render);case f:return Ae(I.type,q,ue);case h:{var ke=I,Xe=ke._payload,at=ke._init;try{return Ae(at(Xe),q,ue)}catch{}}}return""}var ve=Object.prototype.hasOwnProperty,Re={},Ve=m.ReactDebugCurrentFrame;function Qe(I){if(I){var q=I._owner,ue=Ae(I.type,I._source,q?q.type:null);Ve.setExtraStackFrame(ue)}else Ve.setExtraStackFrame(null)}function et(I,q,ue,ke,Xe){{var at=Function.call.bind(ve);for(var Ke in I)if(at(I,Ke)){var $e=void 0;try{if(typeof I[Ke]!="function"){var jt=Error((ke||"React class")+": "+ue+" type `"+Ke+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof I[Ke]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw jt.name="Invariant Violation",jt}$e=I[Ke](q,Ke,ke,ue,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(vt){$e=vt}$e&&!($e instanceof Error)&&(Qe(Xe),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).",ke||"React class",ue,Ke,typeof $e),Qe(null)),$e instanceof Error&&!($e.message in Re)&&(Re[$e.message]=!0,Qe(Xe),b("Failed %s type: %s",ue,$e.message),Qe(null))}}}var Se=Array.isArray;function nt(I){return Se(I)}function ut(I){{var q=typeof Symbol=="function"&&Symbol.toStringTag,ue=q&&I[Symbol.toStringTag]||I.constructor.name||"Object";return ue}}function rt(I){try{return Ye(I),!1}catch{return!0}}function Ye(I){return""+I}function It(I){if(rt(I))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ut(I)),Ye(I)}var dt=m.ReactCurrentOwner,kt={key:!0,ref:!0,__self:!0,__source:!0},Nt,tt;function He(I){if(ve.call(I,"ref")){var q=Object.getOwnPropertyDescriptor(I,"ref").get;if(q&&q.isReactWarning)return!1}return I.ref!==void 0}function Tt(I){if(ve.call(I,"key")){var q=Object.getOwnPropertyDescriptor(I,"key").get;if(q&&q.isReactWarning)return!1}return I.key!==void 0}function Vt(I,q){typeof I.ref=="string"&&dt.current}function zt(I,q){{var ue=function(){Nt||(Nt=!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)",q))};ue.isReactWarning=!0,Object.defineProperty(I,"key",{get:ue,configurable:!0})}}function Kt(I,q){{var ue=function(){tt||(tt=!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)",q))};ue.isReactWarning=!0,Object.defineProperty(I,"ref",{get:ue,configurable:!0})}}var st=function(I,q,ue,ke,Xe,at,Ke){var $e={$$typeof:t,type:I,key:q,ref:ue,props:Ke,_owner:at};return $e._store={},Object.defineProperty($e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty($e,"_self",{configurable:!1,enumerable:!1,writable:!1,value:ke}),Object.defineProperty($e,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Xe}),Object.freeze&&(Object.freeze($e.props),Object.freeze($e)),$e};function Le(I,q,ue,ke,Xe){{var at,Ke={},$e=null,jt=null;ue!==void 0&&(It(ue),$e=""+ue),Tt(q)&&(It(q.key),$e=""+q.key),He(q)&&(jt=q.ref,Vt(q,Xe));for(at in q)ve.call(q,at)&&!kt.hasOwnProperty(at)&&(Ke[at]=q[at]);if(I&&I.defaultProps){var vt=I.defaultProps;for(at in vt)Ke[at]===void 0&&(Ke[at]=vt[at])}if($e||jt){var pt=typeof I=="function"?I.displayName||I.name||"Unknown":I;$e&&zt(Ke,pt),jt&&Kt(Ke,pt)}return st(I,$e,jt,Xe,ke,dt.current,Ke)}}var _t=m.ReactCurrentOwner,yt=m.ReactDebugCurrentFrame;function X(I){if(I){var q=I._owner,ue=Ae(I.type,I._source,q?q.type:null);yt.setExtraStackFrame(ue)}else yt.setExtraStackFrame(null)}var Ce;Ce=!1;function ge(I){return typeof I=="object"&&I!==null&&I.$$typeof===t}function xt(){{if(_t.current){var I=V(_t.current.type);if(I)return`
21
+ `+$e[vt].replace(" at new "," at ");return I.displayName&&qt.includes("<anonymous>")&&(qt=qt.replace("<anonymous>",I.displayName)),typeof I=="function"&&ae.set(I,qt),qt}while(vt>=1&&pt>=0);break}}}finally{X=!1,Te.current=at,ie(),Error.prepareStackTrace=Xe}var Gt=I?I.displayName||I.name:"",J=Gt?D(Gt):"";return typeof I=="function"&&ae.set(I,J),J}function le(I,q,ue){return B(I,!1)}function Q(I){var q=I.prototype;return!!(q&&q.isReactComponent)}function Ae(I,q,ue){if(I==null)return"";if(typeof I=="function")return B(I,Q(I));if(typeof I=="string")return D(I);switch(I){case c:return D("Suspense");case d:return D("SuspenseList")}if(typeof I=="object")switch(I.$$typeof){case l:return le(I.render);case f:return Ae(I.type,q,ue);case h:{var ke=I,Xe=ke._payload,at=ke._init;try{return Ae(at(Xe),q,ue)}catch{}}}return""}var ve=Object.prototype.hasOwnProperty,Re={},Ve=m.ReactDebugCurrentFrame;function Qe(I){if(I){var q=I._owner,ue=Ae(I.type,I._source,q?q.type:null);Ve.setExtraStackFrame(ue)}else Ve.setExtraStackFrame(null)}function et(I,q,ue,ke,Xe){{var at=Function.call.bind(ve);for(var Ke in I)if(at(I,Ke)){var $e=void 0;try{if(typeof I[Ke]!="function"){var jt=Error((ke||"React class")+": "+ue+" type `"+Ke+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof I[Ke]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw jt.name="Invariant Violation",jt}$e=I[Ke](q,Ke,ke,ue,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(vt){$e=vt}$e&&!($e instanceof Error)&&(Qe(Xe),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).",ke||"React class",ue,Ke,typeof $e),Qe(null)),$e instanceof Error&&!($e.message in Re)&&(Re[$e.message]=!0,Qe(Xe),b("Failed %s type: %s",ue,$e.message),Qe(null))}}}var Se=Array.isArray;function nt(I){return Se(I)}function ut(I){{var q=typeof Symbol=="function"&&Symbol.toStringTag,ue=q&&I[Symbol.toStringTag]||I.constructor.name||"Object";return ue}}function rt(I){try{return Ye(I),!1}catch{return!0}}function Ye(I){return""+I}function It(I){if(rt(I))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ut(I)),Ye(I)}var dt=m.ReactCurrentOwner,kt={key:!0,ref:!0,__self:!0,__source:!0},Nt,tt;function He(I){if(ve.call(I,"ref")){var q=Object.getOwnPropertyDescriptor(I,"ref").get;if(q&&q.isReactWarning)return!1}return I.ref!==void 0}function Tt(I){if(ve.call(I,"key")){var q=Object.getOwnPropertyDescriptor(I,"key").get;if(q&&q.isReactWarning)return!1}return I.key!==void 0}function Vt(I,q){typeof I.ref=="string"&&dt.current}function zt(I,q){{var ue=function(){Nt||(Nt=!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)",q))};ue.isReactWarning=!0,Object.defineProperty(I,"key",{get:ue,configurable:!0})}}function Kt(I,q){{var ue=function(){tt||(tt=!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)",q))};ue.isReactWarning=!0,Object.defineProperty(I,"ref",{get:ue,configurable:!0})}}var st=function(I,q,ue,ke,Xe,at,Ke){var $e={$$typeof:t,type:I,key:q,ref:ue,props:Ke,_owner:at};return $e._store={},Object.defineProperty($e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty($e,"_self",{configurable:!1,enumerable:!1,writable:!1,value:ke}),Object.defineProperty($e,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Xe}),Object.freeze&&(Object.freeze($e.props),Object.freeze($e)),$e};function Le(I,q,ue,ke,Xe){{var at,Ke={},$e=null,jt=null;ue!==void 0&&(It(ue),$e=""+ue),Tt(q)&&(It(q.key),$e=""+q.key),He(q)&&(jt=q.ref,Vt(q,Xe));for(at in q)ve.call(q,at)&&!kt.hasOwnProperty(at)&&(Ke[at]=q[at]);if(I&&I.defaultProps){var vt=I.defaultProps;for(at in vt)Ke[at]===void 0&&(Ke[at]=vt[at])}if($e||jt){var pt=typeof I=="function"?I.displayName||I.name||"Unknown":I;$e&&zt(Ke,pt),jt&&Kt(Ke,pt)}return st(I,$e,jt,Xe,ke,dt.current,Ke)}}var _t=m.ReactCurrentOwner,yt=m.ReactDebugCurrentFrame;function G(I){if(I){var q=I._owner,ue=Ae(I.type,I._source,q?q.type:null);yt.setExtraStackFrame(ue)}else yt.setExtraStackFrame(null)}var Ce;Ce=!1;function ge(I){return typeof I=="object"&&I!==null&&I.$$typeof===t}function xt(){{if(_t.current){var I=V(_t.current.type);if(I)return`
22
22
 
23
23
  Check the render method of \``+I+"`."}return""}}function ft(I){return""}var ht={};function Be(I){{var q=xt();if(!q){var ue=typeof I=="string"?I:I.displayName||I.name;ue&&(q=`
24
24
 
25
- Check the top-level render call using <`+ue+">.")}return q}}function Ft(I,q){{if(!I._store||I._store.validated||I.key!=null)return;I._store.validated=!0;var ue=Be(q);if(ht[ue])return;ht[ue]=!0;var ke="";I&&I._owner&&I._owner!==_t.current&&(ke=" It was passed a child from "+V(I._owner.type)+"."),X(I),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',ue,ke),X(null)}}function Oe(I,q){{if(typeof I!="object")return;if(nt(I))for(var ue=0;ue<I.length;ue++){var ke=I[ue];ge(ke)&&Ft(ke,q)}else if(ge(I))I._store&&(I._store.validated=!0);else if(I){var Xe=y(I);if(typeof Xe=="function"&&Xe!==I.entries)for(var at=Xe.call(I),Ke;!(Ke=at.next()).done;)ge(Ke.value)&&Ft(Ke.value,q)}}}function it(I){{var q=I.type;if(q==null||typeof q=="string")return;var ue;if(typeof q=="function")ue=q.propTypes;else if(typeof q=="object"&&(q.$$typeof===l||q.$$typeof===f))ue=q.propTypes;else return;if(ue){var ke=V(q);et(ue,I.props,"prop",ke,I)}else if(q.PropTypes!==void 0&&!Ce){Ce=!0;var Xe=V(q);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Xe||"Unknown")}typeof q.getDefaultProps=="function"&&!q.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ar(I){{for(var q=Object.keys(I.props),ue=0;ue<q.length;ue++){var ke=q[ue];if(ke!=="children"&&ke!=="key"){X(I),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",ke),X(null);break}}I.ref!==null&&(X(I),b("Invalid attribute `ref` supplied to `React.Fragment`."),X(null))}}var jr={};function lr(I,q,ue,ke,Xe,at){{var Ke=j(I);if(!Ke){var $e="";(I===void 0||typeof I=="object"&&I!==null&&Object.keys(I).length===0)&&($e+=" 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 jt=ft();jt?$e+=jt:$e+=xt();var vt;I===null?vt="null":nt(I)?vt="array":I!==void 0&&I.$$typeof===t?(vt="<"+(V(I.type)||"Unknown")+" />",$e=" Did you accidentally export a JSX literal instead of a component?"):vt=typeof I,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",vt,$e)}var pt=Le(I,q,ue,Xe,at);if(pt==null)return pt;if(Ke){var qt=q.children;if(qt!==void 0)if(ke)if(nt(qt)){for(var Gt=0;Gt<qt.length;Gt++)Oe(qt[Gt],I);Object.freeze&&Object.freeze(qt)}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 Oe(qt,I)}if(ve.call(q,"key")){var J=V(I),de=Object.keys(q).filter(function(Ot){return Ot!=="key"}),he=de.length>0?"{key: someKey, "+de.join(": ..., ")+": ...}":"{key: someKey}";if(!jr[J+he]){var wt=de.length>0?"{"+de.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
25
+ Check the top-level render call using <`+ue+">.")}return q}}function Ft(I,q){{if(!I._store||I._store.validated||I.key!=null)return;I._store.validated=!0;var ue=Be(q);if(ht[ue])return;ht[ue]=!0;var ke="";I&&I._owner&&I._owner!==_t.current&&(ke=" It was passed a child from "+V(I._owner.type)+"."),G(I),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',ue,ke),G(null)}}function Oe(I,q){{if(typeof I!="object")return;if(nt(I))for(var ue=0;ue<I.length;ue++){var ke=I[ue];ge(ke)&&Ft(ke,q)}else if(ge(I))I._store&&(I._store.validated=!0);else if(I){var Xe=y(I);if(typeof Xe=="function"&&Xe!==I.entries)for(var at=Xe.call(I),Ke;!(Ke=at.next()).done;)ge(Ke.value)&&Ft(Ke.value,q)}}}function it(I){{var q=I.type;if(q==null||typeof q=="string")return;var ue;if(typeof q=="function")ue=q.propTypes;else if(typeof q=="object"&&(q.$$typeof===l||q.$$typeof===f))ue=q.propTypes;else return;if(ue){var ke=V(q);et(ue,I.props,"prop",ke,I)}else if(q.PropTypes!==void 0&&!Ce){Ce=!0;var Xe=V(q);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Xe||"Unknown")}typeof q.getDefaultProps=="function"&&!q.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ar(I){{for(var q=Object.keys(I.props),ue=0;ue<q.length;ue++){var ke=q[ue];if(ke!=="children"&&ke!=="key"){G(I),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",ke),G(null);break}}I.ref!==null&&(G(I),b("Invalid attribute `ref` supplied to `React.Fragment`."),G(null))}}var jr={};function lr(I,q,ue,ke,Xe,at){{var Ke=j(I);if(!Ke){var $e="";(I===void 0||typeof I=="object"&&I!==null&&Object.keys(I).length===0)&&($e+=" 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 jt=ft();jt?$e+=jt:$e+=xt();var vt;I===null?vt="null":nt(I)?vt="array":I!==void 0&&I.$$typeof===t?(vt="<"+(V(I.type)||"Unknown")+" />",$e=" Did you accidentally export a JSX literal instead of a component?"):vt=typeof I,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",vt,$e)}var pt=Le(I,q,ue,Xe,at);if(pt==null)return pt;if(Ke){var qt=q.children;if(qt!==void 0)if(ke)if(nt(qt)){for(var Gt=0;Gt<qt.length;Gt++)Oe(qt[Gt],I);Object.freeze&&Object.freeze(qt)}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 Oe(qt,I)}if(ve.call(q,"key")){var J=V(I),de=Object.keys(q).filter(function(Ot){return Ot!=="key"}),he=de.length>0?"{key: someKey, "+de.join(": ..., ")+": ...}":"{key: someKey}";if(!jr[J+he]){var wt=de.length>0?"{"+de.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:
@@ -32,10 +32,10 @@ React keys must be passed directly to JSX without using spread:
32
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[oc]=this[oc]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=ao(i);r[a]||(Kg(o,i),r[a]=!0)}return M.isArray(t)?t.forEach(s):s(t),this}};rn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),M.reduceDescriptors(rn.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),M.freezeMethods(rn);function Oi(e,t){const n=this||io,r=t||n,o=rn.from(r.headers);let s=r.data;return M.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function sc(e){return!!(e&&e.__CANCEL__)}function Lr(e,t,n){Fe.call(this,e??"canceled",Fe.ERR_CANCELED,t,n),this.name="CanceledError"}M.inherits(Lr,Fe,{__CANCEL__:!0});function ic(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Fe("Request failed with status code "+n.status,[Fe.ERR_BAD_REQUEST,Fe.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function qg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Gg(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 Xg(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 Jo=(e,t,n=3)=>{let r=0;const o=Gg(50,250);return Xg(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)},ac=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},lc=e=>(...t)=>M.asap(()=>e(...t)),Yg=Xt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Xt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Xt.origin),Xt.navigator&&/(msie|trident)/i.test(Xt.navigator.userAgent)):()=>!0,Jg=Xt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];M.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),M.isString(r)&&i.push("path="+r),M.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 Zg(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Qg(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function cc(e,t,n){let r=!Zg(t);return e&&(r||n==!1)?Qg(e,t):t}const uc=e=>e instanceof rn?{...e}:e;function mr(e,t){t=t||{};const n={};function r(c,d,f,h){return M.isPlainObject(c)&&M.isPlainObject(d)?M.merge.call({caseless:h},c,d):M.isPlainObject(d)?M.merge({},d):M.isArray(d)?d.slice():d}function o(c,d,f,h){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c,f,h)}else return r(c,d,f,h)}function s(c,d){if(!M.isUndefined(d))return r(void 0,d)}function i(c,d){if(M.isUndefined(d)){if(!M.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(uc(c),uc(d),f,!0)};return M.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,h=f(e[d],t[d],d);M.isUndefined(h)&&f!==a||(n[d]=h)}),n}const dc=e=>{const t=mr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=rn.from(i),t.url=ec(cc(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),M.isFormData(n)){if(Xt.hasStandardBrowserEnv||Xt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(M.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(Xt.hasStandardBrowserEnv&&(r&&M.isFunction(r)&&(r=r(t)),r||r!==!1&&Yg(t.url))){const l=o&&s&&Jg.read(s);l&&i.set(o,l)}return t},ex=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=dc(e);let s=o.data;const i=rn.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,h,p,g;function x(){p&&p(),g&&g(),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 m(){if(!y)return;const S=rn.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),k={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:S,config:e,request:y};ic(function(E){n(E),x()},function(E){r(E),x()},k),y=null}"onloadend"in y?y.onloadend=m:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(m)},y.onabort=function(){y&&(r(new Fe("Request aborted",Fe.ECONNABORTED,e,y)),y=null)},y.onerror=function(T){const k=T&&T.message?T.message:"Network Error",C=new Fe(k,Fe.ERR_NETWORK,e,y);C.event=T||null,r(C),y=null},y.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const k=o.transitional||nc;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new Fe(T,k.clarifyTimeoutError?Fe.ETIMEDOUT:Fe.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&M.forEach(i.toJSON(),function(T,k){y.setRequestHeader(k,T)}),M.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([h,g]=Jo(c,!0),y.addEventListener("progress",h)),l&&y.upload&&([f,p]=Jo(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(d=S=>{y&&(r(!S||S.type?new Lr(null,e,y):S),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const b=qg(o.url);if(b&&Xt.protocols.indexOf(b)===-1){r(new Fe("Unsupported protocol "+b+":",Fe.ERR_BAD_REQUEST,e));return}y.send(s||null)})},tx=(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 Fe?d:new Lr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Fe(`timeout ${t} of ms exceeded`,Fe.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=()=>M.asap(a),l}},nx=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},rx=async function*(e,t){for await(const n of ox(e))yield*nx(n,t)},ox=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()}},fc=(e,t,n,r)=>{const o=rx(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})},hc=64*1024,{isFunction:Zo}=M,sx=(({Request:e,Response:t})=>({Request:e,Response:t}))(M.global),{ReadableStream:pc,TextEncoder:mc}=M.global,gc=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ix=e=>{e=M.merge.call({skipUndefined:!0},sx,e);const{fetch:t,Request:n,Response:r}=e,o=t?Zo(t):typeof fetch=="function",s=Zo(n),i=Zo(r);if(!o)return!1;const a=o&&Zo(pc),l=o&&(typeof mc=="function"?(g=>x=>g.encode(x))(new mc):async g=>new Uint8Array(await new n(g).arrayBuffer())),c=s&&a&&gc(()=>{let g=!1;const x=new n(Xt.origin,{body:new pc,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!x}),d=i&&a&&gc(()=>M.isReadableStream(new r("").body)),f={stream:d&&(g=>g.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(x,y)=>{let m=x&&x[g];if(m)return m.call(x);throw new Fe(`Response type '${g}' is not supported`,Fe.ERR_NOT_SUPPORT,y)})});const h=async g=>{if(g==null)return 0;if(M.isBlob(g))return g.size;if(M.isSpecCompliantForm(g))return(await new n(Xt.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(M.isArrayBufferView(g)||M.isArrayBuffer(g))return g.byteLength;if(M.isURLSearchParams(g)&&(g=g+""),M.isString(g))return(await l(g)).byteLength},p=async(g,x)=>{const y=M.toFiniteNumber(g.getContentLength());return y??h(x)};return async g=>{let{url:x,method:y,data:m,signal:b,cancelToken:S,timeout:T,onDownloadProgress:k,onUploadProgress:C,responseType:E,headers:R,withCredentials:_="same-origin",fetchOptions:j}=dc(g),L=t||fetch;E=E?(E+"").toLowerCase():"text";let z=tx([b,S&&S.toAbortSignal()],T),V=null;const O=z&&z.unsubscribe&&(()=>{z.unsubscribe()});let H;try{if(C&&c&&y!=="get"&&y!=="head"&&(H=await p(R,m))!==0){let oe=new n(x,{method:"POST",body:m,duplex:"half"}),we;if(M.isFormData(m)&&(we=oe.headers.get("content-type"))&&R.setContentType(we),oe.body){const[Ne,Z]=ac(H,Jo(lc(C)));m=fc(oe.body,hc,Ne,Z)}}M.isString(_)||(_=_?"include":"omit");const P=s&&"credentials"in n.prototype,W={...j,signal:z,method:y.toUpperCase(),headers:R.normalize().toJSON(),body:m,duplex:"half",credentials:P?_:void 0};V=s&&new n(x,W);let F=await(s?L(V,j):L(x,W));const $=d&&(E==="stream"||E==="response");if(d&&(k||$&&O)){const oe={};["status","statusText","headers"].forEach(ie=>{oe[ie]=F[ie]});const we=M.toFiniteNumber(F.headers.get("content-length")),[Ne,Z]=k&&ac(we,Jo(lc(k),!0))||[];F=new r(fc(F.body,hc,Ne,()=>{Z&&Z(),O&&O()}),oe)}E=E||"text";let ne=await f[M.findKey(f,E)||"text"](F,g);return!$&&O&&O(),await new Promise((oe,we)=>{ic(oe,we,{data:ne,headers:rn.from(F.headers),status:F.status,statusText:F.statusText,config:g,request:V})})}catch(P){throw O&&O(),P&&P.name==="TypeError"&&/Load failed|fetch/i.test(P.message)?Object.assign(new Fe("Network Error",Fe.ERR_NETWORK,g,V),{cause:P.cause||P}):Fe.from(P,P&&P.code,g,V)}}},ax=new Map,xc=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=ax;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:ix(t)),d=c;return c};xc();const Mi={http:Ag,xhr:ex,fetch:{get:xc}};M.forEach(Mi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const yc=e=>`- ${e}`,lx=e=>M.isFunction(e)||e===null||e===!1,vc={getAdapter:(e,t)=>{e=M.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,!lx(r)&&(o=Mi[(a=String(r)).toLowerCase()],o===void 0))throw new Fe(`Unknown adapter '${a}'`);if(o&&(M.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
33
  `+i.map(yc).join(`
34
34
  `):" "+yc(i[0]):"as no adapter specified";throw new Fe("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:Mi};function Di(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Lr(null,e)}function wc(e){return Di(e),e.headers=rn.from(e.headers),e.data=Oi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),vc.getAdapter(e.adapter||io.adapter,e)(e).then(function(r){return Di(e),r.data=Oi.call(e,e.transformResponse,r),r.headers=rn.from(r.headers),r},function(r){return sc(r)||(Di(e),r&&r.response&&(r.response.data=Oi.call(e,e.transformResponse,r.response),r.response.headers=rn.from(r.response.headers))),Promise.reject(r)})}const bc="1.12.2",Qo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Qo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Sc={};Qo.transitional=function(t,n,r){function o(s,i){return"[Axios v"+bc+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Fe(o(i," has been removed"+(n?" in "+n:"")),Fe.ERR_DEPRECATED);return n&&!Sc[i]&&(Sc[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}},Qo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function cx(e,t,n){if(typeof e!="object")throw new Fe("options must be an object",Fe.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 Fe("option "+s+" must be "+l,Fe.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Fe("Unknown option "+s,Fe.ERR_BAD_OPTION)}}const es={assertOptions:cx,validators:Qo},An=es.validators;let gr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new tc,response:new tc}}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=mr(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&es.assertOptions(r,{silentJSONParsing:An.transitional(An.boolean),forcedJSONParsing:An.transitional(An.boolean),clarifyTimeoutError:An.transitional(An.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:es.assertOptions(o,{encode:An.function,serialize:An.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),es.assertOptions(n,{baseUrl:An.spelling("baseURL"),withXsrfToken:An.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=rn.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const g=[wc.bind(this),void 0];for(g.unshift(...a),g.push(...c),h=g.length,d=Promise.resolve(n);f<h;)d=d.then(g[f++],g[f++]);return d}h=a.length;let p=n;for(;f<h;){const g=a[f++],x=a[f++];try{p=g(p)}catch(y){x.call(this,y);break}}try{d=wc.call(this,p)}catch(g){return Promise.reject(g)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=mr(this.defaults,t);const n=cc(t.baseURL,t.url,t.allowAbsoluteUrls);return ec(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){gr.prototype[t]=function(n,r){return this.request(mr(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(mr(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}gr.prototype[t]=n(),gr.prototype[t+"Form"]=n(!0)});let ux=class zm{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 Lr(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 zm(function(o){t=o}),cancel:t}}};function dx(e){return function(n){return e.apply(null,n)}}function fx(e){return M.isObject(e)&&e.isAxiosError===!0}const Li={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(Li).forEach(([e,t])=>{Li[t]=e});function Cc(e){const t=new gr(e),n=Fl(gr.prototype.request,t);return M.extend(n,gr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Cc(mr(e,o))},n}const Rt=Cc(io);Rt.Axios=gr,Rt.CanceledError=Lr,Rt.CancelToken=ux,Rt.isCancel=sc,Rt.VERSION=bc,Rt.toFormData=Xo,Rt.AxiosError=Fe,Rt.Cancel=Rt.CanceledError,Rt.all=function(t){return Promise.all(t)},Rt.spread=dx,Rt.isAxiosError=fx,Rt.mergeConfig=mr,Rt.AxiosHeaders=rn,Rt.formToJSON=e=>rc(M.isHTMLForm(e)?new FormData(e):e),Rt.getAdapter=vc.getAdapter,Rt.HttpStatusCode=Li,Rt.default=Rt;const{Axios:fT,AxiosError:hT,CanceledError:pT,isCancel:mT,CancelToken:gT,VERSION:xT,all:yT,Cancel:vT,isAxiosError:wT,spread:bT,toFormData:ST,AxiosHeaders:CT,HttpStatusCode:kT,formToJSON:TT,getAdapter:ET,mergeConfig:IT}=Rt,kc=typeof window<"u"?window.__API_BASE_URL__:void 0,Tc=kc?zn(kc):void 0;function zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let ts=null;const $i=new Set;function Ec(){return ts}function Fi(e){ts=e,$i.forEach(t=>t(e))}function Ic(e){return $i.add(e),()=>$i.delete(e)}const fn=Rt.create({...Tc?{baseURL:Tc}:{},timeout:3e4,withCredentials:!0});fn.interceptors.request.use(e=>(ts&&(e.headers.Authorization=`Bearer ${ts}`),e)),fn.interceptors.response.use(e=>e,e=>Promise.reject(e));async function bn(e,t){return fn.defaults.baseURL?(await fn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function zi(e,t,n){return fn.defaults.baseURL?(await fn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Nc(e,t,n){return fn.defaults.baseURL?(await fn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Ac(e,t){return fn.defaults.baseURL?(await fn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Sn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class _c{get baseUrl(){const t=fn.defaults.baseURL;return t?zn(String(t)):""}updateConfig(t){t.baseUrl&&(fn.defaults.baseURL=zn(String(t.baseUrl))),t.authToken!==void 0&&Fi(t.authToken)}getAuthToken(){return Ec()}setAuthToken(t){Fi(t)}onTokenChange(t){return Ic(t)}async listThreads(){const t=await bn("/threads"),n=Sn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await zi("/threads",t?{title:t}:void 0);return Sn(r)}async updateThread(t,n){const r=await Nc(`/threads/${t}`,{title:n});return Sn(r)}async deleteThread(t){const n=await Ac(`/threads/${t}`);return Sn(n)}async threadInfo(t){const n=await bn(`/threads/${t}/info`);return Sn(n)}async listAgents(){const t=await bn("/agents"),n=Sn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await bn(`/agents/${t}`);return Sn(n)}async getAgentSchema(t){const n=await bn(`/agents/${t}/schema`);return Sn(n)}async getState(t){const n=await bn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Sn(n)}async getStateHistory(t){const n=await bn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Sn(n)}async cancelRun(t){const n=await zi("/runs/cancel",{threadId:t});return Sn(n)}}const Gn=new _c,jc=w.createContext(null);function hx({children:e,apiConfig:t}){const n=Gn;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(jc.Provider,{value:r,children:e})}function Bi(){const e=w.useContext(jc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function px(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 mx(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await px(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const gx={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Hi(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 lo(e,t){return`${e??""}::${t??""}`}function ns(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(!Hi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=yx(t),i=Rc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Rc(e,t){if(!Hi(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((_,j)=>Tx(_,j)).filter(_=>!!_),d=on(e.config),f=on(d==null?void 0:d.configurable),h=Mt(f,["checkpoint_id","checkpointId"]),p=Mt(f,["checkpoint_ns","checkpointNs"]),g=on(e==null?void 0:e.parentConfig),x=on(g==null?void 0:g.configurable),y=Mt(x,["checkpoint_id","checkpointId"])??null,m=Mt(x,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=on(e==null?void 0:e.metadata),C=Mt(k,["branch_label","branchLabel"]),E=Mt(x,["checkpoint_id","checkpointId"]),R=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:y,nextCursorNs:m,interrupt:xx(a,c,t),createdAt:S,parentId:E??null,branchLabel:C??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:g??null,next:R??null,tasks:l??null,values:i??null}}function xx(e,t,n){const r=Cx(e,n);return r||Sx(t,n)}function yx(e){const t=new Map;e.forEach((o,s)=>{if(!Hi(o))return;const i=Rc(o,s);if(!(i!=null&&i.checkpointId))return;const a=lo(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,vx(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Oc(s.createdAt??"")-Oc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function vx(e,t){return{...e,metadata:rs(e.metadata,t.metadata)??null,config:rs(e.config,t.config)??null,parentConfig:rs(e.parentConfig,t.parentConfig)??null,next:wx(e.next,t.next)??null,tasks:bx(e.tasks,t.tasks)??null,values:rs(e.values,t.values)??null}}function rs(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 wx(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 bx(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 Sx(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 Cx(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=kx(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=co(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=co(r.state,`${o}-state`);if(s)return s}}return null}function kx(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,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",x=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:g,interrupts:x,state:y!==void 0?y:f}}const n=on(e);if(!n)return null;const r=Mt(n,["id","task_id","taskId"])??t,o=Mt(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 co(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=Pc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=co(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=co(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=co(l,t,n+1,r);if(c)return c}}return null}function Pc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Mt(n,["type","event","kind"]),o=Mt(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=Pc(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 Oc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Tx(e,t){if(!e||typeof e!="object")return null;const n=e,r=on(e)??{},o=on(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=gx[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=on(o.additional_kwargs)??on(o.additionalKwargs),d=on(o.response_metadata)??on(o.responseMetadata),f=Mt(c,["createdAt","created_at"])??Mt(o,["created_at","createdAt"]),h=Mt(c,["checkpointId","checkpoint_id"]),p=Mt(c,["checkpointNs","checkpoint_ns"]),g=Ex(o.content),x={id:l,role:i,content:g};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const y=_x(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),m=d?{...d}:void 0;y&&Object.keys(y).length&&(x.additionalKwargs=y),m&&Object.keys(m).length&&(x.responseMetadata=m);const b=Ix((c==null?void 0:c.tool_calls)??o.tool_calls);if(b.length&&(x.content=[...x.content,...b]),i==="tool"){const S=Nx(o,x.content);S&&(x.content=S)}return x}function Ex(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Mc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Mc(e);return t?[t]:[]}return[]}function Mc(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=Mt(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=Mt(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 Dc(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=Mt(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 Dc(e,t){var s;const n=Mt(e,["id","call_id"])??t,r=Mt(e,["name"])??Mt(on(e.function),["name"]);if(!n||!r)return null;const o=Ax(e.args??e.arguments??((s=on(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Ix(e){return Array.isArray(e)?e.map((t,n)=>Dc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Nx(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 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 on(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Mt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function _x(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}function jx(e){return e.type!=="thread_info"&&e.type!=="token"}const Rx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Px(e,t){var n;switch(t.type){case"reset":return{messages:Ui(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Ui(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Ui(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return $c(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>$c(o,s),e):e}case"interrupt_response":return{...e,messages:Fc(e.messages),pendingInterrupt:null};default:return e}}function Lc(e=[]){const[t,n]=w.useReducer(Px,{...Rx,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 $c(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Lx(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??zc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Uc(d.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:g,newMeta:x,changed:y}=Ox(d.content,t.delta,h,p);if(!y)return e;const m={...d,content:g},b=os(l,c,m),S={...f,[a]:x};return{...e,messages:b,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??zc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.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 h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Bc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Hc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,g=(h==null?void 0:h.id)??`tool-${p}`,x=d[0]??p,y={type:"tool_call",id:x,name:c,args:t.args};if(h){const S=Vi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:S},k=f,C=k>=0?os(e.messages,k,T):e.messages,E=ss(T,d),R=Ki(e.toolIndex,g,E);return{...e,messages:C,toolIndex:R}}const m={id:g,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Vi(void 0,d.length?d:[x],c,t.args)},b=ss(m,d.length?d:[x]);return{...e,messages:[...e.messages,m],toolIndex:Ki(e.toolIndex,g,b)}}if(t.type==="tool_end"){const a=Bc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Hc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,g=ss(d,a);let x=t.output;if(typeof t.output=="string")try{const C=t.output.trim();(C.startsWith("{")||C.startsWith("["))&&(x=JSON.parse(C))}catch{x=t.output}const y={type:"text",text:typeof x=="string"?x:JSON.stringify(x)},m=(d==null?void 0:d.createdAt)??new Date().toISOString(),b=Vi(d??void 0,g.length?g:a,f),S={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:m,additionalKwargs:b},T=c>=0?os(e.messages,c,S):[...e.messages,S],k=ss(S,a.length?a:g);return{...e,messages:T,toolIndex:Ki(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Dx(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=ns(t),l=a.interrupt,c=a.latest,d=l===null?Fc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Ui(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function os(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Fc(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 zc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Bc(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 Wi(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 Vi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Wi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};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 ss(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Wi(e);for(const o of r)n.add(o);return Array.from(n)}function Ki(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 Hc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Wi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Uc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Ox(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??Uc(e);let l="",c=e.slice();if(s){const f=Mx(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??"",g={...h,text:p+l};c=[...c.slice(0,c.length-1),g]}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 Wc(e){return e.replace(/\s+/g," ").trim()}function Mx(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=Wc(e),o=Wc(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 os(e,r,s)}return e}function Lx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Vc(e={}){const t=w.useMemo(()=>zn(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,h]=w.useState(""),[p,g]=w.useState(null),[x,y]=w.useState(0),[m,b]=w.useState(!1),S=w.useRef(null),T=w.useRef(!0),k=w.useRef(0),C=w.useRef(null),E=w.useRef(null),R=w.useRef(null),_=w.useRef(null),j=w.useCallback(O=>{o(O)},[]),L=w.useCallback(()=>{h(""),g(null),d(null),E.current=null,R.current=null,_.current=null},[]),z=w.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=S.current)==null||O.abort(),S.current=null,C.current=null,l(!1),b(!1),k.current=0,y(0)},[]),V=w.useCallback((O,H,P)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),g(null),E.current=null,R.current=null,_.current=null;const W=new AbortController;S.current=W;let F=null,$=null,ne=!1;return C.current={threadId:O.threadId??null,headers:{}},(async()=>{var we,Ne,Z,ie,Te,ee,D,G,ae,fe,B,le,Q,Ae,ve,Re,Ve,Qe;const oe=et=>{var Se;try{const nt=JSON.parse(JSON.stringify(et));return(Se=nt==null?void 0:nt.payload)!=null&&Se.files_info&&Array.isArray(nt.payload.files_info)&&(nt.payload.files_info=nt.payload.files_info.map(ut=>({...ut,data:ut!=null&&ut.data?`<base64 ${String(ut.data).length} chars>`:ut==null?void 0:ut.data}))),nt}catch{return et}};try{let et={};try{if(r)et={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Le=window.__AUTH_TOKEN__,_t=((we=window.localStorage)==null?void 0:we.getItem("authToken"))||null;let yt=null;try{const Ce=(Ne=window.localStorage)==null?void 0:Ne.getItem("chat-settings");Ce&&(yt=((Z=JSON.parse(Ce))==null?void 0:Z.apiKey)||null)}catch{}const X=Le||_t||yt||null;X&&(et={Authorization:`Bearer ${X}`})}}catch{}console.debug("[use-chat] POST",t+n,oe(O));let Se={};if(typeof window<"u")try{const st=(ie=window.localStorage)==null?void 0:ie.getItem("authSessionId");st&&(Se={"X-Session-Id":st})}catch{}const nt={...et,...Se,...s.current},ut={"Content-Type":"application/json",Accept:"text/event-stream",...nt},rt=await fetch(t+n,{method:"POST",headers:ut,body:JSON.stringify(O),signal:W.signal,credentials:i});if(C.current&&(C.current.headers=nt),!rt.ok||!rt.body){const st=await rt.text().catch(()=>"");console.debug("[use-chat] non-OK response",rt.status,st==null?void 0:st.slice(0,500));const Le=`stream ${rt.status}${st?": "+st:""}`;throw(Te=P==null?void 0:P.onConnectionError)==null||Te.call(P,Le),ne=!0,F="error",$=Le,new Error(Le)}b(!0);const Ye=rt.body.getReader(),It=new TextDecoder;let dt="",kt=[];k.current=0,y(0);let Nt=0,tt=null;const He=()=>{if(kt.length){const st=kt.join("");kt=[],T.current&&h(Le=>Le+st)}tt=null},Tt=()=>{typeof window<"u"&&tt==null&&(tt=requestAnimationFrame(He))};let Vt=Date.now();const zt=setInterval(()=>{var st;if(Date.now()-Vt>6e4){const Le="Stream idle timeout";d(Le),F="error",$=Le,W.abort(),(st=P==null?void 0:P.onError)==null||st.call(P,Le)}},5e3),Kt=1024*1024;try{const st=rt.headers.get("X-Thread-Id")||rt.headers.get("x-thread-id"),Le=rt.headers.get("X-Thread-Created")||rt.headers.get("x-thread-created"),_t=st??null,yt=String(Le??"").toLowerCase()==="true";for(C.current&&!C.current.threadId&&(C.current={...C.current,threadId:_t}),(ee=P==null?void 0:P.onOpen)==null||ee.call(P,{threadId:_t,created:yt});;){const{value:X,done:Ce}=await Ye.read();if(Ce)break;dt+=It.decode(X,{stream:!0}),dt.length>Kt&&(dt="",console.warn("Stream buffer reset: exceeded 1MB"));let ge;for(;(ge=dt.indexOf(`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=mr(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&es.assertOptions(r,{silentJSONParsing:An.transitional(An.boolean),forcedJSONParsing:An.transitional(An.boolean),clarifyTimeoutError:An.transitional(An.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:es.assertOptions(o,{encode:An.function,serialize:An.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),es.assertOptions(n,{baseUrl:An.spelling("baseURL"),withXsrfToken:An.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=rn.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const g=[wc.bind(this),void 0];for(g.unshift(...a),g.push(...c),h=g.length,d=Promise.resolve(n);f<h;)d=d.then(g[f++],g[f++]);return d}h=a.length;let p=n;for(;f<h;){const g=a[f++],x=a[f++];try{p=g(p)}catch(y){x.call(this,y);break}}try{d=wc.call(this,p)}catch(g){return Promise.reject(g)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=mr(this.defaults,t);const n=cc(t.baseURL,t.url,t.allowAbsoluteUrls);return ec(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){gr.prototype[t]=function(n,r){return this.request(mr(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(mr(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}gr.prototype[t]=n(),gr.prototype[t+"Form"]=n(!0)});let ux=class zm{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 Lr(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 zm(function(o){t=o}),cancel:t}}};function dx(e){return function(n){return e.apply(null,n)}}function fx(e){return M.isObject(e)&&e.isAxiosError===!0}const Li={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(Li).forEach(([e,t])=>{Li[t]=e});function Cc(e){const t=new gr(e),n=Fl(gr.prototype.request,t);return M.extend(n,gr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Cc(mr(e,o))},n}const Rt=Cc(io);Rt.Axios=gr,Rt.CanceledError=Lr,Rt.CancelToken=ux,Rt.isCancel=sc,Rt.VERSION=bc,Rt.toFormData=Xo,Rt.AxiosError=Fe,Rt.Cancel=Rt.CanceledError,Rt.all=function(t){return Promise.all(t)},Rt.spread=dx,Rt.isAxiosError=fx,Rt.mergeConfig=mr,Rt.AxiosHeaders=rn,Rt.formToJSON=e=>rc(M.isHTMLForm(e)?new FormData(e):e),Rt.getAdapter=vc.getAdapter,Rt.HttpStatusCode=Li,Rt.default=Rt;const{Axios:fT,AxiosError:hT,CanceledError:pT,isCancel:mT,CancelToken:gT,VERSION:xT,all:yT,Cancel:vT,isAxiosError:wT,spread:bT,toFormData:ST,AxiosHeaders:CT,HttpStatusCode:kT,formToJSON:TT,getAdapter:ET,mergeConfig:IT}=Rt,kc=typeof window<"u"?window.__API_BASE_URL__:void 0,Tc=kc?zn(kc):void 0;function zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let ts=null;const $i=new Set;function Ec(){return ts}function Fi(e){ts=e,$i.forEach(t=>t(e))}function Ic(e){return $i.add(e),()=>$i.delete(e)}const fn=Rt.create({...Tc?{baseURL:Tc}:{},timeout:3e4,withCredentials:!0});fn.interceptors.request.use(e=>(ts&&(e.headers.Authorization=`Bearer ${ts}`),e)),fn.interceptors.response.use(e=>e,e=>Promise.reject(e));async function bn(e,t){return fn.defaults.baseURL?(await fn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function zi(e,t,n){return fn.defaults.baseURL?(await fn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Nc(e,t,n){return fn.defaults.baseURL?(await fn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Ac(e,t){return fn.defaults.baseURL?(await fn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Sn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class _c{get baseUrl(){const t=fn.defaults.baseURL;return t?zn(String(t)):""}updateConfig(t){t.baseUrl&&(fn.defaults.baseURL=zn(String(t.baseUrl))),t.authToken!==void 0&&Fi(t.authToken)}getAuthToken(){return Ec()}setAuthToken(t){Fi(t)}onTokenChange(t){return Ic(t)}async listThreads(){const t=await bn("/threads"),n=Sn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await zi("/threads",t?{title:t}:void 0);return Sn(r)}async updateThread(t,n){const r=await Nc(`/threads/${t}`,{title:n});return Sn(r)}async deleteThread(t){const n=await Ac(`/threads/${t}`);return Sn(n)}async threadInfo(t){const n=await bn(`/threads/${t}/info`);return Sn(n)}async listAgents(){const t=await bn("/agents"),n=Sn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await bn(`/agents/${t}`);return Sn(n)}async getAgentSchema(t){const n=await bn(`/agents/${t}/schema`);return Sn(n)}async getState(t){const n=await bn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Sn(n)}async getStateHistory(t){const n=await bn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Sn(n)}async cancelRun(t){const n=await zi("/runs/cancel",{threadId:t});return Sn(n)}}const Gn=new _c,jc=w.createContext(null);function hx({children:e,apiConfig:t}){const n=Gn;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(jc.Provider,{value:r,children:e})}function Bi(){const e=w.useContext(jc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function px(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 mx(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await px(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const gx={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Hi(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 lo(e,t){return`${e??""}::${t??""}`}function ns(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(!Hi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=yx(t),i=Rc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Rc(e,t){if(!Hi(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((_,j)=>Tx(_,j)).filter(_=>!!_),d=on(e.config),f=on(d==null?void 0:d.configurable),h=Mt(f,["checkpoint_id","checkpointId"]),p=Mt(f,["checkpoint_ns","checkpointNs"]),g=on(e==null?void 0:e.parentConfig),x=on(g==null?void 0:g.configurable),y=Mt(x,["checkpoint_id","checkpointId"])??null,m=Mt(x,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=on(e==null?void 0:e.metadata),C=Mt(k,["branch_label","branchLabel"]),E=Mt(x,["checkpoint_id","checkpointId"]),R=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:y,nextCursorNs:m,interrupt:xx(a,c,t),createdAt:S,parentId:E??null,branchLabel:C??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:g??null,next:R??null,tasks:l??null,values:i??null}}function xx(e,t,n){const r=Cx(e,n);return r||Sx(t,n)}function yx(e){const t=new Map;e.forEach((o,s)=>{if(!Hi(o))return;const i=Rc(o,s);if(!(i!=null&&i.checkpointId))return;const a=lo(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,vx(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Oc(s.createdAt??"")-Oc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function vx(e,t){return{...e,metadata:rs(e.metadata,t.metadata)??null,config:rs(e.config,t.config)??null,parentConfig:rs(e.parentConfig,t.parentConfig)??null,next:wx(e.next,t.next)??null,tasks:bx(e.tasks,t.tasks)??null,values:rs(e.values,t.values)??null}}function rs(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 wx(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 bx(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 Sx(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 Cx(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=kx(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=co(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=co(r.state,`${o}-state`);if(s)return s}}return null}function kx(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,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",x=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:g,interrupts:x,state:y!==void 0?y:f}}const n=on(e);if(!n)return null;const r=Mt(n,["id","task_id","taskId"])??t,o=Mt(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 co(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=Pc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=co(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=co(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=co(l,t,n+1,r);if(c)return c}}return null}function Pc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Mt(n,["type","event","kind"]),o=Mt(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=Pc(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 Oc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Tx(e,t){if(!e||typeof e!="object")return null;const n=e,r=on(e)??{},o=on(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=gx[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=on(o.additional_kwargs)??on(o.additionalKwargs),d=on(o.response_metadata)??on(o.responseMetadata),f=Mt(c,["createdAt","created_at"])??Mt(o,["created_at","createdAt"]),h=Mt(c,["checkpointId","checkpoint_id"]),p=Mt(c,["checkpointNs","checkpoint_ns"]),g=Ex(o.content),x={id:l,role:i,content:g};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const y=_x(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),m=d?{...d}:void 0;y&&Object.keys(y).length&&(x.additionalKwargs=y),m&&Object.keys(m).length&&(x.responseMetadata=m);const b=Ix((c==null?void 0:c.tool_calls)??o.tool_calls);if(b.length&&(x.content=[...x.content,...b]),i==="tool"){const S=Nx(o,x.content);S&&(x.content=S)}return x}function Ex(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Mc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Mc(e);return t?[t]:[]}return[]}function Mc(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=Mt(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=Mt(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 Dc(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=Mt(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 Dc(e,t){var s;const n=Mt(e,["id","call_id"])??t,r=Mt(e,["name"])??Mt(on(e.function),["name"]);if(!n||!r)return null;const o=Ax(e.args??e.arguments??((s=on(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Ix(e){return Array.isArray(e)?e.map((t,n)=>Dc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Nx(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 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 on(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Mt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function _x(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}function jx(e){return e.type!=="thread_info"&&e.type!=="token"}const Rx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Px(e,t){var n;switch(t.type){case"reset":return{messages:Ui(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Ui(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Ui(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return $c(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>$c(o,s),e):e}case"interrupt_response":return{...e,messages:Fc(e.messages),pendingInterrupt:null};default:return e}}function Lc(e=[]){const[t,n]=w.useReducer(Px,{...Rx,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 $c(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Lx(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??zc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Uc(d.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:g,newMeta:x,changed:y}=Ox(d.content,t.delta,h,p);if(!y)return e;const m={...d,content:g},b=os(l,c,m),S={...f,[a]:x};return{...e,messages:b,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??zc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.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 h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Bc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Hc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,g=(h==null?void 0:h.id)??`tool-${p}`,x=d[0]??p,y={type:"tool_call",id:x,name:c,args:t.args};if(h){const S=Vi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:S},k=f,C=k>=0?os(e.messages,k,T):e.messages,E=ss(T,d),R=Ki(e.toolIndex,g,E);return{...e,messages:C,toolIndex:R}}const m={id:g,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Vi(void 0,d.length?d:[x],c,t.args)},b=ss(m,d.length?d:[x]);return{...e,messages:[...e.messages,m],toolIndex:Ki(e.toolIndex,g,b)}}if(t.type==="tool_end"){const a=Bc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Hc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,g=ss(d,a);let x=t.output;if(typeof t.output=="string")try{const C=t.output.trim();(C.startsWith("{")||C.startsWith("["))&&(x=JSON.parse(C))}catch{x=t.output}const y={type:"text",text:typeof x=="string"?x:JSON.stringify(x)},m=(d==null?void 0:d.createdAt)??new Date().toISOString(),b=Vi(d??void 0,g.length?g:a,f),S={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:m,additionalKwargs:b},T=c>=0?os(e.messages,c,S):[...e.messages,S],k=ss(S,a.length?a:g);return{...e,messages:T,toolIndex:Ki(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Dx(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=ns(t),l=a.interrupt,c=a.latest,d=l===null?Fc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Ui(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function os(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Fc(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 zc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Bc(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 Wi(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 Vi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Wi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};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 ss(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Wi(e);for(const o of r)n.add(o);return Array.from(n)}function Ki(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 Hc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Wi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Uc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Ox(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??Uc(e);let l="",c=e.slice();if(s){const f=Mx(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??"",g={...h,text:p+l};c=[...c.slice(0,c.length-1),g]}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 Wc(e){return e.replace(/\s+/g," ").trim()}function Mx(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=Wc(e),o=Wc(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 os(e,r,s)}return e}function Lx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Vc(e={}){const t=w.useMemo(()=>zn(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,h]=w.useState(""),[p,g]=w.useState(null),[x,y]=w.useState(0),[m,b]=w.useState(!1),S=w.useRef(null),T=w.useRef(!0),k=w.useRef(0),C=w.useRef(null),E=w.useRef(null),R=w.useRef(null),_=w.useRef(null),j=w.useCallback(O=>{o(O)},[]),L=w.useCallback(()=>{h(""),g(null),d(null),E.current=null,R.current=null,_.current=null},[]),z=w.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=S.current)==null||O.abort(),S.current=null,C.current=null,l(!1),b(!1),k.current=0,y(0)},[]),V=w.useCallback((O,H,P)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),g(null),E.current=null,R.current=null,_.current=null;const W=new AbortController;S.current=W;let F=null,$=null,ne=!1;return C.current={threadId:O.threadId??null,headers:{}},(async()=>{var we,Ne,Z,ie,Te,ee,D,X,ae,fe,B,le,Q,Ae,ve,Re,Ve,Qe;const oe=et=>{var Se;try{const nt=JSON.parse(JSON.stringify(et));return(Se=nt==null?void 0:nt.payload)!=null&&Se.files_info&&Array.isArray(nt.payload.files_info)&&(nt.payload.files_info=nt.payload.files_info.map(ut=>({...ut,data:ut!=null&&ut.data?`<base64 ${String(ut.data).length} chars>`:ut==null?void 0:ut.data}))),nt}catch{return et}};try{let et={};try{if(r)et={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Le=window.__AUTH_TOKEN__,_t=((we=window.localStorage)==null?void 0:we.getItem("authToken"))||null;let yt=null;try{const Ce=(Ne=window.localStorage)==null?void 0:Ne.getItem("chat-settings");Ce&&(yt=((Z=JSON.parse(Ce))==null?void 0:Z.apiKey)||null)}catch{}const G=Le||_t||yt||null;G&&(et={Authorization:`Bearer ${G}`})}}catch{}console.debug("[use-chat] POST",t+n,oe(O));let Se={};if(typeof window<"u")try{const st=(ie=window.localStorage)==null?void 0:ie.getItem("authSessionId");st&&(Se={"X-Session-Id":st})}catch{}const nt={...et,...Se,...s.current},ut={"Content-Type":"application/json",Accept:"text/event-stream",...nt},rt=await fetch(t+n,{method:"POST",headers:ut,body:JSON.stringify(O),signal:W.signal,credentials:i});if(C.current&&(C.current.headers=nt),!rt.ok||!rt.body){const st=await rt.text().catch(()=>"");console.debug("[use-chat] non-OK response",rt.status,st==null?void 0:st.slice(0,500));const Le=`stream ${rt.status}${st?": "+st:""}`;throw(Te=P==null?void 0:P.onConnectionError)==null||Te.call(P,Le),ne=!0,F="error",$=Le,new Error(Le)}b(!0);const Ye=rt.body.getReader(),It=new TextDecoder;let dt="",kt=[];k.current=0,y(0);let Nt=0,tt=null;const He=()=>{if(kt.length){const st=kt.join("");kt=[],T.current&&h(Le=>Le+st)}tt=null},Tt=()=>{typeof window<"u"&&tt==null&&(tt=requestAnimationFrame(He))};let Vt=Date.now();const zt=setInterval(()=>{var st;if(Date.now()-Vt>6e4){const Le="Stream idle timeout";d(Le),F="error",$=Le,W.abort(),(st=P==null?void 0:P.onError)==null||st.call(P,Le)}},5e3),Kt=1024*1024;try{const st=rt.headers.get("X-Thread-Id")||rt.headers.get("x-thread-id"),Le=rt.headers.get("X-Thread-Created")||rt.headers.get("x-thread-created"),_t=st??null,yt=String(Le??"").toLowerCase()==="true";for(C.current&&!C.current.threadId&&(C.current={...C.current,threadId:_t}),(ee=P==null?void 0:P.onOpen)==null||ee.call(P,{threadId:_t,created:yt});;){const{value:G,done:Ce}=await Ye.read();if(Ce)break;dt+=It.decode(G,{stream:!0}),dt.length>Kt&&(dt="",console.warn("Stream buffer reset: exceeded 1MB"));let ge;for(;(ge=dt.indexOf(`
36
36
 
37
- `))>=0;){const xt=dt.slice(0,ge);dt=dt.slice(ge+2);const ft=Fx(xt);if(!ft)continue;let ht;try{ht=JSON.parse(ft)}catch{console.debug("[use-chat] malformed SSE:",ft.slice(0,200));continue}const Be=$x(ht)?ht.data:ht;Vt=Date.now();const Ft=Be.seq;if(Ft!==void 0){if(Ft<=Nt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Ft,lastProcessedSeq:Nt,type:Be.type});continue}Nt>0&&Ft>Nt+1&&((D=P==null?void 0:P.onGap)==null||D.call(P,{from:Nt,to:Ft})),Nt=Ft,k.current=Ft,y(Ft)}if(console.debug("[use-chat] received event",{seq:Be.seq,type:Be.type,preview:(()=>{var Oe;try{return Be.type==="message_delta"?{deltaTypes:(Oe=Be.delta)==null?void 0:Oe.map(it=>it.type),textLen:(Be.delta||[]).filter(it=>it.type==="text").map(it=>String(it.text||"").length)}:Be.content||Be.delta?{hasContent:!0}:{}}catch(it){return{err:String(it)}}})()}),Be.type==="checkpoint")E.current=Be.checkpointId??null,R.current=Be.checkpointNs??null,g(Be.checkpointId??null);else if(Be.type==="state_history"){_.current=Be;try{const it=ns(Be).latest;it&&(E.current=it.checkpointId??null,R.current=it.checkpointNs??null,g(it.checkpointId??null))}catch(Oe){console.warn("[use-chat] Failed to hydrate state_history payload",Oe)}}try{H==null||H(Be)}catch(Oe){console.error("[use-chat] Error in onEvent callback:",Oe,"for event:",Be.type)}if(Be.type==="token"&&e.autoAppendAssistant!==!1)kt.push(Be.content),Tt();else if(Be.type==="message_delta"){const Oe=Be.delta.filter(it=>it.type==="text").map(it=>it.text).join("");Oe&&e.autoAppendAssistant!==!1&&(kt.push(Oe),Tt())}else if(Be.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(G=P==null?void 0:P.onHeartbeat)==null||G.call(P,Be)}catch(Oe){console.warn("[use-chat] heartbeat callback failed",Oe)}}else if(tt!==null&&cancelAnimationFrame(tt),He(),Be.type==="checkpoint")g(Be.checkpointId);else if(Be.type==="error"){const Oe=Be;if(d(Oe.message),F="error",$=Oe.message,Oe.error_type==="auth_error"||Oe.code==="TOKEN_EXPIRED"||((ae=Oe.message)==null?void 0:ae.includes("token"))||((fe=Oe.message)==null?void 0:fe.includes("401"))||((B=Oe.message)==null?void 0:B.includes("unauthorized"))||((le=Oe.message)==null?void 0:le.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Oe.message);try{(Q=P==null?void 0:P.onAuthError)==null||Q.call(P,Oe.message)}catch(ar){console.warn("[use-chat] onAuthError handler failed",ar)}W.abort()}}}}He(),F===null&&!W.signal.aborted&&(F="complete")}catch(st){if(st.name==="AbortError")F=F??"aborted";else{const Le=st.message||String(st);F="error",$=Le,d(Le),(Ae=P==null?void 0:P.onError)==null||Ae.call(P,Le)}}finally{try{await Ye.cancel()}catch{}finally{(ve=Ye.releaseLock)==null||ve.call(Ye)}tt!==null&&typeof window<"u"&&window.cancelAnimationFrame(tt),clearInterval(zt)}}catch(et){if(et.name==="AbortError")F=F??"aborted";else{const Se=et.message||String(et);F="error",$=Se,d(Se),(Re=P==null?void 0:P.onError)==null||Re.call(P,Se),ne||((Ve=P==null?void 0:P.onConnectionError)==null||Ve.call(P,Se),ne=!0)}}finally{const et=k.current,Se=E.current,nt=R.current,ut=_.current,rt=F??(W.signal.aborted?"aborted":$?"error":"complete");try{(Qe=P==null?void 0:P.onClosed)==null||Qe.call(P,{reason:rt,lastSeq:et,lastCheckpointId:Se,lastCheckpointNs:nt,lastStateHistory:ut,error:$})}catch(Ye){console.warn("[use-chat] onClosed callback failed",Ye)}l(!1),b(!1),S.current=null,k.current=0,y(0),C.current=null}})(),{close:()=>W.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var O;T.current=!1,(O=S.current)==null||O.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:x,connected:m,stream:V,stop:z,clear:L,setToken:j}}function $x(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Fx(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 Kc=200;function zx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=w.useRef(null),d=w.useRef(null),f=w.useRef(new Map),h=w.useRef(null),p=w.useCallback(_=>{try{const j=globalThis.structuredClone;if(typeof j=="function")return j(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),g=w.useCallback((_,j)=>{if(!_)return;const L=f.current.get(_)??[],z=p(j),V=L.length>=Kc?[...L.slice(L.length-Kc+1),z]:[...L,z];f.current.set(_,V)},[p]),x=w.useCallback(_=>{_&&f.current.set(_,[])},[]),y=w.useCallback(_=>{const j=_??d.current;if(!j)return;const L=f.current.get(j);L!=null&&L.length&&L.forEach(z=>{try{n(z)}catch(V){console.error("[useChatStreamingService] Failed to replay buffered event",V)}})},[n]),m=w.useCallback(_=>{var z,V,O,H,P;const j=_.seq??null;if(j!==null){const W=c.current;if(W!==null){if(j<=W)return;j>W+1&&(o==null||o({from:W,to:j}))}c.current=j}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),x(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(W){console.error("[useChatStreamingService] Error in onThreadInfo handler:",W)}return}if(_.type==="heartbeat"){try{r==null||r(_)}catch(W){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",W)}return}if(_.type==="error"){const W=_;if(W.error_type==="auth_error"||W.code==="TOKEN_EXPIRED"||((z=W.message)==null?void 0:z.includes("token"))||((V=W.message)==null?void 0:V.includes("401"))||((O=W.message)==null?void 0:O.includes("unauthorized"))||((H=W.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",W.message);try{a==null||a(W.message)}catch($){console.warn("[useChatStreamingService] onAuthError handler failed",$)}}}const L=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((P=h.current)==null?void 0:P.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=L??d.current),jx(_)){_.type==="checkpoint"||_.type==="state_history"?x(L??null):g(L??null,_);try{n(_)}catch(W){console.error("[useChatStreamingService] Error in onMessageEvent handler:",W)}return}try{r==null||r(_)}catch(W){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",W)}},[g,x,n,o,t,r]),{stream:b,stop:S,isStreaming:T,error:k,setToken:C}=Vc({baseUrl:e,token:null}),E=w.useCallback((_,j)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:j,manualStop:!1,threadIdGuess:_.threadId??null},b(_,m,{onOpen:j==null?void 0:j.onOpen,onError:L=>{var z;(z=j==null?void 0:j.onError)==null||z.call(j,L)},onGap:(j==null?void 0:j.onGap)??o,onConnectionError:L=>{var z;i==null||i(L),(z=j==null?void 0:j.onConnectionError)==null||z.call(j,L)},onAuthError:L=>{var z;a==null||a(L),(z=j==null?void 0:j.onAuthError)==null||z.call(j,L)},onHeartbeat:L=>{var z;try{l==null||l(L)}catch(V){console.warn("[useChatStreamingService] onHeartbeat handler failed",V)}try{(z=j==null?void 0:j.onHeartbeat)==null||z.call(j,L)}catch(V){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",V)}},onClosed:L=>{var H,P,W,F;const z=((H=h.current)==null?void 0:H.manualStop)??!1,V=d.current??((P=h.current)==null?void 0:P.threadIdGuess)??((W=L.lastStateHistory)==null?void 0:W.threadId)??null;(L.reason==="complete"||L.reason==="aborted"&&z)&&x(V);const O={...L,threadId:V,manualStop:z};try{s==null||s(O)}catch($){console.warn("[useChatStreamingService] onStreamClosed handler failed",$)}try{(F=j==null?void 0:j.onClosed)==null||F.call(j,O)}catch($){console.warn("[useChatStreamingService] downstream onClosed handler failed",$)}h.current&&(h.current=null)}})},[x,m,a,i,l,o,s,b]),R=w.useCallback(()=>{h.current&&(h.current.manualStop=!0),S()},[S]);return w.useMemo(()=>({startStream:E,stop:R,isStreaming:T,error:k,setAuthToken:C,replayBufferedEvents:y}),[E,R,T,k,C,y])}function qi(e){return e==null?e:{...e}}function Bx(e){return e==null?e:{...e}}function Hx(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function Ux(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function hn(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=qi(e==null?void 0:e.metadata),s=qi(e==null?void 0:e.config),i=qi(e==null?void 0:e.parentConfig),a=Hx(e==null?void 0:e.next),l=Ux(e==null?void 0:e.tasks),c=Bx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function Wx(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function qc(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}const is=300;function Gc(e,t=is){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function xr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Gi(e){if(!xr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Xi(e,t){if(!xr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function Yi(e){if(xr())try{window.localStorage.removeItem(e)}catch{}}const Vx="cachedThreads",Kx="v1",Ji=200;function qx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function Zi(e,t){return`cachedThreads:v1:${e}:${qx(t||"anon")}`}function Gx(){const e=Gi(Vx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function Xx(e){const t=Gi(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function Qi(e,t){Xi(e,JSON.stringify(t))}function ea(e){const t=Xx(e);if(t.length>0)return t;const n=Gx();if(n.length>0)try{Qi(e,n.slice(0,Ji))}catch{}return n}function as(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function ta(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function na(e,t){return`${e}${t}`}function Yx(e,t){const n=Gi(na(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:hn(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function Jx(e,t,n=100){if(!xr())return;const r=hn(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=na(e,t.threadId),i=JSON.stringify(o);if(!Xi(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),Xi(s,i))break}catch{}}function Zx(e,t){Yi(na(e,t))}function Qx(e){if(xr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}const Xc=w.createContext(null),Yc=w.createContext(null),Jc=w.createContext(null),ey=w.createContext(!1),Zc=50,ty=750,ny=5,ry=1e3,oy=15e3;function Qc(e,t,n){return`${e}__${t??""}__${n??""}`}function ls(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 sy(e,t){return ls(e,t)}function iy(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 ay(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 eu(e,t){const n=ls(e.metadata,t.metadata),r=ls(e.config,t.config),o=ls(e.parentConfig,t.parentConfig),s=iy(e.next,t.next),i=ay(e.tasks,t.tasks),a=sy(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function ly({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Bi(),f=w.useMemo(()=>zn(d),[d]),h=w.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=w.useMemo(()=>`threadPayload:${Kx}:${h}:`,[h]),g=w.useCallback(N=>Yx(p,N),[p]),x=w.useCallback((N,A=100)=>{Jx(p,N,A)},[p]),y=w.useCallback(N=>{Zx(p,N)},[p]),m=w.useCallback(()=>{Qx(p)},[p]),[b,S]=w.useState(()=>{var N;return Zi(h,(N=c.getAuthToken)==null?void 0:N.call(c))}),[T,k]=w.useState(()=>{var A;const N=ea(Zi(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return as(N)}),C=w.useMemo(()=>ta(T),[T]),[E,R]=w.useState(t),[_,j]=w.useState(!1),[L,z]=w.useState(!1),[V,O]=w.useState(null),[H,P]=w.useState(null),[W,F]=w.useState(null),[$,ne]=w.useState([]),oe=w.useCallback(()=>{const N=ea(b);w.startTransition(()=>{k(as(N))})},[b]),[we,Ne]=w.useState(!1),[Z,ie]=w.useState(!1),[Te,ee]=w.useState(null),[D,G]=w.useState(void 0),[ae,fe]=w.useState(void 0),[B,le]=w.useState(void 0),{state:Q,dispatch:Ae,seed:ve,prepend:Re,pushUser:Ve,onEvent:Qe,reset:et}=Lc(),Se=w.useRef(E);w.useEffect(()=>{Se.current=E},[E]);const nt=w.useRef(!1),ut=w.useRef([]),rt=w.useRef(null),Ye=w.useRef(null),It=w.useRef(new Map),dt=w.useRef(E),kt=w.useRef(!1),Nt=w.useRef(null),tt=w.useRef(new Map),He=w.useRef(new Map),Tt=w.useRef(new Map),Vt=w.useRef(new Map),zt=w.useCallback(N=>{if(!N){ne([]);return}const A=tt.current.get(N);if(!A||!A.length){ne([]);return}ne(A.map(U=>hn(U,{cloneMessages:!0})))},[]);w.useEffect(()=>{zt(E)},[E,zt]);const Kt=w.useCallback(()=>{var K;const N=Vt.current;if(N.size<=Zc)return;const A=Array.from(N.entries()).sort((ce,re)=>ce[1].timestamp-re[1].timestamp),U=N.size-Zc;for(let ce=0;ce<U;ce++){const re=(K=A[ce])==null?void 0:K[0];re&&N.delete(re)}},[]),st=w.useCallback((N,A,U)=>{if(!N)return;const K=U==="replace"?[]:tt.current.get(N)??[],ce=U==="replace"?A:[...A,...K];if(!ce.length){U==="replace"&&tt.current.set(N,[]);return}const re=new Map;for(const Ge of ce){if(!(Ge!=null&&Ge.checkpointId))continue;const Ue=`${Ge.checkpointId}::${Ge.checkpointNs??""}`,bt=hn(Ge,{cloneMessages:!0}),At=re.get(Ue);if(!At){re.set(Ue,bt);continue}const Qt=eu(At,bt);re.set(Ue,{...At,...Qt})}const qe=Array.from(re.values()).sort((Ge,Ue)=>{const bt=Number.isFinite(Date.parse(Ge.createdAt??""))?Date.parse(Ge.createdAt??""):0;return(Number.isFinite(Date.parse(Ue.createdAt??""))?Date.parse(Ue.createdAt??""):0)-bt});tt.current.set(N,qe),N===Se.current&&zt(N)},[zt]),Le=w.useCallback((N,A,U)=>{if(!N)return;const K=He.current.get(N),ce=U==="replace"||!K?new Map:new Map(K);if(A&&typeof A=="object")for(const[re,qe]of Object.entries(A)){if(!(qe!=null&&qe.checkpointId))continue;const Ge=re||lo(qe.checkpointId,qe.checkpointNs??null);ce.set(Ge,hn(qe,{cloneMessages:!0}))}He.current.set(N,ce)},[]),_t=w.useCallback((N,A)=>{const{threadId:U,checkpointId:K=null,checkpointNs:ce=null}=N,re=Qc(U,K,ce);if(A!=null&&A.force)Tt.current.delete(re),Vt.current.delete(re);else{if(A!=null&&A.preferCache){const bt=Vt.current.get(re);if(bt)return Promise.resolve(bt.payload)}const Ue=Tt.current.get(re);if(Ue)return Ue}const Ge=c.getStateHistory({threadId:U,checkpointId:K??void 0,checkpointNs:ce??void 0}).then(Ue=>(Vt.current.set(re,{payload:Ue,timestamp:Date.now()}),Kt(),Ue)).finally(()=>{Tt.current.get(re)===Ge&&Tt.current.delete(re)});return Tt.current.set(re,Ge),Ge},[c,Kt]),yt=w.useCallback((N,A)=>new Promise((U,K)=>{const ce=async()=>{nt.current=!0;try{await N(),U()}catch(re){K(re)}finally{nt.current=!1;const re=ut.current.shift();re&&re().catch(()=>{})}};nt.current?ut.current.push(ce):ce().catch(re=>{K(re)})}),[]),X=w.useRef(C.length),Ce=w.useRef(!1);w.useEffect(()=>{X.current=C.length},[C.length]),w.useEffect(()=>{const N=Q.pendingInterrupt??Wx(Q.messages);qc(W,N)||F(N??null)},[W,Q.messages,Q.pendingInterrupt]);const ge=w.useCallback(async()=>{const N=X.current>0;N||j(!0);try{const A=await c.listThreads();w.startTransition(()=>{k(U=>{const K=qe=>qe.map(Ge=>`${Ge.threadId}:${Ge.updatedAt??""}:${Ge.messageCount??""}`).join("|"),ce=ta(U);return K(ce)===K(A)||A.length===0&&ce.length>0&&!Ce.current?U:as(A)})}),O(null),Ce.current||(Ce.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A))}finally{N||j(!1)}},[c,i]),xt=w.useRef(!1),ft=w.useRef(null),ht=w.useRef(null),Be=w.useRef(""),[Ft,Oe]=w.useState("idle"),it=w.useRef({attempts:0,timer:null,reason:null}),ar=w.useRef(null),jr=w.useRef(0),lr=w.useRef(()=>{}),Rr=w.useRef(()=>{}),Pr=w.useRef(()=>{}),Kn=w.useCallback((N,A)=>{if(!xr())return;ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null);const U=N.map(ce=>`${ce.threadId}:${ce.updatedAt??""}:${ce.messageCount??""}`).join("|");if(N.length===0){try{Yi(b)}catch{}Be.current="";return}if(U===Be.current)return;const K=()=>{try{const ce=N.slice(0,Ji);Qi(b,ce),Be.current=U}catch{}finally{ht.current=null}};if(A!=null&&A.immediate){K();return}ht.current=window.setTimeout(()=>{Gc(K)},is)},[b]),Qr=w.useCallback(()=>{Kn(C,{immediate:!0})},[Kn,C]),I=w.useCallback((N,A,U,K)=>{var Ol;const ce=U??Se.current;if(!ce)return;const re=hn(N),qe=ce===Se.current,Ge=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(Ge){const Ht={threadId:ce,snapshot:hn(N,{cloneMessages:!0})};It.current.set(ce,Ht),dt.current=ce}if(!qe)return;ve(re.messages,{checkpointId:re.checkpointId??null,checkpointNs:re.checkpointNs??null,pendingInterrupt:re.interrupt??null}),F(re.interrupt??null),ee(re.nextCursor??null),Ne(!!re.nextCursor),G(re.checkpointId??void 0),fe(re.checkpointNs??void 0),le(re.nextCursorNs??void 0);return}const Ue=It.current.get(ce),bt=(Ue==null?void 0:Ue.snapshot)??null,At=Array.isArray(bt==null?void 0:bt.messages)?bt.messages:[],Qt=hn(bt),Fn=Array.isArray(N==null?void 0:N.messages)?N.messages:[],Bt=new Set,Lt=[...Fn,...At].filter(Ht=>{const Ml=Ht==null?void 0:Ht.id;return Ml?Bt.has(Ml)?!1:(Bt.add(Ml),!0):!0}),Bo=eu(Qt,re),Ho={checkpointId:Qt.checkpointId??re.checkpointId??null,checkpointNs:Qt.checkpointNs??re.checkpointNs??null,createdAt:re.createdAt??Qt.createdAt??null,parentId:re.parentId??Qt.parentId??null,branchLabel:re.branchLabel??Qt.branchLabel??null,lastMessageId:((Ol=Lt[Lt.length-1])==null?void 0:Ol.id)??null,messagesLen:Lt.length,hasMessages:Lt.length>0,messages:Lt,nextCursor:re.nextCursor??Qt.nextCursor??null,nextCursorNs:re.nextCursorNs??Qt.nextCursorNs??null,interrupt:Qt.interrupt??re.interrupt??null,...Bo};if(It.current.set(ce,{threadId:ce,snapshot:hn(Ho,{cloneMessages:!0})}),!qe)return;Fn.length&&Re(Fn);const eo=N&&Object.prototype.hasOwnProperty.call(N,"checkpointId")?N.checkpointId:void 0,dr=N&&Object.prototype.hasOwnProperty.call(N,"checkpointNs")?N.checkpointNs:void 0,Or=N&&Object.prototype.hasOwnProperty.call(N,"nextCursor")?N.nextCursor:void 0,fr=N&&Object.prototype.hasOwnProperty.call(N,"nextCursorNs")?N.nextCursorNs:void 0;ee(Ht=>Or!==void 0?Or??Ht??null:Ht??null),Ne(Ht=>Or!==void 0?!!Or:Ht),G(Ht=>eo!==void 0?eo??Ht??void 0:Ht??void 0),fe(Ht=>dr!==void 0?dr??Ht??void 0:Ht??void 0),le(Ht=>fr!==void 0?fr??void 0:Ht)},[Re,ve,F]),q=w.useCallback(N=>{if(N.threadId!=null&&N.threadId!==Se.current)return;const A=hn(N.snapshot,{cloneMessages:!0});ve(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),F(A.interrupt??null),ee(A.nextCursor??null),Ne(!!A.nextCursor),G(A.checkpointId??void 0),fe(A.checkpointNs??void 0),le(A.nextCursorNs??void 0),dt.current=N.threadId,zt(N.threadId??Se.current??null)},[ve,F,zt]),ue=w.useCallback(N=>{if(!N)return;It.current.delete(N),y(N),tt.current.delete(N),He.current.delete(N),N===Se.current&&ne([]);const A=`${N}__`;for(const U of Tt.current.keys())U.startsWith(A)&&Tt.current.delete(U);for(const U of Vt.current.keys())U.startsWith(A)&&Vt.current.delete(U);dt.current===N&&(dt.current=null)},[y]),ke=w.useCallback(()=>{const N=Se.current;N&&ue(N),et([]),Ne(!1),ie(!1),ee(null),G(void 0),fe(void 0),le(void 0)},[ue,et]),Xe=w.useCallback(({from:N,to:A})=>{const U=Se.current;U&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${N} -> ${A}) for thread ${U}`)},[]),at=w.useCallback(N=>{const A=N.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:N.title,created:N.created,currentThreads:C.length});const U={threadId:A,title:N.title||`Thread ${A.slice(0,8)}`,createdAt:N.createdAt||new Date().toISOString(),updatedAt:N.updatedAt||new Date().toISOString(),messageCount:N.messageCount||0};Se.current!==A&&(!Se.current&&Q.messages.length<=1&&(Ye.current=A),R(A)),w.startTransition(()=>{k(K=>{const ce=K.byId[A];return ce?ce.title===U.title&&ce.updatedAt===U.updatedAt&&ce.messageCount===U.messageCount?K:{byId:{...K.byId,[A]:U},order:K.order}:{byId:{...K.byId,[A]:U},order:[A,...K.order]}})})},[Q.messages.length]),{startStream:Ke,stop:$e,isStreaming:jt,error:vt,setAuthToken:pt,replayBufferedEvents:qt}=zx({baseUrl:f,onThreadInfo:at,onMessageEvent:Qe,onUnhandledEvent:N=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${N.type}`,N)},onSequenceGap:Xe,onStreamClosed:N=>{lr.current(N)},onConnectionError:N=>{Rr.current(N)},onAuthError:a,onHeartbeat:N=>{Pr.current(N)}}),Gt=w.useCallback(()=>{const N=it.current;N.timer!==null&&(window.clearTimeout(N.timer),N.timer=null),N.reason=null},[]),J=w.useCallback((N,A)=>{Oe("connecting"),Ke(N,{onOpen:U=>{var K;Gt(),it.current.attempts=0,Oe("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,U)},onError:U=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,U)},onGap:(A==null?void 0:A.onGap)??Xe,onConnectionError:U=>{var K;Rr.current(U),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,U)},onHeartbeat:U=>{var K;Pr.current(U),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,U)},onClosed:U=>{var K;lr.current(U),(K=A==null?void 0:A.onClosed)==null||K.call(A,U)}})},[Gt,Xe,Oe,Ke]),de=w.useCallback(()=>{const N=Se.current;if(!N)return null;const A=ar.current,U=Q.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=Q.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,ce={};return U&&(ce.checkpointId=U),K&&(ce.checkpointNs=K),{threadId:N,checkpointId:U,checkpointNs:K,command:{kind:"resume",value:ce}}},[Q.lastCheckpointId,Q.lastCheckpointNs]),he=w.useCallback(N=>{const A=it.current;if(A.timer!==null)return;if(A.attempts>=ny){Oe("error");return}A.attempts+=1,A.reason=N;const U=Math.min(ry*Math.pow(2,A.attempts-1),oy);Oe("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=de();if(!K){Oe("error");return}qt(K.threadId??void 0),J(K)},U)},[de,qt,Oe,J]),wt=w.useCallback(N=>{if(ar.current=N,N.manualStop||N.reason==="complete"){Gt(),it.current.attempts=0,Oe("idle");return}if(N.error&&(N.error.includes("token")||N.error.includes("401")||N.error.includes("unauthorized")||N.error.includes("Unauthorized")||N.error.includes("TOKEN_EXPIRED")||N.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",N.error);try{a==null||a(N.error)}catch(U){console.error("[ChatSessionProvider] Error in onAuthError handler:",U)}return}(N.reason==="error"||N.reason==="aborted")&&he(`closed:${N.reason}`)},[Gt,he,Oe,a]),Ot=w.useCallback(N=>{console.warn("[ChatSessionProvider] Stream connection error:",N),he("connection-error")},[he]),an=w.useCallback(N=>{jr.current=Date.now(),Oe(A=>A==="reconnecting"?"connected":A)},[Oe]);lr.current=wt,Rr.current=Ot,Pr.current=an,w.useEffect(()=>()=>{Gt()},[Gt]);const qn=w.useCallback(()=>{Gt(),it.current.attempts=0,Oe("idle"),$e()},[Gt,Oe,$e]);w.useEffect(()=>{xt.current=jt},[jt]),w.useEffect(()=>{if(!xr())return;ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null);const N=C.map(U=>`${U.threadId}:${U.updatedAt??""}:${U.messageCount??""}`).join("|");if(C.length===0){try{Yi(b)}catch{}Be.current="";return}if(N===Be.current)return;const A=()=>{try{const U=C.slice(0,Ji);Qi(b,U),Be.current=N}catch{}finally{ht.current=null}};return ht.current=window.setTimeout(()=>{Gc(A),ht.current=null},is),()=>{ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null)}},[C,Kn]),w.useEffect(()=>{var K;const N=c.getAuthToken();pt(N);const A=ce=>{const re=Zi(h,ce);Nt.current!==re&&(Nt.current=re,kt.current=!1),S(re);const qe=ea(re);w.startTransition(()=>{k(as(qe))}),ce&&!kt.current&&(kt.current=!0)};A(N);const U=(K=c.onTokenChange)==null?void 0:K.call(c,ce=>{ce!==N&&(pt(ce),m(),Tt.current.clear(),Vt.current.clear(),A(ce))});return()=>{U==null||U()}},[c,h,pt,m]);const cr=w.useCallback(async N=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,U={threadId:A,title:N||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(ce=>({byId:{...ce.byId,[A]:U},order:[A,...ce.order]})),R(A);try{const ce=await c.createThread(N),re=typeof ce=="string"?ce:ce.threadId;return k(qe=>{const Ge=qe.byId[A];if(!Ge)return qe;const Ue={...qe.byId};delete Ue[A],Ue[re]={...Ge,threadId:re};const bt=qe.order.map(At=>At===A?re:At);return{byId:Ue,order:bt}}),R(re),setTimeout(()=>ge(),10),O(null),re}catch(ce){throw k(re=>{if(!re.byId[A])return re;const qe={...re.byId};delete qe[A];const Ge=re.order.filter(Ue=>Ue!==A);return{byId:qe,order:Ge}}),R(null),O(String(ce)),ce}},[c,ge]),Fo=w.useCallback(async N=>{try{await c.deleteThread(N);let A=null;k(U=>{if(!U.byId[N])return U;const K={...U.byId};delete K[N];const ce=U.order.filter(qe=>qe!==N),re={byId:K,order:ce};return A=ta(re),re}),A&&Kn(A,{immediate:!0}),ue(N),Se.current===N&&(Ye.current=N,R(null),Se.current=null,dt.current=null,ke()),await ge(),O(null)}catch(A){throw O(String(A)),A}},[c,ke,ue,ge,Kn]),Rm=w.useCallback(async(N,A)=>{try{await c.updateThread(N,A),k(U=>{const K=U.byId[N];return K?{byId:{...U.byId,[N]:{...K,title:A}},order:U.order}:U}),O(null)}catch(U){throw await ge(),O(String(U)),U}},[c,ge]),ur=w.useCallback(async(N,A,U,K=!1)=>{await yt(async()=>{if(Ye.current===N&&!K){Ye.current=null;return}if(rt.current===N&&!K)return;R(Bt=>Bt===N?Bt:N),Se.current=N;const qe=Qc(N,A??null,U??null),Ge=Vt.current.get(qe),Ue=!K&&!A&&!U&&Ge&&Date.now()-Ge.timestamp<ty,bt=!K&&!A&&!U;let At=!1;if(bt){const Bt=It.current.get(N);if(Bt)q(Bt),At=!0;else{const Lt=g(N);Lt&&(It.current.set(N,Lt),q(Lt),At=!0)}}const Qt=K||!At||!!A||!!U,Fn=async Bt=>{Bt&&z(!0),rt.current=N;try{const Lt=await _t({threadId:N,checkpointId:A,checkpointNs:U},{force:K}),{latest:Bo,checkpoints:Ho,snapshots:eo}=ns(Lt);I(Bo,"replace",N),st(N,Ho,"replace"),Le(N,eo,"replace"),P(null)}catch(Lt){throw(!At||K||Bt)&&(i==null||i(String(Lt))),P(String(Lt)),Lt}finally{rt.current=null,Bt&&z(!1)}};Qt?await Fn(!0):bt&&At&&!Ue&&Fn(!1).catch(Bt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Bt)})},`loadThread-${N}`)},[q,I,yt,_t,i,st,Le]),Pm=w.useCallback(async()=>{await yt(async()=>{const N=Se.current;N&&ue(N),Ye.current=null,R(null),Se.current=null,dt.current=null,ke(),G(void 0),fe(void 0),le(void 0),ne([]);try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[ke,ue,yt]),Om=w.useCallback(async(N,A)=>{var re;const U=Se.current;if(!U)throw new Error("No active thread");const K=lo(N,A??null),ce=(re=He.current.get(U))==null?void 0:re.get(K);if(ce){await yt(async()=>{I(ce,"replace",U,{persist:!1})},`navigateToCheckpoint-${U}-${K}`);return}await ur(U,N,A??void 0,!0)},[I,yt,ur]),Mm=w.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await ur(Se.current,void 0,void 0,!0)},[ur]),Dm=w.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(Z||!we)return;const N=Te;if(N){ie(!0);try{const A=Se.current,U=await _t({threadId:A,checkpointId:N??D??null,checkpointNs:B??ae??null}),{latest:K,checkpoints:ce,snapshots:re}=ns(U),qe=A?He.current.get(A):null;let Ge=ce.length>0;if(Ge&&qe&&qe.size>0&&(Ge=ce.some(Ue=>{if(!(Ue!=null&&Ue.checkpointId))return!1;const bt=lo(Ue.checkpointId,Ue.checkpointNs??null);return!qe.has(bt)})),!Ge){ee(null),le(void 0),Ne(!1),P(null);return}I(K,"prepend",A??void 0),A&&(st(A,ce,"prepend"),Le(A,re,"prepend")),P(null)}catch(A){throw P(String(A)),A}finally{ie(!1)}}},[I,_t,we,D,ae,B,Te,Z,st,Le]),Lm=w.useCallback(N=>{if(N!=null&&N.threadId){if(N.checkpointId){const A=lo(N.checkpointId,N.checkpointNs??null),U=hn({...N,interrupt:N.interrupt??null},{cloneMessages:!0});Le(N.threadId,{[A]:U},"prepend")}I(N,"replace",N.threadId)}},[I,Le]),zo=w.useCallback(async(N,A)=>{var Or;const U=Se.current,K=(N==null?void 0:N.text)??"",ce=(N==null?void 0:N.attachments)??[],re=ce.length?ce:(A==null?void 0:A.attachments)??[],qe=N==null?void 0:N.messageAdditionalKwargs,Ge={...(A==null?void 0:A.payloadExtras)??{},...(N==null?void 0:N.payload)??{}};if(!U&&!Object.keys(Ge).length&&re.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!U&&!Ge.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Ue,filesInfo:bt}=await mx(c,re),At=[...Ue];K&&K.trim()&&At.push({type:"text",text:K.trim()});const Qt=!!U,Fn=Qt?(A==null?void 0:A.checkpointId)??Q.lastCheckpointId??void 0:void 0,Bt=Qt?(A==null?void 0:A.checkpointNs)??Q.lastCheckpointNs??void 0:void 0,Lt={id:((Or=crypto.randomUUID)==null?void 0:Or.call(crypto))||`user-${Date.now()}`,role:"user",content:At,createdAt:new Date().toISOString(),...Fn!=null?{checkpointId:Fn}:{},...Bt!=null?{checkpointNs:Bt}:{}};qe&&Object.keys(qe).length&&(Lt.additionalKwargs={...Lt.additionalKwargs??{},...qe}),At.length>0&&Ve(Lt);const Bo={...Lt,content:At},Ho=re.length>0,eo={messages:At.length>0?[Bo]:[],files_info:bt,...o&&Ho&&s?{active_agent:s}:{},...Ge},dr={threadId:U??null,payload:eo,checkpointId:Fn??null,checkpointNs:Bt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};dr.threadId||delete dr.threadId,dr.command||delete dr.command,J(dr,{onError:fr=>{console.warn("[ChatSessionProvider] Stream error:",fr)},onOpen:({threadId:fr})=>{!Se.current&&fr&&(Q.messages.length<=1&&(Ye.current=fr),R(fr))},onGap:Xe})},[c,o,s,Xe,Q.lastCheckpointId,Q.lastCheckpointNs,Q.messages.length,Ve,J]),$m=w.useCallback(async(N,A,U)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const ce=A?U??!0:!1;try{try{Ae({type:"interrupt_response",payload:{interruptId:N}})}catch(re){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",re)}await zo({payload:{}},{checkpointId:Q.lastCheckpointId??void 0,checkpointNs:Q.lastCheckpointNs??void 0,command:{kind:"resume",value:ce}}),F(null)}catch(re){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${N}:`,re),re}},[Ae,Q.lastCheckpointId,Q.lastCheckpointNs,zo]);w.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(N){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",N)}},[E,l]),w.useEffect(()=>((async()=>{try{if(ge().catch(A=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",A),i==null||i(String(A))}),!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(R(A),n&&await ur(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else t&&n&&await ur(t)}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),w.useEffect(()=>{const N=Se.current;if(!N||dt.current!==N)return;Q.messages.length&&Q.messages[Q.messages.length-1];const A=hn({checkpointId:Q.lastCheckpointId??null,checkpointNs:Q.lastCheckpointNs??null,messages:Q.messages.slice(),nextCursor:Te??null,nextCursorNs:B??null,interrupt:Q.pendingInterrupt??W??null}),U=It.current.get(N),K=U==null?void 0:U.snapshot,ce=!K||K.messages.length!==A.messages.length||K.messages.some((Ue,bt)=>{var At;return(Ue==null?void 0:Ue.id)!==((At=A.messages[bt])==null?void 0:At.id)}),re=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,qe=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,Ge=!qc((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(ce||re||qe||Ge){const Ue={threadId:N,snapshot:A};It.current.set(N,Ue),ft.current&&window.clearTimeout(ft.current),ft.current=window.setTimeout(()=>{try{x(Ue,100)}catch(bt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",bt)}},is)}},[Te,B,Q.lastCheckpointId,Q.lastCheckpointNs,Q.messages,Q.pendingInterrupt,W,x]);const tT=w.useMemo(()=>({threads:C,currentThreadId:E,setCurrentThreadId:R,isLoading:_,error:V,actions:{createThread:cr,deleteThread:Fo,renameThread:Rm,refreshThreads:()=>ge()},persistThreadsCache:Qr,hydrateFromCache:oe}),[C,E,_,V,cr,Fo,Rm,ge,Qr,oe,R]),nT=w.useMemo(()=>{const N=Q.lastBranch??null,A=Q.assemblingId??null,U=N||A?{branchLabel:(N==null?void 0:N.branchLabel)??null,lastBranch:N,assemblingMessageId:A}:null;return{threadId:E,messages:Q.messages,interrupt:W,checkpoint:{id:Q.lastCheckpointId??null,namespace:Q.lastCheckpointNs??null},checkpoints:$,metadata:U,isLoading:L,isHistoryLoading:Z,error:H,hasMore:we,loadOlder:Dm,seedFromSnapshot:Lm,clearState:ke,navigateToCheckpoint:Om,returnToLatest:Mm,loadThread:ur,clearThread:Pm,respondToInterrupt:$m}},[Pm,ke,E,W,we,Z,L,Dm,ur,Q.assemblingId,Q.lastBranch,Q.lastCheckpointId,Q.lastCheckpointNs,Q.messages,Om,$m,Mm,Lm,H,$]),rT=w.useMemo(()=>({isStreaming:jt,error:vt,connectionState:Ft,submit:zo,send:zo,stop:qn,setAuthToken:pt}),[Ft,jt,vt,qn,zo,pt]);return u.jsx(ey.Provider,{value:!0,children:u.jsx(Jc.Provider,{value:rT,children:u.jsx(Xc.Provider,{value:tT,children:u.jsx(Yc.Provider,{value:nT,children:e})})})})}function cs(){const e=w.useContext(Xc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function us(){const e=w.useContext(Yc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function tu(){const e=w.useContext(Jc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function ds({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(hx,{apiConfig:t,children:u.jsx(ly,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function se(...e){return Hm.twMerge(Bm.clsx(e))}const cy=Uo.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"}}),lt=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?hr.Slot:"button";return u.jsx(i,{className:se(cy({variant:t,size:n,className:e})),ref:s,...o})});lt.displayName="Button";const nu=v.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}));nu.displayName="Textarea";function uy({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 g=i!==void 0,[x,y]=w.useState(e),m=(g?i:x)??"",[b,S]=w.useTransition(),T=w.useRef(null),k=w.useRef(0),C=w.useRef(null);w.useEffect(()=>{g||(y(e??""),C.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,g]);const E=w.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,m]);const R=w.useCallback((H,{fromUser:P})=>{g||y(H),P&&(a==null||a(H))},[g,a]),_=w.useCallback(async H=>{H&&H.preventDefault();const P=(m??"").trim();if(!P&&!p)return;const W=++k.current;C.current={id:W,shouldClear:!0},S(()=>{var F,$,ne;try{const oe=l(P);oe&&typeof oe.then=="function"?oe.then(()=>{var we,Ne;((we=C.current)==null?void 0:we.id)===W&&C.current.shouldClear&&(g||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((Ne=C.current)==null?void 0:Ne.id)===W&&(C.current=null)}).catch(()=>{var we;((we=C.current)==null?void 0:we.id)===W&&(C.current=null)}):(((F=C.current)==null?void 0:F.id)===W&&C.current.shouldClear&&(g||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),(($=C.current)==null?void 0:$.id)===W&&(C.current=null))}catch{((ne=C.current)==null?void 0:ne.id)===W&&(C.current=null)}})},[m,l,p,g,a]),j=w.useCallback(H=>{const P=H.target.value;R(P,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[R]),L=w.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`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:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(nu,{ref:T,value:m,onChange:j,onKeyDown:L,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(lt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(pe.Square,{size:16})}):u.jsx(lt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!m.trim()&&!p||b,children:u.jsx(pe.Send,{size:16})})})]})})}const dy=w.memo(uy),fs=0,Xn=1,$r=2,ru=4;function ou(e){return()=>e}function fy(e){e()}function su(e,t){return n=>e(t(n))}function iu(e,t){return()=>e(t)}function hy(e,t){return n=>e(t,n)}function ra(e){return e!==void 0}function py(...e){return()=>{e.map(fy)}}function Fr(){}function hs(e,t){return t(e),e}function my(e,t){return t(e)}function St(...e){return e}function ct(e,t){return e(Xn,t)}function ze(e,t){e(fs,t)}function oa(e){e($r)}function Pt(e){return e(ru)}function be(e,t){return ct(e,hy(t,fs))}function Cn(e,t){const n=e(Xn,r=>{n(),t(r)});return n}function au(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function lu(e,t){return e===t}function Ct(e=lu){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function je(e){return t=>n=>{e(n)&&t(n)}}function me(e){return t=>su(t,e)}function _n(e){return t=>()=>{t(e)}}function Y(e,...t){const n=gy(...t);return(r,o)=>{switch(r){case $r:oa(e);return;case Xn:return ct(e,n(o))}}}function jn(e,t){return n=>r=>{n(t=e(t,r))}}function yr(e){return t=>n=>{e>0?e--:t(n)}}function Bn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function We(...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);ct(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 gy(...e){return t=>e.reduceRight(my,t)}function xy(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Xn:return s?n===s?void 0:(r(),n=s,t=ct(e,s),t):(r(),Fr);case $r:r(),n=null;return}}}function te(e){let t=e;const n=Je();return(r,o)=>{switch(r){case fs:t=o;break;case Xn:{o(t);break}case ru:return t}return n(r,o)}}function Yt(e,t){return hs(te(t),n=>be(e,n))}function Je(){const e=[];return(t,n)=>{switch(t){case fs:e.slice().forEach(r=>{r(n)});return;case $r:e.splice(0,e.length);return;case Xn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function ln(e){return hs(Je(),t=>be(e,t))}function ot(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:yy(),singleton:n}}const yy=()=>Symbol();function vy(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 Dt(...e){const t=Je(),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);ct(s,l=>{n[i]=l,r=r|a,r===o&&ze(t,n)})}),function(s,i){switch(s){case $r:{oa(t);return}case Xn:return r===o&&i(n),ct(t,i)}}}function _e(e,t=lu){return Y(e,Ct(t))}function sa(...e){return function(t,n){switch(t){case $r:return;case Xn:return py(...e.map(r=>ct(r,n)))}}}var sn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(sn||{});const wy={0:"debug",3:"error",1:"log",2:"warn"},by=()=>typeof globalThis>"u"?window:globalThis,Yn=ot(()=>{const e=te(3);return{log:te((t,n,r=1)=>{var o;const s=(o=by().VIRTUOSO_LOG_LEVEL)!=null?o:Pt(e);r>=s&&console[wy[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function vr(e,t,n){return ia(e,t,n).callbackRef}function ia(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 Sy(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=Cy(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 g;p&&(g=h.ownerDocument.defaultView);const x=i?a?i.scrollLeft:i.scrollTop:p?a?g.scrollX||g.document.documentElement.scrollLeft:g.scrollY||g.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:p?a?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,m=i?a?i.offsetWidth:i.offsetHeight:p?a?g.innerWidth:g.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(x,0),viewportHeight:m}),s==null||s(a?cu("column-gap",getComputedStyle(d).columnGap,o):cu("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return ia(c,n,l)}function Cy(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},sn.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 cu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,sn.WARN),t==="normal"?0:parseInt(t??"0",10)}function uu(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,h;if(t){const p=t.getBoundingClientRect(),g=c.top-p.top;h=p.height-Math.max(0,g),f=g+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}=ia(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 en=ot(()=>{const e=Je(),t=Je(),n=te(0),r=Je(),o=te(0),s=Je(),i=Je(),a=te(0),l=te(0),c=te(0),d=te(0),f=Je(),h=Je(),p=te(!1),g=te(!1),x=te(!1);return be(Y(e,me(({scrollTop:y})=>y)),t),be(Y(e,me(({scrollHeight:y})=>y)),i),be(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:g,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:x,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),uo={lvl:0};function du(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 mt(e){return e===uo}function fo(e,t){if(!mt(e))return t===e.k?e.v:t<e.k?fo(e.l,t):fo(e.r,t)}function kn(e,t,n="k"){if(mt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=kn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return kn(e.l,t,n)}function cn(e,t,n){return mt(e)?pu(t,n,1):t===e.k?$t(e,{k:t,v:n}):t<e.k?mu($t(e,{l:cn(e.l,t,n)})):mu($t(e,{r:cn(e.r,t,n)}))}function zr(){return uo}function ps(e,t,n){if(mt(e))return[];const r=kn(e,t)[0];return ky(la(e,r,n))}function aa(e,t){if(mt(e))return uo;const{k:n,l:r,r:o}=e;if(t===n){if(mt(r))return o;if(mt(o))return r;{const[s,i]=hu(r);return ms($t(e,{k:s,l:fu(r),v:i}))}}else return t<n?ms($t(e,{l:aa(r,t)})):ms($t(e,{r:aa(o,t)}))}function wr(e){return mt(e)?[]:[...wr(e.l),{k:e.k,v:e.v},...wr(e.r)]}function la(e,t,n){if(mt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(la(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(la(s,t,n))),a}function ms(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(ca(t))return gu($t(e,{lvl:n-1}));if(!mt(t)&&!mt(t.r))return $t(t.r,{l:$t(t,{r:t.r.l}),lvl:n,r:$t(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(ca(e))return ua($t(e,{lvl:n-1}));if(!mt(r)&&!mt(r.l)){const o=r.l,s=ca(o)?r.lvl-1:r.lvl;return $t(o,{l:$t(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:ua($t(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function $t(e,t){return pu(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 fu(e){return mt(e.r)?e.l:ms($t(e,{r:fu(e.r)}))}function ca(e){return mt(e)||e.lvl>e.r.lvl}function hu(e){return mt(e.r)?[e.k,e.v]:hu(e.r)}function pu(e,t,n,r=uo,o=uo){return{k:e,l:r,lvl:n,r:o,v:t}}function mu(e){return ua(gu(e))}function gu(e){const{l:t}=e;return!mt(t)&&t.lvl===e.lvl?$t(t,{r:$t(e,{l:t.r})}):e}function ua(e){const{lvl:t,r:n}=e;return!mt(n)&&!mt(n.r)&&n.lvl===t&&n.r.lvl===t?$t(n,{l:$t(e,{r:n.l}),lvl:t+1}):e}function ky(e){return du(e,({k:t,v:n})=>({index:t,value:n}))}function xu(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function ho(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const da=ot(()=>({recalcInProgress:te(!1)}),[],{singleton:!0});function yu(e,t,n){return e[gs(e,t,n)]}function gs(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 Ty(e,t,n,r){const o=gs(e,t,r),s=gs(e,n,r,o);return e.slice(o,s+1)}function Jn(e,t){return Math.round(e.getBoundingClientRect()[t])}function xs(e){return!mt(e.groupOffsetTree)}function fa({index:e},t){return t===e?0:t<e?-1:1}function Ey(){return{groupIndices:[],groupOffsetTree:zr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:zr()}}function Iy(e,t){let n=mt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),mt(e)){e=cn(e,0,s);continue}const a=ps(e,i-1,o+1);if(a.some(Oy(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=aa(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=cn(e,o+1,h));c&&(e=cn(e,i,s))}return[e,n]}function Ny(e){return typeof e.groupIndex<"u"}function Ay({offset:e},t){return t===e?0:t<e?-1:1}function po(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=yu(t,e,fa),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function vu(e,t){if(!xs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function wu(e,t,n){if(Ny(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=vu(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function _y(e,t,n,r=0){return r>0&&(t=Math.max(t,yu(e,r,fa).offset)),du(Ty(e,t,n,Ay),Py)}function jy(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,sn.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&mt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((g,x)=>cn(cn(g,x,h),x+1,p),i)}else[i,a]=Iy(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=ha(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>cn(h,p,po(p,f,o)),zr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Ry(e){return wr(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 bu(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 ha(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=gs(o,t-1,fa),a=o[l].offset;const c=kn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===kn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of ps(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 Py(e){return{index:e.index,value:e}}function Oy(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 My={offsetHeight:"height",offsetWidth:"width"},Rn=ot(([{log:e},{recalcInProgress:t}])=>{const n=Je(),r=Je(),o=Yt(r,0),s=Je(),i=Je(),a=te(0),l=te([]),c=te(void 0),d=te(void 0),f=te((k,C)=>Jn(k,My[C])),h=te(void 0),p=te(0),g=Ey(),x=Yt(Y(n,We(l,e,p),jn(jy,g),Ct()),g),y=Yt(Y(l,Ct(),jn((k,C)=>({current:C,prev:k.current}),{current:[],prev:[]}),me(({prev:k})=>k)),[]);be(Y(l,je(k=>k.length>0),We(x,p),me(([k,C,E])=>{const R=k.reduce((_,j,L)=>cn(_,j,po(j,C.offsetTree,E)||L),zr());return{...C,groupIndices:k,groupOffsetTree:R}})),x),be(Y(r,We(x),je(([k,{lastIndex:C}])=>k<C),me(([k,{lastIndex:C,lastSize:E}])=>[{endIndex:C,size:E,startIndex:k}])),n),be(c,d);const m=Yt(Y(c,me(k=>k===void 0)),!0);be(Y(d,je(k=>k!==void 0&&mt(Pt(x).sizeTree)),me(k=>[{endIndex:0,size:k,startIndex:0}])),n);const b=ln(Y(n,We(x),jn(({sizes:k},[C,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:g}),me(k=>k.changed)));ct(Y(a,jn((k,C)=>({diff:k.prev-C,prev:C}),{diff:0,prev:0}),me(k=>k.diff)),k=>{const{groupIndices:C}=Pt(x);if(k>0)ze(t,!0),ze(s,k+bu(k,C));else if(k<0){const E=Pt(y);E.length>0&&(k-=bu(-k,E)),ze(i,k)}}),ct(Y(a,We(e)),([k,C])=>{k<0&&C("`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},sn.ERROR)});const S=ln(s);be(Y(s,We(x),me(([k,C])=>{const E=C.groupIndices.length>0,R=[],_=C.lastSize;if(E){const j=fo(C.sizeTree,0);let L=0,z=0;for(;L<k;){const O=C.groupIndices[z],H=C.groupIndices.length===z+1?1/0:C.groupIndices[z+1]-O-1;R.push({endIndex:O,size:j,startIndex:O}),R.push({endIndex:O+1+H-1,size:_,startIndex:O+1}),z++,L+=H+1}const V=wr(C.sizeTree);return L!==k&&V.shift(),V.reduce((O,{k:H,v:P})=>{let W=O.ranges;return O.prevSize!==0&&(W=[...O.ranges,{endIndex:H+k-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:H+k,prevSize:P,ranges:W}},{prevIndex:k,prevSize:0,ranges:R}).ranges}return wr(C.sizeTree).reduce((j,{k:L,v:z})=>({prevIndex:L+k,prevSize:z,ranges:[...j.ranges,{endIndex:L+k-1,size:j.prevSize,startIndex:j.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const T=ln(Y(i,We(x,p),me(([k,{offsetTree:C},E])=>{const R=-k;return po(R,C,E)})));return be(Y(i,We(x,p),me(([k,C,E])=>{if(C.groupIndices.length>0){if(mt(C.sizeTree))return C;let R=zr();const _=Pt(y);let j=0,L=0,z=0;for(;j<-k;){z=_[L];const V=_[L+1]-z-1;L++,j+=V+1}if(R=wr(C.sizeTree).reduce((V,{k:O,v:H})=>cn(V,Math.max(0,O+k),H),R),j!==-k){const V=fo(C.sizeTree,z);R=cn(R,0,V);const O=kn(C.sizeTree,-k+1)[1];R=cn(R,1,O)}return{...C,sizeTree:R,...ha(C.offsetTree,0,R,E)}}else{const R=wr(C.sizeTree).reduce((_,{k:j,v:L})=>cn(_,Math.max(0,j+k),L),zr());return{...C,sizeTree:R,...ha(C.offsetTree,0,R,E)}}})),x),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:x,statefulTotalCount:o,totalCount:r,trackItemSizes:m,unshiftWith:s}},St(Yn,da),{singleton:!0});function Dy(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Su=ot(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Je(),i=Je(),a=ln(Y(s,me(Dy)));return be(Y(a,me(l=>l.totalCount)),n),be(Y(a,me(l=>l.groupIndices)),e),be(Y(Dt(o,t,r),je(([l,c])=>xs(c)),me(([l,c,d])=>kn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),Ct(),me(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},St(Rn,en)),Zn=ot(([{log:e}])=>{const t=te(!1),n=ln(Y(t,je(r=>r),Ct()));return ct(t,r=>{r&&Pt(e)("props updated",{},sn.DEBUG)}),{didMount:n,propsReady:t}},St(Yn),{singleton:!0}),Ly=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Cu(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Ly)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const mo=ot(([{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=Je(),g=Je(),x=te(0);let y=null,m=null,b=null;function S(){y&&(y(),y=null),b&&(b(),b=null),m&&(clearTimeout(m),m=null),ze(l,!1)}return be(Y(p,We(n,f,r,x,a,i,h),We(e,s,o),me(([[T,k,C,E,R,_,j,L],z,V,O])=>{const H=Cu(T),{align:P,behavior:W,offset:F}=H,$=E-1,ne=wu(H,k,$);let oe=po(ne,k.offsetTree,z)+_;P==="end"?(oe+=V+kn(k.sizeTree,ne)[1]-C+O,ne===$&&(oe+=j)):P==="center"?oe+=(V+kn(k.sizeTree,ne)[1]-C+O)/2:oe-=R,F&&(oe+=F);const we=Ne=>{S(),Ne?(L("retrying to scroll to",{location:T},sn.DEBUG),ze(p,T)):(ze(g,!0),L("list did not change, scroll successful",{},sn.DEBUG))};if(S(),W==="smooth"){let Ne=!1;b=ct(t,Z=>{Ne=Ne||Z}),y=Cn(d,()=>{we(Ne)})}else y=Cn(Y(t,$y(150)),we);return m=setTimeout(()=>{S()},1200),ze(l,!0),L("scrolling from index to",{behavior:W,index:ne,top:oe},sn.DEBUG),{behavior:W,top:oe}})),c),{scrollTargetReached:g,scrollToIndex:p,topListHeight:x}},St(Rn,en,Yn),{singleton:!0});function $y(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function pa(e,t){e==0?t():requestAnimationFrame(()=>{pa(e-1,t)})}function ma(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const go=ot(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=te(!0),l=te(0),c=te(!0);return be(Y(i,We(l),je(([d,f])=>!!f),_n(!1)),a),be(Y(i,We(l),je(([d,f])=>!!f),_n(!1)),c),ct(Y(Dt(t,i),We(a,n,e,c),je(([[,d],f,{sizeTree:h},p,g])=>d&&(!mt(h)||ra(p))&&!f&&!g),We(l)),([,d])=>{Cn(o,()=>{ze(c,!0)}),pa(4,()=>{Cn(r,()=>{ze(a,!0)}),ze(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},St(Rn,en,mo,Zn),{singleton:!0});function ku(e,t){return Math.abs(e-t)<1.01}const xo="up",yo="down",Fy="none",zy={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},By=0,vo=ot(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=te(!1),a=te(!0),l=Je(),c=Je(),d=te(4),f=te(By),h=Yt(Y(sa(Y(_e(o),yr(1),_n(!0)),Y(_e(o),yr(1),_n(!1),au(100))),Ct()),!1),p=Yt(Y(sa(Y(n,_n(!0)),Y(n,_n(!1),au(200))),Ct()),!1);be(Y(Dt(_e(o),_e(f)),me(([b,S])=>b<=S),Ct()),a),be(Y(a,Bn(50)),c);const g=ln(Y(Dt(r,_e(s),_e(t),_e(e),_e(d)),jn((b,[{scrollHeight:S,scrollTop:T},k,C,E,R])=>{const _=T+k-S>-R,j={scrollHeight:S,scrollTop:T,viewportHeight:k};if(_){let z,V;return T>b.state.scrollTop?(z="SCROLLED_DOWN",V=b.state.scrollTop-T):(z="SIZE_DECREASED",V=b.state.scrollTop-T||b.scrollTopDelta),{atBottom:!0,atBottomBecause:z,scrollTopDelta:V,state:j}}let L;return j.scrollHeight>b.state.scrollHeight?L="SIZE_INCREASED":k<b.state.viewportHeight?L="VIEWPORT_HEIGHT_DECREASING":T<b.state.scrollTop?L="SCROLLING_UPWARDS":L="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:L,state:j}},zy),Ct((b,S)=>b&&b.atBottom===S.atBottom))),x=Yt(Y(r,jn((b,{scrollHeight:S,scrollTop:T,viewportHeight:k})=>{if(ku(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:T};{const C=S-(T+k)<1;return b.scrollTop!==T&&C?{changed:!0,jump:b.scrollTop-T,scrollHeight:S,scrollTop:T}:{changed:!0,jump:0,scrollHeight:S,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),je(b=>b.changed),me(b=>b.jump)),0);be(Y(g,me(b=>b.atBottom)),i),be(Y(i,Bn(50)),l);const y=te(yo);be(Y(r,me(({scrollTop:b})=>b),Ct(),jn((b,S)=>Pt(p)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?xo:yo,prevScrollTop:S},{direction:yo,prevScrollTop:0}),me(b=>b.direction)),y),be(Y(r,Bn(50),_n(Fy)),y);const m=te(0);return be(Y(h,je(b=>!b),_n(0)),m),be(Y(o,Bn(100),We(h),je(([b,S])=>!!S),jn(([b,S],[T])=>[S,T],[0,0]),me(([b,S])=>S-b)),m),{atBottomState:g,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:x,scrollDirection:y,scrollVelocity:m}},St(en)),ys="top",vs="bottom",Tu="none";function Eu(e,t,n){return typeof e=="number"?n===xo&&t===ys||n===yo&&t===vs?e:0:n===xo?t===ys?e.main:e.reverse:t===vs?e.main:e.reverse}function Iu(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const ga=ot(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Je(),i=te(0),a=te(0),l=te(0),c=Yt(Y(Dt(_e(r),_e(o),_e(n),_e(s,ho),_e(l),_e(i),_e(t),_e(e),_e(a)),me(([d,f,h,[p,g],x,y,m,b,S])=>{const T=d-b,k=y+m,C=Math.max(h-T,0);let E=Tu;const R=Iu(S,ys),_=Iu(S,vs);return p-=b,p+=h+m,g+=h+m,g-=b,p>d+k-R&&(E=xo),g<d-C+f+_&&(E=yo),E!==Tu?[Math.max(T-h-Eu(x,ys,E)-R,0),T-C-m+f+Eu(x,vs,E)+_]:null}),je(d=>d!=null),Ct(ho)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},St(en),{singleton:!0});function Hy(e,t,n){if(xs(t)){const r=vu(e,t);return[{index:kn(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 xa={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function ws(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 x=e[e.length-1];d=x.offset+x.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,g=h-d;return{bottom:d,firstItemIndex:s,items:Au(e,o,s),offsetBottom:g,offsetTop:c,top:p,topItems:Au(t,o,s),topListHeight:t.reduce((x,y)=>y.size+x,0),totalCount:n}}function Nu(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=ma(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return ws(c,[],a,o,n,r)}function Au(e,t,n){if(e.length===0)return[];if(!xs(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=ps(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 br=ot(([{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:g}])=>{const x=te([]),y=te(0),m=Je();be(s.topItemsIndexes,x);const b=Yt(Y(Dt(p,g,_e(l,ho),_e(o),_e(r),_e(c),d,_e(x),_e(t),_e(n),e),je(([C,E,,R,,,,,,,_])=>{const j=_&&_.length!==R;return C&&!E&&!j}),me(([,,[C,E],R,_,j,L,z,V,O,H])=>{const P=_,{offsetTree:W,sizeTree:F}=P,$=Pt(y);if(R===0)return{...xa,totalCount:R};if(C===0&&E===0)return $===0?{...xa,totalCount:R}:Nu($,j,_,V,O,H||[]);if(mt(F))return $>0?null:ws(Hy(ma(j,R),P,H),[],R,O,P,V);const ne=[];if(z.length>0){const ie=z[0],Te=z[z.length-1];let ee=0;for(const D of ps(F,ie,Te)){const G=D.value,ae=Math.max(D.start,ie),fe=Math.min(D.end,Te);for(let B=ae;B<=fe;B++)ne.push({data:H==null?void 0:H[B],index:B,offset:ee,size:G}),ee+=G}}if(!L)return ws([],ne,R,O,P,V);const oe=z.length>0?z[z.length-1]+1:0,we=_y(W,C,E,oe);if(we.length===0)return null;const Ne=R-1,Z=hs([],ie=>{for(const Te of we){const ee=Te.value;let D=ee.offset,G=Te.start;const ae=ee.size;if(ee.offset<C){G+=Math.floor((C-ee.offset+O)/(ae+O));const B=G-Te.start;D+=B*ae+B*O}G<oe&&(D+=(oe-G)*ae,G=oe);const fe=Math.min(Te.end,Ne);for(let B=G;B<=fe&&!(D>=E);B++)ie.push({data:H==null?void 0:H[B],index:B,offset:D,size:ae}),D+=ae+O}});return ws(Z,ne,R,O,P,V)}),je(C=>C!==null),Ct()),xa);be(Y(e,je(ra),me(C=>C==null?void 0:C.length)),o),be(Y(b,me(C=>C.topListHeight)),f),be(f,a),be(Y(b,me(C=>[C.top,C.bottom])),i),be(Y(b,me(C=>C.items)),m);const S=ln(Y(b,je(({items:C})=>C.length>0),We(o,e),je(([{items:C},E])=>C[C.length-1].originalIndex===E-1),me(([,C,E])=>[C-1,E]),Ct(ho),me(([C])=>C))),T=ln(Y(b,Bn(200),je(({items:C,topItems:E})=>C.length>0&&C[0].originalIndex===E.length),me(({items:C})=>C[0].index),Ct())),k=ln(Y(b,je(({items:C})=>C.length>0),me(({items:C})=>{let E=0,R=C.length-1;for(;C[E].type==="group"&&E<R;)E++;for(;C[R].type==="group"&&R>E;)R--;return{endIndex:C[R].index,startIndex:C[E].index}}),Ct(xu)));return{endReached:S,initialItemCount:y,itemsRendered:m,listState:b,rangeChanged:k,startReached:T,topItemsIndexes:x,...h}},St(Rn,Su,ga,go,mo,vo,Zn,da),{singleton:!0}),_u=ot(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Je(),i=Yt(Y(Dt(n,e,r,t,o),me(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return be(_e(i),s),{totalListHeight:i,totalListHeightChanged:s}},St(en,br),{singleton:!0}),Uy=ot(([{viewportHeight:e},{totalListHeight:t}])=>{const n=te(!1),r=Yt(Y(Dt(n,e,t),je(([o])=>o),me(([,o,s])=>Math.max(0,o-s)),Bn(0),Ct()),0);return{alignToBottom:n,paddingTopAddition:r}},St(en,_u),{singleton:!0}),ju=ot(()=>({context:te(null)})),Wy=({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,Ru=ot(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Je();return be(Y(d,We(t,l,n,s,o,r,a),We(e),me(([[f,h,p,g,x,y,m,b],S])=>{const{align:T,behavior:k,calculateViewLocation:C=Wy,done:E,...R}=f,_=wu(f,h,g-1),j=po(_,h.offsetTree,S)+x+y,L=j+kn(h.sizeTree,_)[1],z=b+y,V=b+p-m,O=C({itemBottom:L,itemTop:j,locationParams:{align:T,behavior:k,...R},viewportBottom:V,viewportTop:z});return O?E&&Cn(Y(i,je(H=>!H),yr(Pt(i)?1:2)),E):E&&E(),O}),je(f=>f!==null)),c),{scrollIntoView:d}},St(Rn,en,mo,br,Yn),{singleton:!0});function Pu(e){return e?e==="smooth"?"smooth":"auto":!1}const Vy=(e,t)=>typeof e=="function"?Pu(e(t)):t&&Pu(e),Ky=ot(([{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 g=te(!1),x=Je();let y=null;function m(k){ze(i,{align:"end",behavior:k,index:"LAST"})}ct(Y(Dt(Y(_e(t),yr(1)),l),We(_e(g),s,a,f),me(([[k,C],E,R,_,j])=>{let L=C&&_,z="auto";return L&&(z=Vy(E,R||j),L=L&&!!z),{followOutputBehavior:z,shouldFollow:L,totalCount:k}}),je(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:C})=>{y&&(y(),y=null),Pt(n)?requestAnimationFrame(()=>{Pt(d)("following output to ",{totalCount:C},sn.DEBUG),m(k)}):y=Cn(e,()=>{Pt(d)("following output to ",{totalCount:C},sn.DEBUG),m(k),y=null})});function b(k){const C=Cn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(Pt(d)("scrolling to bottom due to increased size",{},sn.DEBUG),m("auto"))});setTimeout(C,100)}ct(Y(Dt(_e(g),t,c),je(([k,,C])=>k&&C),jn(({value:k},[,C])=>({refreshed:k===C,value:C}),{refreshed:!1,value:0}),je(({refreshed:k})=>k),We(g,t)),([,k])=>{Pt(a)&&b(k!==!1)}),ct(x,()=>{b(Pt(g)!==!1)}),ct(Dt(_e(g),o),([k,C])=>{k&&!C.atBottom&&C.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&m("auto")});const S=te(null),T=Je();return be(sa(Y(_e(r),me(k=>{var C;return(C=k==null?void 0:k.length)!=null?C:0})),Y(_e(t))),T),ct(Y(Dt(Y(T,yr(1)),l),We(_e(S),a,f,h),me(([[k,C],E,R,_,j])=>C&&R&&(E==null?void 0:E({context:j,totalCount:k,scrollingInProgress:_}))),je(k=>!!k),Bn(0)),k=>{y&&(y(),y=null),Pt(n)?requestAnimationFrame(()=>{Pt(d)("scrolling into view",{}),ze(p,k)}):y=Cn(e,()=>{Pt(d)("scrolling into view",{}),ze(p,k),y=null})}),{autoscrollToBottom:x,followOutput:g,scrollIntoViewOnChange:S}},St(Rn,vo,mo,go,Zn,Yn,en,ju,Ru)),qy=ot(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(be(Y(a,We(s),je(([,l])=>l!==0),We(o,r,t,n,e),me(([[,l],c,d,f,h,p=[]])=>Nu(l,c,d,f,h,p))),i),{}),St(Rn,go,br,Zn),{singleton:!0}),Gy=ot(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=te(0);return ct(Y(e,We(r),je(([,o])=>o!==0),me(([,o])=>({top:o}))),o=>{Cn(Y(n,yr(1),je(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{ze(t,o)})})}),{initialScrollTop:r}},St(Zn,en,br),{singleton:!0}),Ou=ot(([{scrollVelocity:e}])=>{const t=te(!1),n=Je(),r=te(!1);return be(Y(e,We(r,t,n),je(([o,s])=>!!s),me(([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}),Ct()),t),ct(Y(Dt(t,e,n),We(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},St(vo),{singleton:!0}),ya=ot(([{scrollContainerState:e,scrollTo:t}])=>{const n=Je(),r=Je(),o=Je(),s=te(!1),i=te(void 0);return be(Y(Dt(n,r),me(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),be(Y(t,We(r),me(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},St(en)),Xy=ot(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Je(),d=te(void 0),f=te(null),h=te(null);return be(a,f),be(l,h),ct(Y(c,We(t,r,i,f,h,n)),([p,g,x,y,m,b,S])=>{const T=Ry(g.sizeTree);y&&m!==null&&b!==null&&(x=m.scrollTop-b.offsetTop),x-=S,p({ranges:T,scrollTop:x})}),be(Y(d,je(ra),me(Yy)),o),be(Y(s,We(d),je(([,p])=>p!==void 0),Ct(),me(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},St(Rn,en,go,Zn,ya));function Yy(e){return{align:"start",index:0,offset:e.scrollTop}}const Jy=ot(([{topItemsIndexes:e}])=>{const t=te(0);return be(Y(t,je(n=>n>=0),me(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},St(br));function Mu(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const Zy=Mu(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Qy=ot(([{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:g}])=>{const x=ln(Y(l,We(i),jn(([,m,b,S],[{bottom:T,items:k,offsetBottom:C,totalCount:E},R])=>{const _=T+C;let j=0;return b===E&&m.length>0&&k.length>0&&(k[0].originalIndex===0&&m[0].originalIndex===0||(j=_-S,j!==0&&(j+=R))),[j,k,E,_]},[0,[],0,0]),je(([m])=>m!==0),We(r,a,n,o,p,g),je(([,m,b,S,,,T])=>!T&&!S&&m!==0&&b===xo),me(([[m],,,,,b])=>(b("Upward scrolling compensation",{amount:m},sn.DEBUG),m))));function y(m){m>0?(ze(t,{behavior:"auto",top:-m}),ze(e,0)):(ze(e,0),ze(t,{behavior:"auto",top:-m}))}return ct(Y(x,We(e,s)),([m,b,S])=>{S&&Zy()?ze(e,b-m):y(-m)}),ct(Y(Dt(Yt(s,!1),e,g),je(([m,b,S])=>!m&&!S&&b!==0),me(([m,b])=>b),Bn(1)),y),be(Y(f,me(m=>({top:-m}))),t),ct(Y(c,We(h,d),me(([m,{groupIndices:b,lastSize:S,sizeTree:T},k])=>{function C(E){return E*(S+k)}if(b.length===0)return C(m);{let E=0;const R=fo(T,0);let _=0,j=0;for(;_<m;){_++,E+=R;let L=b.length===j+1?1/0:b[j+1]-b[j]-1;_+L>m&&(E-=R,L=m-_+1),_+=L,E+=C(L),j++}return E}})),m=>{ze(e,m),requestAnimationFrame(()=>{ze(t,{top:m}),requestAnimationFrame(()=>{ze(e,0),ze(g,!1)})})}),{deviation:e}},St(en,vo,br,Rn,Yn,da)),ev=ot(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),St(ga,qy,Zn,Ou,_u,Gy,Uy,ya,Ru,Yn,ju)),Du=ot(([{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:g},x,y,m,{listState:b,topItemsIndexes:S,...T},{scrollToIndex:k},C,{topItemCount:E},{groupCounts:R},_])=>(be(T.rangeChanged,_.scrollSeekRangeChanged),be(Y(_.windowViewportRect,me(j=>j.visibleHeight)),x.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:R,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:g,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...m,groupIndices:s,itemSize:i,listState:b,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,..._,...x,sizes:l,...y}),St(Rn,go,en,Xy,Ky,br,mo,Qy,Jy,Su,ev));function tv(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 bs=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Lu(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,m){y.propsReady&&ze(y.propsReady,!1);for(const b of r){const S=y[t.required[b]];ze(S,m[b])}for(const b of o)if(b in m){const S=y[t.optional[b]];ze(S,m[b])}y.propsReady&&ze(y.propsReady,!0)}function c(y){return s.reduce((m,b)=>(m[b]=S=>{const T=y[t.methods[b]];ze(T,S)},m),{})}function d(y){return i.reduce((m,b)=>(m[b]=xy(y[t.events[b]]),m),{})}const f=w.forwardRef((y,m)=>{const{children:b,...S}=y,[T]=w.useState(()=>hs(vy(e),E=>{l(E,S)})),[k]=w.useState(iu(d,T));bs(()=>{for(const E of i)E in S&&ct(k[E],S[E]);return()=>{Object.values(k).map(oa)}},[S,k,T]),bs(()=>{l(T,S)}),w.useImperativeHandle(m,ou(c(T)));const C=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(C,{...tv([...r,...o,...i],S),children:b}):b})}),h=y=>{const m=w.useContext(a);return w.useCallback(b=>{ze(m[y],b)},[m,y])},p=y=>{const m=w.useContext(a)[y],b=w.useCallback(S=>ct(m,S),[m]);return w.useSyncExternalStore(b,()=>Pt(m),()=>Pt(m))},g=y=>{const m=w.useContext(a)[y],[b,S]=w.useState(iu(Pt,m));return bs(()=>ct(m,T=>{T!==b&&S(ou(T))}),[m,b]),b},x=w.version.startsWith("18")?p:g;return{Component:f,useEmitter:(y,m)=>{const b=w.useContext(a)[y];bs(()=>ct(b,m),[m,b])},useEmitterValue:x,usePublisher:h}}const $u=w.createContext(void 0),Fu=w.createContext(void 0),zu=typeof document<"u"?w.useLayoutEffect:w.useEffect;function va(e){return"self"in e}function nv(e){return"body"in e}function Bu(e,t,n,r=Fr,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(h=>{let p,g,x;const y=h.target;if(nv(y)||va(y)){const b=va(y)?y:y.defaultView;x=s?b.scrollX:b.scrollY,p=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,g=s?b.innerWidth:b.innerHeight}else x=s?y.scrollLeft:y.scrollTop,p=s?y.scrollWidth:y.scrollHeight,g=s?y.offsetWidth:y.offsetHeight;const m=()=>{e({scrollHeight:p,scrollTop:Math.max(x,0),viewportHeight:g})};h.suppressFlushSync?m():Ti.flushSync(m),a.current!==null&&(x===a.current||x<=0||x===p-g)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.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 g=h.behavior==="smooth";let x,y,m;va(p)?(y=Math.max(Jn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),x=s?p.innerWidth:p.innerHeight,m=s?window.scrollX:window.scrollY):(y=p[s?"scrollWidth":"scrollHeight"],x=Jn(p,s?"width":"height"),m=p[s?"scrollLeft":"scrollTop"]);const b=y-x;if(h.top=Math.ceil(Math.max(Math.min(b,h.top),0)),ku(x,y)||h.top===m){e({scrollHeight:y,scrollTop:m,viewportHeight:x}),g&&t(!0);return}g?(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 wa="-webkit-sticky",Hu="sticky",ba=Mu(()=>{if(typeof document>"u")return Hu;const e=document.createElement("div");return e.style.position=wa,e.style.position===wa?wa:Hu});function Sa(e){return e}const rv=ot(()=>{const e=te(a=>`Item ${a}`),t=te(a=>`Group ${a}`),n=te({}),r=te(Sa),o=te("div"),s=te(Fr),i=(a,l=null)=>Yt(Y(n,me(c=>c[a]),Ct()),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")}}),ov=ot(([e,t])=>({...e,...t}),St(Du,rv)),sv=({height:e})=>u.jsx("div",{style:{height:e}}),iv={overflowAnchor:"none",position:ba(),zIndex:1},Uu={overflowAnchor:"none"},av={...Uu,display:"inline-block",height:"100%"},Wu=w.memo(function({showTopList:e=!1}){const t=Me("listState"),n=pn("sizeRanges"),r=Me("useWindowScroll"),o=Me("customScrollParent"),s=pn("windowScrollContainerState"),i=pn("scrollContainerState"),a=o||r?s:i,l=Me("itemContent"),c=Me("context"),d=Me("groupContent"),f=Me("trackItemSizes"),h=Me("itemSize"),p=Me("log"),g=pn("gap"),x=Me("horizontalDirection"),{callbackRef:y}=Sy(n,h,f,e?Fr:a,p,g,o,x,Me("skipAnimationFrameInResizeObserver")),[m,b]=w.useState(0);Ca("deviation",O=>{m!==O&&b(O)});const S=Me("EmptyPlaceholder"),T=Me("ScrollSeekPlaceholder")||sv,k=Me("ListComponent"),C=Me("ItemComponent"),E=Me("GroupComponent"),R=Me("computeItemKey"),_=Me("isSeeking"),j=Me("groupIndices").length>0,L=Me("alignToBottom"),z=Me("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginLeft:m!==0?m:L?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:m!==0?m:L?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...z?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...Jt(S,c)}):u.jsx(k,{...Jt(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:V,children:(e?t.topItems:t.items).map(O=>{const H=O.originalIndex,P=R(H+t.firstItemIndex,O.data,c);return _?w.createElement(T,{...Jt(T,c),height:O.size,index:O.index,key:P,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?w.createElement(E,{...Jt(E,c),"data-index":H,"data-item-index":O.index,"data-known-size":O.size,key:P,style:iv},d(O.index,c)):w.createElement(C,{...Jt(C,c),...dv(C,O.data),"data-index":H,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:P,style:x?av:Uu},j?l(O.index,O.groupIndex,O.data,c):l(O.index,O.data,c))})})}),lv={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},cv={outline:"none",overflowX:"auto",position:"relative"},Ss=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),uv={position:ba(),top:0,width:"100%",zIndex:1};function Jt(e,t){if(typeof e!="string")return{context:t}}function dv(e,t){return{item:typeof e=="string"?void 0:t}}const fv=w.memo(function(){const e=Me("HeaderComponent"),t=pn("headerHeight"),n=Me("HeaderFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,Me("skipAnimationFrameInResizeObserver")),o=Me("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null}),hv=w.memo(function(){const e=Me("FooterComponent"),t=pn("footerHeight"),n=Me("HeaderFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,Me("skipAnimationFrameInResizeObserver")),o=Me("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null});function Vu({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:h,scrollerRef:p,scrollToCallback:g}=Bu(a,c,l,d,void 0,f);return e("scrollTo",g),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?cv:lv,...o},tabIndex:0,...i,...Jt(l,s),children:r})})}function Ku({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"),h=t("customScrollParent"),p=w.useRef(null),g=t("scrollerRef"),{scrollByCallback:x,scrollerRef:y,scrollToCallback:m}=Bu(a,c,l,g,h);return zu(()=>{var b;return y.current=h||((b=p.current)==null?void 0:b.ownerDocument.defaultView),()=>{y.current=null}},[y,h]),e("windowScrollTo",m),e("scrollBy",x),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 pv=({children:e})=>{const t=w.useContext($u),n=pn("viewportHeight"),r=pn("fixedItemHeight"),o=Me("alignToBottom"),s=Me("horizontalDirection"),i=w.useMemo(()=>su(n,l=>Jn(l,s?"width":"height")),[n,s]),a=vr(i,!0,Me("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:Ss(o),children:e})},mv=({children:e})=>{const t=w.useContext($u),n=pn("windowViewportRect"),r=pn("fixedItemHeight"),o=Me("customScrollParent"),s=uu(n,o,Me("skipAnimationFrameInResizeObserver")),i=Me("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:Ss(i),children:e})},gv=({children:e})=>{const t=Me("TopItemListComponent")||"div",n=Me("headerHeight"),r={...uv,marginTop:`${n}px`},o=Me("context");return u.jsx(t,{style:r,...Jt(t,o),children:e})},xv=w.memo(function(e){const t=Me("useWindowScroll"),n=Me("topItemsIndexes").length>0,r=Me("customScrollParent"),o=Me("context");return u.jsxs(r||t?wv:vv,{...e,context:o,children:[n&&u.jsx(gv,{children:u.jsx(Wu,{showTopList:!0})}),u.jsxs(r||t?mv:pv,{children:[u.jsx(fv,{}),u.jsx(Wu,{}),u.jsx(hv,{})]})]})}),{Component:yv,useEmitter:Ca,useEmitterValue:Me,usePublisher:pn}=Lu(ov,{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"}},xv),vv=Vu({useEmitter:Ca,useEmitterValue:Me,usePublisher:pn}),wv=Ku({useEmitter:Ca,useEmitterValue:Me,usePublisher:pn}),bv=yv;St(Du,ot(()=>{const e=te(c=>u.jsxs("td",{children:["Item $",c]})),t=te(null),n=te(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=te(null),o=te(null),s=te({}),i=te(Sa),a=te(Fr),l=(c,d=null)=>Yt(Y(s,me(f=>f[c]),Ct()),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")}})),ba();const qu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Sv={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Gu,floor:Cs,max:wo,min:ka,round:Xu}=Math;function Yu(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Cv(e){return{...Sv,items:e}}function ks(e,t){return e&&e.width===t.width&&e.height===t.height}function kv(e,t){return e&&e.column===t.column&&e.row===t.row}const Tv=ot(([{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:g,propsReady:x},{customScrollParent:y,useWindowScroll:m,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T},k])=>{const C=te(0),E=te(0),R=te(qu),_=te({height:0,width:0}),j=te({height:0,width:0}),L=Je(),z=Je(),V=te(0),O=te(null),H=te({column:0,row:0}),P=Je(),W=Je(),F=te(!1),$=te(0),ne=te(!0),oe=te(!1),we=te(!1);ct(Y(g,We($),je(([D,G])=>!!G)),()=>{ze(ne,!1)}),ct(Y(Dt(g,ne,j,_,$,oe),je(([D,G,ae,fe,,B])=>D&&!G&&ae.height!==0&&fe.height!==0&&!B)),([,,,,D])=>{ze(oe,!0),pa(1,()=>{ze(L,D)}),Cn(Y(c),()=>{ze(t,[0,0]),ze(ne,!0)})}),be(Y(W,je(D=>D!=null&&D.scrollTop>0),_n(0)),E),ct(Y(g,We(W),je(([,D])=>D!=null)),([,D])=>{D&&(ze(_,D.viewport),ze(j,D.item),ze(H,D.gap),D.scrollTop>0&&(ze(F,!0),Cn(Y(c,yr(1)),G=>{ze(F,!1)}),ze(l,{top:D.scrollTop})))}),be(Y(_,me(({height:D})=>D)),f),be(Y(Dt(_e(_,ks),_e(j,ks),_e(H,(D,G)=>D&&D.column===G.column&&D.row===G.row),_e(c)),me(([D,G,ae,fe])=>({gap:ae,item:G,scrollTop:fe,viewport:D}))),P),be(Y(Dt(_e(C),r,_e(H,kv),_e(j,ks),_e(_,ks),_e(O),_e(E),_e(F),_e(ne),_e($)),je(([,,,,,,,D])=>!D),me(([D,[G,ae],fe,B,le,Q,Ae,,ve,Re])=>{const{column:Ve,row:Qe}=fe,{height:et,width:Se}=B,{width:nt}=le;if(Ae===0&&(D===0||nt===0))return qu;if(Se===0){const He=ma(Re,D),Tt=He+Math.max(Ae-1,0);return Cv(Yu(He,Tt,Q))}const ut=Ju(nt,Se,Ve);let rt,Ye;ve?G===0&&ae===0&&Ae>0?(rt=0,Ye=Ae-1):(rt=ut*Cs((G+Qe)/(et+Qe)),Ye=ut*Gu((ae+Qe)/(et+Qe))-1,Ye=ka(D-1,wo(Ye,ut-1)),rt=ka(Ye,wo(0,rt))):(rt=0,Ye=-1);const It=Yu(rt,Ye,Q),{bottom:dt,top:kt}=Zu(le,fe,B,It),Nt=Gu(D/ut),tt=Nt*et+(Nt-1)*Qe-dt;return{bottom:dt,itemHeight:et,items:It,itemWidth:Se,offsetBottom:tt,offsetTop:kt,top:kt}})),R),be(Y(O,je(D=>D!==null),me(D=>D.length)),C),be(Y(Dt(_,j,R,H),je(([D,G,{items:ae}])=>ae.length>0&&G.height!==0&&D.height!==0),me(([D,G,{items:ae},fe])=>{const{bottom:B,top:le}=Zu(D,fe,G,ae);return[le,B]}),Ct(ho)),t);const Ne=te(!1);be(Y(c,We(Ne),me(([D,G])=>G||D!==0)),Ne);const Z=ln(Y(Dt(R,C),je(([{items:D}])=>D.length>0),We(Ne),je(([[D,G],ae])=>{const fe=D.items[D.items.length-1].index===G-1;return(ae||D.bottom>0&&D.itemHeight>0&&D.offsetBottom===0&&D.items.length===G)&&fe}),me(([[,D]])=>D-1),Ct())),ie=ln(Y(_e(R),je(({items:D})=>D.length>0&&D[0].index===0),_n(0),Ct())),Te=ln(Y(_e(R),We(F),je(([{items:D},G])=>D.length>0&&!G),me(([{items:D}])=>({endIndex:D[D.length-1].index,startIndex:D[0].index})),Ct(xu),Bn(0)));be(Te,p.scrollSeekRangeChanged),be(Y(L,We(_,j,C,H),me(([D,G,ae,fe,B])=>{const le=Cu(D),{align:Q,behavior:Ae,offset:ve}=le;let Re=le.index;Re==="LAST"&&(Re=fe-1),Re=wo(0,Re,ka(fe-1,Re));let Ve=Ta(G,B,ae,Re);return Q==="end"?Ve=Xu(Ve-G.height+ae.height):Q==="center"&&(Ve=Xu(Ve-G.height/2+ae.height/2)),ve&&(Ve+=ve),{behavior:Ae,top:Ve}})),l);const ee=Yt(Y(R,me(D=>D.offsetBottom+D.bottom)),0);return be(Y(T,me(D=>({height:D.visibleHeight,width:D.visibleWidth}))),_),{customScrollParent:y,data:O,deviation:V,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:j,overscan:n,restoreStateFrom:W,scrollBy:i,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:L,scrollTop:c,smoothScrollTargetReached:d,totalCount:C,useWindowScroll:m,viewportDimensions:_,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T,...p,gridState:R,horizontalDirection:we,initialTopMostItemIndex:$,totalListHeight:ee,...h,endReached:Z,propsReady:x,rangeChanged:Te,startReached:ie,stateChanged:P,stateRestoreInProgress:F,...k}},St(ga,en,vo,Ou,Zn,ya,Yn));function Ju(e,t,n){return wo(1,Cs((e+n)/(Cs(t)+n)))}function Zu(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Ta(e,t,n,r[0].index);return{bottom:Ta(e,t,n,r[r.length-1].index)+o,top:s}}function Ta(e,t,n,r){const o=Ju(e.width,n.width,t.column),s=Cs(r/o),i=s*n.height+wo(0,s-1)*t.row;return i>0?i+t.row:i}const Ev=ot(()=>{const e=te(f=>`Item ${f}`),t=te({}),n=te(null),r=te("virtuoso-grid-item"),o=te("virtuoso-grid-list"),s=te(Sa),i=te("div"),a=te(Fr),l=(f,h=null)=>Yt(Y(t,me(p=>p[f]),Ct()),h),c=te(!1),d=te(!1);return be(_e(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")}}),Iv=ot(([e,t])=>({...e,...t}),St(Tv,Ev)),Nv=w.memo(function(){const e=Et("gridState"),t=Et("listClassName"),n=Et("itemClassName"),r=Et("itemContent"),o=Et("computeItemKey"),s=Et("isSeeking"),i=mn("scrollHeight"),a=Et("ItemComponent"),l=Et("ListComponent"),c=Et("ScrollSeekPlaceholder"),d=Et("context"),f=mn("itemDimensions"),h=mn("gap"),p=Et("log"),g=Et("stateRestoreInProgress"),x=mn("reportReadyState"),y=vr(w.useMemo(()=>m=>{const b=m.parentElement.parentElement.scrollHeight;i(b);const S=m.firstChild;if(S){const{height:T,width:k}=S.getBoundingClientRect();f({height:T,width:k})}h({column:ed("column-gap",getComputedStyle(m).columnGap,p),row:ed("row-gap",getComputedStyle(m).rowGap,p)})},[i,f,h,p]),!0,!1);return zu(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),g?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(m=>{const b=o(m.index,m.data,d);return s?u.jsx(c,{...Jt(c,d),height:e.itemHeight,index:m.index,width:e.itemWidth},b):w.createElement(a,{...Jt(a,d),className:n,"data-index":m.index,key:b},r(m.index,m.data,d))})})}),Av=w.memo(function(){const e=Et("HeaderComponent"),t=mn("headerHeight"),n=Et("headerFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,!1),o=Et("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null}),_v=w.memo(function(){const e=Et("FooterComponent"),t=mn("footerHeight"),n=Et("headerFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,!1),o=Et("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null}),jv=({children:e})=>{const t=w.useContext(Fu),n=mn("itemDimensions"),r=mn("viewportDimensions"),o=vr(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:Ss(!1),children:e})},Rv=({children:e})=>{const t=w.useContext(Fu),n=mn("windowViewportRect"),r=mn("itemDimensions"),o=Et("customScrollParent"),s=uu(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:Ss(!1),children:e})},Pv=w.memo(function({...e}){const t=Et("useWindowScroll"),n=Et("customScrollParent"),r=n||t?Mv:Ov,o=n||t?Rv:jv,s=Et("context");return u.jsx(r,{...e,...Jt(r,s),children:u.jsxs(o,{children:[u.jsx(Av,{}),u.jsx(Nv,{}),u.jsx(_v,{})]})})}),{useEmitter:Qu,useEmitterValue:Et,usePublisher:mn}=Lu(Iv,{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"}},Pv),Ov=Vu({useEmitter:Qu,useEmitterValue:Et,usePublisher:mn}),Mv=Ku({useEmitter:Qu,useEmitterValue:Et,usePublisher:mn});function ed(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,sn.WARN),t==="normal"?0:parseInt(t??"0",10)}const Dv=Uo.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 td({className:e,variant:t,...n}){return u.jsx("div",{className:se(Dv({variant:t}),e),...n})}const bo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));bo.displayName="Card";const So=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex flex-col space-y-1.5 p-6",e),...t}));So.displayName="CardHeader";const Co=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:se("text-2xl font-semibold leading-none tracking-tight",e),...t}));Co.displayName="CardTitle";const nd=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:se("text-sm text-muted-foreground",e),...t}));nd.displayName="CardDescription";const ko=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("p-6 pt-0",e),...t}));ko.displayName="CardContent";const rd=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex items-center p-6 pt-0",e),...t}));rd.displayName="CardFooter";const Lv=1,$v=1e6;let Ea=0;function Fv(){return Ea=(Ea+1)%Number.MAX_SAFE_INTEGER,Ea.toString()}const Ia=new Map,od=e=>{if(Ia.has(e))return;const t=setTimeout(()=>{Ia.delete(e),To({type:"REMOVE_TOAST",toastId:e})},$v);Ia.set(e,t)},zv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Lv)};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?od(n):e.toasts.forEach(r=>{od(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)}}},Ts=[];let Es={toasts:[]};function To(e){Es=zv(Es,e),Ts.forEach(t=>{t(Es)})}function Bv({...e}){const t=Fv(),n=o=>To({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>To({type:"DISMISS_TOAST",toastId:t});return To({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Na(){const[e,t]=v.useState(Es);return v.useEffect(()=>(Ts.push(t),()=>{const n=Ts.indexOf(t);n>-1&&Ts.splice(n,1)}),[e]),{...e,toast:Bv,dismiss:n=>To({type:"DISMISS_TOAST",toastId:n})}}async function sd(e,t){return await bn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function id(e,t){return await(await sd(`/files/${e}/view`,t)).text()}async function Hv(e,t){const n=await sd(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await bn(`/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 Uv(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await bn("/files",{params:r})}function Aa(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 ad(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Eo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Eo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(ad(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=Eo(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 Io(e){if(typeof e=="string")return e;if(ad(e))return"";try{const t=Eo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function Wv(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function Vv(e){const t=Io(e);return typeof e=="string"&&Wv(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=Aa(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 ye(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 ld(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _a(...e){return t=>{let n=!1;const r=e.map(o=>{const s=ld(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():ld(e[o],null)}}}}function Ze(...e){return v.useCallback(_a(...e),e)}function Kv(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 Hn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var m;const{scope:h,children:p,...g}=f,x=((m=h==null?void 0:h[e])==null?void 0:m[l])||a,y=v.useMemo(()=>g,Object.values(g));return u.jsx(x.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,g=v.useContext(p);if(g)return g;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,qv(o,...t)]}function qv(...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 Ut=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},Gv=v[" useId ".trim().toString()]||(()=>{}),Xv=0;function Un(e){const[t,n]=v.useState(Gv());return Ut(()=>{n(r=>r??String(Xv++))},[e]),e||(t?`radix-${t}`:"")}var Yv=v[" useInsertionEffect ".trim().toString()]||Ut;function Br({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Jv({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=Zv(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 Jv({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return Yv(()=>{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 Zv(e){return typeof e=="function"}var Qv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=Qv.reduce((e,t)=>{const n=hr.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 cd(e,t){e&&Wo.flushSync(()=>e.dispatchEvent(t))}function Wt(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 ew(e,t=globalThis==null?void 0:globalThis.document){const n=Wt(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 tw="DismissableLayer",ja="dismissableLayer.update",nw="dismissableLayer.pointerDownOutside",rw="dismissableLayer.focusOutside",ud,dd=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ns=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(dd),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),g=Ze(t,E=>f(E)),x=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),m=x.indexOf(y),b=d?x.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,T=b>=m,k=iw(E=>{const R=E.target,_=[...c.branches].some(j=>j.contains(R));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=aw(E=>{const R=E.target;[...c.branches].some(j=>j.contains(R))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return ew(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(ud=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),fd(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=ud)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),fd())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(ja,E),()=>document.removeEventListener(ja,E)},[]),u.jsx(De.div,{...l,ref:g,style:{pointerEvents:S?T?"auto":"none":void 0,...e.style},onFocusCapture:ye(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ye(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ye(e.onPointerDownCapture,k.onPointerDownCapture)})});Ns.displayName=tw;var ow="DismissableLayerBranch",sw=v.forwardRef((e,t)=>{const n=v.useContext(dd),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});sw.displayName=ow;function iw(e,t=globalThis==null?void 0:globalThis.document){const n=Wt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){hd(nw,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 aw(e,t=globalThis==null?void 0:globalThis.document){const n=Wt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&hd(rw,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 fd(){const e=new CustomEvent(ja);document.dispatchEvent(e)}function hd(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?cd(o,s):o.dispatchEvent(s)}var Ra="focusScope.autoFocusOnMount",Pa="focusScope.autoFocusOnUnmount",pd={bubbles:!1,cancelable:!0},lw="FocusScope",As=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=Wt(o),d=Wt(s),f=v.useRef(null),h=Ze(t,x=>l(x)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let x=function(S){if(p.paused||!a)return;const T=S.target;a.contains(T)?f.current=T:Qn(f.current,{select:!0})},y=function(S){if(p.paused||!a)return;const T=S.relatedTarget;T!==null&&(a.contains(T)||Qn(f.current,{select:!0}))},m=function(S){if(document.activeElement===document.body)for(const k of S)k.removedNodes.length>0&&Qn(a)};document.addEventListener("focusin",x),document.addEventListener("focusout",y);const b=new MutationObserver(m);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",y),b.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){xd.add(p);const x=document.activeElement;if(!a.contains(x)){const m=new CustomEvent(Ra,pd);a.addEventListener(Ra,c),a.dispatchEvent(m),m.defaultPrevented||(cw(pw(md(a)),{select:!0}),document.activeElement===x&&Qn(a))}return()=>{a.removeEventListener(Ra,c),setTimeout(()=>{const m=new CustomEvent(Pa,pd);a.addEventListener(Pa,d),a.dispatchEvent(m),m.defaultPrevented||Qn(x??document.body,{select:!0}),a.removeEventListener(Pa,d),xd.remove(p)},0)}}},[a,c,d,p]);const g=v.useCallback(x=>{if(!n&&!r||p.paused)return;const y=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,m=document.activeElement;if(y&&m){const b=x.currentTarget,[S,T]=uw(b);S&&T?!x.shiftKey&&m===T?(x.preventDefault(),n&&Qn(S,{select:!0})):x.shiftKey&&m===S&&(x.preventDefault(),n&&Qn(T,{select:!0})):m===b&&x.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});As.displayName=lw;function cw(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qn(r,{select:t}),document.activeElement!==n)return}function uw(e){const t=md(e),n=gd(t,e),r=gd(t.reverse(),e);return[n,r]}function md(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 gd(e,t){for(const n of e)if(!dw(n,{upTo:t}))return n}function dw(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 fw(e){return e instanceof HTMLInputElement&&"select"in e}function Qn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fw(e)&&t&&e.select()}}var xd=hw();function hw(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=yd(e,t),e.unshift(t)},remove(t){var n;e=yd(e,t),(n=e[0])==null||n.resume()}}}function yd(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pw(e){return e.filter(t=>t.tagName!=="A")}var mw="Portal",_s=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Ut(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ti.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});_s.displayName=mw;function gw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var gn=e=>{const{present:t,children:n}=e,r=xw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Ze(r.ref,yw(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};gn.displayName="Presence";function xw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=gw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=js(r.current);s.current=a==="mounted"?c:"none"},[a]),Ut(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=js(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]),Ut(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const x=js(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(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)})}},h=p=>{p.target===t&&(s.current=js(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 js(e){return(e==null?void 0:e.animationName)||"none"}function yw(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 Oa=0;function Ma(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??vd()),document.body.insertAdjacentElement("beforeend",e[1]??vd()),Oa++,()=>{Oa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Oa--}},[])}function vd(){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 Pn=function(){return Pn=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},Pn.apply(this,arguments)};function wd(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 vw(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 Rs="right-scroll-bar-position",Ps="width-before-scroll-bar",ww="with-scroll-bars-hidden",bw="--removed-body-scroll-bar-size";function Da(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Sw(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 Cw=typeof window<"u"?v.useLayoutEffect:v.useEffect,bd=new WeakMap;function kw(e,t){var n=Sw(null,function(r){return e.forEach(function(o){return Da(o,r)})});return Cw(function(){var r=bd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Da(a,null)}),s.forEach(function(a){o.has(a)||Da(a,i)})}bd.set(n,e)},[e]),n}function Tw(e){return e}function Ew(e,t){t===void 0&&(t=Tw);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 Iw(e){e===void 0&&(e={});var t=Ew(null);return t.options=Pn({async:!0,ssr:!1},e),t}var Sd=function(e){var t=e.sideCar,n=wd(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,Pn({},n))};Sd.isSideCarExport=!0;function Nw(e,t){return e.useMedium(t),Sd}var Cd=Iw(),La=function(){},Os=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:La,onWheelCapture:La,onTouchMoveCapture:La}),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,g=e.noIsolation,x=e.inert,y=e.allowPinchZoom,m=e.as,b=m===void 0?"div":m,S=e.gapMode,T=wd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,C=kw([n,t]),E=Pn(Pn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:Cd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:g,inert:x,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),Pn(Pn({},E),{ref:C})):v.createElement(b,Pn({},E,{className:l,ref:C}),a))});Os.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Os.classNames={fullWidth:Ps,zeroRight:Rs};var Aw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function _w(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Aw();return t&&e.setAttribute("nonce",t),e}function jw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Rw(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Pw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=_w())&&(jw(t,n),Rw(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ow=function(){var e=Pw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},kd=function(){var e=Ow(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Mw={left:0,top:0,right:0,gap:0},$a=function(e){return parseInt(e||"",10)||0},Dw=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[$a(n),$a(r),$a(o)]},Lw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Mw;var t=Dw(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])}},$w=kd(),Hr="data-scroll-locked",Fw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
37
+ `))>=0;){const xt=dt.slice(0,ge);dt=dt.slice(ge+2);const ft=Fx(xt);if(!ft)continue;let ht;try{ht=JSON.parse(ft)}catch{console.debug("[use-chat] malformed SSE:",ft.slice(0,200));continue}const Be=$x(ht)?ht.data:ht;Vt=Date.now();const Ft=Be.seq;if(Ft!==void 0){if(Ft<=Nt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Ft,lastProcessedSeq:Nt,type:Be.type});continue}Nt>0&&Ft>Nt+1&&((D=P==null?void 0:P.onGap)==null||D.call(P,{from:Nt,to:Ft})),Nt=Ft,k.current=Ft,y(Ft)}if(console.debug("[use-chat] received event",{seq:Be.seq,type:Be.type,preview:(()=>{var Oe;try{return Be.type==="message_delta"?{deltaTypes:(Oe=Be.delta)==null?void 0:Oe.map(it=>it.type),textLen:(Be.delta||[]).filter(it=>it.type==="text").map(it=>String(it.text||"").length)}:Be.content||Be.delta?{hasContent:!0}:{}}catch(it){return{err:String(it)}}})()}),Be.type==="checkpoint")E.current=Be.checkpointId??null,R.current=Be.checkpointNs??null,g(Be.checkpointId??null);else if(Be.type==="state_history"){_.current=Be;try{const it=ns(Be).latest;it&&(E.current=it.checkpointId??null,R.current=it.checkpointNs??null,g(it.checkpointId??null))}catch(Oe){console.warn("[use-chat] Failed to hydrate state_history payload",Oe)}}try{H==null||H(Be)}catch(Oe){console.error("[use-chat] Error in onEvent callback:",Oe,"for event:",Be.type)}if(Be.type==="token"&&e.autoAppendAssistant!==!1)kt.push(Be.content),Tt();else if(Be.type==="message_delta"){const Oe=Be.delta.filter(it=>it.type==="text").map(it=>it.text).join("");Oe&&e.autoAppendAssistant!==!1&&(kt.push(Oe),Tt())}else if(Be.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(X=P==null?void 0:P.onHeartbeat)==null||X.call(P,Be)}catch(Oe){console.warn("[use-chat] heartbeat callback failed",Oe)}}else if(tt!==null&&cancelAnimationFrame(tt),He(),Be.type==="checkpoint")g(Be.checkpointId);else if(Be.type==="error"){const Oe=Be;if(d(Oe.message),F="error",$=Oe.message,Oe.error_type==="auth_error"||Oe.code==="TOKEN_EXPIRED"||((ae=Oe.message)==null?void 0:ae.includes("token"))||((fe=Oe.message)==null?void 0:fe.includes("401"))||((B=Oe.message)==null?void 0:B.includes("unauthorized"))||((le=Oe.message)==null?void 0:le.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Oe.message);try{(Q=P==null?void 0:P.onAuthError)==null||Q.call(P,Oe.message)}catch(ar){console.warn("[use-chat] onAuthError handler failed",ar)}W.abort()}}}}He(),F===null&&!W.signal.aborted&&(F="complete")}catch(st){if(st.name==="AbortError")F=F??"aborted";else{const Le=st.message||String(st);F="error",$=Le,d(Le),(Ae=P==null?void 0:P.onError)==null||Ae.call(P,Le)}}finally{try{await Ye.cancel()}catch{}finally{(ve=Ye.releaseLock)==null||ve.call(Ye)}tt!==null&&typeof window<"u"&&window.cancelAnimationFrame(tt),clearInterval(zt)}}catch(et){if(et.name==="AbortError")F=F??"aborted";else{const Se=et.message||String(et);F="error",$=Se,d(Se),(Re=P==null?void 0:P.onError)==null||Re.call(P,Se),ne||((Ve=P==null?void 0:P.onConnectionError)==null||Ve.call(P,Se),ne=!0)}}finally{const et=k.current,Se=E.current,nt=R.current,ut=_.current,rt=F??(W.signal.aborted?"aborted":$?"error":"complete");try{(Qe=P==null?void 0:P.onClosed)==null||Qe.call(P,{reason:rt,lastSeq:et,lastCheckpointId:Se,lastCheckpointNs:nt,lastStateHistory:ut,error:$})}catch(Ye){console.warn("[use-chat] onClosed callback failed",Ye)}l(!1),b(!1),S.current=null,k.current=0,y(0),C.current=null}})(),{close:()=>W.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var O;T.current=!1,(O=S.current)==null||O.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:x,connected:m,stream:V,stop:z,clear:L,setToken:j}}function $x(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Fx(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 Kc=200;function zx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=w.useRef(null),d=w.useRef(null),f=w.useRef(new Map),h=w.useRef(null),p=w.useCallback(_=>{try{const j=globalThis.structuredClone;if(typeof j=="function")return j(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),g=w.useCallback((_,j)=>{if(!_)return;const L=f.current.get(_)??[],z=p(j),V=L.length>=Kc?[...L.slice(L.length-Kc+1),z]:[...L,z];f.current.set(_,V)},[p]),x=w.useCallback(_=>{_&&f.current.set(_,[])},[]),y=w.useCallback(_=>{const j=_??d.current;if(!j)return;const L=f.current.get(j);L!=null&&L.length&&L.forEach(z=>{try{n(z)}catch(V){console.error("[useChatStreamingService] Failed to replay buffered event",V)}})},[n]),m=w.useCallback(_=>{var z,V,O,H,P;const j=_.seq??null;if(j!==null){const W=c.current;if(W!==null){if(j<=W)return;j>W+1&&(o==null||o({from:W,to:j}))}c.current=j}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),x(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(W){console.error("[useChatStreamingService] Error in onThreadInfo handler:",W)}return}if(_.type==="heartbeat"){try{r==null||r(_)}catch(W){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",W)}return}if(_.type==="error"){const W=_;if(W.error_type==="auth_error"||W.code==="TOKEN_EXPIRED"||((z=W.message)==null?void 0:z.includes("token"))||((V=W.message)==null?void 0:V.includes("401"))||((O=W.message)==null?void 0:O.includes("unauthorized"))||((H=W.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",W.message);try{a==null||a(W.message)}catch($){console.warn("[useChatStreamingService] onAuthError handler failed",$)}}}const L=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((P=h.current)==null?void 0:P.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=L??d.current),jx(_)){_.type==="checkpoint"||_.type==="state_history"?x(L??null):g(L??null,_);try{n(_)}catch(W){console.error("[useChatStreamingService] Error in onMessageEvent handler:",W)}return}try{r==null||r(_)}catch(W){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",W)}},[g,x,n,o,t,r]),{stream:b,stop:S,isStreaming:T,error:k,setToken:C}=Vc({baseUrl:e,token:null}),E=w.useCallback((_,j)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:j,manualStop:!1,threadIdGuess:_.threadId??null},b(_,m,{onOpen:j==null?void 0:j.onOpen,onError:L=>{var z;(z=j==null?void 0:j.onError)==null||z.call(j,L)},onGap:(j==null?void 0:j.onGap)??o,onConnectionError:L=>{var z;i==null||i(L),(z=j==null?void 0:j.onConnectionError)==null||z.call(j,L)},onAuthError:L=>{var z;a==null||a(L),(z=j==null?void 0:j.onAuthError)==null||z.call(j,L)},onHeartbeat:L=>{var z;try{l==null||l(L)}catch(V){console.warn("[useChatStreamingService] onHeartbeat handler failed",V)}try{(z=j==null?void 0:j.onHeartbeat)==null||z.call(j,L)}catch(V){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",V)}},onClosed:L=>{var H,P,W,F;const z=((H=h.current)==null?void 0:H.manualStop)??!1,V=d.current??((P=h.current)==null?void 0:P.threadIdGuess)??((W=L.lastStateHistory)==null?void 0:W.threadId)??null;(L.reason==="complete"||L.reason==="aborted"&&z)&&x(V);const O={...L,threadId:V,manualStop:z};try{s==null||s(O)}catch($){console.warn("[useChatStreamingService] onStreamClosed handler failed",$)}try{(F=j==null?void 0:j.onClosed)==null||F.call(j,O)}catch($){console.warn("[useChatStreamingService] downstream onClosed handler failed",$)}h.current&&(h.current=null)}})},[x,m,a,i,l,o,s,b]),R=w.useCallback(()=>{h.current&&(h.current.manualStop=!0),S()},[S]);return w.useMemo(()=>({startStream:E,stop:R,isStreaming:T,error:k,setAuthToken:C,replayBufferedEvents:y}),[E,R,T,k,C,y])}function qi(e){return e==null?e:{...e}}function Bx(e){return e==null?e:{...e}}function Hx(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function Ux(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function hn(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=qi(e==null?void 0:e.metadata),s=qi(e==null?void 0:e.config),i=qi(e==null?void 0:e.parentConfig),a=Hx(e==null?void 0:e.next),l=Ux(e==null?void 0:e.tasks),c=Bx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function Wx(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function qc(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}const is=300;function Gc(e,t=is){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function xr(){return typeof window<"u"&&typeof window.localStorage<"u"}function Gi(e){if(!xr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function Xi(e,t){if(!xr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function Yi(e){if(xr())try{window.localStorage.removeItem(e)}catch{}}const Vx="cachedThreads",Kx="v1",Ji=200;function qx(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function Zi(e,t){return`cachedThreads:v1:${e}:${qx(t||"anon")}`}function Gx(){const e=Gi(Vx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function Xx(e){const t=Gi(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function Qi(e,t){Xi(e,JSON.stringify(t))}function ea(e){const t=Xx(e);if(t.length>0)return t;const n=Gx();if(n.length>0)try{Qi(e,n.slice(0,Ji))}catch{}return n}function as(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function ta(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function na(e,t){return`${e}${t}`}function Yx(e,t){const n=Gi(na(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:hn(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function Jx(e,t,n=100){if(!xr())return;const r=hn(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=na(e,t.threadId),i=JSON.stringify(o);if(!Xi(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),Xi(s,i))break}catch{}}function Zx(e,t){Yi(na(e,t))}function Qx(e){if(xr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}const Xc=w.createContext(null),Yc=w.createContext(null),Jc=w.createContext(null),ey=w.createContext(!1),Zc=50,ty=750,ny=5,ry=1e3,oy=15e3;function Qc(e,t,n){return`${e}__${t??""}__${n??""}`}function ls(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 sy(e,t){return ls(e,t)}function iy(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 ay(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 eu(e,t){const n=ls(e.metadata,t.metadata),r=ls(e.config,t.config),o=ls(e.parentConfig,t.parentConfig),s=iy(e.next,t.next),i=ay(e.tasks,t.tasks),a=sy(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function ly({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Bi(),f=w.useMemo(()=>zn(d),[d]),h=w.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=w.useMemo(()=>`threadPayload:${Kx}:${h}:`,[h]),g=w.useCallback(N=>Yx(p,N),[p]),x=w.useCallback((N,A=100)=>{Jx(p,N,A)},[p]),y=w.useCallback(N=>{Zx(p,N)},[p]),m=w.useCallback(()=>{Qx(p)},[p]),[b,S]=w.useState(()=>{var N;return Zi(h,(N=c.getAuthToken)==null?void 0:N.call(c))}),[T,k]=w.useState(()=>{var A;const N=ea(Zi(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return as(N)}),C=w.useMemo(()=>ta(T),[T]),[E,R]=w.useState(t),[_,j]=w.useState(!1),[L,z]=w.useState(!1),[V,O]=w.useState(null),[H,P]=w.useState(null),[W,F]=w.useState(null),[$,ne]=w.useState([]),oe=w.useCallback(()=>{const N=ea(b);w.startTransition(()=>{k(as(N))})},[b]),[we,Ne]=w.useState(!1),[Z,ie]=w.useState(!1),[Te,ee]=w.useState(null),[D,X]=w.useState(void 0),[ae,fe]=w.useState(void 0),[B,le]=w.useState(void 0),{state:Q,dispatch:Ae,seed:ve,prepend:Re,pushUser:Ve,onEvent:Qe,reset:et}=Lc(),Se=w.useRef(E);w.useEffect(()=>{Se.current=E},[E]);const nt=w.useRef(!1),ut=w.useRef([]),rt=w.useRef(null),Ye=w.useRef(null),It=w.useRef(new Map),dt=w.useRef(E),kt=w.useRef(!1),Nt=w.useRef(null),tt=w.useRef(new Map),He=w.useRef(new Map),Tt=w.useRef(new Map),Vt=w.useRef(new Map),zt=w.useCallback(N=>{if(!N){ne([]);return}const A=tt.current.get(N);if(!A||!A.length){ne([]);return}ne(A.map(U=>hn(U,{cloneMessages:!0})))},[]);w.useEffect(()=>{zt(E)},[E,zt]);const Kt=w.useCallback(()=>{var K;const N=Vt.current;if(N.size<=Zc)return;const A=Array.from(N.entries()).sort((ce,re)=>ce[1].timestamp-re[1].timestamp),U=N.size-Zc;for(let ce=0;ce<U;ce++){const re=(K=A[ce])==null?void 0:K[0];re&&N.delete(re)}},[]),st=w.useCallback((N,A,U)=>{if(!N)return;const K=U==="replace"?[]:tt.current.get(N)??[],ce=U==="replace"?A:[...A,...K];if(!ce.length){U==="replace"&&tt.current.set(N,[]);return}const re=new Map;for(const Ge of ce){if(!(Ge!=null&&Ge.checkpointId))continue;const Ue=`${Ge.checkpointId}::${Ge.checkpointNs??""}`,bt=hn(Ge,{cloneMessages:!0}),At=re.get(Ue);if(!At){re.set(Ue,bt);continue}const Qt=eu(At,bt);re.set(Ue,{...At,...Qt})}const qe=Array.from(re.values()).sort((Ge,Ue)=>{const bt=Number.isFinite(Date.parse(Ge.createdAt??""))?Date.parse(Ge.createdAt??""):0;return(Number.isFinite(Date.parse(Ue.createdAt??""))?Date.parse(Ue.createdAt??""):0)-bt});tt.current.set(N,qe),N===Se.current&&zt(N)},[zt]),Le=w.useCallback((N,A,U)=>{if(!N)return;const K=He.current.get(N),ce=U==="replace"||!K?new Map:new Map(K);if(A&&typeof A=="object")for(const[re,qe]of Object.entries(A)){if(!(qe!=null&&qe.checkpointId))continue;const Ge=re||lo(qe.checkpointId,qe.checkpointNs??null);ce.set(Ge,hn(qe,{cloneMessages:!0}))}He.current.set(N,ce)},[]),_t=w.useCallback((N,A)=>{const{threadId:U,checkpointId:K=null,checkpointNs:ce=null}=N,re=Qc(U,K,ce);if(A!=null&&A.force)Tt.current.delete(re),Vt.current.delete(re);else{if(A!=null&&A.preferCache){const bt=Vt.current.get(re);if(bt)return Promise.resolve(bt.payload)}const Ue=Tt.current.get(re);if(Ue)return Ue}const Ge=c.getStateHistory({threadId:U,checkpointId:K??void 0,checkpointNs:ce??void 0}).then(Ue=>(Vt.current.set(re,{payload:Ue,timestamp:Date.now()}),Kt(),Ue)).finally(()=>{Tt.current.get(re)===Ge&&Tt.current.delete(re)});return Tt.current.set(re,Ge),Ge},[c,Kt]),yt=w.useCallback((N,A)=>new Promise((U,K)=>{const ce=async()=>{nt.current=!0;try{await N(),U()}catch(re){K(re)}finally{nt.current=!1;const re=ut.current.shift();re&&re().catch(()=>{})}};nt.current?ut.current.push(ce):ce().catch(re=>{K(re)})}),[]),G=w.useRef(C.length),Ce=w.useRef(!1);w.useEffect(()=>{G.current=C.length},[C.length]),w.useEffect(()=>{const N=Q.pendingInterrupt??Wx(Q.messages);qc(W,N)||F(N??null)},[W,Q.messages,Q.pendingInterrupt]);const ge=w.useCallback(async()=>{const N=G.current>0;N||j(!0);try{const A=await c.listThreads();w.startTransition(()=>{k(U=>{const K=qe=>qe.map(Ge=>`${Ge.threadId}:${Ge.updatedAt??""}:${Ge.messageCount??""}`).join("|"),ce=ta(U);return K(ce)===K(A)||A.length===0&&ce.length>0&&!Ce.current?U:as(A)})}),O(null),Ce.current||(Ce.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A))}finally{N||j(!1)}},[c,i]),xt=w.useRef(!1),ft=w.useRef(null),ht=w.useRef(null),Be=w.useRef(""),[Ft,Oe]=w.useState("idle"),it=w.useRef({attempts:0,timer:null,reason:null}),ar=w.useRef(null),jr=w.useRef(0),lr=w.useRef(()=>{}),Rr=w.useRef(()=>{}),Pr=w.useRef(()=>{}),Kn=w.useCallback((N,A)=>{if(!xr())return;ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null);const U=N.map(ce=>`${ce.threadId}:${ce.updatedAt??""}:${ce.messageCount??""}`).join("|");if(N.length===0){try{Yi(b)}catch{}Be.current="";return}if(U===Be.current)return;const K=()=>{try{const ce=N.slice(0,Ji);Qi(b,ce),Be.current=U}catch{}finally{ht.current=null}};if(A!=null&&A.immediate){K();return}ht.current=window.setTimeout(()=>{Gc(K)},is)},[b]),Qr=w.useCallback(()=>{Kn(C,{immediate:!0})},[Kn,C]),I=w.useCallback((N,A,U,K)=>{var Ol;const ce=U??Se.current;if(!ce)return;const re=hn(N),qe=ce===Se.current,Ge=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(Ge){const Ht={threadId:ce,snapshot:hn(N,{cloneMessages:!0})};It.current.set(ce,Ht),dt.current=ce}if(!qe)return;ve(re.messages,{checkpointId:re.checkpointId??null,checkpointNs:re.checkpointNs??null,pendingInterrupt:re.interrupt??null}),F(re.interrupt??null),ee(re.nextCursor??null),Ne(!!re.nextCursor),X(re.checkpointId??void 0),fe(re.checkpointNs??void 0),le(re.nextCursorNs??void 0);return}const Ue=It.current.get(ce),bt=(Ue==null?void 0:Ue.snapshot)??null,At=Array.isArray(bt==null?void 0:bt.messages)?bt.messages:[],Qt=hn(bt),Fn=Array.isArray(N==null?void 0:N.messages)?N.messages:[],Bt=new Set,Lt=[...Fn,...At].filter(Ht=>{const Ml=Ht==null?void 0:Ht.id;return Ml?Bt.has(Ml)?!1:(Bt.add(Ml),!0):!0}),Bo=eu(Qt,re),Ho={checkpointId:Qt.checkpointId??re.checkpointId??null,checkpointNs:Qt.checkpointNs??re.checkpointNs??null,createdAt:re.createdAt??Qt.createdAt??null,parentId:re.parentId??Qt.parentId??null,branchLabel:re.branchLabel??Qt.branchLabel??null,lastMessageId:((Ol=Lt[Lt.length-1])==null?void 0:Ol.id)??null,messagesLen:Lt.length,hasMessages:Lt.length>0,messages:Lt,nextCursor:re.nextCursor??Qt.nextCursor??null,nextCursorNs:re.nextCursorNs??Qt.nextCursorNs??null,interrupt:Qt.interrupt??re.interrupt??null,...Bo};if(It.current.set(ce,{threadId:ce,snapshot:hn(Ho,{cloneMessages:!0})}),!qe)return;Fn.length&&Re(Fn);const eo=N&&Object.prototype.hasOwnProperty.call(N,"checkpointId")?N.checkpointId:void 0,dr=N&&Object.prototype.hasOwnProperty.call(N,"checkpointNs")?N.checkpointNs:void 0,Or=N&&Object.prototype.hasOwnProperty.call(N,"nextCursor")?N.nextCursor:void 0,fr=N&&Object.prototype.hasOwnProperty.call(N,"nextCursorNs")?N.nextCursorNs:void 0;ee(Ht=>Or!==void 0?Or??Ht??null:Ht??null),Ne(Ht=>Or!==void 0?!!Or:Ht),X(Ht=>eo!==void 0?eo??Ht??void 0:Ht??void 0),fe(Ht=>dr!==void 0?dr??Ht??void 0:Ht??void 0),le(Ht=>fr!==void 0?fr??void 0:Ht)},[Re,ve,F]),q=w.useCallback(N=>{if(N.threadId!=null&&N.threadId!==Se.current)return;const A=hn(N.snapshot,{cloneMessages:!0});ve(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),F(A.interrupt??null),ee(A.nextCursor??null),Ne(!!A.nextCursor),X(A.checkpointId??void 0),fe(A.checkpointNs??void 0),le(A.nextCursorNs??void 0),dt.current=N.threadId,zt(N.threadId??Se.current??null)},[ve,F,zt]),ue=w.useCallback(N=>{if(!N)return;It.current.delete(N),y(N),tt.current.delete(N),He.current.delete(N),N===Se.current&&ne([]);const A=`${N}__`;for(const U of Tt.current.keys())U.startsWith(A)&&Tt.current.delete(U);for(const U of Vt.current.keys())U.startsWith(A)&&Vt.current.delete(U);dt.current===N&&(dt.current=null)},[y]),ke=w.useCallback(()=>{const N=Se.current;N&&ue(N),et([]),Ne(!1),ie(!1),ee(null),X(void 0),fe(void 0),le(void 0)},[ue,et]),Xe=w.useCallback(({from:N,to:A})=>{const U=Se.current;U&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${N} -> ${A}) for thread ${U}`)},[]),at=w.useCallback(N=>{const A=N.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:N.title,created:N.created,currentThreads:C.length});const U={threadId:A,title:N.title||`Thread ${A.slice(0,8)}`,createdAt:N.createdAt||new Date().toISOString(),updatedAt:N.updatedAt||new Date().toISOString(),messageCount:N.messageCount||0};Se.current!==A&&(!Se.current&&Q.messages.length<=1&&(Ye.current=A),R(A)),w.startTransition(()=>{k(K=>{const ce=K.byId[A];return ce?ce.title===U.title&&ce.updatedAt===U.updatedAt&&ce.messageCount===U.messageCount?K:{byId:{...K.byId,[A]:U},order:K.order}:{byId:{...K.byId,[A]:U},order:[A,...K.order]}})})},[Q.messages.length]),{startStream:Ke,stop:$e,isStreaming:jt,error:vt,setAuthToken:pt,replayBufferedEvents:qt}=zx({baseUrl:f,onThreadInfo:at,onMessageEvent:Qe,onUnhandledEvent:N=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${N.type}`,N)},onSequenceGap:Xe,onStreamClosed:N=>{lr.current(N)},onConnectionError:N=>{Rr.current(N)},onAuthError:a,onHeartbeat:N=>{Pr.current(N)}}),Gt=w.useCallback(()=>{const N=it.current;N.timer!==null&&(window.clearTimeout(N.timer),N.timer=null),N.reason=null},[]),J=w.useCallback((N,A)=>{Oe("connecting"),Ke(N,{onOpen:U=>{var K;Gt(),it.current.attempts=0,Oe("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,U)},onError:U=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,U)},onGap:(A==null?void 0:A.onGap)??Xe,onConnectionError:U=>{var K;Rr.current(U),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,U)},onHeartbeat:U=>{var K;Pr.current(U),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,U)},onClosed:U=>{var K;lr.current(U),(K=A==null?void 0:A.onClosed)==null||K.call(A,U)}})},[Gt,Xe,Oe,Ke]),de=w.useCallback(()=>{const N=Se.current;if(!N)return null;const A=ar.current,U=Q.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=Q.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,ce={};return U&&(ce.checkpointId=U),K&&(ce.checkpointNs=K),{threadId:N,checkpointId:U,checkpointNs:K,command:{kind:"resume",value:ce}}},[Q.lastCheckpointId,Q.lastCheckpointNs]),he=w.useCallback(N=>{const A=it.current;if(A.timer!==null)return;if(A.attempts>=ny){Oe("error");return}A.attempts+=1,A.reason=N;const U=Math.min(ry*Math.pow(2,A.attempts-1),oy);Oe("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=de();if(!K){Oe("error");return}qt(K.threadId??void 0),J(K)},U)},[de,qt,Oe,J]),wt=w.useCallback(N=>{if(ar.current=N,N.manualStop||N.reason==="complete"){Gt(),it.current.attempts=0,Oe("idle");return}if(N.error&&(N.error.includes("token")||N.error.includes("401")||N.error.includes("unauthorized")||N.error.includes("Unauthorized")||N.error.includes("TOKEN_EXPIRED")||N.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",N.error);try{a==null||a(N.error)}catch(U){console.error("[ChatSessionProvider] Error in onAuthError handler:",U)}return}(N.reason==="error"||N.reason==="aborted")&&he(`closed:${N.reason}`)},[Gt,he,Oe,a]),Ot=w.useCallback(N=>{console.warn("[ChatSessionProvider] Stream connection error:",N),he("connection-error")},[he]),an=w.useCallback(N=>{jr.current=Date.now(),Oe(A=>A==="reconnecting"?"connected":A)},[Oe]);lr.current=wt,Rr.current=Ot,Pr.current=an,w.useEffect(()=>()=>{Gt()},[Gt]);const qn=w.useCallback(()=>{Gt(),it.current.attempts=0,Oe("idle"),$e()},[Gt,Oe,$e]);w.useEffect(()=>{xt.current=jt},[jt]),w.useEffect(()=>{if(!xr())return;ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null);const N=C.map(U=>`${U.threadId}:${U.updatedAt??""}:${U.messageCount??""}`).join("|");if(C.length===0){try{Yi(b)}catch{}Be.current="";return}if(N===Be.current)return;const A=()=>{try{const U=C.slice(0,Ji);Qi(b,U),Be.current=N}catch{}finally{ht.current=null}};return ht.current=window.setTimeout(()=>{Gc(A),ht.current=null},is),()=>{ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null)}},[C,Kn]),w.useEffect(()=>{var K;const N=c.getAuthToken();pt(N);const A=ce=>{const re=Zi(h,ce);Nt.current!==re&&(Nt.current=re,kt.current=!1),S(re);const qe=ea(re);w.startTransition(()=>{k(as(qe))}),ce&&!kt.current&&(kt.current=!0)};A(N);const U=(K=c.onTokenChange)==null?void 0:K.call(c,ce=>{ce!==N&&(pt(ce),m(),Tt.current.clear(),Vt.current.clear(),A(ce))});return()=>{U==null||U()}},[c,h,pt,m]);const cr=w.useCallback(async N=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,U={threadId:A,title:N||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(ce=>({byId:{...ce.byId,[A]:U},order:[A,...ce.order]})),R(A);try{const ce=await c.createThread(N),re=typeof ce=="string"?ce:ce.threadId;return k(qe=>{const Ge=qe.byId[A];if(!Ge)return qe;const Ue={...qe.byId};delete Ue[A],Ue[re]={...Ge,threadId:re};const bt=qe.order.map(At=>At===A?re:At);return{byId:Ue,order:bt}}),R(re),setTimeout(()=>ge(),10),O(null),re}catch(ce){throw k(re=>{if(!re.byId[A])return re;const qe={...re.byId};delete qe[A];const Ge=re.order.filter(Ue=>Ue!==A);return{byId:qe,order:Ge}}),R(null),O(String(ce)),ce}},[c,ge]),Fo=w.useCallback(async N=>{try{await c.deleteThread(N);let A=null;k(U=>{if(!U.byId[N])return U;const K={...U.byId};delete K[N];const ce=U.order.filter(qe=>qe!==N),re={byId:K,order:ce};return A=ta(re),re}),A&&Kn(A,{immediate:!0}),ue(N),Se.current===N&&(Ye.current=N,R(null),Se.current=null,dt.current=null,ke()),await ge(),O(null)}catch(A){throw O(String(A)),A}},[c,ke,ue,ge,Kn]),Rm=w.useCallback(async(N,A)=>{try{await c.updateThread(N,A),k(U=>{const K=U.byId[N];return K?{byId:{...U.byId,[N]:{...K,title:A}},order:U.order}:U}),O(null)}catch(U){throw await ge(),O(String(U)),U}},[c,ge]),ur=w.useCallback(async(N,A,U,K=!1)=>{await yt(async()=>{if(Ye.current===N&&!K){Ye.current=null;return}if(rt.current===N&&!K)return;R(Bt=>Bt===N?Bt:N),Se.current=N;const qe=Qc(N,A??null,U??null),Ge=Vt.current.get(qe),Ue=!K&&!A&&!U&&Ge&&Date.now()-Ge.timestamp<ty,bt=!K&&!A&&!U;let At=!1;if(bt){const Bt=It.current.get(N);if(Bt)q(Bt),At=!0;else{const Lt=g(N);Lt&&(It.current.set(N,Lt),q(Lt),At=!0)}}const Qt=K||!At||!!A||!!U,Fn=async Bt=>{Bt&&z(!0),rt.current=N;try{const Lt=await _t({threadId:N,checkpointId:A,checkpointNs:U},{force:K}),{latest:Bo,checkpoints:Ho,snapshots:eo}=ns(Lt);I(Bo,"replace",N),st(N,Ho,"replace"),Le(N,eo,"replace"),P(null)}catch(Lt){throw(!At||K||Bt)&&(i==null||i(String(Lt))),P(String(Lt)),Lt}finally{rt.current=null,Bt&&z(!1)}};Qt?await Fn(!0):bt&&At&&!Ue&&Fn(!1).catch(Bt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Bt)})},`loadThread-${N}`)},[q,I,yt,_t,i,st,Le]),Pm=w.useCallback(async()=>{await yt(async()=>{const N=Se.current;N&&ue(N),Ye.current=null,R(null),Se.current=null,dt.current=null,ke(),X(void 0),fe(void 0),le(void 0),ne([]);try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[ke,ue,yt]),Om=w.useCallback(async(N,A)=>{var re;const U=Se.current;if(!U)throw new Error("No active thread");const K=lo(N,A??null),ce=(re=He.current.get(U))==null?void 0:re.get(K);if(ce){await yt(async()=>{I(ce,"replace",U,{persist:!1})},`navigateToCheckpoint-${U}-${K}`);return}await ur(U,N,A??void 0,!0)},[I,yt,ur]),Mm=w.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await ur(Se.current,void 0,void 0,!0)},[ur]),Dm=w.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(Z||!we)return;const N=Te;if(N){ie(!0);try{const A=Se.current,U=await _t({threadId:A,checkpointId:N??D??null,checkpointNs:B??ae??null}),{latest:K,checkpoints:ce,snapshots:re}=ns(U),qe=A?He.current.get(A):null;let Ge=ce.length>0;if(Ge&&qe&&qe.size>0&&(Ge=ce.some(Ue=>{if(!(Ue!=null&&Ue.checkpointId))return!1;const bt=lo(Ue.checkpointId,Ue.checkpointNs??null);return!qe.has(bt)})),!Ge){ee(null),le(void 0),Ne(!1),P(null);return}I(K,"prepend",A??void 0),A&&(st(A,ce,"prepend"),Le(A,re,"prepend")),P(null)}catch(A){throw P(String(A)),A}finally{ie(!1)}}},[I,_t,we,D,ae,B,Te,Z,st,Le]),Lm=w.useCallback(N=>{if(N!=null&&N.threadId){if(N.checkpointId){const A=lo(N.checkpointId,N.checkpointNs??null),U=hn({...N,interrupt:N.interrupt??null},{cloneMessages:!0});Le(N.threadId,{[A]:U},"prepend")}I(N,"replace",N.threadId)}},[I,Le]),zo=w.useCallback(async(N,A)=>{var Or;const U=Se.current,K=(N==null?void 0:N.text)??"",ce=(N==null?void 0:N.attachments)??[],re=ce.length?ce:(A==null?void 0:A.attachments)??[],qe=N==null?void 0:N.messageAdditionalKwargs,Ge={...(A==null?void 0:A.payloadExtras)??{},...(N==null?void 0:N.payload)??{}};if(!U&&!Object.keys(Ge).length&&re.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!U&&!Ge.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Ue,filesInfo:bt}=await mx(c,re),At=[...Ue];K&&K.trim()&&At.push({type:"text",text:K.trim()});const Qt=!!U,Fn=Qt?(A==null?void 0:A.checkpointId)??Q.lastCheckpointId??void 0:void 0,Bt=Qt?(A==null?void 0:A.checkpointNs)??Q.lastCheckpointNs??void 0:void 0,Lt={id:((Or=crypto.randomUUID)==null?void 0:Or.call(crypto))||`user-${Date.now()}`,role:"user",content:At,createdAt:new Date().toISOString(),...Fn!=null?{checkpointId:Fn}:{},...Bt!=null?{checkpointNs:Bt}:{}};qe&&Object.keys(qe).length&&(Lt.additionalKwargs={...Lt.additionalKwargs??{},...qe}),At.length>0&&Ve(Lt);const Bo={...Lt,content:At},Ho=re.length>0,eo={messages:At.length>0?[Bo]:[],files_info:bt,...o&&Ho&&s?{active_agent:s}:{},...Ge},dr={threadId:U??null,payload:eo,checkpointId:Fn??null,checkpointNs:Bt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};dr.threadId||delete dr.threadId,dr.command||delete dr.command,J(dr,{onError:fr=>{console.warn("[ChatSessionProvider] Stream error:",fr)},onOpen:({threadId:fr})=>{!Se.current&&fr&&(Q.messages.length<=1&&(Ye.current=fr),R(fr))},onGap:Xe})},[c,o,s,Xe,Q.lastCheckpointId,Q.lastCheckpointNs,Q.messages.length,Ve,J]),$m=w.useCallback(async(N,A,U)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const ce=A?U??!0:!1;try{try{Ae({type:"interrupt_response",payload:{interruptId:N}})}catch(re){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",re)}await zo({payload:{}},{checkpointId:Q.lastCheckpointId??void 0,checkpointNs:Q.lastCheckpointNs??void 0,command:{kind:"resume",value:ce}}),F(null)}catch(re){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${N}:`,re),re}},[Ae,Q.lastCheckpointId,Q.lastCheckpointNs,zo]);w.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(N){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",N)}},[E,l]),w.useEffect(()=>((async()=>{try{if(ge().catch(A=>{console.error("[ChatSessionProvider] Failed to refresh threads (background):",A),i==null||i(String(A))}),!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(R(A),n&&await ur(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else t&&n&&await ur(t)}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),w.useEffect(()=>{const N=Se.current;if(!N||dt.current!==N)return;Q.messages.length&&Q.messages[Q.messages.length-1];const A=hn({checkpointId:Q.lastCheckpointId??null,checkpointNs:Q.lastCheckpointNs??null,messages:Q.messages.slice(),nextCursor:Te??null,nextCursorNs:B??null,interrupt:Q.pendingInterrupt??W??null}),U=It.current.get(N),K=U==null?void 0:U.snapshot,ce=!K||K.messages.length!==A.messages.length||K.messages.some((Ue,bt)=>{var At;return(Ue==null?void 0:Ue.id)!==((At=A.messages[bt])==null?void 0:At.id)}),re=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,qe=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,Ge=!qc((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(ce||re||qe||Ge){const Ue={threadId:N,snapshot:A};It.current.set(N,Ue),ft.current&&window.clearTimeout(ft.current),ft.current=window.setTimeout(()=>{try{x(Ue,100)}catch(bt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",bt)}},is)}},[Te,B,Q.lastCheckpointId,Q.lastCheckpointNs,Q.messages,Q.pendingInterrupt,W,x]);const tT=w.useMemo(()=>({threads:C,currentThreadId:E,setCurrentThreadId:R,isLoading:_,error:V,actions:{createThread:cr,deleteThread:Fo,renameThread:Rm,refreshThreads:()=>ge()},persistThreadsCache:Qr,hydrateFromCache:oe}),[C,E,_,V,cr,Fo,Rm,ge,Qr,oe,R]),nT=w.useMemo(()=>{const N=Q.lastBranch??null,A=Q.assemblingId??null,U=N||A?{branchLabel:(N==null?void 0:N.branchLabel)??null,lastBranch:N,assemblingMessageId:A}:null;return{threadId:E,messages:Q.messages,interrupt:W,checkpoint:{id:Q.lastCheckpointId??null,namespace:Q.lastCheckpointNs??null},checkpoints:$,metadata:U,isLoading:L,isHistoryLoading:Z,error:H,hasMore:we,loadOlder:Dm,seedFromSnapshot:Lm,clearState:ke,navigateToCheckpoint:Om,returnToLatest:Mm,loadThread:ur,clearThread:Pm,respondToInterrupt:$m}},[Pm,ke,E,W,we,Z,L,Dm,ur,Q.assemblingId,Q.lastBranch,Q.lastCheckpointId,Q.lastCheckpointNs,Q.messages,Om,$m,Mm,Lm,H,$]),rT=w.useMemo(()=>({isStreaming:jt,error:vt,connectionState:Ft,submit:zo,send:zo,stop:qn,setAuthToken:pt}),[Ft,jt,vt,qn,zo,pt]);return u.jsx(ey.Provider,{value:!0,children:u.jsx(Jc.Provider,{value:rT,children:u.jsx(Xc.Provider,{value:tT,children:u.jsx(Yc.Provider,{value:nT,children:e})})})})}function cs(){const e=w.useContext(Xc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function us(){const e=w.useContext(Yc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function tu(){const e=w.useContext(Jc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function ds({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(hx,{apiConfig:t,children:u.jsx(ly,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function se(...e){return Hm.twMerge(Bm.clsx(e))}const cy=Uo.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"}}),lt=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?hr.Slot:"button";return u.jsx(i,{className:se(cy({variant:t,size:n,className:e})),ref:s,...o})});lt.displayName="Button";const nu=v.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}));nu.displayName="Textarea";function uy({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 g=i!==void 0,[x,y]=w.useState(e),m=(g?i:x)??"",[b,S]=w.useTransition(),T=w.useRef(null),k=w.useRef(0),C=w.useRef(null);w.useEffect(()=>{g||(y(e??""),C.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,g]);const E=w.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,m]);const R=w.useCallback((H,{fromUser:P})=>{g||y(H),P&&(a==null||a(H))},[g,a]),_=w.useCallback(async H=>{H&&H.preventDefault();const P=(m??"").trim();if(!P&&!p)return;const W=++k.current;C.current={id:W,shouldClear:!0},S(()=>{var F,$,ne;try{const oe=l(P);oe&&typeof oe.then=="function"?oe.then(()=>{var we,Ne;((we=C.current)==null?void 0:we.id)===W&&C.current.shouldClear&&(g||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((Ne=C.current)==null?void 0:Ne.id)===W&&(C.current=null)}).catch(()=>{var we;((we=C.current)==null?void 0:we.id)===W&&(C.current=null)}):(((F=C.current)==null?void 0:F.id)===W&&C.current.shouldClear&&(g||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),(($=C.current)==null?void 0:$.id)===W&&(C.current=null))}catch{((ne=C.current)==null?void 0:ne.id)===W&&(C.current=null)}})},[m,l,p,g,a]),j=w.useCallback(H=>{const P=H.target.value;R(P,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[R]),L=w.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`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:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(nu,{ref:T,value:m,onChange:j,onKeyDown:L,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(lt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(pe.Square,{size:16})}):u.jsx(lt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!m.trim()&&!p||b,children:u.jsx(pe.Send,{size:16})})})]})})}const dy=w.memo(uy),fs=0,Xn=1,$r=2,ru=4;function ou(e){return()=>e}function fy(e){e()}function su(e,t){return n=>e(t(n))}function iu(e,t){return()=>e(t)}function hy(e,t){return n=>e(t,n)}function ra(e){return e!==void 0}function py(...e){return()=>{e.map(fy)}}function Fr(){}function hs(e,t){return t(e),e}function my(e,t){return t(e)}function St(...e){return e}function ct(e,t){return e(Xn,t)}function ze(e,t){e(fs,t)}function oa(e){e($r)}function Pt(e){return e(ru)}function be(e,t){return ct(e,hy(t,fs))}function Cn(e,t){const n=e(Xn,r=>{n(),t(r)});return n}function au(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function lu(e,t){return e===t}function Ct(e=lu){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function je(e){return t=>n=>{e(n)&&t(n)}}function me(e){return t=>su(t,e)}function _n(e){return t=>()=>{t(e)}}function Y(e,...t){const n=gy(...t);return(r,o)=>{switch(r){case $r:oa(e);return;case Xn:return ct(e,n(o))}}}function jn(e,t){return n=>r=>{n(t=e(t,r))}}function yr(e){return t=>n=>{e>0?e--:t(n)}}function Bn(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function We(...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);ct(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 gy(...e){return t=>e.reduceRight(my,t)}function xy(e){let t,n;const r=()=>t==null?void 0:t();return function(o,s){switch(o){case Xn:return s?n===s?void 0:(r(),n=s,t=ct(e,s),t):(r(),Fr);case $r:r(),n=null;return}}}function te(e){let t=e;const n=Je();return(r,o)=>{switch(r){case fs:t=o;break;case Xn:{o(t);break}case ru:return t}return n(r,o)}}function Yt(e,t){return hs(te(t),n=>be(e,n))}function Je(){const e=[];return(t,n)=>{switch(t){case fs:e.slice().forEach(r=>{r(n)});return;case $r:e.splice(0,e.length);return;case Xn:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)}}}}function ln(e){return hs(Je(),t=>be(e,t))}function ot(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:yy(),singleton:n}}const yy=()=>Symbol();function vy(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 Dt(...e){const t=Je(),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);ct(s,l=>{n[i]=l,r=r|a,r===o&&ze(t,n)})}),function(s,i){switch(s){case $r:{oa(t);return}case Xn:return r===o&&i(n),ct(t,i)}}}function _e(e,t=lu){return Y(e,Ct(t))}function sa(...e){return function(t,n){switch(t){case $r:return;case Xn:return py(...e.map(r=>ct(r,n)))}}}var sn=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(sn||{});const wy={0:"debug",3:"error",1:"log",2:"warn"},by=()=>typeof globalThis>"u"?window:globalThis,Yn=ot(()=>{const e=te(3);return{log:te((t,n,r=1)=>{var o;const s=(o=by().VIRTUOSO_LOG_LEVEL)!=null?o:Pt(e);r>=s&&console[wy[r]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function vr(e,t,n){return ia(e,t,n).callbackRef}function ia(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 Sy(e,t,n,r,o,s,i,a,l){const c=w.useCallback(d=>{const f=Cy(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 g;p&&(g=h.ownerDocument.defaultView);const x=i?a?i.scrollLeft:i.scrollTop:p?a?g.scrollX||g.document.documentElement.scrollLeft:g.scrollY||g.document.documentElement.scrollTop:a?h.scrollLeft:h.scrollTop,y=i?a?i.scrollWidth:i.scrollHeight:p?a?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight:a?h.scrollWidth:h.scrollHeight,m=i?a?i.offsetWidth:i.offsetHeight:p?a?g.innerWidth:g.innerHeight:a?h.offsetWidth:h.offsetHeight;r({scrollHeight:y,scrollTop:Math.max(x,0),viewportHeight:m}),s==null||s(a?cu("column-gap",getComputedStyle(d).columnGap,o):cu("row-gap",getComputedStyle(d).rowGap,o)),f!==null&&e(f)},[e,t,o,s,i,r,a]);return ia(c,n,l)}function Cy(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},sn.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 cu(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,sn.WARN),t==="normal"?0:parseInt(t??"0",10)}function uu(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,h;if(t){const p=t.getBoundingClientRect(),g=c.top-p.top;h=p.height-Math.max(0,g),f=g+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}=ia(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 en=ot(()=>{const e=Je(),t=Je(),n=te(0),r=Je(),o=te(0),s=Je(),i=Je(),a=te(0),l=te(0),c=te(0),d=te(0),f=Je(),h=Je(),p=te(!1),g=te(!1),x=te(!1);return be(Y(e,me(({scrollTop:y})=>y)),t),be(Y(e,me(({scrollHeight:y})=>y)),i),be(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:g,scrollBy:h,scrollContainerState:e,scrollHeight:i,scrollingInProgress:p,scrollTo:f,scrollTop:t,skipAnimationFrameInResizeObserver:x,smoothScrollTargetReached:r,statefulScrollTop:o,viewportHeight:s}},[],{singleton:!0}),uo={lvl:0};function du(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 mt(e){return e===uo}function fo(e,t){if(!mt(e))return t===e.k?e.v:t<e.k?fo(e.l,t):fo(e.r,t)}function kn(e,t,n="k"){if(mt(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const r=kn(e.r,t,n);return r[0]===-1/0?[e.k,e.v]:r}return kn(e.l,t,n)}function cn(e,t,n){return mt(e)?pu(t,n,1):t===e.k?$t(e,{k:t,v:n}):t<e.k?mu($t(e,{l:cn(e.l,t,n)})):mu($t(e,{r:cn(e.r,t,n)}))}function zr(){return uo}function ps(e,t,n){if(mt(e))return[];const r=kn(e,t)[0];return ky(la(e,r,n))}function aa(e,t){if(mt(e))return uo;const{k:n,l:r,r:o}=e;if(t===n){if(mt(r))return o;if(mt(o))return r;{const[s,i]=hu(r);return ms($t(e,{k:s,l:fu(r),v:i}))}}else return t<n?ms($t(e,{l:aa(r,t)})):ms($t(e,{r:aa(o,t)}))}function wr(e){return mt(e)?[]:[...wr(e.l),{k:e.k,v:e.v},...wr(e.r)]}function la(e,t,n){if(mt(e))return[];const{k:r,l:o,r:s,v:i}=e;let a=[];return r>t&&(a=a.concat(la(o,t,n))),r>=t&&r<=n&&a.push({k:r,v:i}),r<=n&&(a=a.concat(la(s,t,n))),a}function ms(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(ca(t))return gu($t(e,{lvl:n-1}));if(!mt(t)&&!mt(t.r))return $t(t.r,{l:$t(t,{r:t.r.l}),lvl:n,r:$t(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}else{if(ca(e))return ua($t(e,{lvl:n-1}));if(!mt(r)&&!mt(r.l)){const o=r.l,s=ca(o)?r.lvl-1:r.lvl;return $t(o,{l:$t(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:ua($t(r,{l:o.r,lvl:s}))})}else throw new Error("Unexpected empty nodes")}}function $t(e,t){return pu(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 fu(e){return mt(e.r)?e.l:ms($t(e,{r:fu(e.r)}))}function ca(e){return mt(e)||e.lvl>e.r.lvl}function hu(e){return mt(e.r)?[e.k,e.v]:hu(e.r)}function pu(e,t,n,r=uo,o=uo){return{k:e,l:r,lvl:n,r:o,v:t}}function mu(e){return ua(gu(e))}function gu(e){const{l:t}=e;return!mt(t)&&t.lvl===e.lvl?$t(t,{r:$t(e,{l:t.r})}):e}function ua(e){const{lvl:t,r:n}=e;return!mt(n)&&!mt(n.r)&&n.lvl===t&&n.r.lvl===t?$t(n,{l:$t(e,{r:n.l}),lvl:t+1}):e}function ky(e){return du(e,({k:t,v:n})=>({index:t,value:n}))}function xu(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function ho(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const da=ot(()=>({recalcInProgress:te(!1)}),[],{singleton:!0});function yu(e,t,n){return e[gs(e,t,n)]}function gs(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 Ty(e,t,n,r){const o=gs(e,t,r),s=gs(e,n,r,o);return e.slice(o,s+1)}function Jn(e,t){return Math.round(e.getBoundingClientRect()[t])}function xs(e){return!mt(e.groupOffsetTree)}function fa({index:e},t){return t===e?0:t<e?-1:1}function Ey(){return{groupIndices:[],groupOffsetTree:zr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:zr()}}function Iy(e,t){let n=mt(e)?0:1/0;for(const r of t){const{endIndex:o,size:s,startIndex:i}=r;if(n=Math.min(n,i),mt(e)){e=cn(e,0,s);continue}const a=ps(e,i-1,o+1);if(a.some(Oy(r)))continue;let l=!1,c=!1;for(const{end:d,start:f,value:h}of a)l?(o>=f||s===h)&&(e=aa(e,f)):(c=h!==s,l=!0),d>o&&o>=f&&h!==s&&(e=cn(e,o+1,h));c&&(e=cn(e,i,s))}return[e,n]}function Ny(e){return typeof e.groupIndex<"u"}function Ay({offset:e},t){return t===e?0:t<e?-1:1}function po(e,t,n){if(t.length===0)return 0;const{index:r,offset:o,size:s}=yu(t,e,fa),i=e-r,a=s*i+(i-1)*n+o;return a>0?a+n:a}function vu(e,t){if(!xs(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function wu(e,t,n){if(Ny(e))return t.groupIndices[e.groupIndex]+1;{const r=e.index==="LAST"?n:e.index;let o=vu(r,t);return o=Math.max(0,o,Math.min(n,o)),o}}function _y(e,t,n,r=0){return r>0&&(t=Math.max(t,yu(e,r,fa).offset)),du(Ty(e,t,n,Ay),Py)}function jy(e,[t,n,r,o]){t.length>0&&r("received item sizes",t,sn.DEBUG);const s=e.sizeTree;let i=s,a=0;if(n.length>0&&mt(s)&&t.length===2){const h=t[0].size,p=t[1].size;i=n.reduce((g,x)=>cn(cn(g,x,h),x+1,p),i)}else[i,a]=Iy(i,t);if(i===s)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f}=ha(e.offsetTree,a,i,o);return{groupIndices:n,groupOffsetTree:n.reduce((h,p)=>cn(h,p,po(p,f,o)),zr()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:f,sizeTree:i}}function Ry(e){return wr(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 bu(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 ha(e,t,n,r){let o=e,s=0,i=0,a=0,l=0;if(t!==0){l=gs(o,t-1,fa),a=o[l].offset;const c=kn(n,t-1);s=c[0],i=c[1],o.length&&o[l].size===kn(n,t)[1]&&(l-=1),o=o.slice(0,l+1)}else o=[];for(const{start:c,value:d}of ps(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 Py(e){return{index:e.index,value:e}}function Oy(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 My={offsetHeight:"height",offsetWidth:"width"},Rn=ot(([{log:e},{recalcInProgress:t}])=>{const n=Je(),r=Je(),o=Yt(r,0),s=Je(),i=Je(),a=te(0),l=te([]),c=te(void 0),d=te(void 0),f=te((k,C)=>Jn(k,My[C])),h=te(void 0),p=te(0),g=Ey(),x=Yt(Y(n,We(l,e,p),jn(jy,g),Ct()),g),y=Yt(Y(l,Ct(),jn((k,C)=>({current:C,prev:k.current}),{current:[],prev:[]}),me(({prev:k})=>k)),[]);be(Y(l,je(k=>k.length>0),We(x,p),me(([k,C,E])=>{const R=k.reduce((_,j,L)=>cn(_,j,po(j,C.offsetTree,E)||L),zr());return{...C,groupIndices:k,groupOffsetTree:R}})),x),be(Y(r,We(x),je(([k,{lastIndex:C}])=>k<C),me(([k,{lastIndex:C,lastSize:E}])=>[{endIndex:C,size:E,startIndex:k}])),n),be(c,d);const m=Yt(Y(c,me(k=>k===void 0)),!0);be(Y(d,je(k=>k!==void 0&&mt(Pt(x).sizeTree)),me(k=>[{endIndex:0,size:k,startIndex:0}])),n);const b=ln(Y(n,We(x),jn(({sizes:k},[C,E])=>({changed:E!==k,sizes:E}),{changed:!1,sizes:g}),me(k=>k.changed)));ct(Y(a,jn((k,C)=>({diff:k.prev-C,prev:C}),{diff:0,prev:0}),me(k=>k.diff)),k=>{const{groupIndices:C}=Pt(x);if(k>0)ze(t,!0),ze(s,k+bu(k,C));else if(k<0){const E=Pt(y);E.length>0&&(k-=bu(-k,E)),ze(i,k)}}),ct(Y(a,We(e)),([k,C])=>{k<0&&C("`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},sn.ERROR)});const S=ln(s);be(Y(s,We(x),me(([k,C])=>{const E=C.groupIndices.length>0,R=[],_=C.lastSize;if(E){const j=fo(C.sizeTree,0);let L=0,z=0;for(;L<k;){const O=C.groupIndices[z],H=C.groupIndices.length===z+1?1/0:C.groupIndices[z+1]-O-1;R.push({endIndex:O,size:j,startIndex:O}),R.push({endIndex:O+1+H-1,size:_,startIndex:O+1}),z++,L+=H+1}const V=wr(C.sizeTree);return L!==k&&V.shift(),V.reduce((O,{k:H,v:P})=>{let W=O.ranges;return O.prevSize!==0&&(W=[...O.ranges,{endIndex:H+k-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:H+k,prevSize:P,ranges:W}},{prevIndex:k,prevSize:0,ranges:R}).ranges}return wr(C.sizeTree).reduce((j,{k:L,v:z})=>({prevIndex:L+k,prevSize:z,ranges:[...j.ranges,{endIndex:L+k-1,size:j.prevSize,startIndex:j.prevIndex}]}),{prevIndex:0,prevSize:_,ranges:[]}).ranges})),n);const T=ln(Y(i,We(x,p),me(([k,{offsetTree:C},E])=>{const R=-k;return po(R,C,E)})));return be(Y(i,We(x,p),me(([k,C,E])=>{if(C.groupIndices.length>0){if(mt(C.sizeTree))return C;let R=zr();const _=Pt(y);let j=0,L=0,z=0;for(;j<-k;){z=_[L];const V=_[L+1]-z-1;L++,j+=V+1}if(R=wr(C.sizeTree).reduce((V,{k:O,v:H})=>cn(V,Math.max(0,O+k),H),R),j!==-k){const V=fo(C.sizeTree,z);R=cn(R,0,V);const O=kn(C.sizeTree,-k+1)[1];R=cn(R,1,O)}return{...C,sizeTree:R,...ha(C.offsetTree,0,R,E)}}else{const R=wr(C.sizeTree).reduce((_,{k:j,v:L})=>cn(_,Math.max(0,j+k),L),zr());return{...C,sizeTree:R,...ha(C.offsetTree,0,R,E)}}})),x),{beforeUnshiftWith:S,data:h,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,gap:p,groupIndices:l,itemSize:f,listRefresh:b,shiftWith:i,shiftWithOffset:T,sizeRanges:n,sizes:x,statefulTotalCount:o,totalCount:r,trackItemSizes:m,unshiftWith:s}},St(Yn,da),{singleton:!0});function Dy(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const Su=ot(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:r,scrollTop:o}])=>{const s=Je(),i=Je(),a=ln(Y(s,me(Dy)));return be(Y(a,me(l=>l.totalCount)),n),be(Y(a,me(l=>l.groupIndices)),e),be(Y(Dt(o,t,r),je(([l,c])=>xs(c)),me(([l,c,d])=>kn(c.groupOffsetTree,Math.max(l-d,0),"v")[0]),Ct(),me(l=>[l])),i),{groupCounts:s,topItemsIndexes:i}},St(Rn,en)),Zn=ot(([{log:e}])=>{const t=te(!1),n=ln(Y(t,je(r=>r),Ct()));return ct(t,r=>{r&&Pt(e)("props updated",{},sn.DEBUG)}),{didMount:n,propsReady:t}},St(Yn),{singleton:!0}),Ly=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function Cu(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Ly)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const mo=ot(([{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=Je(),g=Je(),x=te(0);let y=null,m=null,b=null;function S(){y&&(y(),y=null),b&&(b(),b=null),m&&(clearTimeout(m),m=null),ze(l,!1)}return be(Y(p,We(n,f,r,x,a,i,h),We(e,s,o),me(([[T,k,C,E,R,_,j,L],z,V,O])=>{const H=Cu(T),{align:P,behavior:W,offset:F}=H,$=E-1,ne=wu(H,k,$);let oe=po(ne,k.offsetTree,z)+_;P==="end"?(oe+=V+kn(k.sizeTree,ne)[1]-C+O,ne===$&&(oe+=j)):P==="center"?oe+=(V+kn(k.sizeTree,ne)[1]-C+O)/2:oe-=R,F&&(oe+=F);const we=Ne=>{S(),Ne?(L("retrying to scroll to",{location:T},sn.DEBUG),ze(p,T)):(ze(g,!0),L("list did not change, scroll successful",{},sn.DEBUG))};if(S(),W==="smooth"){let Ne=!1;b=ct(t,Z=>{Ne=Ne||Z}),y=Cn(d,()=>{we(Ne)})}else y=Cn(Y(t,$y(150)),we);return m=setTimeout(()=>{S()},1200),ze(l,!0),L("scrolling from index to",{behavior:W,index:ne,top:oe},sn.DEBUG),{behavior:W,top:oe}})),c),{scrollTargetReached:g,scrollToIndex:p,topListHeight:x}},St(Rn,en,Yn),{singleton:!0});function $y(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return r=>{r&&(t(!0),clearTimeout(n))}}}function pa(e,t){e==0?t():requestAnimationFrame(()=>{pa(e-1,t)})}function ma(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}const go=ot(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:r},{scrollTargetReached:o,scrollToIndex:s},{didMount:i}])=>{const a=te(!0),l=te(0),c=te(!0);return be(Y(i,We(l),je(([d,f])=>!!f),_n(!1)),a),be(Y(i,We(l),je(([d,f])=>!!f),_n(!1)),c),ct(Y(Dt(t,i),We(a,n,e,c),je(([[,d],f,{sizeTree:h},p,g])=>d&&(!mt(h)||ra(p))&&!f&&!g),We(l)),([,d])=>{Cn(o,()=>{ze(c,!0)}),pa(4,()=>{Cn(r,()=>{ze(a,!0)}),ze(s,d)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},St(Rn,en,mo,Zn),{singleton:!0});function ku(e,t){return Math.abs(e-t)<1.01}const xo="up",yo="down",Fy="none",zy={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},By=0,vo=ot(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:r,scrollTop:o,viewportHeight:s}])=>{const i=te(!1),a=te(!0),l=Je(),c=Je(),d=te(4),f=te(By),h=Yt(Y(sa(Y(_e(o),yr(1),_n(!0)),Y(_e(o),yr(1),_n(!1),au(100))),Ct()),!1),p=Yt(Y(sa(Y(n,_n(!0)),Y(n,_n(!1),au(200))),Ct()),!1);be(Y(Dt(_e(o),_e(f)),me(([b,S])=>b<=S),Ct()),a),be(Y(a,Bn(50)),c);const g=ln(Y(Dt(r,_e(s),_e(t),_e(e),_e(d)),jn((b,[{scrollHeight:S,scrollTop:T},k,C,E,R])=>{const _=T+k-S>-R,j={scrollHeight:S,scrollTop:T,viewportHeight:k};if(_){let z,V;return T>b.state.scrollTop?(z="SCROLLED_DOWN",V=b.state.scrollTop-T):(z="SIZE_DECREASED",V=b.state.scrollTop-T||b.scrollTopDelta),{atBottom:!0,atBottomBecause:z,scrollTopDelta:V,state:j}}let L;return j.scrollHeight>b.state.scrollHeight?L="SIZE_INCREASED":k<b.state.viewportHeight?L="VIEWPORT_HEIGHT_DECREASING":T<b.state.scrollTop?L="SCROLLING_UPWARDS":L="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:L,state:j}},zy),Ct((b,S)=>b&&b.atBottom===S.atBottom))),x=Yt(Y(r,jn((b,{scrollHeight:S,scrollTop:T,viewportHeight:k})=>{if(ku(b.scrollHeight,S))return{changed:!1,jump:0,scrollHeight:S,scrollTop:T};{const C=S-(T+k)<1;return b.scrollTop!==T&&C?{changed:!0,jump:b.scrollTop-T,scrollHeight:S,scrollTop:T}:{changed:!0,jump:0,scrollHeight:S,scrollTop:T}}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),je(b=>b.changed),me(b=>b.jump)),0);be(Y(g,me(b=>b.atBottom)),i),be(Y(i,Bn(50)),l);const y=te(yo);be(Y(r,me(({scrollTop:b})=>b),Ct(),jn((b,S)=>Pt(p)?{direction:b.direction,prevScrollTop:S}:{direction:S<b.prevScrollTop?xo:yo,prevScrollTop:S},{direction:yo,prevScrollTop:0}),me(b=>b.direction)),y),be(Y(r,Bn(50),_n(Fy)),y);const m=te(0);return be(Y(h,je(b=>!b),_n(0)),m),be(Y(o,Bn(100),We(h),je(([b,S])=>!!S),jn(([b,S],[T])=>[S,T],[0,0]),me(([b,S])=>S-b)),m),{atBottomState:g,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:f,isAtBottom:i,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:x,scrollDirection:y,scrollVelocity:m}},St(en)),ys="top",vs="bottom",Tu="none";function Eu(e,t,n){return typeof e=="number"?n===xo&&t===ys||n===yo&&t===vs?e:0:n===xo?t===ys?e.main:e.reverse:t===vs?e.main:e.reverse}function Iu(e,t){var n;return typeof e=="number"?e:(n=e[t])!=null?n:0}const ga=ot(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:r,viewportHeight:o}])=>{const s=Je(),i=te(0),a=te(0),l=te(0),c=Yt(Y(Dt(_e(r),_e(o),_e(n),_e(s,ho),_e(l),_e(i),_e(t),_e(e),_e(a)),me(([d,f,h,[p,g],x,y,m,b,S])=>{const T=d-b,k=y+m,C=Math.max(h-T,0);let E=Tu;const R=Iu(S,ys),_=Iu(S,vs);return p-=b,p+=h+m,g+=h+m,g-=b,p>d+k-R&&(E=xo),g<d-C+f+_&&(E=yo),E!==Tu?[Math.max(T-h-Eu(x,ys,E)-R,0),T-C-m+f+Eu(x,vs,E)+_]:null}),je(d=>d!=null),Ct(ho)),[0,0]);return{increaseViewportBy:a,listBoundary:s,overscan:l,topListHeight:i,visibleRange:c}},St(en),{singleton:!0});function Hy(e,t,n){if(xs(t)){const r=vu(e,t);return[{index:kn(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 xa={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function ws(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 x=e[e.length-1];d=x.offset+x.size}const f=n-i,h=a+f*l+(f-1)*r,p=c,g=h-d;return{bottom:d,firstItemIndex:s,items:Au(e,o,s),offsetBottom:g,offsetTop:c,top:p,topItems:Au(t,o,s),topListHeight:t.reduce((x,y)=>y.size+x,0),totalCount:n}}function Nu(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=ma(t,a),c=Array.from({length:a}).map((d,f)=>({data:s[f+l],index:f+l,offset:0,size:0}));return ws(c,[],a,o,n,r)}function Au(e,t,n){if(e.length===0)return[];if(!xs(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=ps(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 br=ot(([{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:g}])=>{const x=te([]),y=te(0),m=Je();be(s.topItemsIndexes,x);const b=Yt(Y(Dt(p,g,_e(l,ho),_e(o),_e(r),_e(c),d,_e(x),_e(t),_e(n),e),je(([C,E,,R,,,,,,,_])=>{const j=_&&_.length!==R;return C&&!E&&!j}),me(([,,[C,E],R,_,j,L,z,V,O,H])=>{const P=_,{offsetTree:W,sizeTree:F}=P,$=Pt(y);if(R===0)return{...xa,totalCount:R};if(C===0&&E===0)return $===0?{...xa,totalCount:R}:Nu($,j,_,V,O,H||[]);if(mt(F))return $>0?null:ws(Hy(ma(j,R),P,H),[],R,O,P,V);const ne=[];if(z.length>0){const ie=z[0],Te=z[z.length-1];let ee=0;for(const D of ps(F,ie,Te)){const X=D.value,ae=Math.max(D.start,ie),fe=Math.min(D.end,Te);for(let B=ae;B<=fe;B++)ne.push({data:H==null?void 0:H[B],index:B,offset:ee,size:X}),ee+=X}}if(!L)return ws([],ne,R,O,P,V);const oe=z.length>0?z[z.length-1]+1:0,we=_y(W,C,E,oe);if(we.length===0)return null;const Ne=R-1,Z=hs([],ie=>{for(const Te of we){const ee=Te.value;let D=ee.offset,X=Te.start;const ae=ee.size;if(ee.offset<C){X+=Math.floor((C-ee.offset+O)/(ae+O));const B=X-Te.start;D+=B*ae+B*O}X<oe&&(D+=(oe-X)*ae,X=oe);const fe=Math.min(Te.end,Ne);for(let B=X;B<=fe&&!(D>=E);B++)ie.push({data:H==null?void 0:H[B],index:B,offset:D,size:ae}),D+=ae+O}});return ws(Z,ne,R,O,P,V)}),je(C=>C!==null),Ct()),xa);be(Y(e,je(ra),me(C=>C==null?void 0:C.length)),o),be(Y(b,me(C=>C.topListHeight)),f),be(f,a),be(Y(b,me(C=>[C.top,C.bottom])),i),be(Y(b,me(C=>C.items)),m);const S=ln(Y(b,je(({items:C})=>C.length>0),We(o,e),je(([{items:C},E])=>C[C.length-1].originalIndex===E-1),me(([,C,E])=>[C-1,E]),Ct(ho),me(([C])=>C))),T=ln(Y(b,Bn(200),je(({items:C,topItems:E})=>C.length>0&&C[0].originalIndex===E.length),me(({items:C})=>C[0].index),Ct())),k=ln(Y(b,je(({items:C})=>C.length>0),me(({items:C})=>{let E=0,R=C.length-1;for(;C[E].type==="group"&&E<R;)E++;for(;C[R].type==="group"&&R>E;)R--;return{endIndex:C[R].index,startIndex:C[E].index}}),Ct(xu)));return{endReached:S,initialItemCount:y,itemsRendered:m,listState:b,rangeChanged:k,startReached:T,topItemsIndexes:x,...h}},St(Rn,Su,ga,go,mo,vo,Zn,da),{singleton:!0}),_u=ot(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:r},{listState:o}])=>{const s=Je(),i=Yt(Y(Dt(n,e,r,t,o),me(([a,l,c,d,f])=>a+l+c+d+f.offsetBottom+f.bottom)),0);return be(_e(i),s),{totalListHeight:i,totalListHeightChanged:s}},St(en,br),{singleton:!0}),Uy=ot(([{viewportHeight:e},{totalListHeight:t}])=>{const n=te(!1),r=Yt(Y(Dt(n,e,t),je(([o])=>o),me(([,o,s])=>Math.max(0,o-s)),Bn(0),Ct()),0);return{alignToBottom:n,paddingTopAddition:r}},St(en,_u),{singleton:!0}),ju=ot(()=>({context:te(null)})),Wy=({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,Ru=ot(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:r,fixedHeaderHeight:o,headerHeight:s,scrollingInProgress:i,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Je();return be(Y(d,We(t,l,n,s,o,r,a),We(e),me(([[f,h,p,g,x,y,m,b],S])=>{const{align:T,behavior:k,calculateViewLocation:C=Wy,done:E,...R}=f,_=wu(f,h,g-1),j=po(_,h.offsetTree,S)+x+y,L=j+kn(h.sizeTree,_)[1],z=b+y,V=b+p-m,O=C({itemBottom:L,itemTop:j,locationParams:{align:T,behavior:k,...R},viewportBottom:V,viewportTop:z});return O?E&&Cn(Y(i,je(H=>!H),yr(Pt(i)?1:2)),E):E&&E(),O}),je(f=>f!==null)),c),{scrollIntoView:d}},St(Rn,en,mo,br,Yn),{singleton:!0});function Pu(e){return e?e==="smooth"?"smooth":"auto":!1}const Vy=(e,t)=>typeof e=="function"?Pu(e(t)):t&&Pu(e),Ky=ot(([{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 g=te(!1),x=Je();let y=null;function m(k){ze(i,{align:"end",behavior:k,index:"LAST"})}ct(Y(Dt(Y(_e(t),yr(1)),l),We(_e(g),s,a,f),me(([[k,C],E,R,_,j])=>{let L=C&&_,z="auto";return L&&(z=Vy(E,R||j),L=L&&!!z),{followOutputBehavior:z,shouldFollow:L,totalCount:k}}),je(({shouldFollow:k})=>k)),({followOutputBehavior:k,totalCount:C})=>{y&&(y(),y=null),Pt(n)?requestAnimationFrame(()=>{Pt(d)("following output to ",{totalCount:C},sn.DEBUG),m(k)}):y=Cn(e,()=>{Pt(d)("following output to ",{totalCount:C},sn.DEBUG),m(k),y=null})});function b(k){const C=Cn(o,E=>{k&&!E.atBottom&&E.notAtBottomBecause==="SIZE_INCREASED"&&!y&&(Pt(d)("scrolling to bottom due to increased size",{},sn.DEBUG),m("auto"))});setTimeout(C,100)}ct(Y(Dt(_e(g),t,c),je(([k,,C])=>k&&C),jn(({value:k},[,C])=>({refreshed:k===C,value:C}),{refreshed:!1,value:0}),je(({refreshed:k})=>k),We(g,t)),([,k])=>{Pt(a)&&b(k!==!1)}),ct(x,()=>{b(Pt(g)!==!1)}),ct(Dt(_e(g),o),([k,C])=>{k&&!C.atBottom&&C.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&m("auto")});const S=te(null),T=Je();return be(sa(Y(_e(r),me(k=>{var C;return(C=k==null?void 0:k.length)!=null?C:0})),Y(_e(t))),T),ct(Y(Dt(Y(T,yr(1)),l),We(_e(S),a,f,h),me(([[k,C],E,R,_,j])=>C&&R&&(E==null?void 0:E({context:j,totalCount:k,scrollingInProgress:_}))),je(k=>!!k),Bn(0)),k=>{y&&(y(),y=null),Pt(n)?requestAnimationFrame(()=>{Pt(d)("scrolling into view",{}),ze(p,k)}):y=Cn(e,()=>{Pt(d)("scrolling into view",{}),ze(p,k),y=null})}),{autoscrollToBottom:x,followOutput:g,scrollIntoViewOnChange:S}},St(Rn,vo,mo,go,Zn,Yn,en,ju,Ru)),qy=ot(([{data:e,firstItemIndex:t,gap:n,sizes:r},{initialTopMostItemIndex:o},{initialItemCount:s,listState:i},{didMount:a}])=>(be(Y(a,We(s),je(([,l])=>l!==0),We(o,r,t,n,e),me(([[,l],c,d,f,h,p=[]])=>Nu(l,c,d,f,h,p))),i),{}),St(Rn,go,br,Zn),{singleton:!0}),Gy=ot(([{didMount:e},{scrollTo:t},{listState:n}])=>{const r=te(0);return ct(Y(e,We(r),je(([,o])=>o!==0),me(([,o])=>({top:o}))),o=>{Cn(Y(n,yr(1),je(s=>s.items.length>1)),()=>{requestAnimationFrame(()=>{ze(t,o)})})}),{initialScrollTop:r}},St(Zn,en,br),{singleton:!0}),Ou=ot(([{scrollVelocity:e}])=>{const t=te(!1),n=Je(),r=te(!1);return be(Y(e,We(r,t,n),je(([o,s])=>!!s),me(([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}),Ct()),t),ct(Y(Dt(t,e,n),We(r)),([[o,s,i],a])=>{o&&a&&a.change&&a.change(s,i)}),{isSeeking:t,scrollSeekConfiguration:r,scrollSeekRangeChanged:n,scrollVelocity:e}},St(vo),{singleton:!0}),ya=ot(([{scrollContainerState:e,scrollTo:t}])=>{const n=Je(),r=Je(),o=Je(),s=te(!1),i=te(void 0);return be(Y(Dt(n,r),me(([{scrollHeight:a,scrollTop:l,viewportHeight:c},{offsetTop:d}])=>({scrollHeight:a,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),be(Y(t,We(r),me(([a,{offsetTop:l}])=>({...a,top:a.top+l}))),o),{customScrollParent:i,useWindowScroll:s,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:r}},St(en)),Xy=ot(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:r},{initialTopMostItemIndex:o},{didMount:s},{useWindowScroll:i,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Je(),d=te(void 0),f=te(null),h=te(null);return be(a,f),be(l,h),ct(Y(c,We(t,r,i,f,h,n)),([p,g,x,y,m,b,S])=>{const T=Ry(g.sizeTree);y&&m!==null&&b!==null&&(x=m.scrollTop-b.offsetTop),x-=S,p({ranges:T,scrollTop:x})}),be(Y(d,je(ra),me(Yy)),o),be(Y(s,We(d),je(([,p])=>p!==void 0),Ct(),me(([,p])=>p.ranges)),e),{getState:c,restoreStateFrom:d}},St(Rn,en,go,Zn,ya));function Yy(e){return{align:"start",index:0,offset:e.scrollTop}}const Jy=ot(([{topItemsIndexes:e}])=>{const t=te(0);return be(Y(t,je(n=>n>=0),me(n=>Array.from({length:n}).map((r,o)=>o))),e),{topItemCount:t}},St(br));function Mu(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const Zy=Mu(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Qy=ot(([{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:g}])=>{const x=ln(Y(l,We(i),jn(([,m,b,S],[{bottom:T,items:k,offsetBottom:C,totalCount:E},R])=>{const _=T+C;let j=0;return b===E&&m.length>0&&k.length>0&&(k[0].originalIndex===0&&m[0].originalIndex===0||(j=_-S,j!==0&&(j+=R))),[j,k,E,_]},[0,[],0,0]),je(([m])=>m!==0),We(r,a,n,o,p,g),je(([,m,b,S,,,T])=>!T&&!S&&m!==0&&b===xo),me(([[m],,,,,b])=>(b("Upward scrolling compensation",{amount:m},sn.DEBUG),m))));function y(m){m>0?(ze(t,{behavior:"auto",top:-m}),ze(e,0)):(ze(e,0),ze(t,{behavior:"auto",top:-m}))}return ct(Y(x,We(e,s)),([m,b,S])=>{S&&Zy()?ze(e,b-m):y(-m)}),ct(Y(Dt(Yt(s,!1),e,g),je(([m,b,S])=>!m&&!S&&b!==0),me(([m,b])=>b),Bn(1)),y),be(Y(f,me(m=>({top:-m}))),t),ct(Y(c,We(h,d),me(([m,{groupIndices:b,lastSize:S,sizeTree:T},k])=>{function C(E){return E*(S+k)}if(b.length===0)return C(m);{let E=0;const R=fo(T,0);let _=0,j=0;for(;_<m;){_++,E+=R;let L=b.length===j+1?1/0:b[j+1]-b[j]-1;_+L>m&&(E-=R,L=m-_+1),_+=L,E+=C(L),j++}return E}})),m=>{ze(e,m),requestAnimationFrame(()=>{ze(t,{top:m}),requestAnimationFrame(()=>{ze(e,0),ze(g,!1)})})}),{deviation:e}},St(en,vo,br,Rn,Yn,da)),ev=ot(([e,t,n,r,o,s,i,a,l,c,d])=>({...e,...t,...n,...r,...o,...s,...i,...a,...l,...c,...d}),St(ga,qy,Zn,Ou,_u,Gy,Uy,ya,Ru,Yn,ju)),Du=ot(([{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:g},x,y,m,{listState:b,topItemsIndexes:S,...T},{scrollToIndex:k},C,{topItemCount:E},{groupCounts:R},_])=>(be(T.rangeChanged,_.scrollSeekRangeChanged),be(Y(_.windowViewportRect,me(j=>j.visibleHeight)),x.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:r,gap:o,groupCounts:R,initialItemFinalLocationReached:h,initialTopMostItemIndex:p,scrolledToInitialItem:g,sizeRanges:a,topItemCount:E,topItemsIndexes:S,totalCount:d,...m,groupIndices:s,itemSize:i,listState:b,scrollToIndex:k,statefulTotalCount:c,trackItemSizes:f,...T,..._,...x,sizes:l,...y}),St(Rn,go,en,Xy,Ky,br,mo,Qy,Jy,Su,ev));function tv(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 bs=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Lu(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,m){y.propsReady&&ze(y.propsReady,!1);for(const b of r){const S=y[t.required[b]];ze(S,m[b])}for(const b of o)if(b in m){const S=y[t.optional[b]];ze(S,m[b])}y.propsReady&&ze(y.propsReady,!0)}function c(y){return s.reduce((m,b)=>(m[b]=S=>{const T=y[t.methods[b]];ze(T,S)},m),{})}function d(y){return i.reduce((m,b)=>(m[b]=xy(y[t.events[b]]),m),{})}const f=w.forwardRef((y,m)=>{const{children:b,...S}=y,[T]=w.useState(()=>hs(vy(e),E=>{l(E,S)})),[k]=w.useState(iu(d,T));bs(()=>{for(const E of i)E in S&&ct(k[E],S[E]);return()=>{Object.values(k).map(oa)}},[S,k,T]),bs(()=>{l(T,S)}),w.useImperativeHandle(m,ou(c(T)));const C=n;return u.jsx(a.Provider,{value:T,children:n?u.jsx(C,{...tv([...r,...o,...i],S),children:b}):b})}),h=y=>{const m=w.useContext(a);return w.useCallback(b=>{ze(m[y],b)},[m,y])},p=y=>{const m=w.useContext(a)[y],b=w.useCallback(S=>ct(m,S),[m]);return w.useSyncExternalStore(b,()=>Pt(m),()=>Pt(m))},g=y=>{const m=w.useContext(a)[y],[b,S]=w.useState(iu(Pt,m));return bs(()=>ct(m,T=>{T!==b&&S(ou(T))}),[m,b]),b},x=w.version.startsWith("18")?p:g;return{Component:f,useEmitter:(y,m)=>{const b=w.useContext(a)[y];bs(()=>ct(b,m),[m,b])},useEmitterValue:x,usePublisher:h}}const $u=w.createContext(void 0),Fu=w.createContext(void 0),zu=typeof document<"u"?w.useLayoutEffect:w.useEffect;function va(e){return"self"in e}function nv(e){return"body"in e}function Bu(e,t,n,r=Fr,o,s){const i=w.useRef(null),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(h=>{let p,g,x;const y=h.target;if(nv(y)||va(y)){const b=va(y)?y:y.defaultView;x=s?b.scrollX:b.scrollY,p=s?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,g=s?b.innerWidth:b.innerHeight}else x=s?y.scrollLeft:y.scrollTop,p=s?y.scrollWidth:y.scrollHeight,g=s?y.offsetWidth:y.offsetHeight;const m=()=>{e({scrollHeight:p,scrollTop:Math.max(x,0),viewportHeight:g})};h.suppressFlushSync?m():Ti.flushSync(m),a.current!==null&&(x===a.current||x<=0||x===p-g)&&(a.current=null,t(!0),l.current&&(clearTimeout(l.current),l.current=null))},[e,t,s]);w.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 g=h.behavior==="smooth";let x,y,m;va(p)?(y=Math.max(Jn(p.document.documentElement,s?"width":"height"),s?p.document.documentElement.scrollWidth:p.document.documentElement.scrollHeight),x=s?p.innerWidth:p.innerHeight,m=s?window.scrollX:window.scrollY):(y=p[s?"scrollWidth":"scrollHeight"],x=Jn(p,s?"width":"height"),m=p[s?"scrollLeft":"scrollTop"]);const b=y-x;if(h.top=Math.ceil(Math.max(Math.min(b,h.top),0)),ku(x,y)||h.top===m){e({scrollHeight:y,scrollTop:m,viewportHeight:x}),g&&t(!0);return}g?(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 wa="-webkit-sticky",Hu="sticky",ba=Mu(()=>{if(typeof document>"u")return Hu;const e=document.createElement("div");return e.style.position=wa,e.style.position===wa?wa:Hu});function Sa(e){return e}const rv=ot(()=>{const e=te(a=>`Item ${a}`),t=te(a=>`Group ${a}`),n=te({}),r=te(Sa),o=te("div"),s=te(Fr),i=(a,l=null)=>Yt(Y(n,me(c=>c[a]),Ct()),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")}}),ov=ot(([e,t])=>({...e,...t}),St(Du,rv)),sv=({height:e})=>u.jsx("div",{style:{height:e}}),iv={overflowAnchor:"none",position:ba(),zIndex:1},Uu={overflowAnchor:"none"},av={...Uu,display:"inline-block",height:"100%"},Wu=w.memo(function({showTopList:e=!1}){const t=Me("listState"),n=pn("sizeRanges"),r=Me("useWindowScroll"),o=Me("customScrollParent"),s=pn("windowScrollContainerState"),i=pn("scrollContainerState"),a=o||r?s:i,l=Me("itemContent"),c=Me("context"),d=Me("groupContent"),f=Me("trackItemSizes"),h=Me("itemSize"),p=Me("log"),g=pn("gap"),x=Me("horizontalDirection"),{callbackRef:y}=Sy(n,h,f,e?Fr:a,p,g,o,x,Me("skipAnimationFrameInResizeObserver")),[m,b]=w.useState(0);Ca("deviation",O=>{m!==O&&b(O)});const S=Me("EmptyPlaceholder"),T=Me("ScrollSeekPlaceholder")||sv,k=Me("ListComponent"),C=Me("ItemComponent"),E=Me("GroupComponent"),R=Me("computeItemKey"),_=Me("isSeeking"),j=Me("groupIndices").length>0,L=Me("alignToBottom"),z=Me("initialItemFinalLocationReached"),V=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginLeft:m!==0?m:L?"auto":0,paddingLeft:t.offsetTop,paddingRight:t.offsetBottom,whiteSpace:"nowrap"}:{marginTop:m!==0?m:L?"auto":0,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...z?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&S?u.jsx(S,{...Jt(S,c)}):u.jsx(k,{...Jt(k,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:V,children:(e?t.topItems:t.items).map(O=>{const H=O.originalIndex,P=R(H+t.firstItemIndex,O.data,c);return _?w.createElement(T,{...Jt(T,c),height:O.size,index:O.index,key:P,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?w.createElement(E,{...Jt(E,c),"data-index":H,"data-item-index":O.index,"data-known-size":O.size,key:P,style:iv},d(O.index,c)):w.createElement(C,{...Jt(C,c),...dv(C,O.data),"data-index":H,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:P,style:x?av:Uu},j?l(O.index,O.groupIndex,O.data,c):l(O.index,O.data,c))})})}),lv={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},cv={outline:"none",overflowX:"auto",position:"relative"},Ss=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),uv={position:ba(),top:0,width:"100%",zIndex:1};function Jt(e,t){if(typeof e!="string")return{context:t}}function dv(e,t){return{item:typeof e=="string"?void 0:t}}const fv=w.memo(function(){const e=Me("HeaderComponent"),t=pn("headerHeight"),n=Me("HeaderFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,Me("skipAnimationFrameInResizeObserver")),o=Me("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null}),hv=w.memo(function(){const e=Me("FooterComponent"),t=pn("footerHeight"),n=Me("HeaderFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,Me("skipAnimationFrameInResizeObserver")),o=Me("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null});function Vu({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:h,scrollerRef:p,scrollToCallback:g}=Bu(a,c,l,d,void 0,f);return e("scrollTo",g),e("scrollBy",h),u.jsx(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:p,style:{...f?cv:lv,...o},tabIndex:0,...i,...Jt(l,s),children:r})})}function Ku({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"),h=t("customScrollParent"),p=w.useRef(null),g=t("scrollerRef"),{scrollByCallback:x,scrollerRef:y,scrollToCallback:m}=Bu(a,c,l,g,h);return zu(()=>{var b;return y.current=h||((b=p.current)==null?void 0:b.ownerDocument.defaultView),()=>{y.current=null}},[y,h]),e("windowScrollTo",m),e("scrollBy",x),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 pv=({children:e})=>{const t=w.useContext($u),n=pn("viewportHeight"),r=pn("fixedItemHeight"),o=Me("alignToBottom"),s=Me("horizontalDirection"),i=w.useMemo(()=>su(n,l=>Jn(l,s?"width":"height")),[n,s]),a=vr(i,!0,Me("skipAnimationFrameInResizeObserver"));return w.useEffect(()=>{t&&(n(t.viewportHeight),r(t.itemHeight))},[t,n,r]),u.jsx("div",{"data-viewport-type":"element",ref:a,style:Ss(o),children:e})},mv=({children:e})=>{const t=w.useContext($u),n=pn("windowViewportRect"),r=pn("fixedItemHeight"),o=Me("customScrollParent"),s=uu(n,o,Me("skipAnimationFrameInResizeObserver")),i=Me("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:Ss(i),children:e})},gv=({children:e})=>{const t=Me("TopItemListComponent")||"div",n=Me("headerHeight"),r={...uv,marginTop:`${n}px`},o=Me("context");return u.jsx(t,{style:r,...Jt(t,o),children:e})},xv=w.memo(function(e){const t=Me("useWindowScroll"),n=Me("topItemsIndexes").length>0,r=Me("customScrollParent"),o=Me("context");return u.jsxs(r||t?wv:vv,{...e,context:o,children:[n&&u.jsx(gv,{children:u.jsx(Wu,{showTopList:!0})}),u.jsxs(r||t?mv:pv,{children:[u.jsx(fv,{}),u.jsx(Wu,{}),u.jsx(hv,{})]})]})}),{Component:yv,useEmitter:Ca,useEmitterValue:Me,usePublisher:pn}=Lu(ov,{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"}},xv),vv=Vu({useEmitter:Ca,useEmitterValue:Me,usePublisher:pn}),wv=Ku({useEmitter:Ca,useEmitterValue:Me,usePublisher:pn}),bv=yv;St(Du,ot(()=>{const e=te(c=>u.jsxs("td",{children:["Item $",c]})),t=te(null),n=te(c=>u.jsxs("td",{colSpan:1e3,children:["Group ",c]})),r=te(null),o=te(null),s=te({}),i=te(Sa),a=te(Fr),l=(c,d=null)=>Yt(Y(s,me(f=>f[c]),Ct()),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")}})),ba();const qu={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},Sv={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Gu,floor:Cs,max:wo,min:ka,round:Xu}=Math;function Yu(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>({data:n===null?null:n[o+e],index:o+e}))}function Cv(e){return{...Sv,items:e}}function ks(e,t){return e&&e.width===t.width&&e.height===t.height}function kv(e,t){return e&&e.column===t.column&&e.row===t.row}const Tv=ot(([{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:g,propsReady:x},{customScrollParent:y,useWindowScroll:m,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T},k])=>{const C=te(0),E=te(0),R=te(qu),_=te({height:0,width:0}),j=te({height:0,width:0}),L=Je(),z=Je(),V=te(0),O=te(null),H=te({column:0,row:0}),P=Je(),W=Je(),F=te(!1),$=te(0),ne=te(!0),oe=te(!1),we=te(!1);ct(Y(g,We($),je(([D,X])=>!!X)),()=>{ze(ne,!1)}),ct(Y(Dt(g,ne,j,_,$,oe),je(([D,X,ae,fe,,B])=>D&&!X&&ae.height!==0&&fe.height!==0&&!B)),([,,,,D])=>{ze(oe,!0),pa(1,()=>{ze(L,D)}),Cn(Y(c),()=>{ze(t,[0,0]),ze(ne,!0)})}),be(Y(W,je(D=>D!=null&&D.scrollTop>0),_n(0)),E),ct(Y(g,We(W),je(([,D])=>D!=null)),([,D])=>{D&&(ze(_,D.viewport),ze(j,D.item),ze(H,D.gap),D.scrollTop>0&&(ze(F,!0),Cn(Y(c,yr(1)),X=>{ze(F,!1)}),ze(l,{top:D.scrollTop})))}),be(Y(_,me(({height:D})=>D)),f),be(Y(Dt(_e(_,ks),_e(j,ks),_e(H,(D,X)=>D&&D.column===X.column&&D.row===X.row),_e(c)),me(([D,X,ae,fe])=>({gap:ae,item:X,scrollTop:fe,viewport:D}))),P),be(Y(Dt(_e(C),r,_e(H,kv),_e(j,ks),_e(_,ks),_e(O),_e(E),_e(F),_e(ne),_e($)),je(([,,,,,,,D])=>!D),me(([D,[X,ae],fe,B,le,Q,Ae,,ve,Re])=>{const{column:Ve,row:Qe}=fe,{height:et,width:Se}=B,{width:nt}=le;if(Ae===0&&(D===0||nt===0))return qu;if(Se===0){const He=ma(Re,D),Tt=He+Math.max(Ae-1,0);return Cv(Yu(He,Tt,Q))}const ut=Ju(nt,Se,Ve);let rt,Ye;ve?X===0&&ae===0&&Ae>0?(rt=0,Ye=Ae-1):(rt=ut*Cs((X+Qe)/(et+Qe)),Ye=ut*Gu((ae+Qe)/(et+Qe))-1,Ye=ka(D-1,wo(Ye,ut-1)),rt=ka(Ye,wo(0,rt))):(rt=0,Ye=-1);const It=Yu(rt,Ye,Q),{bottom:dt,top:kt}=Zu(le,fe,B,It),Nt=Gu(D/ut),tt=Nt*et+(Nt-1)*Qe-dt;return{bottom:dt,itemHeight:et,items:It,itemWidth:Se,offsetBottom:tt,offsetTop:kt,top:kt}})),R),be(Y(O,je(D=>D!==null),me(D=>D.length)),C),be(Y(Dt(_,j,R,H),je(([D,X,{items:ae}])=>ae.length>0&&X.height!==0&&D.height!==0),me(([D,X,{items:ae},fe])=>{const{bottom:B,top:le}=Zu(D,fe,X,ae);return[le,B]}),Ct(ho)),t);const Ne=te(!1);be(Y(c,We(Ne),me(([D,X])=>X||D!==0)),Ne);const Z=ln(Y(Dt(R,C),je(([{items:D}])=>D.length>0),We(Ne),je(([[D,X],ae])=>{const fe=D.items[D.items.length-1].index===X-1;return(ae||D.bottom>0&&D.itemHeight>0&&D.offsetBottom===0&&D.items.length===X)&&fe}),me(([[,D]])=>D-1),Ct())),ie=ln(Y(_e(R),je(({items:D})=>D.length>0&&D[0].index===0),_n(0),Ct())),Te=ln(Y(_e(R),We(F),je(([{items:D},X])=>D.length>0&&!X),me(([{items:D}])=>({endIndex:D[D.length-1].index,startIndex:D[0].index})),Ct(xu),Bn(0)));be(Te,p.scrollSeekRangeChanged),be(Y(L,We(_,j,C,H),me(([D,X,ae,fe,B])=>{const le=Cu(D),{align:Q,behavior:Ae,offset:ve}=le;let Re=le.index;Re==="LAST"&&(Re=fe-1),Re=wo(0,Re,ka(fe-1,Re));let Ve=Ta(X,B,ae,Re);return Q==="end"?Ve=Xu(Ve-X.height+ae.height):Q==="center"&&(Ve=Xu(Ve-X.height/2+ae.height/2)),ve&&(Ve+=ve),{behavior:Ae,top:Ve}})),l);const ee=Yt(Y(R,me(D=>D.offsetBottom+D.bottom)),0);return be(Y(T,me(D=>({height:D.visibleHeight,width:D.visibleWidth}))),_),{customScrollParent:y,data:O,deviation:V,footerHeight:o,gap:H,headerHeight:s,increaseViewportBy:e,initialItemCount:E,itemDimensions:j,overscan:n,restoreStateFrom:W,scrollBy:i,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:L,scrollTop:c,smoothScrollTargetReached:d,totalCount:C,useWindowScroll:m,viewportDimensions:_,windowScrollContainerState:b,windowScrollTo:S,windowViewportRect:T,...p,gridState:R,horizontalDirection:we,initialTopMostItemIndex:$,totalListHeight:ee,...h,endReached:Z,propsReady:x,rangeChanged:Te,startReached:ie,stateChanged:P,stateRestoreInProgress:F,...k}},St(ga,en,vo,Ou,Zn,ya,Yn));function Ju(e,t,n){return wo(1,Cs((e+n)/(Cs(t)+n)))}function Zu(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{bottom:0,top:0};const s=Ta(e,t,n,r[0].index);return{bottom:Ta(e,t,n,r[r.length-1].index)+o,top:s}}function Ta(e,t,n,r){const o=Ju(e.width,n.width,t.column),s=Cs(r/o),i=s*n.height+wo(0,s-1)*t.row;return i>0?i+t.row:i}const Ev=ot(()=>{const e=te(f=>`Item ${f}`),t=te({}),n=te(null),r=te("virtuoso-grid-item"),o=te("virtuoso-grid-list"),s=te(Sa),i=te("div"),a=te(Fr),l=(f,h=null)=>Yt(Y(t,me(p=>p[f]),Ct()),h),c=te(!1),d=te(!1);return be(_e(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")}}),Iv=ot(([e,t])=>({...e,...t}),St(Tv,Ev)),Nv=w.memo(function(){const e=Et("gridState"),t=Et("listClassName"),n=Et("itemClassName"),r=Et("itemContent"),o=Et("computeItemKey"),s=Et("isSeeking"),i=mn("scrollHeight"),a=Et("ItemComponent"),l=Et("ListComponent"),c=Et("ScrollSeekPlaceholder"),d=Et("context"),f=mn("itemDimensions"),h=mn("gap"),p=Et("log"),g=Et("stateRestoreInProgress"),x=mn("reportReadyState"),y=vr(w.useMemo(()=>m=>{const b=m.parentElement.parentElement.scrollHeight;i(b);const S=m.firstChild;if(S){const{height:T,width:k}=S.getBoundingClientRect();f({height:T,width:k})}h({column:ed("column-gap",getComputedStyle(m).columnGap,p),row:ed("row-gap",getComputedStyle(m).rowGap,p)})},[i,f,h,p]),!0,!1);return zu(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),g?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(m=>{const b=o(m.index,m.data,d);return s?u.jsx(c,{...Jt(c,d),height:e.itemHeight,index:m.index,width:e.itemWidth},b):w.createElement(a,{...Jt(a,d),className:n,"data-index":m.index,key:b},r(m.index,m.data,d))})})}),Av=w.memo(function(){const e=Et("HeaderComponent"),t=mn("headerHeight"),n=Et("headerFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,!1),o=Et("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null}),_v=w.memo(function(){const e=Et("FooterComponent"),t=mn("footerHeight"),n=Et("headerFooterTag"),r=vr(w.useMemo(()=>s=>{t(Jn(s,"height"))},[t]),!0,!1),o=Et("context");return e?u.jsx(n,{ref:r,children:u.jsx(e,{...Jt(e,o)})}):null}),jv=({children:e})=>{const t=w.useContext(Fu),n=mn("itemDimensions"),r=mn("viewportDimensions"),o=vr(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:Ss(!1),children:e})},Rv=({children:e})=>{const t=w.useContext(Fu),n=mn("windowViewportRect"),r=mn("itemDimensions"),o=Et("customScrollParent"),s=uu(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:Ss(!1),children:e})},Pv=w.memo(function({...e}){const t=Et("useWindowScroll"),n=Et("customScrollParent"),r=n||t?Mv:Ov,o=n||t?Rv:jv,s=Et("context");return u.jsx(r,{...e,...Jt(r,s),children:u.jsxs(o,{children:[u.jsx(Av,{}),u.jsx(Nv,{}),u.jsx(_v,{})]})})}),{useEmitter:Qu,useEmitterValue:Et,usePublisher:mn}=Lu(Iv,{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"}},Pv),Ov=Vu({useEmitter:Qu,useEmitterValue:Et,usePublisher:mn}),Mv=Ku({useEmitter:Qu,useEmitterValue:Et,usePublisher:mn});function ed(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,sn.WARN),t==="normal"?0:parseInt(t??"0",10)}const Dv=Uo.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 td({className:e,variant:t,...n}){return u.jsx("div",{className:se(Dv({variant:t}),e),...n})}const bo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));bo.displayName="Card";const So=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex flex-col space-y-1.5 p-6",e),...t}));So.displayName="CardHeader";const Co=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:se("text-2xl font-semibold leading-none tracking-tight",e),...t}));Co.displayName="CardTitle";const nd=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:se("text-sm text-muted-foreground",e),...t}));nd.displayName="CardDescription";const ko=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("p-6 pt-0",e),...t}));ko.displayName="CardContent";const rd=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex items-center p-6 pt-0",e),...t}));rd.displayName="CardFooter";const Lv=1,$v=1e6;let Ea=0;function Fv(){return Ea=(Ea+1)%Number.MAX_SAFE_INTEGER,Ea.toString()}const Ia=new Map,od=e=>{if(Ia.has(e))return;const t=setTimeout(()=>{Ia.delete(e),To({type:"REMOVE_TOAST",toastId:e})},$v);Ia.set(e,t)},zv=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,Lv)};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?od(n):e.toasts.forEach(r=>{od(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)}}},Ts=[];let Es={toasts:[]};function To(e){Es=zv(Es,e),Ts.forEach(t=>{t(Es)})}function Bv({...e}){const t=Fv(),n=o=>To({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>To({type:"DISMISS_TOAST",toastId:t});return To({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Na(){const[e,t]=v.useState(Es);return v.useEffect(()=>(Ts.push(t),()=>{const n=Ts.indexOf(t);n>-1&&Ts.splice(n,1)}),[e]),{...e,toast:Bv,dismiss:n=>To({type:"DISMISS_TOAST",toastId:n})}}async function sd(e,t){return await bn(e,{responseType:"blob",onDownloadProgress:r=>{try{t&&r.lengthComputable}catch{}},maxBodyLength:1/0})}async function id(e,t){return await(await sd(`/files/${e}/view`,t)).text()}async function Hv(e,t){const n=await sd(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await bn(`/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 Uv(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await bn("/files",{params:r})}function Aa(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 ad(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Eo(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Eo).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(ad(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=Eo(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 Io(e){if(typeof e=="string")return e;if(ad(e))return"";try{const t=Eo(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function Wv(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function Vv(e){const t=Io(e);return typeof e=="string"&&Wv(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=Aa(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 ye(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 ld(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _a(...e){return t=>{let n=!1;const r=e.map(o=>{const s=ld(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():ld(e[o],null)}}}}function Ze(...e){return v.useCallback(_a(...e),e)}function Kv(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 Hn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var m;const{scope:h,children:p,...g}=f,x=((m=h==null?void 0:h[e])==null?void 0:m[l])||a,y=v.useMemo(()=>g,Object.values(g));return u.jsx(x.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,g=v.useContext(p);if(g)return g;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,qv(o,...t)]}function qv(...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 Ut=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},Gv=v[" useId ".trim().toString()]||(()=>{}),Xv=0;function Un(e){const[t,n]=v.useState(Gv());return Ut(()=>{n(r=>r??String(Xv++))},[e]),e||(t?`radix-${t}`:"")}var Yv=v[" useInsertionEffect ".trim().toString()]||Ut;function Br({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Jv({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=Zv(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 Jv({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return Yv(()=>{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 Zv(e){return typeof e=="function"}var Qv=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=Qv.reduce((e,t)=>{const n=hr.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 cd(e,t){e&&Wo.flushSync(()=>e.dispatchEvent(t))}function Wt(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 ew(e,t=globalThis==null?void 0:globalThis.document){const n=Wt(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 tw="DismissableLayer",ja="dismissableLayer.update",nw="dismissableLayer.pointerDownOutside",rw="dismissableLayer.focusOutside",ud,dd=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ns=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(dd),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),g=Ze(t,E=>f(E)),x=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),m=x.indexOf(y),b=d?x.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,T=b>=m,k=iw(E=>{const R=E.target,_=[...c.branches].some(j=>j.contains(R));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=aw(E=>{const R=E.target;[...c.branches].some(j=>j.contains(R))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return ew(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(ud=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),fd(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=ud)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),fd())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(ja,E),()=>document.removeEventListener(ja,E)},[]),u.jsx(De.div,{...l,ref:g,style:{pointerEvents:S?T?"auto":"none":void 0,...e.style},onFocusCapture:ye(e.onFocusCapture,C.onFocusCapture),onBlurCapture:ye(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:ye(e.onPointerDownCapture,k.onPointerDownCapture)})});Ns.displayName=tw;var ow="DismissableLayerBranch",sw=v.forwardRef((e,t)=>{const n=v.useContext(dd),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});sw.displayName=ow;function iw(e,t=globalThis==null?void 0:globalThis.document){const n=Wt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){hd(nw,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 aw(e,t=globalThis==null?void 0:globalThis.document){const n=Wt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&hd(rw,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 fd(){const e=new CustomEvent(ja);document.dispatchEvent(e)}function hd(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?cd(o,s):o.dispatchEvent(s)}var Ra="focusScope.autoFocusOnMount",Pa="focusScope.autoFocusOnUnmount",pd={bubbles:!1,cancelable:!0},lw="FocusScope",As=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=Wt(o),d=Wt(s),f=v.useRef(null),h=Ze(t,x=>l(x)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let x=function(S){if(p.paused||!a)return;const T=S.target;a.contains(T)?f.current=T:Qn(f.current,{select:!0})},y=function(S){if(p.paused||!a)return;const T=S.relatedTarget;T!==null&&(a.contains(T)||Qn(f.current,{select:!0}))},m=function(S){if(document.activeElement===document.body)for(const k of S)k.removedNodes.length>0&&Qn(a)};document.addEventListener("focusin",x),document.addEventListener("focusout",y);const b=new MutationObserver(m);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",y),b.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){xd.add(p);const x=document.activeElement;if(!a.contains(x)){const m=new CustomEvent(Ra,pd);a.addEventListener(Ra,c),a.dispatchEvent(m),m.defaultPrevented||(cw(pw(md(a)),{select:!0}),document.activeElement===x&&Qn(a))}return()=>{a.removeEventListener(Ra,c),setTimeout(()=>{const m=new CustomEvent(Pa,pd);a.addEventListener(Pa,d),a.dispatchEvent(m),m.defaultPrevented||Qn(x??document.body,{select:!0}),a.removeEventListener(Pa,d),xd.remove(p)},0)}}},[a,c,d,p]);const g=v.useCallback(x=>{if(!n&&!r||p.paused)return;const y=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,m=document.activeElement;if(y&&m){const b=x.currentTarget,[S,T]=uw(b);S&&T?!x.shiftKey&&m===T?(x.preventDefault(),n&&Qn(S,{select:!0})):x.shiftKey&&m===S&&(x.preventDefault(),n&&Qn(T,{select:!0})):m===b&&x.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});As.displayName=lw;function cw(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qn(r,{select:t}),document.activeElement!==n)return}function uw(e){const t=md(e),n=gd(t,e),r=gd(t.reverse(),e);return[n,r]}function md(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 gd(e,t){for(const n of e)if(!dw(n,{upTo:t}))return n}function dw(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 fw(e){return e instanceof HTMLInputElement&&"select"in e}function Qn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fw(e)&&t&&e.select()}}var xd=hw();function hw(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=yd(e,t),e.unshift(t)},remove(t){var n;e=yd(e,t),(n=e[0])==null||n.resume()}}}function yd(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pw(e){return e.filter(t=>t.tagName!=="A")}var mw="Portal",_s=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Ut(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ti.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});_s.displayName=mw;function gw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var gn=e=>{const{present:t,children:n}=e,r=xw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Ze(r.ref,yw(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};gn.displayName="Presence";function xw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=gw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=js(r.current);s.current=a==="mounted"?c:"none"},[a]),Ut(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=js(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]),Ut(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const x=js(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(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)})}},h=p=>{p.target===t&&(s.current=js(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 js(e){return(e==null?void 0:e.animationName)||"none"}function yw(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 Oa=0;function Ma(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??vd()),document.body.insertAdjacentElement("beforeend",e[1]??vd()),Oa++,()=>{Oa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Oa--}},[])}function vd(){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 Pn=function(){return Pn=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},Pn.apply(this,arguments)};function wd(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 vw(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 Rs="right-scroll-bar-position",Ps="width-before-scroll-bar",ww="with-scroll-bars-hidden",bw="--removed-body-scroll-bar-size";function Da(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Sw(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 Cw=typeof window<"u"?v.useLayoutEffect:v.useEffect,bd=new WeakMap;function kw(e,t){var n=Sw(null,function(r){return e.forEach(function(o){return Da(o,r)})});return Cw(function(){var r=bd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Da(a,null)}),s.forEach(function(a){o.has(a)||Da(a,i)})}bd.set(n,e)},[e]),n}function Tw(e){return e}function Ew(e,t){t===void 0&&(t=Tw);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 Iw(e){e===void 0&&(e={});var t=Ew(null);return t.options=Pn({async:!0,ssr:!1},e),t}var Sd=function(e){var t=e.sideCar,n=wd(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,Pn({},n))};Sd.isSideCarExport=!0;function Nw(e,t){return e.useMedium(t),Sd}var Cd=Iw(),La=function(){},Os=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:La,onWheelCapture:La,onTouchMoveCapture:La}),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,g=e.noIsolation,x=e.inert,y=e.allowPinchZoom,m=e.as,b=m===void 0?"div":m,S=e.gapMode,T=wd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,C=kw([n,t]),E=Pn(Pn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:Cd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:g,inert:x,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),Pn(Pn({},E),{ref:C})):v.createElement(b,Pn({},E,{className:l,ref:C}),a))});Os.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Os.classNames={fullWidth:Ps,zeroRight:Rs};var Aw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function _w(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Aw();return t&&e.setAttribute("nonce",t),e}function jw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Rw(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Pw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=_w())&&(jw(t,n),Rw(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ow=function(){var e=Pw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},kd=function(){var e=Ow(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Mw={left:0,top:0,right:0,gap:0},$a=function(e){return parseInt(e||"",10)||0},Dw=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[$a(n),$a(r),$a(o)]},Lw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Mw;var t=Dw(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])}},$w=kd(),Hr="data-scroll-locked",Fw=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
39
  .`.concat(ww,` {
40
40
  overflow: hidden `).concat(r,`;
41
41
  padding-right: `).concat(a,"px ").concat(r,`;
@@ -125,8 +125,8 @@ ${t}</tr>
125
125
  `}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=lf(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=lf(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 hf{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 pf{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 tr{constructor(t){this.options=t||kr,this.options.renderer=this.options.renderer||new Ka,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new hf,this.slugger=new pf}static parse(t,n){return new tr(n).parse(t)}static parseInline(t,n){return new tr(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,h,p,g,x,y,m,b,S,T,k,C;const E=t.length;for(o=0;o<E;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(C=this.options.extensions.renderers[p.type].call({parser:this},p),C!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=C||"";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,af(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(g=p.ordered,x=p.start,y=p.loose,a=p.items.length,h="",s=0;s<a;s++)b=p.items[s],S=b.checked,T=b.task,m="",b.task&&(k=this.renderer.checkbox(S),y?b.tokens.length>0&&b.tokens[0].type==="paragraph"?(b.tokens[0].text=k+" "+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=k+" "+b.tokens[0].tokens[0].text)):b.tokens.unshift({type:"text",text:k}):m+=k),m+=this.parse(b.tokens,y),h+=this.renderer.listitem(m,T,S);r+=this.renderer.list(h,g,x);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<E&&t[o+1].type==="text";)p=t[++o],h+=`
126
126
  `+(p.tokens?this.parseInline(p.tokens):p.text);r+=n?this.renderer.paragraph(h):h;continue}default:{const R='Token with "'+p.type+'" type was not found.';if(this.options.silent){console.error(R);return}else throw new Error(R)}}}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 Gs{constructor(t){this.options=t||kr}preprocess(t){return t}postprocess(t){return t}}Fm(Gs,"passThroughHooks",new Set(["preprocess","postprocess"]));function Ob(e,t,n){return r=>{if(r.message+=`
127
127
  Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Zt(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 mf(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...Ie.defaults,...s};const i=Ob(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(jb(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&&Ie.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;Ie.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(Ie.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&&Ie.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function Ie(e,t,n){return mf(er.lex,tr.parse)(e,t,n)}Ie.options=Ie.setOptions=function(e){return Ie.defaults={...Ie.defaults,...e},yb(Ie.defaults),Ie},Ie.getDefaults=nf,Ie.defaults=kr,Ie.use=function(...e){const t=Ie.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=Ie.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=Ie.defaults.renderer||new Ka;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=Ie.defaults.tokenizer||new Va;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=Ie.defaults.hooks||new Gs;for(const s in n.hooks){const i=o[s];Gs.passThroughHooks.has(s)?o[s]=a=>{if(Ie.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=Ie.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}}Ie.setOptions(r)})},Ie.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(Ie,r)),r.type){case"table":{for(const o of r.header)n=n.concat(Ie.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(Ie.walkTokens(s.tokens,t));break}case"list":{n=n.concat(Ie.walkTokens(r.items,t));break}default:Ie.defaults.extensions&&Ie.defaults.extensions.childTokens&&Ie.defaults.extensions.childTokens[r.type]?Ie.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(Ie.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(Ie.walkTokens(r.tokens,t)))}return n},Ie.parseInline=mf(er.lexInline,tr.parseInline),Ie.Parser=tr,Ie.parser=tr.parse,Ie.Renderer=Ka,Ie.TextRenderer=hf,Ie.Lexer=er,Ie.lexer=er.lex,Ie.Tokenizer=Va,Ie.Slugger=pf,Ie.Hooks=Gs,Ie.parse=Ie,Ie.options,Ie.setOptions,Ie.use,Ie.walkTokens,Ie.parseInline,tr.parse,er.lex;function No({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 Ie.parse(i)}return Ie.parse(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 Mb="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 Db(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function gf(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 Xs(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Lb(e){const t=o=>{try{const s=Eo(o);return typeof s=="string"?s:JSON.stringify(s??"")}catch{return""}},n=e.filter(o=>o.type==="text");let r="";return n.length?r=t(n.map(o=>o.text).join(`
128
- `)):r=t(e),r||""}function $b(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function xf(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 Fb({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)]})}const qa=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,customStyles:h={},onEdit:p,onRegenerate:g,onCancelEdit:x,onCopy:y,activeInterrupt:m,disableInterruptActions:b=!1,onInterruptActionStart:S,onInterruptActionEnd:T,checkpointCandidates:k=[],activeCheckpointId:C=null,onSelectCheckpoint:E,defaultCheckpointId:R=null,messageParentCheckpointId:_=null}){const[j,L]=w.useState(!1),[z,V]=w.useState("preview"),[O,H]=w.useState(!1),{currentThreadId:P}=cs(),{respondToInterrupt:W}=us(),F=l==="phone"||l==="half-screen",$=t.role,ne=$==="tool",oe=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),we=!!oe,Ne=!(r&&$!=="user"),{uploadingFiles:Z,handleFileClick:ie,fileViewerOpen:Te,currentFileInfo:ee,closeFileViewer:D}=Bb({allowFileOpen:Ne,currentThreadId:P}),G=w.useMemo(()=>{switch($){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))]"}},[$]),ae=w.useMemo(()=>oe?"":Db(t.content),[oe,t]),fe=w.useMemo(()=>oe?{}:gf(t),[oe,t]),B=w.useMemo(()=>oe?[]:t.content.filter(X=>X.type==="image_url"),[oe,t]),le=w.useMemo(()=>oe?[]:t.content.filter(X=>X.type==="file"),[oe,t]),Q=w.useMemo(()=>oe?[]:t.content.filter(X=>X.type==="interrupt"),[oe,t]),Ae=(m==null?void 0:m.id)??(m==null?void 0:m.interrupt_id),ve=Xs(Ae),Re=m==null?void 0:m.value,Ve=w.useMemo(()=>oe?"":Lb(t.content),[oe,t]),Qe=w.useCallback(async()=>{const X=ne?Ve:ae;async function Ce(ge){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ge);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const xt=new Blob([ge],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":xt})]);return}throw new Error("Clipboard API not supported in this context.")}try{await Ce(X),L(!0),setTimeout(()=>L(!1),2e3),y==null||y(X)}catch(ge){console.error("Failed to copy:",ge)}},[ne,Ve,ae,y]),et=w.useCallback(()=>{if(!p)return;const X=ne?Ve:ae,Ce="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};p(t.id,X,Ce)},[p,t.id,ne,Ve,ae,t]),Se=w.useCallback(()=>{g==null||g(n)},[g,n]),nt=w.useCallback(()=>{const Ce=se(F?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",G);switch($){case"user":return u.jsx(pe.User,{className:Ce});case"assistant":return u.jsx(pe.Bot,{className:Ce});case"tool":return u.jsx(pe.Wrench,{className:Ce});default:return u.jsx(pe.Bot,{className:Ce})}},[F,G,$]),ut=w.useCallback(()=>{const X="group relative mb-4 flex w-full";switch($){case"user":return se(X,"justify-end");case"assistant":case"tool":case"system":return se(X,"justify-start");default:return X}},[$]),rt=w.useCallback(()=>{const X=se("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",F&&"px-3 py-2 text-sm");if(we)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($){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")}},[F,we,$]);if(we&&oe)return u.jsx("div",{className:se(ut(),h.container),children:u.jsxs("div",{className:se(rt(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(pe.Bot,{className:se("h-4 w-4",G)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(No,{content:oe.content,className:"text-current"})]})});const Ye=w.useCallback(async X=>{if(b)return;const Ce=Xs((X==null?void 0:X.id)??(X==null?void 0:X.interrupt_id));if(!Ce){console.warn("Interrupt part missing id",X);return}try{S==null||S(),await W(Ce,!0)}catch(ge){console.error("Failed to approve interrupt:",ge)}finally{T==null||T()}},[b,T,S,W]),It=w.useCallback(async X=>{if(b)return;const Ce=Xs((X==null?void 0:X.id)??(X==null?void 0:X.interrupt_id));if(!Ce){console.warn("Interrupt part missing id",X);return}try{S==null||S(),await W(Ce,!1)}catch(ge){console.error("Failed to reject interrupt:",ge)}finally{T==null||T()}},[b,T,S,W]),dt=w.useCallback(({part:X,i:Ce})=>{if(X.type==="text"){const ge=X.text??"",xt=ge.trim(),ft=Aa(xt);return ft&&$!=="tool"?u.jsx(yf,{data:ft},Ce):$==="user"&&c&&xt.length>d?u.jsx(Hb,{text:xt,expanded:O,onExpandedChange:H,previewLength:d,isCompact:F},Ce):u.jsx(No,{content:ge,allowHtml:!1},Ce)}if(X.type==="image_url"){const ge=X;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ge.url,alt:ge.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},Ce)}if(X.type==="file"){const ge=X,xt=ge.name||"file";return u.jsxs("a",{href:ge.url,onClick:ft=>ie(ft,ge,Ce),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
129
- dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[Z[Ce]?u.jsx(pe.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[xt,Z[Ce]?" (processing)":""]})]},Ce)}if(X.type==="interrupt"){const ge=X,xt=Xs((ge==null?void 0:ge.id)??(ge==null?void 0:ge.interrupt_id)),ft=!!(ve&&xt&&xt===ve),ht=ft?Re??(ge==null?void 0:ge.value):ge==null?void 0:ge.value,Be=xt?{...ge,id:xt,interrupt_id:xt}:ge;return u.jsx(zb,{interruptPart:Be,onApprove:Ye,onReject:It,disabled:b,isActive:ft,payload:ht},Ce)}return null},[ie,Z,Ye,It,$,c,d,O,F,ve,Re,m,b,Q]),kt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(pe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),Nt=w.useCallback(()=>{const X=ae.trim().length>0||B.length>0||le.length>0||Q.length>0;if(!ne&&le.length>0&&!r)return kt();if(!ne&&!X&&!r)return null;if(ne)return u.jsx(Ub,{message:t,viewMode:z},t.id);if(!ne&&!oe){const Ce=t,ge=u.jsx("div",{className:"space-y-2",children:Ce.content.map((xt,ft)=>u.jsx(dt,{part:xt,i:ft},ft))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ge,u.jsx(Fb,{className:G})]}):ge}},[ae,B.length,le.length,Q.length,r,ne,z,kt,G]),tt=w.useMemo(()=>oe?"Assistant":$b(t),[oe,t]),He=w.useMemo(()=>oe?[]:Array.isArray(k)?k:[],[k,oe]),Tt=w.useMemo(()=>{var X;return He.length?R&&He.some(Ce=>Ce.id===R)?R:((X=He[0])==null?void 0:X.id)??null:null},[R,He]),zt=w.useMemo(()=>!He.length||!C?null:He.some(X=>X.id===C)?C:null,[C,He])??Tt,Kt=$==="user"&&He.length>0&&typeof E=="function",st=w.useCallback(X=>{if(!E)return;const Ce=(X==null?void 0:X.id)??null,ge=(X==null?void 0:X.parentId)??_??null;E(Ce,ge)},[_,E]),Le=w.useMemo(()=>zt?He.findIndex(X=>X.id===zt):-1,[zt,He]),_t=w.useMemo(()=>Le<0?null:He[Le]??null,[Le,He]),yt=w.useCallback(X=>{const Ce=[];if(X.step!==null&&Ce.push(`Step ${X.step}`),X.source&&Ce.push(X.source),!X.createdAt)return Ce.length?Ce.join(" • "):X.id.slice(0,8);let ge="";try{const ft=new Date(X.createdAt);Number.isNaN(ft.getTime())||(ge=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(ft))}catch{ge=""}const xt=Ce.length?` • ${Ce.join(" • ")}`:"";return`${ge||X.id.slice(0,8)}${xt}`},[]);return ne&&!f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:se(ut(),h.container),children:u.jsxs("div",{className:se(rt(),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",F&&"mb-1 pb-1",G,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[nt(),a&&tt&&u.jsx("span",{className:se("font-medium",F?"text-xs":"text-sm"),children:tt}),ne&&u.jsxs(td,{variant:"outline",className:se("text-xs flex items-center gap-1 cursor-pointer select-none",G,"border border-current/40",F&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":z==="expanded",onClick:()=>V(X=>X==="expanded"?"preview":"expanded"),onKeyDown:X=>{(X.key==="Enter"||X.key===" ")&&(X.preventDefault(),V(Ce=>Ce==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:fe.name??"Tool Output"}),fe.toolCallId&&u.jsx("span",{className:"opacity-70",children:fe.toolCallId.slice(0,8)}),z==="expanded"?u.jsx(pe.ChevronUp,{className:"h-3 w-3"}):u.jsx(pe.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[Kt&&_t&&Le>=0&&u.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Le>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Le<=0)return;const X=He[Le-1];X&&st(X)},"aria-label":"Previous checkpoint",disabled:Le<=0,children:u.jsx(pe.ChevronLeft,{className:"h-3 w-3"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"whitespace-nowrap",children:[Le+1," / ",He.length]}),u.jsx("span",{className:"text-muted-foreground",children:yt(_t)})]}),u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Le<He.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Le>=He.length-1)return;const X=He[Le+1];X&&st(X)},"aria-label":"Next checkpoint",disabled:Le>=He.length-1,children:u.jsx(pe.ChevronRight,{className:"h-3 w-3"})})]}),i&&t.createdAt&&u.jsx("time",{className:se("text-xs opacity-60",G,F&&"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(lt,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:se("h-6 w-6 p-0 hover:bg-foreground/10",G,F&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(pe.Copy,{className:se(j?"text-success":G,F?"h-3 w-3":"h-4 w-4")})})}),$==="user"&&p&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:et,className:se("h-6 w-6 p-0 hover:bg-foreground/10",G,F&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(pe.Edit,{className:se(G,F?"h-3 w-3":"h-4 w-4")})}),$==="assistant"&&g&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:Se,className:se("h-6 w-6 p-0 hover:bg-foreground/10",G,F&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(pe.RotateCcw,{className:se(G,F?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:Nt()}),ne&&z==="expanded"&&(fe.toolCallId||fe.name)&&u.jsxs("div",{className:se("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",F&&"text-xs"),children:[fe.name&&u.jsxs("div",{children:["Function: ",fe.name]}),fe.toolCallId&&u.jsxs("div",{children:["Call ID: ",fe.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(lt,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:u.jsx(pe.Copy,{className:se(j?"text-success":"text-current",F?"h-3 w-3":"h-4 w-4")})}),$==="user"&&p&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:et,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:u.jsx(pe.Edit,{className:se("text-current",F?"h-3 w-3":"h-4 w-4")})}),$==="assistant"&&g&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:Se,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:u.jsx(pe.RotateCcw,{className:se("text-current",F?"h-3 w-3":"h-4 w-4")})})]})]})}),ee&&u.jsx(xb,{isOpen:Te,onClose:D,fileId:ee.id,fileName:ee.name,mimeType:ee.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,h,p;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&xf(e.message)===xf(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(g=>e[g]===t[g]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((h=e.customStyles)==null?void 0:h.header)===((p=t.customStyles)==null?void 0:p.header);return o&&s});function yf({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:Mb,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:Io(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Io(e)})}function zb({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=Io(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(bo,{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(So,{className:"pb-3",children:[u.jsx(Co,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(nd,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(ko,{className:"pt-0 pb-3",children:a}),u.jsx(rd,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(lt,{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(lt,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function Bb(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=Na(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(p=>{a(p),c(!0)},[]),h=w.useCallback(async(p,g,x)=>{var y,m;if(!t){p.preventDefault();return}if(o[x]){p.preventDefault();return}try{const b=String(g.url??""),S=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){p.preventDefault();const T=S[1],k=g.name||`file_${T}`,C=g.mimeType||"application/octet-stream";f({id:T,name:k,mimeType:C});return}if(b.startsWith("data:")){p.preventDefault(),s(k=>({...k,[x]:!0}));const T=r({title:"Fetching file...",description:"",open:!0});try{const k=await Uv(n??void 0);if(!k||!Array.isArray(k))throw new Error("Invalid file list response");const C=k.find(E=>!E||typeof E!="object"||!((E.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof E.size=="number"?E.size===g.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");f({id:C.id,name:g.name||C.filename||`file_${C.id}`,mimeType:g.mimeType||C.mime_type||"application/octet-stream"}),(y=T.update)==null||y.call(T,{id:T.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(k){console.error("Failed to fetch server file:",k);const C=k instanceof Error?k.message:"Unknown error occurred";(m=T.update)==null||m.call(T,{id:T.id,title:"Failed",description:C}),r({title:"Failed to fetch file",description:C,open:!0})}finally{s(k=>({...k,[x]:!1}))}}}catch(b){console.error("File click error:",b),s(S=>({...S,[x]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function Hb({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(No,{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(lt,{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(pe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(pe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function Ub({message:e,viewMode:t}){const r=gf(e).name||"tool",o=c=>{if(c==null)return null;const d=typeof c=="string"?Aa(c)??c:c;if(d&&typeof d=="object")return u.jsx(yf,{data:d});const f=typeof d=="string"?d:(()=>{try{return Io(d)}catch{return String(d??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:f})},s=c=>{if(c==null)return null;const{content:d,isMarkdown:f}=Vv(c);return f?u.jsx(No,{content:d,className:"text-current"}):o(c)};if(t==="preview")return null;const i=e.content.find(c=>c.type!=="tool_call");if(!i)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(pe.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(i.type==="text"){const d=(i.text??"").trim();if(!d)return null;const f=Is(d);return s(f)}const a=Eo(i),l=Is(a);return s(l)}const vf=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Wb=e=>{const t=e.additionalKwargs??{},n=e.responseMetadata??{},r=t.originalMessageId??n.originalMessageId??t.original_message_id??n.original_message_id;return typeof r=="string"&&r.trim()?r.trim():e.id},Ga=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:h,emptyMessage:p,followNewMessages:g=!0,isNavigatingCheckpoint:x=!1,onScrollAway:y,onAtBottom:m,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C=!0,checkpointMetaById:E,checkpointIndexByKey:R,activeCheckpointId:_,onSelectCheckpoint:j},L)=>{const z=w.useRef(null),V=w.useRef(null),O=w.useRef(!1),[H,P]=w.useState(!0),W=w.useMemo(()=>b?e.some(B=>"type"in B&&B.type==="default_message"?!1:Array.isArray(B==null?void 0:B.content)&&B.content.some(le=>le&&le.type==="interrupt"&&(le.id??le.interrupt_id)===b.id)):!1,[b,e]),F=w.useMemo(()=>{if(!b||W)return null;const B=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let le;const Q=b.value;if(Q&&typeof Q=="object"&&!Array.isArray(Q)){const Ae=Q.title;typeof Ae=="string"&&Ae.trim()&&(le=Ae.trim())}return{id:`interrupt-${B}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:B,value:Q,title:le}]}},[b,W]),$=w.useMemo(()=>F?[...e,F]:e,[e,F]),ne=w.useMemo(()=>C?$:$.filter(B=>(B==null?void 0:B.role)!=="tool"),[$,C]),oe=w.useMemo(()=>{const B=new Set,le=[];for(let Q=ne.length-1;Q>=0;Q--){const Ae=ne[Q];if(!Ae)continue;if("type"in Ae&&Ae.type==="default_message"){le.push(Ae);continue}const ve=Ae,Re=Wb(ve);B.has(Re)||(B.add(Re),le.push(ve))}return le.reverse()},[ne]),we=w.useCallback(B=>{P(B),y&&y(!B),m&&m(B)},[y,m]),Ne=w.useMemo(()=>{if(a)return async()=>{if(!O.current){O.current=!0;try{await a()}finally{O.current=!1}}}},[a]),Z=w.useMemo(()=>!g||x?!1:H?"auto":!1,[H,g,x]),ie=w.useMemo(()=>{if(!E||E.size===0)return[];const B=Array.from(E.values()).filter(le=>!!(le!=null&&le.id));return B.length?B.sort((le,Q)=>{const Ae=typeof le.step=="number"?le.step:Number.MAX_SAFE_INTEGER,ve=typeof Q.step=="number"?Q.step:Number.MAX_SAFE_INTEGER;if(Ae!==ve)return Ae-ve;const Re=le.createdAt?Date.parse(le.createdAt):Number.MAX_VALUE,Ve=Q.createdAt?Date.parse(Q.createdAt):Number.MAX_VALUE;return Re-Ve}):[]},[E]),Te=w.useMemo(()=>_||(ie.length?ie[ie.length-1].id:null),[_,ie]),ee=w.useCallback(B=>{if(!B)return null;const le=Date.parse(B);if(Number.isNaN(le))return null;try{return new Date(le).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return null}},[]),D=w.useMemo(()=>{if(!ie.length)return null;const B=ie[0],le=ie[ie.length-1],Q=[B==null?void 0:B.createdAt,le==null?void 0:le.createdAt].map(ve=>ve?ee(ve):null).filter(Boolean).join(" → "),Ae=ve=>{j&&j(ve)};return u.jsx("div",{className:"absolute inset-y-0 left-0 hidden w-[15rem] border-r border-border/50 bg-gradient-to-b from-background/95 to-background/70 md:flex",children:u.jsxs("div",{className:"flex h-full w-full flex-col px-4 py-4",children:[u.jsxs("div",{children:[u.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Timeline"}),u.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[ie.length," step",ie.length===1?"":"s"]}),Q&&u.jsx("div",{className:"mt-3 text-[10px] uppercase tracking-wider text-muted-foreground/80",children:Q})]}),u.jsx("div",{className:"mt-4 space-y-2 overflow-y-auto pr-1",children:ie.map(ve=>{const Re=[];ve.source&&Re.push(ve.source);const Ve=ee(ve.createdAt);Ve&&Re.push(Ve),ve.namespace&&Re.push(ve.namespace);const Qe=Te===ve.id,et=typeof ve.step=="number"?`Step ${ve.step}`:ve.source??"Checkpoint";return u.jsxs("button",{type:"button",onClick:()=>Ae(ve.id),disabled:!j,className:`w-full rounded-md border px-3 py-2 text-left text-xs transition ${Qe?"border-primary bg-primary/10 text-primary":"border-border/60 bg-muted/40 text-foreground hover:border-foreground/60"} ${j?"":"cursor-default opacity-70"}`,children:[u.jsxs("div",{className:"flex items-center justify-between gap-2",children:[u.jsx("span",{className:"font-semibold",children:et}),ve.parentId&&u.jsx("span",{className:"text-[10px] text-muted-foreground/80",children:"↩︎"})]}),Re.length>0&&u.jsx("div",{className:"mt-1 text-[11px] leading-tight text-muted-foreground",children:Re.join(" • ")})]},ve.id)})}),j&&u.jsx("button",{type:"button",onClick:()=>Ae(null),className:"mt-3 rounded-md border border-border/70 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Return to latest"})]})})},[Te,ee,j,ie]),G=ie.length>0,ae=w.useMemo(()=>{if(typeof p!="string")return null;const B=p.trim();return B?{id:"default-message",role:"assistant",type:"default_message",content:B,createdAt:new Date().toISOString()}:null},[p]);if(oe.length===0)return ae?u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"p-6 overflow-y-auto h-full flex items-start justify-center",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(qa,{message:ae,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{}})})})}):u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-center max-w-2xl mx-auto",children:p||"No messages yet. Start a conversation!"})});const fe=["flex h-full flex-col",G?"md:pl-0":"",f].filter(Boolean).join(" ");return u.jsx("div",{className:fe,style:h,children:u.jsxs("div",{className:"relative flex-1 min-h-0",children:[D,u.jsx(bv,{ref:B=>{z.current=B},scrollerRef:B=>{V.current=B instanceof HTMLDivElement?B:null},data:oe,followOutput:Z,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!1,startReached:()=>{Ne&&Ne()},atBottomStateChange:we,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(B,le)=>vf(le,B),itemContent:(B,le)=>{var dt;const Q=vf(le,B),Ae="type"in le&&le.type==="default_message";let ve=[],Re=null,Ve={},Qe={},et=null,Se=null,nt=null;if(!Ae){const kt=le,Nt=kt.checkpointId??null;Ve=kt.additionalKwargs??{},Qe=kt.responseMetadata??{};const tt=Nt&&E?E.get(Nt)??null:null;et=typeof Ve.step=="number"?Ve.step:typeof Qe.step=="number"?Qe.step:(tt==null?void 0:tt.step)??null;const He=typeof Ve.source=="string"?Ve.source:typeof Qe.source=="string"?Qe.source:(tt==null?void 0:tt.source)??null;Se=He?String(He):null,nt=(tt==null?void 0:tt.namespace)??null;const Tt=et!==null&&Se?`${et}:${Se}`:null;Tt&&(R!=null&&R.has(Tt))?ve=R.get(Tt)??[]:Nt&&tt&&(ve=[tt]),Re=Nt??((dt=ve[0])==null?void 0:dt.id)??null}const ut=(()=>{if(typeof Ve.parentCheckpointId=="string")return Ve.parentCheckpointId;if(typeof Qe.parentCheckpointId=="string")return Qe.parentCheckpointId})(),rt=Se||(typeof et=="number"?`Step ${et}`:null)||nt||null,Ye=Re,It=G&&Ye&&Te===Ye;return u.jsxs("div",{className:`relative mb-4 last:mb-0 ${G?"md:pl-[15rem]":""}`,"data-message-id":Q,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:[G&&u.jsx("div",{className:"pointer-events-none absolute left-0 top-1 hidden h-full w-[15rem] items-start md:flex",children:u.jsxs("div",{className:"flex items-start gap-3 pt-3",children:[u.jsx("span",{className:"mt-2 h-px w-10 bg-border/50"}),u.jsxs("div",{className:"pointer-events-auto flex flex-col gap-1",children:[u.jsx("button",{type:"button",disabled:!Ye||!j,onClick:()=>Ye&&(j==null?void 0:j(Ye)),className:`flex h-6 w-6 items-center justify-center rounded-full border transition ${It?"border-primary bg-primary/10 text-primary":"border-border/70 bg-background text-muted-foreground hover:border-foreground/60"} ${j?"":"cursor-default opacity-80"}`,children:u.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current"})}),rt&&u.jsx("div",{className:"text-[11px] leading-tight text-muted-foreground",children:rt})]})]})}),u.jsx(qa,{message:le,messageIndex:B,isStreamingMessage:t&&n===le.id,streamingDebounceMs:r,isEditing:i===le.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(B),onCancelEdit:d,activeInterrupt:b,disableInterruptActions:S,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C,checkpointCandidates:ve,activeCheckpointId:_??null,onSelectCheckpoint:j,defaultCheckpointId:Re,messageParentCheckpointId:ut})]})}})]})})});Ga.displayName="MessageList";const Ys=1e4;function Vb(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,`
128
+ `)):r=t(e),r||""}function $b(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function xf(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 Fb({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)]})}const qa=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,customStyles:h={},onEdit:p,onRegenerate:g,onCancelEdit:x,onCopy:y,activeInterrupt:m,disableInterruptActions:b=!1,onInterruptActionStart:S,onInterruptActionEnd:T,checkpointCandidates:k=[],activeCheckpointId:C=null,onSelectCheckpoint:E,defaultCheckpointId:R=null,messageParentCheckpointId:_=null}){const[j,L]=w.useState(!1),[z,V]=w.useState("preview"),[O,H]=w.useState(!1),{currentThreadId:P}=cs(),{respondToInterrupt:W}=us(),F=l==="phone"||l==="half-screen",$=t.role,ne=$==="tool",oe=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),we=!!oe,Ne=!(r&&$!=="user"),{uploadingFiles:Z,handleFileClick:ie,fileViewerOpen:Te,currentFileInfo:ee,closeFileViewer:D}=Bb({allowFileOpen:Ne,currentThreadId:P}),X=w.useMemo(()=>{switch($){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))]"}},[$]),ae=w.useMemo(()=>oe?"":Db(t.content),[oe,t]),fe=w.useMemo(()=>oe?{}:gf(t),[oe,t]),B=w.useMemo(()=>oe?[]:t.content.filter(G=>G.type==="image_url"),[oe,t]),le=w.useMemo(()=>oe?[]:t.content.filter(G=>G.type==="file"),[oe,t]),Q=w.useMemo(()=>oe?[]:t.content.filter(G=>G.type==="interrupt"),[oe,t]),Ae=(m==null?void 0:m.id)??(m==null?void 0:m.interrupt_id),ve=Xs(Ae),Re=m==null?void 0:m.value,Ve=w.useMemo(()=>oe?"":Lb(t.content),[oe,t]),Qe=w.useCallback(async()=>{const G=ne?Ve:ae;async function Ce(ge){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ge);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const xt=new Blob([ge],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":xt})]);return}throw new Error("Clipboard API not supported in this context.")}try{await Ce(G),L(!0),setTimeout(()=>L(!1),2e3),y==null||y(G)}catch(ge){console.error("Failed to copy:",ge)}},[ne,Ve,ae,y]),et=w.useCallback(()=>{if(!p)return;const G=ne?Ve:ae,Ce="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};p(t.id,G,Ce)},[p,t.id,ne,Ve,ae,t]),Se=w.useCallback(()=>{g==null||g(n)},[g,n]),nt=w.useCallback(()=>{const Ce=se(F?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",X);switch($){case"user":return u.jsx(pe.User,{className:Ce});case"assistant":return u.jsx(pe.Bot,{className:Ce});case"tool":return u.jsx(pe.Wrench,{className:Ce});default:return u.jsx(pe.Bot,{className:Ce})}},[F,X,$]),ut=w.useCallback(()=>{const G="group relative mb-4 flex w-full";switch($){case"user":return se(G,"justify-end");case"assistant":case"tool":case"system":return se(G,"justify-start");default:return G}},[$]),rt=w.useCallback(()=>{const G=se("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",F&&"px-3 py-2 text-sm");if(we)return se(G,"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($){case"user":return se(G,"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(G,"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(G,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return se(G,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return se(G,"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")}},[F,we,$]);if(we&&oe)return u.jsx("div",{className:se(ut(),h.container),children:u.jsxs("div",{className:se(rt(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(pe.Bot,{className:se("h-4 w-4",X)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(No,{content:oe.content,className:"text-current"})]})});const Ye=w.useCallback(async G=>{if(b)return;const Ce=Xs((G==null?void 0:G.id)??(G==null?void 0:G.interrupt_id));if(!Ce){console.warn("Interrupt part missing id",G);return}try{S==null||S(),await W(Ce,!0)}catch(ge){console.error("Failed to approve interrupt:",ge)}finally{T==null||T()}},[b,T,S,W]),It=w.useCallback(async G=>{if(b)return;const Ce=Xs((G==null?void 0:G.id)??(G==null?void 0:G.interrupt_id));if(!Ce){console.warn("Interrupt part missing id",G);return}try{S==null||S(),await W(Ce,!1)}catch(ge){console.error("Failed to reject interrupt:",ge)}finally{T==null||T()}},[b,T,S,W]),dt=w.useCallback(({part:G,i:Ce})=>{if(G.type==="text"){const ge=G.text??"",xt=ge.trim(),ft=Aa(xt);return ft&&$!=="tool"?u.jsx(yf,{data:ft},Ce):$==="user"&&c&&xt.length>d?u.jsx(Hb,{text:xt,expanded:O,onExpandedChange:H,previewLength:d,isCompact:F},Ce):u.jsx(No,{content:ge,allowHtml:!1},Ce)}if(G.type==="image_url"){const ge=G;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ge.url,alt:ge.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},Ce)}if(G.type==="file"){const ge=G,xt=ge.name||"file";return u.jsxs("a",{href:ge.url,onClick:ft=>ie(ft,ge,Ce),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
129
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[Z[Ce]?u.jsx(pe.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[xt,Z[Ce]?" (processing)":""]})]},Ce)}if(G.type==="interrupt"){const ge=G,xt=Xs((ge==null?void 0:ge.id)??(ge==null?void 0:ge.interrupt_id)),ft=!!(ve&&xt&&xt===ve),ht=ft?Re??(ge==null?void 0:ge.value):ge==null?void 0:ge.value,Be=xt?{...ge,id:xt,interrupt_id:xt}:ge;return u.jsx(zb,{interruptPart:Be,onApprove:Ye,onReject:It,disabled:b,isActive:ft,payload:ht},Ce)}return null},[ie,Z,Ye,It,$,c,d,O,F,ve,Re,m,b,Q]),kt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(pe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),Nt=w.useCallback(()=>{const G=ae.trim().length>0||B.length>0||le.length>0||Q.length>0;if(!ne&&le.length>0&&!r)return kt();if(!ne&&!G&&!r)return null;if(ne)return u.jsx(Ub,{message:t,viewMode:z},t.id);if(!ne&&!oe){const Ce=t,ge=u.jsx("div",{className:"space-y-2",children:Ce.content.map((xt,ft)=>u.jsx(dt,{part:xt,i:ft},ft))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ge,u.jsx(Fb,{className:X})]}):ge}},[ae,B.length,le.length,Q.length,r,ne,z,kt,X]),tt=w.useMemo(()=>oe?"Assistant":$b(t),[oe,t]),He=w.useMemo(()=>oe?[]:Array.isArray(k)?k:[],[k,oe]),Tt=w.useMemo(()=>{var G;return He.length?R&&He.some(Ce=>Ce.id===R)?R:((G=He[0])==null?void 0:G.id)??null:null},[R,He]),zt=w.useMemo(()=>!He.length||!C?null:He.some(G=>G.id===C)?C:null,[C,He])??Tt,Kt=$==="user"&&He.length>0&&typeof E=="function",st=w.useCallback(G=>{if(!E)return;const Ce=(G==null?void 0:G.id)??null,ge=(G==null?void 0:G.parentId)??_??null;E(Ce,ge)},[_,E]),Le=w.useMemo(()=>zt?He.findIndex(G=>G.id===zt):-1,[zt,He]),_t=w.useMemo(()=>Le<0?null:He[Le]??null,[Le,He]),yt=w.useCallback(G=>{const Ce=[];if(G.step!==null&&Ce.push(`Step ${G.step}`),G.source&&Ce.push(G.source),!G.createdAt)return Ce.length?Ce.join(" • "):G.id.slice(0,8);let ge="";try{const ft=new Date(G.createdAt);Number.isNaN(ft.getTime())||(ge=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(ft))}catch{ge=""}const xt=Ce.length?` • ${Ce.join(" • ")}`:"";return`${ge||G.id.slice(0,8)}${xt}`},[]);return ne&&!f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:se(ut(),h.container),children:u.jsxs("div",{className:se(rt(),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",F&&"mb-1 pb-1",X,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[nt(),a&&tt&&u.jsx("span",{className:se("font-medium",F?"text-xs":"text-sm"),children:tt}),ne&&u.jsxs(td,{variant:"outline",className:se("text-xs flex items-center gap-1 cursor-pointer select-none",X,"border border-current/40",F&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":z==="expanded",onClick:()=>V(G=>G==="expanded"?"preview":"expanded"),onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),V(Ce=>Ce==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:fe.name??"Tool Output"}),fe.toolCallId&&u.jsx("span",{className:"opacity-70",children:fe.toolCallId.slice(0,8)}),z==="expanded"?u.jsx(pe.ChevronUp,{className:"h-3 w-3"}):u.jsx(pe.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[Kt&&_t&&Le>=0&&u.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Le>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Le<=0)return;const G=He[Le-1];G&&st(G)},"aria-label":"Previous checkpoint",disabled:Le<=0,children:u.jsx(pe.ChevronLeft,{className:"h-3 w-3"})}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"whitespace-nowrap",children:[Le+1," / ",He.length]}),u.jsx("span",{className:"text-muted-foreground",children:yt(_t)})]}),u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Le<He.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Le>=He.length-1)return;const G=He[Le+1];G&&st(G)},"aria-label":"Next checkpoint",disabled:Le>=He.length-1,children:u.jsx(pe.ChevronRight,{className:"h-3 w-3"})})]}),i&&t.createdAt&&u.jsx("time",{className:se("text-xs opacity-60",X,F&&"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(lt,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:se("h-6 w-6 p-0 hover:bg-foreground/10",X,F&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(pe.Copy,{className:se(j?"text-success":X,F?"h-3 w-3":"h-4 w-4")})})}),$==="user"&&p&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:et,className:se("h-6 w-6 p-0 hover:bg-foreground/10",X,F&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(pe.Edit,{className:se(X,F?"h-3 w-3":"h-4 w-4")})}),$==="assistant"&&g&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:Se,className:se("h-6 w-6 p-0 hover:bg-foreground/10",X,F&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(pe.RotateCcw,{className:se(X,F?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsx("div",{className:"relative",children:Nt()}),ne&&z==="expanded"&&(fe.toolCallId||fe.name)&&u.jsxs("div",{className:se("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",F&&"text-xs"),children:[fe.name&&u.jsxs("div",{children:["Function: ",fe.name]}),fe.toolCallId&&u.jsxs("div",{children:["Call ID: ",fe.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(lt,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:u.jsx(pe.Copy,{className:se(j?"text-success":"text-current",F?"h-3 w-3":"h-4 w-4")})}),$==="user"&&p&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:et,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:u.jsx(pe.Edit,{className:se("text-current",F?"h-3 w-3":"h-4 w-4")})}),$==="assistant"&&g&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:Se,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",F&&"h-5 w-5"),children:u.jsx(pe.RotateCcw,{className:se("text-current",F?"h-3 w-3":"h-4 w-4")})})]})]})}),ee&&u.jsx(xb,{isOpen:Te,onClose:D,fileId:ee.id,fileName:ee.name,mimeType:ee.mimeType})]})},(e,t)=>{var i,a,l,c,d,f,h,p;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&xf(e.message)===xf(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(g=>e[g]===t[g]),s=((i=e.customStyles)==null?void 0:i.container)===((a=t.customStyles)==null?void 0:a.container)&&((l=e.customStyles)==null?void 0:l.content)===((c=t.customStyles)==null?void 0:c.content)&&((d=e.customStyles)==null?void 0:d.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((h=e.customStyles)==null?void 0:h.header)===((p=t.customStyles)==null?void 0:p.header);return o&&s});function yf({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:Mb,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:Io(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:Io(e)})}function zb({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=Io(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(bo,{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(So,{className:"pb-3",children:[u.jsx(Co,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(nd,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(ko,{className:"pt-0 pb-3",children:a}),u.jsx(rd,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(lt,{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(lt,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}function Bb(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=Na(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(p=>{a(p),c(!0)},[]),h=w.useCallback(async(p,g,x)=>{var y,m;if(!t){p.preventDefault();return}if(o[x]){p.preventDefault();return}try{const b=String(g.url??""),S=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){p.preventDefault();const T=S[1],k=g.name||`file_${T}`,C=g.mimeType||"application/octet-stream";f({id:T,name:k,mimeType:C});return}if(b.startsWith("data:")){p.preventDefault(),s(k=>({...k,[x]:!0}));const T=r({title:"Fetching file...",description:"",open:!0});try{const k=await Uv(n??void 0);if(!k||!Array.isArray(k))throw new Error("Invalid file list response");const C=k.find(E=>!E||typeof E!="object"||!((E.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof E.size=="number"?E.size===g.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");f({id:C.id,name:g.name||C.filename||`file_${C.id}`,mimeType:g.mimeType||C.mime_type||"application/octet-stream"}),(y=T.update)==null||y.call(T,{id:T.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(k){console.error("Failed to fetch server file:",k);const C=k instanceof Error?k.message:"Unknown error occurred";(m=T.update)==null||m.call(T,{id:T.id,title:"Failed",description:C}),r({title:"Failed to fetch file",description:C,open:!0})}finally{s(k=>({...k,[x]:!1}))}}}catch(b){console.error("File click error:",b),s(S=>({...S,[x]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function Hb({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(No,{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(lt,{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(pe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(pe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function Ub({message:e,viewMode:t}){const r=gf(e).name||"tool",o=c=>{if(c==null)return null;const d=typeof c=="string"?Aa(c)??c:c;if(d&&typeof d=="object")return u.jsx(yf,{data:d});const f=typeof d=="string"?d:(()=>{try{return Io(d)}catch{return String(d??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:f})},s=c=>{if(c==null)return null;const{content:d,isMarkdown:f}=Vv(c);return f?u.jsx(No,{content:d,className:"text-current"}):o(c)};if(t==="preview")return null;const i=e.content.find(c=>c.type!=="tool_call");if(!i)return u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(pe.Loader,{className:"h-4 w-4 animate-spin"}),u.jsxs("span",{children:["Waiting for ",r," output…"]})]});if(i.type==="text"){const d=(i.text??"").trim();if(!d)return null;const f=Is(d);return s(f)}const a=Eo(i),l=Is(a);return s(l)}const vf=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Wb=e=>{const t=e.additionalKwargs??{},n=e.responseMetadata??{},r=t.originalMessageId??n.originalMessageId??t.original_message_id??n.original_message_id;return typeof r=="string"&&r.trim()?r.trim():e.id},Ga=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:h,emptyMessage:p,followNewMessages:g=!0,isNavigatingCheckpoint:x=!1,onScrollAway:y,onAtBottom:m,activeInterrupt:b,disableInterruptActions:S=!1,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C=!0,checkpointMetaById:E,checkpointIndexByKey:R,activeCheckpointId:_,onSelectCheckpoint:j},L)=>{const z=w.useRef(null),V=w.useRef(null),O=w.useRef(!1),[H,P]=w.useState(!0),W=w.useMemo(()=>b?e.some(B=>"type"in B&&B.type==="default_message"?!1:Array.isArray(B==null?void 0:B.content)&&B.content.some(le=>le&&le.type==="interrupt"&&(le.id??le.interrupt_id)===b.id)):!1,[b,e]),F=w.useMemo(()=>{if(!b||W)return null;const B=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let le;const Q=b.value;if(Q&&typeof Q=="object"&&!Array.isArray(Q)){const Ae=Q.title;typeof Ae=="string"&&Ae.trim()&&(le=Ae.trim())}return{id:`interrupt-${B}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:B,value:Q,title:le}]}},[b,W]),$=w.useMemo(()=>F?[...e,F]:e,[e,F]),ne=w.useMemo(()=>C?$:$.filter(B=>(B==null?void 0:B.role)!=="tool"),[$,C]),oe=w.useMemo(()=>{const B=new Set,le=[];for(let Q=ne.length-1;Q>=0;Q--){const Ae=ne[Q];if(!Ae)continue;if("type"in Ae&&Ae.type==="default_message"){le.push(Ae);continue}const ve=Ae,Re=Wb(ve);B.has(Re)||(B.add(Re),le.push(ve))}return le.reverse()},[ne]),we=w.useCallback(B=>{P(B),y&&y(!B),m&&m(B)},[y,m]),Ne=w.useMemo(()=>{if(a)return async()=>{if(!O.current){O.current=!0;try{await a()}finally{O.current=!1}}}},[a]),Z=w.useMemo(()=>!g||x?!1:H?"auto":!1,[H,g,x]),ie=w.useMemo(()=>{if(!E||E.size===0)return[];const B=Array.from(E.values()).filter(le=>!!(le!=null&&le.id));return B.length?B.sort((le,Q)=>{const Ae=typeof le.step=="number"?le.step:Number.MAX_SAFE_INTEGER,ve=typeof Q.step=="number"?Q.step:Number.MAX_SAFE_INTEGER;if(Ae!==ve)return Ae-ve;const Re=le.createdAt?Date.parse(le.createdAt):Number.MAX_VALUE,Ve=Q.createdAt?Date.parse(Q.createdAt):Number.MAX_VALUE;return Re-Ve}):[]},[E]),Te=w.useMemo(()=>_||(ie.length?ie[ie.length-1].id:null),[_,ie]),ee=w.useCallback(B=>{if(!B)return null;const le=Date.parse(B);if(Number.isNaN(le))return null;try{return new Date(le).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return null}},[]),D=w.useMemo(()=>{if(!ie.length)return null;const B=ie[0],le=ie[ie.length-1],Q=[B==null?void 0:B.createdAt,le==null?void 0:le.createdAt].map(ve=>ve?ee(ve):null).filter(Boolean).join(" → "),Ae=ve=>{j&&j(ve)};return u.jsx("div",{className:"absolute inset-y-0 left-0 z-10 hidden w-[15rem] border-r border-border/50 bg-gradient-to-b from-background/95 to-background/70 md:flex",children:u.jsxs("div",{className:"flex h-full w-full flex-col px-4 py-4",children:[u.jsxs("div",{children:[u.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Timeline"}),u.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:[ie.length," step",ie.length===1?"":"s"]}),Q&&u.jsx("div",{className:"mt-3 text-[10px] uppercase tracking-wider text-muted-foreground/80",children:Q})]}),u.jsx("div",{className:"mt-4 space-y-2 overflow-y-auto pr-1",children:ie.map(ve=>{const Re=[];ve.source&&Re.push(ve.source);const Ve=ee(ve.createdAt);Ve&&Re.push(Ve),ve.namespace&&Re.push(ve.namespace);const Qe=Te===ve.id,et=typeof ve.step=="number"?`Step ${ve.step}`:ve.source??"Checkpoint";return u.jsxs("button",{type:"button",onClick:()=>Ae(ve.id),disabled:!j,className:`w-full rounded-md border px-3 py-2 text-left text-xs transition ${Qe?"border-primary bg-primary/10 text-primary":"border-border/60 bg-muted/40 text-foreground hover:border-foreground/60"} ${j?"":"cursor-default opacity-70"}`,children:[u.jsxs("div",{className:"flex items-center justify-between gap-2",children:[u.jsx("span",{className:"font-semibold",children:et}),ve.parentId&&u.jsx("span",{className:"text-[10px] text-muted-foreground/80",children:"↩︎"})]}),Re.length>0&&u.jsx("div",{className:"mt-1 text-[11px] leading-tight text-muted-foreground",children:Re.join(" • ")})]},ve.id)})}),j&&u.jsx("button",{type:"button",onClick:()=>Ae(null),className:"mt-3 rounded-md border border-border/70 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Return to latest"})]})})},[Te,ee,j,ie]),X=ie.length>0,ae=w.useMemo(()=>{if(typeof p!="string")return null;const B=p.trim();return B?{id:"default-message",role:"assistant",type:"default_message",content:B,createdAt:new Date().toISOString()}:null},[p]);if(oe.length===0)return ae?u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"p-6 overflow-y-auto h-full flex items-start justify-center",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(qa,{message:ae,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{}})})})}):u.jsx("div",{className:f,style:h,children:u.jsx("div",{className:"flex items-center justify-center py-8 text-muted-foreground text-center max-w-2xl mx-auto",children:p||"No messages yet. Start a conversation!"})});const fe=["flex h-full flex-col",X?"md:pl-[15rem]":"",f].filter(Boolean).join(" ");return u.jsx("div",{className:fe,style:h,children:u.jsxs("div",{className:"relative flex-1 min-h-0",children:[D,u.jsx(bv,{ref:B=>{z.current=B},scrollerRef:B=>{V.current=B instanceof HTMLDivElement?B:null},data:oe,followOutput:Z,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,alignToBottom:!1,startReached:()=>{Ne&&Ne()},atBottomStateChange:we,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(B,le)=>vf(le,B),itemContent:(B,le)=>{var dt;const Q=vf(le,B),Ae="type"in le&&le.type==="default_message";let ve=[],Re=null,Ve={},Qe={},et=null,Se=null,nt=null;if(!Ae){const kt=le,Nt=kt.checkpointId??null;Ve=kt.additionalKwargs??{},Qe=kt.responseMetadata??{};const tt=Nt&&E?E.get(Nt)??null:null;et=typeof Ve.step=="number"?Ve.step:typeof Qe.step=="number"?Qe.step:(tt==null?void 0:tt.step)??null;const He=typeof Ve.source=="string"?Ve.source:typeof Qe.source=="string"?Qe.source:(tt==null?void 0:tt.source)??null;Se=He?String(He):null,nt=(tt==null?void 0:tt.namespace)??null;const Tt=et!==null&&Se?`${et}:${Se}`:null;Tt&&(R!=null&&R.has(Tt))?ve=R.get(Tt)??[]:Nt&&tt&&(ve=[tt]),Re=Nt??((dt=ve[0])==null?void 0:dt.id)??null}const ut=(()=>{if(typeof Ve.parentCheckpointId=="string")return Ve.parentCheckpointId;if(typeof Qe.parentCheckpointId=="string")return Qe.parentCheckpointId})(),rt=Se||(typeof et=="number"?`Step ${et}`:null)||nt||null,Ye=Re,It=X&&Ye&&Te===Ye;return u.jsxs("div",{className:"relative mb-4 last:mb-0","data-message-id":Q,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:[X&&u.jsx("div",{className:"pointer-events-none absolute left-0 top-1 hidden h-full w-[15rem] items-start md:flex",children:u.jsxs("div",{className:"flex items-start gap-3 pt-3",children:[u.jsx("span",{className:"mt-2 h-px w-10 bg-border/50"}),u.jsxs("div",{className:"pointer-events-auto flex flex-col gap-1",children:[u.jsx("button",{type:"button",disabled:!Ye||!j,onClick:()=>Ye&&(j==null?void 0:j(Ye)),className:`flex h-6 w-6 items-center justify-center rounded-full border transition ${It?"border-primary bg-primary/10 text-primary":"border-border/70 bg-background text-muted-foreground hover:border-foreground/60"} ${j?"":"cursor-default opacity-80"}`,children:u.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current"})}),rt&&u.jsx("div",{className:"text-[11px] leading-tight text-muted-foreground",children:rt})]})]})}),u.jsx(qa,{message:le,messageIndex:B,isStreamingMessage:t&&n===le.id,streamingDebounceMs:r,isEditing:i===le.id,showActions:s,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:l,onRegenerate:()=>c(B),onCancelEdit:d,activeInterrupt:b,disableInterruptActions:S,onInterruptActionStart:T,onInterruptActionEnd:k,showToolMessages:C,checkpointCandidates:ve,activeCheckpointId:_??null,onSelectCheckpoint:j,defaultCheckpointId:Re,messageParentCheckpointId:ut})]})}})]})})});Ga.displayName="MessageList";const Ys=1e4;function Vb(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,`
130
130
  `).replace(/<p>(.*?)<\/p>/gi,`$1
131
131
 
132
132
  `).replace(/<h([1-6])>(.*?)<\/h[1-6]>/gi,(o,s,i)=>`${"#".repeat(parseInt(s))} ${i}
@@ -134,4 +134,4 @@ Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An err
134
134
  `).replace(/<ul>/gi,"").replace(/<\/ul>/gi,`
135
135
  `).replace(/<ol>/gi,"").replace(/<\/ol>/gi,`
136
136
  `).replace(/<li>(.*?)<\/li>/gi,`- $1
137
- `).trim():n.replace(/</g,"&lt;").replace(/>/g,"&gt;").trim()}function Kb(e,t=Ys){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 qb(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),Kb(t),Vb(t)}function Xa(e){const t=e+"CollectionProvider",[n,r]=Hn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:y,children:m}=x,b=w.useRef(null),S=w.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:b,children:m})};i.displayName=t;const a=e+"CollectionSlot",l=hr.createSlot(a),c=w.forwardRef((x,y)=>{const{scope:m,children:b}=x,S=s(a,m),T=Ze(y,S.collectionRef);return u.jsx(l,{ref:T,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=hr.createSlot(d),p=w.forwardRef((x,y)=>{const{scope:m,children:b,...S}=x,T=w.useRef(null),k=Ze(y,T),C=s(d,m);return w.useEffect(()=>(C.itemMap.set(T,{ref:T,...S}),()=>void C.itemMap.delete(T))),u.jsx(h,{[f]:"",ref:k,children:b})});p.displayName=d;function g(x){const y=s(e+"CollectionConsumer",x);return w.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const S=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((C,E)=>S.indexOf(C.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},g,r]}var Gb=v.createContext(void 0);function Js(e){const t=v.useContext(Gb);return e||t||"ltr"}const Xb=["top","right","bottom","left"],nr=Math.min,un=Math.max,Zs=Math.round,Qs=Math.floor,On=e=>({x:e,y:e}),Yb={left:"right",right:"left",bottom:"top",top:"bottom"},Jb={start:"end",end:"start"};function Ya(e,t,n){return un(e,nr(t,n))}function Wn(e,t){return typeof e=="function"?e(t):e}function Vn(e){return e.split("-")[0]}function Kr(e){return e.split("-")[1]}function Ja(e){return e==="x"?"y":"x"}function Za(e){return e==="y"?"height":"width"}const Zb=new Set(["top","bottom"]);function Mn(e){return Zb.has(Vn(e))?"y":"x"}function Qa(e){return Ja(Mn(e))}function Qb(e,t,n){n===void 0&&(n=!1);const r=Kr(e),o=Qa(e),s=Za(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=ei(i)),[i,ei(i)]}function e0(e){const t=ei(e);return[el(e),t,el(t)]}function el(e){return e.replace(/start|end/g,t=>Jb[t])}const wf=["left","right"],bf=["right","left"],t0=["top","bottom"],n0=["bottom","top"];function r0(e,t,n){switch(e){case"top":case"bottom":return n?t?bf:wf:t?wf:bf;case"left":case"right":return t?t0:n0;default:return[]}}function o0(e,t,n,r){const o=Kr(e);let s=r0(Vn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(el)))),s}function ei(e){return e.replace(/left|right|bottom|top/g,t=>Yb[t])}function s0(e){return{top:0,right:0,bottom:0,left:0,...e}}function Sf(e){return typeof e!="number"?s0(e):{top:e,right:e,bottom:e,left:e}}function ti(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 Cf(e,t,n){let{reference:r,floating:o}=e;const s=Mn(t),i=Qa(t),a=Za(i),l=Vn(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(Kr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const i0=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}=Cf(c,r,l),h=r,p={},g=0;for(let x=0;x<a.length;x++){const{name:y,fn:m}=a[x],{x:b,y:S,data:T,reset:k}=await m({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=S??f,p={...p,[y]:{...p[y],...T}},k&&g<=50&&(g++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(c=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=Cf(c,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Ao(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}=Wn(t,e),g=Sf(p),y=a[h?f==="floating"?"reference":"floating":f],m=ti(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,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),T=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},k=ti(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:S,strategy:l}):b);return{top:(m.top-k.top+g.top)/T.y,bottom:(k.bottom-m.bottom+g.bottom)/T.y,left:(m.left-k.left+g.left)/T.x,right:(k.right-m.right+g.right)/T.x}}const a0=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}=Wn(e,t)||{};if(c==null)return{};const f=Sf(d),h={x:n,y:r},p=Qa(o),g=Za(p),x=await i.getDimensions(c),y=p==="y",m=y?"top":"left",b=y?"bottom":"right",S=y?"clientHeight":"clientWidth",T=s.reference[g]+s.reference[p]-h[p]-s.floating[g],k=h[p]-s.reference[p],C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=C?C[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(C)))&&(E=a.floating[S]||s.floating[g]);const R=T/2-k/2,_=E/2-x[g]/2-1,j=nr(f[m],_),L=nr(f[b],_),z=j,V=E-x[g]-L,O=E/2-x[g]/2+R,H=Ya(z,O,V),P=!l.arrow&&Kr(o)!=null&&O!==H&&s.reference[g]/2-(O<z?j:L)-x[g]/2<0,W=P?O<z?O-z:O-V:0;return{[p]:h[p]+W,data:{[p]:H,centerOffset:O-H-W,...P&&{alignmentOffset:W}},reset:P}}}),l0=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:g="none",flipAlignment:x=!0,...y}=Wn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const m=Vn(o),b=Mn(a),S=Vn(a)===a,T=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(S||!x?[ei(a)]:e0(a)),C=g!=="none";!h&&C&&k.push(...o0(a,x,g,T));const E=[a,...k],R=await Ao(t,y),_=[];let j=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(R[m]),f){const O=Qb(o,i,T);_.push(R[O[0]],R[O[1]])}if(j=[...j,{placement:o,overflows:_}],!_.every(O=>O<=0)){var L,z;const O=(((L=s.flip)==null?void 0:L.index)||0)+1,H=E[O];if(H&&(!(f==="alignment"?b!==Mn(H):!1)||j.every(F=>Mn(F.placement)===b?F.overflows[0]>0:!0)))return{data:{index:O,overflows:j},reset:{placement:H}};let P=(z=j.filter(W=>W.overflows[0]<=0).sort((W,F)=>W.overflows[1]-F.overflows[1])[0])==null?void 0:z.placement;if(!P)switch(p){case"bestFit":{var V;const W=(V=j.filter(F=>{if(C){const $=Mn(F.placement);return $===b||$==="y"}return!0}).map(F=>[F.placement,F.overflows.filter($=>$>0).reduce(($,ne)=>$+ne,0)]).sort((F,$)=>F[1]-$[1])[0])==null?void 0:V[0];W&&(P=W);break}case"initialPlacement":P=a;break}if(o!==P)return{reset:{placement:P}}}return{}}}};function kf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Tf(e){return Xb.some(t=>e[t]>=0)}const c0=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Wn(e,t);switch(r){case"referenceHidden":{const s=await Ao(t,{...o,elementContext:"reference"}),i=kf(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Tf(i)}}}case"escaped":{const s=await Ao(t,{...o,altBoundary:!0}),i=kf(s,n.floating);return{data:{escapedOffsets:i,escaped:Tf(i)}}}default:return{}}}}},Ef=new Set(["left","top"]);async function u0(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Vn(n),a=Kr(n),l=Mn(n)==="y",c=Ef.has(i)?-1:1,d=s&&l?-1:1,f=Wn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(p=a==="end"?g*-1:g),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const d0=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 u0(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}}}}},f0=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:m,y:b}=y;return{x:m,y:b}}},...l}=Wn(e,t),c={x:n,y:r},d=await Ao(t,l),f=Mn(Vn(o)),h=Ja(f);let p=c[h],g=c[f];if(s){const y=h==="y"?"top":"left",m=h==="y"?"bottom":"right",b=p+d[y],S=p-d[m];p=Ya(b,p,S)}if(i){const y=f==="y"?"top":"left",m=f==="y"?"bottom":"right",b=g+d[y],S=g-d[m];g=Ya(b,g,S)}const x=a.fn({...t,[h]:p,[f]:g});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},h0=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}=Wn(e,t),d={x:n,y:r},f=Mn(o),h=Ja(f);let p=d[h],g=d[f];const x=Wn(a,t),y=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const S=h==="y"?"height":"width",T=s.reference[h]-s.floating[S]+y.mainAxis,k=s.reference[h]+s.reference[S]-y.mainAxis;p<T?p=T:p>k&&(p=k)}if(c){var m,b;const S=h==="y"?"width":"height",T=Ef.has(Vn(o)),k=s.reference[f]-s.floating[S]+(T&&((m=i.offset)==null?void 0:m[f])||0)+(T?0:y.crossAxis),C=s.reference[f]+s.reference[S]+(T?0:((b=i.offset)==null?void 0:b[f])||0)-(T?y.crossAxis:0);g<k?g=k:g>C&&(g=C)}return{[h]:p,[f]:g}}}},p0=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}=Wn(e,t),d=await Ao(t,c),f=Vn(o),h=Kr(o),p=Mn(o)==="y",{width:g,height:x}=s.floating;let y,m;f==="top"||f==="bottom"?(y=f,m=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(m=f,y=h==="end"?"top":"bottom");const b=x-d.top-d.bottom,S=g-d.left-d.right,T=nr(x-d[y],b),k=nr(g-d[m],S),C=!t.middlewareData.shift;let E=T,R=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=b),C&&!h){const j=un(d.left,0),L=un(d.right,0),z=un(d.top,0),V=un(d.bottom,0);p?R=g-2*(j!==0||L!==0?j+L:un(d.left,d.right)):E=x-2*(z!==0||V!==0?z+V:un(d.top,d.bottom))}await l({...t,availableWidth:R,availableHeight:E});const _=await i.getDimensions(a.floating);return g!==_.width||x!==_.height?{reset:{rects:!0}}:{}}}};function ni(){return typeof window<"u"}function qr(e){return If(e)?(e.nodeName||"").toLowerCase():"#document"}function dn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dn(e){var t;return(t=(If(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function If(e){return ni()?e instanceof Node||e instanceof dn(e).Node:!1}function En(e){return ni()?e instanceof Element||e instanceof dn(e).Element:!1}function Ln(e){return ni()?e instanceof HTMLElement||e instanceof dn(e).HTMLElement:!1}function Nf(e){return!ni()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof dn(e).ShadowRoot}const m0=new Set(["inline","contents"]);function _o(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=In(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!m0.has(o)}const g0=new Set(["table","td","th"]);function x0(e){return g0.has(qr(e))}const y0=[":popover-open",":modal"];function ri(e){return y0.some(t=>{try{return e.matches(t)}catch{return!1}})}const v0=["transform","translate","scale","rotate","perspective"],w0=["transform","translate","scale","rotate","perspective","filter"],b0=["paint","layout","strict","content"];function tl(e){const t=nl(),n=En(e)?In(e):e;return v0.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)||w0.some(r=>(n.willChange||"").includes(r))||b0.some(r=>(n.contain||"").includes(r))}function S0(e){let t=rr(e);for(;Ln(t)&&!Gr(t);){if(tl(t))return t;if(ri(t))return null;t=rr(t)}return null}function nl(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const C0=new Set(["html","body","#document"]);function Gr(e){return C0.has(qr(e))}function In(e){return dn(e).getComputedStyle(e)}function oi(e){return En(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function rr(e){if(qr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Nf(e)&&e.host||Dn(e);return Nf(t)?t.host:t}function Af(e){const t=rr(e);return Gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ln(t)&&_o(t)?t:Af(t)}function jo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Af(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=dn(o);if(s){const a=rl(i);return t.concat(i,i.visualViewport||[],_o(o)?o:[],a&&n?jo(a):[])}return t.concat(o,jo(o,[],n))}function rl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _f(e){const t=In(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ln(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Zs(n)!==s||Zs(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ol(e){return En(e)?e:e.contextElement}function Xr(e){const t=ol(e);if(!Ln(t))return On(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=_f(t);let i=(s?Zs(n.width):n.width)/r,a=(s?Zs(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const k0=On(0);function jf(e){const t=dn(e);return!nl()||!t.visualViewport?k0:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function T0(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==dn(e)?!1:t}function Tr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ol(e);let i=On(1);t&&(r?En(r)&&(i=Xr(r)):i=Xr(e));const a=T0(s,n,r)?jf(s):On(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=dn(s),p=r&&En(r)?dn(r):r;let g=h,x=rl(g);for(;x&&r&&p!==g;){const y=Xr(x),m=x.getBoundingClientRect(),b=In(x),S=m.left+(x.clientLeft+parseFloat(b.paddingLeft))*y.x,T=m.top+(x.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=T,g=dn(x),x=rl(g)}}return ti({width:d,height:f,x:l,y:c})}function si(e,t){const n=oi(e).scrollLeft;return t?t.left+n:Tr(Dn(e)).left+n}function Rf(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-si(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function E0(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Dn(r),a=t?ri(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=On(1);const d=On(0),f=Ln(r);if((f||!f&&!s)&&((qr(r)!=="body"||_o(i))&&(l=oi(r)),Ln(r))){const p=Tr(r);c=Xr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Rf(i,l):On(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 I0(e){return Array.from(e.getClientRects())}function N0(e){const t=Dn(e),n=oi(e),r=e.ownerDocument.body,o=un(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=un(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+si(e);const a=-n.scrollTop;return In(r).direction==="rtl"&&(i+=un(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Pf=25;function A0(e,t){const n=dn(e),r=Dn(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=nl();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=si(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,g=Math.abs(r.clientWidth-f.clientWidth-p);g<=Pf&&(s-=g)}else c<=Pf&&(s+=c);return{width:s,height:i,x:a,y:l}}const _0=new Set(["absolute","fixed"]);function j0(e,t){const n=Tr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Ln(e)?Xr(e):On(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 Of(e,t,n){let r;if(t==="viewport")r=A0(e,n);else if(t==="document")r=N0(Dn(e));else if(En(t))r=j0(t,n);else{const o=jf(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ti(r)}function Mf(e,t){const n=rr(e);return n===t||!En(n)||Gr(n)?!1:In(n).position==="fixed"||Mf(n,t)}function R0(e,t){const n=t.get(e);if(n)return n;let r=jo(e,[],!1).filter(a=>En(a)&&qr(a)!=="body"),o=null;const s=In(e).position==="fixed";let i=s?rr(e):e;for(;En(i)&&!Gr(i);){const a=In(i),l=tl(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&_0.has(o.position)||_o(i)&&!l&&Mf(e,i))?r=r.filter(d=>d!==i):o=a,i=rr(i)}return t.set(e,r),r}function P0(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?ri(t)?[]:R0(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Of(t,d,o);return c.top=un(f.top,c.top),c.right=nr(f.right,c.right),c.bottom=nr(f.bottom,c.bottom),c.left=un(f.left,c.left),c},Of(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function O0(e){const{width:t,height:n}=_f(e);return{width:t,height:n}}function M0(e,t,n){const r=Ln(t),o=Dn(t),s=n==="fixed",i=Tr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=On(0);function c(){l.x=si(o)}if(r||!r&&!s)if((qr(t)!=="body"||_o(o))&&(a=oi(t)),r){const p=Tr(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?Rf(o,a):On(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 sl(e){return In(e).position==="static"}function Df(e,t){if(!Ln(e)||In(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dn(e)===n&&(n=n.ownerDocument.body),n}function Lf(e,t){const n=dn(e);if(ri(e))return n;if(!Ln(e)){let o=rr(e);for(;o&&!Gr(o);){if(En(o)&&!sl(o))return o;o=rr(o)}return n}let r=Df(e,t);for(;r&&x0(r)&&sl(r);)r=Df(r,t);return r&&Gr(r)&&sl(r)&&!tl(r)?n:r||S0(e)||n}const D0=async function(e){const t=this.getOffsetParent||Lf,n=this.getDimensions,r=await n(e.floating);return{reference:M0(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function L0(e){return In(e).direction==="rtl"}const $0={convertOffsetParentRelativeRectToViewportRelativeRect:E0,getDocumentElement:Dn,getClippingRect:P0,getOffsetParent:Lf,getElementRects:D0,getClientRects:I0,getDimensions:O0,getScale:Xr,isElement:En,isRTL:L0};function $f(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function F0(e,t){let n=null,r;const o=Dn(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 g=Qs(f),x=Qs(o.clientWidth-(d+h)),y=Qs(o.clientHeight-(f+p)),m=Qs(d),S={rootMargin:-g+"px "+-x+"px "+-y+"px "+-m+"px",threshold:un(0,nr(1,l))||1};let T=!0;function k(C){const E=C[0].intersectionRatio;if(E!==l){if(!T)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!$f(c,e.getBoundingClientRect())&&i(),T=!1}try{n=new IntersectionObserver(k,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,S)}n.observe(e)}return i(!0),s}function z0(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=ol(e),d=o||s?[...c?jo(c):[],...jo(t)]:[];d.forEach(m=>{o&&m.addEventListener("scroll",n,{passive:!0}),s&&m.addEventListener("resize",n)});const f=c&&a?F0(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(m=>{let[b]=m;b&&b.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 g,x=l?Tr(e):null;l&&y();function y(){const m=Tr(e);x&&!$f(x,m)&&n(),x=m,g=requestAnimationFrame(y)}return n(),()=>{var m;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(m=p)==null||m.disconnect(),p=null,l&&cancelAnimationFrame(g)}}const B0=d0,H0=f0,U0=l0,W0=p0,V0=c0,Ff=a0,K0=h0,q0=(e,t,n)=>{const r=new Map,o={platform:$0,...n},s={...o.platform,_c:r};return i0(e,t,{...o,platform:s})};var G0=typeof document<"u",X0=function(){},ii=G0?w.useLayoutEffect:X0;function ai(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(!ai(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)&&!ai(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function zf(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Bf(e,t){const n=zf(e);return Math.round(t*n)/n}function il(e){const t=v.useRef(e);return ii(()=>{t.current=e}),t}function Y0(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);ai(h,r)||p(r);const[g,x]=v.useState(null),[y,m]=v.useState(null),b=v.useCallback(F=>{F!==C.current&&(C.current=F,x(F))},[]),S=v.useCallback(F=>{F!==E.current&&(E.current=F,m(F))},[]),T=s||g,k=i||y,C=v.useRef(null),E=v.useRef(null),R=v.useRef(d),_=l!=null,j=il(l),L=il(o),z=il(c),V=v.useCallback(()=>{if(!C.current||!E.current)return;const F={placement:t,strategy:n,middleware:h};L.current&&(F.platform=L.current),q0(C.current,E.current,F).then($=>{const ne={...$,isPositioned:z.current!==!1};O.current&&!ai(R.current,ne)&&(R.current=ne,Wo.flushSync(()=>{f(ne)}))})},[h,t,n,L,z]);ii(()=>{c===!1&&R.current.isPositioned&&(R.current.isPositioned=!1,f(F=>({...F,isPositioned:!1})))},[c]);const O=v.useRef(!1);ii(()=>(O.current=!0,()=>{O.current=!1}),[]),ii(()=>{if(T&&(C.current=T),k&&(E.current=k),T&&k){if(j.current)return j.current(T,k,V);V()}},[T,k,V,j,_]);const H=v.useMemo(()=>({reference:C,floating:E,setReference:b,setFloating:S}),[b,S]),P=v.useMemo(()=>({reference:T,floating:k}),[T,k]),W=v.useMemo(()=>{const F={position:n,left:0,top:0};if(!P.floating)return F;const $=Bf(P.floating,d.x),ne=Bf(P.floating,d.y);return a?{...F,transform:"translate("+$+"px, "+ne+"px)",...zf(P.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:$,top:ne}},[n,a,P.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:H,elements:P,floatingStyles:W}),[d,V,H,P,W])}const J0=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?Ff({element:r.current,padding:o}).fn(n):{}:r?Ff({element:r,padding:o}).fn(n):{}}}},Z0=(e,t)=>({...B0(e),options:[e,t]}),Q0=(e,t)=>({...H0(e),options:[e,t]}),eS=(e,t)=>({...K0(e),options:[e,t]}),tS=(e,t)=>({...U0(e),options:[e,t]}),nS=(e,t)=>({...W0(e),options:[e,t]}),rS=(e,t)=>({...V0(e),options:[e,t]}),oS=(e,t)=>({...J0(e),options:[e,t]});var sS="Arrow",Hf=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(De.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"})})});Hf.displayName=sS;var iS=Hf;function Uf(e){const[t,n]=v.useState(void 0);return Ut(()=>{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 al="Popper",[Wf,li]=Hn(al),[aS,Vf]=Wf(al),Kf=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(aS,{scope:t,anchor:r,onAnchorChange:o,children:n})};Kf.displayName=al;var qf="PopperAnchor",Gf=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Vf(qf,n),i=v.useRef(null),a=Ze(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(De.div,{...o,ref:a})});Gf.displayName=qf;var ll="PopperContent",[lS,cS]=Wf(ll),Xf=v.forwardRef((e,t)=>{var ee,D,G,ae,fe,B;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:g,...x}=e,y=Vf(ll,n),[m,b]=v.useState(null),S=Ze(t,le=>b(le)),[T,k]=v.useState(null),C=Uf(T),E=(C==null?void 0:C.width)??0,R=(C==null?void 0:C.height)??0,_=r+(s!=="center"?"-"+s:""),j=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},L=Array.isArray(c)?c:[c],z=L.length>0,V={padding:j,boundary:L.filter(dS),altBoundary:z},{refs:O,floatingStyles:H,placement:P,isPositioned:W,middlewareData:F}=Y0({strategy:"fixed",placement:_,whileElementsMounted:(...le)=>z0(...le,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Z0({mainAxis:o+R,alignmentAxis:i}),l&&Q0({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?eS():void 0,...V}),l&&tS({...V}),nS({...V,apply:({elements:le,rects:Q,availableWidth:Ae,availableHeight:ve})=>{const{width:Re,height:Ve}=Q.reference,Qe=le.floating.style;Qe.setProperty("--radix-popper-available-width",`${Ae}px`),Qe.setProperty("--radix-popper-available-height",`${ve}px`),Qe.setProperty("--radix-popper-anchor-width",`${Re}px`),Qe.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),T&&oS({element:T,padding:a}),fS({arrowWidth:E,arrowHeight:R}),h&&rS({strategy:"referenceHidden",...V})]}),[$,ne]=Zf(P),oe=Wt(g);Ut(()=>{W&&(oe==null||oe())},[W,oe]);const we=(ee=F.arrow)==null?void 0:ee.x,Ne=(D=F.arrow)==null?void 0:D.y,Z=((G=F.arrow)==null?void 0:G.centerOffset)!==0,[ie,Te]=v.useState();return Ut(()=>{m&&Te(window.getComputedStyle(m).zIndex)},[m]),u.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:W?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ie,"--radix-popper-transform-origin":[(ae=F.transformOrigin)==null?void 0:ae.x,(fe=F.transformOrigin)==null?void 0:fe.y].join(" "),...((B=F.hide)==null?void 0:B.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(lS,{scope:n,placedSide:$,onArrowChange:k,arrowX:we,arrowY:Ne,shouldHideArrow:Z,children:u.jsx(De.div,{"data-side":$,"data-align":ne,...x,ref:S,style:{...x.style,animation:W?void 0:"none"}})})})});Xf.displayName=ll;var Yf="PopperArrow",uS={top:"bottom",right:"left",bottom:"top",left:"right"},Jf=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=cS(Yf,r),i=uS[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(iS,{...o,ref:n,style:{...o.style,display:"block"}})})});Jf.displayName=Yf;function dS(e){return e!==null}var fS=e=>({name:"transformOrigin",options:e,fn(t){var y,m,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]=Zf(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((m=o.arrow)==null?void 0:m.x)??0)+a/2,p=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let g="",x="";return c==="bottom"?(g=i?f:`${h}px`,x=`${-l}px`):c==="top"?(g=i?f:`${h}px`,x=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,x=i?f:`${p}px`):c==="left"&&(g=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:g,y:x}}}});function Zf(e){const[t,n="center"]=e.split("-");return[t,n]}var Qf=Kf,eh=Gf,th=Xf,nh=Jf,cl="rovingFocusGroup.onEntryFocus",hS={bubbles:!1,cancelable:!0},Ro="RovingFocusGroup",[ul,rh,pS]=Xa(Ro),[mS,oh]=Hn(Ro,[pS]),[gS,xS]=mS(Ro),sh=v.forwardRef((e,t)=>u.jsx(ul.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(ul.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(yS,{...e,ref:t})})}));sh.displayName=Ro;var yS=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=Ze(t,h),g=Js(s),[x,y]=Br({prop:i,defaultProp:a??null,onChange:l,caller:Ro}),[m,b]=v.useState(!1),S=Wt(c),T=rh(n),k=v.useRef(!1),[C,E]=v.useState(0);return v.useEffect(()=>{const R=h.current;if(R)return R.addEventListener(cl,S),()=>R.removeEventListener(cl,S)},[S]),u.jsx(gS,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:x,onItemFocus:v.useCallback(R=>y(R),[y]),onItemShiftTab:v.useCallback(()=>b(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(R=>R+1),[]),onFocusableItemRemove:v.useCallback(()=>E(R=>R-1),[]),children:u.jsx(De.div,{tabIndex:m||C===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:ye(e.onMouseDown,()=>{k.current=!0}),onFocus:ye(e.onFocus,R=>{const _=!k.current;if(R.target===R.currentTarget&&_&&!m){const j=new CustomEvent(cl,hS);if(R.currentTarget.dispatchEvent(j),!j.defaultPrevented){const L=T().filter(P=>P.focusable),z=L.find(P=>P.active),V=L.find(P=>P.id===x),H=[z,V,...L].filter(Boolean).map(P=>P.ref.current);lh(H,d)}}k.current=!1}),onBlur:ye(e.onBlur,()=>b(!1))})})}),ih="RovingFocusGroupItem",ah=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=Un(),c=s||l,d=xS(ih,n),f=d.currentTabStopId===c,h=rh(n),{onFocusableItemAdd:p,onFocusableItemRemove:g,currentTabStopId:x}=d;return v.useEffect(()=>{if(r)return p(),()=>g()},[r,p,g]),u.jsx(ul.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(De.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:ye(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:ye(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ye(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const m=bS(y,d.orientation,d.dir);if(m!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=h().filter(T=>T.focusable).map(T=>T.ref.current);if(m==="last")S.reverse();else if(m==="prev"||m==="next"){m==="prev"&&S.reverse();const T=S.indexOf(y.currentTarget);S=d.loop?SS(S,T+1):S.slice(T+1)}setTimeout(()=>lh(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});ah.displayName=ih;var vS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function wS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function bS(e,t,n){const r=wS(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return vS[r]}function lh(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function SS(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var CS=sh,kS=ah,dl=["Enter"," "],TS=["ArrowDown","PageUp","Home"],ch=["ArrowUp","PageDown","End"],ES=[...TS,...ch],IS={ltr:[...dl,"ArrowRight"],rtl:[...dl,"ArrowLeft"]},NS={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Po="Menu",[Oo,AS,_S]=Xa(Po),[Er,uh]=Hn(Po,[_S,li,oh]),ci=li(),dh=oh(),[jS,Ir]=Er(Po),[RS,Mo]=Er(Po),fh=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=ci(t),[l,c]=v.useState(null),d=v.useRef(!1),f=Wt(s),h=Js(o);return v.useEffect(()=>{const p=()=>{d.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>d.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),u.jsx(Qf,{...a,children:u.jsx(jS,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:c,children:u.jsx(RS,{scope:t,onClose:v.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:h,modal:i,children:r})})})};fh.displayName=Po;var PS="MenuAnchor",fl=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ci(n);return u.jsx(eh,{...o,...r,ref:t})});fl.displayName=PS;var hl="MenuPortal",[OS,hh]=Er(hl,{forceMount:void 0}),ph=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Ir(hl,t);return u.jsx(OS,{scope:t,forceMount:n,children:u.jsx(gn,{present:n||s.open,children:u.jsx(_s,{asChild:!0,container:o,children:r})})})};ph.displayName=hl;var xn="MenuContent",[MS,pl]=Er(xn),mh=v.forwardRef((e,t)=>{const n=hh(xn,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Ir(xn,e.__scopeMenu),i=Mo(xn,e.__scopeMenu);return u.jsx(Oo.Provider,{scope:e.__scopeMenu,children:u.jsx(gn,{present:r||s.open,children:u.jsx(Oo.Slot,{scope:e.__scopeMenu,children:i.modal?u.jsx(DS,{...o,ref:t}):u.jsx(LS,{...o,ref:t})})})})}),DS=v.forwardRef((e,t)=>{const n=Ir(xn,e.__scopeMenu),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return Ba(s)},[]),u.jsx(ml,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ye(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),LS=v.forwardRef((e,t)=>{const n=Ir(xn,e.__scopeMenu);return u.jsx(ml,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),$S=hr.createSlot("MenuContent.ScrollLock"),ml=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:g,...x}=e,y=Ir(xn,n),m=Mo(xn,n),b=ci(n),S=dh(n),T=AS(n),[k,C]=v.useState(null),E=v.useRef(null),R=Ze(t,E,y.onContentChange),_=v.useRef(0),j=v.useRef(""),L=v.useRef(0),z=v.useRef(null),V=v.useRef("right"),O=v.useRef(0),H=g?Ls:v.Fragment,P=g?{as:$S,allowPinchZoom:!0}:void 0,W=$=>{var ee,D;const ne=j.current+$,oe=T().filter(G=>!G.disabled),we=document.activeElement,Ne=(ee=oe.find(G=>G.ref.current===we))==null?void 0:ee.textValue,Z=oe.map(G=>G.textValue),ie=YS(Z,ne,Ne),Te=(D=oe.find(G=>G.textValue===ie))==null?void 0:D.ref.current;(function G(ae){j.current=ae,window.clearTimeout(_.current),ae!==""&&(_.current=window.setTimeout(()=>G(""),1e3))})(ne),Te&&setTimeout(()=>Te.focus())};v.useEffect(()=>()=>window.clearTimeout(_.current),[]),Ma();const F=v.useCallback($=>{var oe,we;return V.current===((oe=z.current)==null?void 0:oe.side)&&ZS($,(we=z.current)==null?void 0:we.area)},[]);return u.jsx(MS,{scope:n,searchRef:j,onItemEnter:v.useCallback($=>{F($)&&$.preventDefault()},[F]),onItemLeave:v.useCallback($=>{var ne;F($)||((ne=E.current)==null||ne.focus(),C(null))},[F]),onTriggerLeave:v.useCallback($=>{F($)&&$.preventDefault()},[F]),pointerGraceTimerRef:L,onPointerGraceIntentChange:v.useCallback($=>{z.current=$},[]),children:u.jsx(H,{...P,children:u.jsx(As,{asChild:!0,trapped:o,onMountAutoFocus:ye(s,$=>{var ne;$.preventDefault(),(ne=E.current)==null||ne.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:u.jsx(Ns,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:u.jsx(CS,{asChild:!0,...S,dir:m.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:C,onEntryFocus:ye(l,$=>{m.isUsingKeyboardRef.current||$.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(th,{role:"menu","aria-orientation":"vertical","data-state":Rh(y.open),"data-radix-menu-content":"",dir:m.dir,...b,...x,ref:R,style:{outline:"none",...x.style},onKeyDown:ye(x.onKeyDown,$=>{const oe=$.target.closest("[data-radix-menu-content]")===$.currentTarget,we=$.ctrlKey||$.altKey||$.metaKey,Ne=$.key.length===1;oe&&($.key==="Tab"&&$.preventDefault(),!we&&Ne&&W($.key));const Z=E.current;if($.target!==Z||!ES.includes($.key))return;$.preventDefault();const Te=T().filter(ee=>!ee.disabled).map(ee=>ee.ref.current);ch.includes($.key)&&Te.reverse(),GS(Te)}),onBlur:ye(e.onBlur,$=>{$.currentTarget.contains($.target)||(window.clearTimeout(_.current),j.current="")}),onPointerMove:ye(e.onPointerMove,Lo($=>{const ne=$.target,oe=O.current!==$.clientX;if($.currentTarget.contains(ne)&&oe){const we=$.clientX>O.current?"right":"left";V.current=we,O.current=$.clientX}}))})})})})})})});mh.displayName=xn;var FS="MenuGroup",gl=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(De.div,{role:"group",...r,ref:t})});gl.displayName=FS;var zS="MenuLabel",gh=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(De.div,{...r,ref:t})});gh.displayName=zS;var ui="MenuItem",xh="menu.itemSelect",di=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=v.useRef(null),i=Mo(ui,e.__scopeMenu),a=pl(ui,e.__scopeMenu),l=Ze(t,s),c=v.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(xh,{bubbles:!0,cancelable:!0});f.addEventListener(xh,p=>r==null?void 0:r(p),{once:!0}),cd(f,h),h.defaultPrevented?c.current=!1:i.onClose()}};return u.jsx(yh,{...o,ref:l,disabled:n,onClick:ye(e.onClick,d),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),c.current=!0},onPointerUp:ye(e.onPointerUp,f=>{var h;c.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:ye(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||dl.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});di.displayName=ui;var yh=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=pl(ui,n),a=dh(n),l=v.useRef(null),c=Ze(t,l),[d,f]=v.useState(!1),[h,p]=v.useState("");return v.useEffect(()=>{const g=l.current;g&&p((g.textContent??"").trim())},[s.children]),u.jsx(Oo.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:u.jsx(kS,{asChild:!0,...a,focusable:!r,children:u.jsx(De.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:ye(e.onPointerMove,Lo(g=>{r?i.onItemLeave(g):(i.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ye(e.onPointerLeave,Lo(g=>i.onItemLeave(g))),onFocus:ye(e.onFocus,()=>f(!0)),onBlur:ye(e.onBlur,()=>f(!1))})})})}),BS="MenuCheckboxItem",vh=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return u.jsx(kh,{scope:e.__scopeMenu,checked:n,children:u.jsx(di,{role:"menuitemcheckbox","aria-checked":fi(n)?"mixed":n,...o,ref:t,"data-state":yl(n),onSelect:ye(o.onSelect,()=>r==null?void 0:r(fi(n)?!0:!n),{checkForDefaultPrevented:!1})})})});vh.displayName=BS;var wh="MenuRadioGroup",[HS,US]=Er(wh,{value:void 0,onValueChange:()=>{}}),bh=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=Wt(r);return u.jsx(HS,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(gl,{...o,ref:t})})});bh.displayName=wh;var Sh="MenuRadioItem",Ch=v.forwardRef((e,t)=>{const{value:n,...r}=e,o=US(Sh,e.__scopeMenu),s=n===o.value;return u.jsx(kh,{scope:e.__scopeMenu,checked:s,children:u.jsx(di,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":yl(s),onSelect:ye(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Ch.displayName=Sh;var xl="MenuItemIndicator",[kh,WS]=Er(xl,{checked:!1}),Th=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=WS(xl,n);return u.jsx(gn,{present:r||fi(s.checked)||s.checked===!0,children:u.jsx(De.span,{...o,ref:t,"data-state":yl(s.checked)})})});Th.displayName=xl;var VS="MenuSeparator",Eh=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(De.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Eh.displayName=VS;var KS="MenuArrow",Ih=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ci(n);return u.jsx(nh,{...o,...r,ref:t})});Ih.displayName=KS;var qS="MenuSub",[jT,Nh]=Er(qS),Do="MenuSubTrigger",Ah=v.forwardRef((e,t)=>{const n=Ir(Do,e.__scopeMenu),r=Mo(Do,e.__scopeMenu),o=Nh(Do,e.__scopeMenu),s=pl(Do,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(fl,{asChild:!0,...c,children:u.jsx(yh,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Rh(n.open),...e,ref:_a(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:ye(e.onPointerMove,Lo(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:ye(e.onPointerLeave,Lo(f=>{var p,g;d();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const x=(g=n.content)==null?void 0:g.dataset.side,y=x==="right",m=y?-5:5,b=h[y?"left":"right"],S=h[y?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+m,y:f.clientY},{x:b,y:h.top},{x:S,y:h.top},{x:S,y:h.bottom},{x:b,y:h.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:ye(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||IS[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});Ah.displayName=Do;var _h="MenuSubContent",jh=v.forwardRef((e,t)=>{const n=hh(xn,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Ir(xn,e.__scopeMenu),i=Mo(xn,e.__scopeMenu),a=Nh(_h,e.__scopeMenu),l=v.useRef(null),c=Ze(t,l);return u.jsx(Oo.Provider,{scope:e.__scopeMenu,children:u.jsx(gn,{present:r||s.open,children:u.jsx(Oo.Slot,{scope:e.__scopeMenu,children:u.jsx(ml,{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:ye(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:ye(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:ye(e.onKeyDown,d=>{var p;const f=d.currentTarget.contains(d.target),h=NS[i.dir].includes(d.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),d.preventDefault())})})})})})});jh.displayName=_h;function Rh(e){return e?"open":"closed"}function fi(e){return e==="indeterminate"}function yl(e){return fi(e)?"indeterminate":e?"checked":"unchecked"}function GS(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function XS(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function YS(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=XS(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 JS(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 ZS(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return JS(n,t)}function Lo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var QS=fh,eC=fl,tC=ph,nC=mh,rC=gl,oC=gh,sC=di,iC=vh,aC=bh,lC=Ch,cC=Th,uC=Eh,dC=Ih,fC=Ah,hC=jh,hi="DropdownMenu",[pC,RT]=Hn(hi,[uh]),tn=uh(),[mC,Ph]=pC(hi),Oh=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=tn(t),c=v.useRef(null),[d,f]=Br({prop:o,defaultProp:s??!1,onChange:i,caller:hi});return u.jsx(mC,{scope:t,triggerId:Un(),triggerRef:c,contentId:Un(),open:d,onOpenChange:f,onOpenToggle:v.useCallback(()=>f(h=>!h),[f]),modal:a,children:u.jsx(QS,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};Oh.displayName=hi;var Mh="DropdownMenuTrigger",Dh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=Ph(Mh,n),i=tn(n);return u.jsx(eC,{asChild:!0,...i,children:u.jsx(De.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:_a(t,s.triggerRef),onPointerDown:ye(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:ye(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Dh.displayName=Mh;var gC="DropdownMenuPortal",Lh=e=>{const{__scopeDropdownMenu:t,...n}=e,r=tn(t);return u.jsx(tC,{...r,...n})};Lh.displayName=gC;var $h="DropdownMenuContent",Fh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ph($h,n),s=tn(n),i=v.useRef(!1);return u.jsx(nC,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:ye(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:ye(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)"}})});Fh.displayName=$h;var xC="DropdownMenuGroup",yC=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(rC,{...o,...r,ref:t})});yC.displayName=xC;var vC="DropdownMenuLabel",zh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(oC,{...o,...r,ref:t})});zh.displayName=vC;var wC="DropdownMenuItem",Bh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(sC,{...o,...r,ref:t})});Bh.displayName=wC;var bC="DropdownMenuCheckboxItem",Hh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(iC,{...o,...r,ref:t})});Hh.displayName=bC;var SC="DropdownMenuRadioGroup",CC=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(aC,{...o,...r,ref:t})});CC.displayName=SC;var kC="DropdownMenuRadioItem",Uh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(lC,{...o,...r,ref:t})});Uh.displayName=kC;var TC="DropdownMenuItemIndicator",Wh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(cC,{...o,...r,ref:t})});Wh.displayName=TC;var EC="DropdownMenuSeparator",Vh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(uC,{...o,...r,ref:t})});Vh.displayName=EC;var IC="DropdownMenuArrow",NC=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(dC,{...o,...r,ref:t})});NC.displayName=IC;var AC="DropdownMenuSubTrigger",Kh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(fC,{...o,...r,ref:t})});Kh.displayName=AC;var _C="DropdownMenuSubContent",qh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(hC,{...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)"}})});qh.displayName=_C;var jC=Oh,RC=Dh,PC=Lh,Gh=Fh,Xh=zh,Yh=Bh,Jh=Hh,Zh=Uh,Qh=Wh,ep=Vh,tp=Kh,np=qh;const OC=jC,MC=RC,DC=v.forwardRef(({className:e,inset:t,children:n,...r},o)=>u.jsxs(tp,{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(pe.ChevronRight,{className:"ml-auto h-4 w-4"})]}));DC.displayName=tp.displayName;const LC=v.forwardRef(({className:e,...t},n)=>u.jsx(np,{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}));LC.displayName=np.displayName;const rp=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(PC,{children:u.jsx(Gh,{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})}));rp.displayName=Gh.displayName;const vl=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(Yh,{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}));vl.displayName=Yh.displayName;const $C=v.forwardRef(({className:e,children:t,checked:n,...r},o)=>u.jsxs(Jh,{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(Qh,{children:u.jsx(pe.Check,{className:"h-4 w-4"})})}),t]}));$C.displayName=Jh.displayName;const FC=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Zh,{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(Qh,{children:u.jsx(pe.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));FC.displayName=Zh.displayName;const zC=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(Xh,{ref:r,className:se("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));zC.displayName=Xh.displayName;const BC=v.forwardRef(({className:e,...t},n)=>u.jsx(ep,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));BC.displayName=ep.displayName;const op={value:""};function pi({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,customStyles:f={},onMessageSent:h,onExcelUploadSuccess:p,onError:g}){const{api:x}=Bi(),{currentThreadId:y}=cs(),{threadId:m,messages:b,hasMore:S,isHistoryLoading:T,isLoading:k,loadOlder:C,navigateToCheckpoint:E,returnToLatest:R,checkpoint:_,checkpoints:j,interrupt:L,metadata:z}=us(),{isStreaming:V,error:O,connectionState:H,submit:P,stop:W}=tu(),F=m??y??null,$=(_==null?void 0:_.id)??null,ne=(_==null?void 0:_.namespace)??null,oe=(z==null?void 0:z.assemblingMessageId)??null,we=L,[Ne,Z]=w.useState(!1);w.useEffect(()=>{we||Z(!1)},[we]);const ie=w.useCallback(()=>{Z(!0)},[]),Te=w.useCallback(()=>{Z(!1)},[]),ee=!!we||Ne,[D,G]=w.useState(null),[ae,fe]=w.useState(""),[B,le]=w.useState(null),[Q,Ae]=w.useState(null),[ve,Re]=w.useState([]),[Ve,Qe]=w.useState(0),[et,Se]=w.useState(0),[nt,ut]=w.useState(!1),[rt,Ye]=w.useState(null),[It,dt]=w.useState(null),[kt,Nt]=w.useState(!1),[tt,He]=w.useState(null),[Tt,Vt]=w.useState(!1),zt=w.useRef(!1),[Kt,st]=w.useState(()=>op.value),Le=w.useRef(Kt),_t=w.useRef(null),yt=w.useCallback(J=>{op.value=J,st(J)},[]),[X,Ce]=w.useState(!1),ge=w.useCallback((J,de)=>{if(!J||typeof J!="object")return null;const he=J[de];return typeof he=="number"?he:null},[]),xt=w.useCallback((J,de)=>{if(!J||typeof J!="object")return null;const he=J[de];return typeof he=="string"&&he.trim()?he:null},[]),ft=w.useMemo(()=>{const J=Array.isArray(j)?[...j]:[];return J.some(he=>ge(he.metadata,"step")!==null)&&J.sort((he,wt)=>{const Ot=ge(he.metadata,"step"),an=ge(wt.metadata,"step");if(Ot!==null||an!==null)return(an??Number.NEGATIVE_INFINITY)-(Ot??Number.NEGATIVE_INFINITY);const qn=Date.parse(he.createdAt??""),cr=Date.parse(wt.createdAt??"");return Number.isNaN(qn)||Number.isNaN(cr)?0:cr-qn}),J},[j,ge]),{checkpointMetaById:ht,checkpointIndexByKey:Be}=w.useMemo(()=>{const J=new Map,de=new Map;for(const he of ft){const wt=he.checkpointId??null;if(!wt)continue;const Ot=ge(he.metadata,"step"),an=xt(he.metadata,"source"),qn={id:wt,step:Ot,source:an,createdAt:he.createdAt??null,namespace:he.checkpointNs??null,parentId:he.parentId??null};if(J.set(wt,qn),Ot!==null&&an){const cr=`${Ot}:${an}`,Fo=de.get(cr)??[];Fo.push(qn),de.set(cr,Fo)}}for(const he of de.values())he.sort((wt,Ot)=>{const an=wt.createdAt??"";return(Ot.createdAt??"").localeCompare(an)});return{checkpointMetaById:J,checkpointIndexByKey:de}},[ft,ge,xt]),Ft=w.useRef(null),Oe=w.useRef(null),it=w.useCallback(()=>{Ft.current&&(Ft.current.value=""),Oe.current&&(Oe.current.value=""),Qe(J=>J+1),Se(J=>J+1)},[]),ar=w.useCallback(J=>{yt(J)},[yt]),jr=w.useRef(!1);w.useEffect(()=>{jr.current&&!V&&(Re([]),it()),jr.current=V},[V,it]);const[lr,Rr]=w.useState("desktop");w.useEffect(()=>{const J=()=>{const de=window.innerWidth;Rr(de<640?"phone":de<1024?"tablet":"desktop")};return J(),window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),w.useEffect(()=>{Vt(!1),zt.current=!1},[F]),w.useEffect(()=>{Le.current=Kt},[Kt]),w.useEffect(()=>{if(!D){_t.current=null;return}_t.current===null&&(_t.current=Le.current),yt(ae??"")},[ae,D,yt]);const Pr=w.useCallback(async()=>{if(!(!S||T||!Tt))try{await C()}catch(J){console.warn("loadOlder failed",J)}},[S,Tt,T,C]);w.useEffect(()=>{(async()=>{if(!x.baseUrl){He(null);return}try{const he=(await x.getAgent("default")).uiDefaultMessage||"";He(he||null)}catch(de){console.warn("Failed to fetch default message:",de),He(null)}})()},[x.baseUrl]),w.useEffect(()=>{O&&!kt&&(g==null||g(O))},[O,kt,g]);const Kn=J=>{if(J.length>Ys)return`Message too long (${J.length}/${Ys} characters)`;try{return qb(J),null}catch(de){return(de==null?void 0:de.message)||"Invalid message"}},Qr=async J=>{const de=J.trim();if(!(!de&&ve.length===0)){if(de){const he=Kn(de);if(he){Ae(he);return}}try{const he=$??void 0,wt=ne??void 0,Ot=D?{edit:!0,originalMessageId:D,...B!=null&&B.checkpointId?{originalCheckpointId:B.checkpointId}:{},...B!=null&&B.checkpointNs?{originalCheckpointNs:B.checkpointNs}:{}}:void 0;await P({text:de||"",attachments:ve,messageAdditionalKwargs:Ot},{checkpointId:he,checkpointNs:wt}),h==null||h(de),yt(""),Ae(null),Re([]),it(),G(null),fe(""),le(null)}catch(he){const wt=(he==null?void 0:he.message)||"Failed to send message";Ae(wt),g==null||g(wt)}}},I=w.useCallback((J,de,he)=>{c&&(_t.current=Kt,G(J),fe(de),yt(de),Ae(null),le({checkpointId:(he==null?void 0:he.checkpointId)??null,checkpointNs:(he==null?void 0:he.checkpointNs)??null}))},[Kt,c,yt]),q=w.useCallback(()=>{G(null),fe(""),le(null),Ae(null),yt(_t.current??Kt),_t.current=null},[Kt,yt]),ue=w.useCallback((J,de,he)=>{I(J,de,he)},[I]),ke=w.useCallback(J=>{for(let de=J-1;de>=0;de--)if(b[de].role==="user"){const he=b[de].content||[],Ot=he.filter(an=>an.type==="text").map(an=>an.text).join("")||(()=>{try{return JSON.stringify(he,null,2)}catch{return String(he)}})();Ot&&P({text:Ot},{checkpointId:$??void 0,checkpointNs:ne??void 0});break}},[b,P,$,ne]),Xe=J=>{const de=Array.from(J.target.files||[]);Re(he=>[...he,...de]),J.target.value=""},at=J=>{Re(de=>{const he=de.filter((wt,Ot)=>J!==Ot);return he.length===0&&it(),he})},Ke=async J=>{const de=(J.target.files||[])[0];if(de){Ye(null),dt(null),ut(!0);try{await P({attachments:[de]},{checkpointId:$??void 0,checkpointNs:ne??void 0});const he=`Uploaded ${de.name} - processing through chat stream`;dt(he)}catch(he){const wt=he instanceof Error?he.message:"Failed to upload Excel file";console.error("Excel upload failed",he),Ye(wt),g==null||g(wt)}finally{ut(!1),J.target.value="",it()}}},$e=async J=>{if(y){Ce(!0);try{if(!J){await R();return}const de=ft.find(wt=>wt.checkpointId===J),he=(de==null?void 0:de.checkpointNs)??null;await E(J,he)}finally{Ce(!1)}}},jt=w.useCallback(async J=>{await $e(J)},[$e]),vt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${f.container||""}`,pt=`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 ${f.messagesArea||""}`,qt=`flex-shrink-0 w-full border-t p-4 bg-transparent ${f.inputArea||""}`,Gt=w.useCallback(J=>{if(!J)return"Latest";const de=[];J.step!==null&&de.push(`Step ${J.step}`),J.source&&de.push(J.source);const he=J.createdAt?new Date(J.createdAt):null,wt=he&&!Number.isNaN(he.getTime())?he.toLocaleString():J.createdAt??J.id,Ot=de.length?` — ${de.join(" • ")}`:"";return`${wt}${Ot}`},[]);return u.jsxs("div",{className:vt,children:[!!O&&!kt&&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:O}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:()=>Nt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(pe.X,{size:16})})]}),y&&ft.length>0&&u.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50",children:[u.jsx("span",{className:"opacity-70",children:"Checkpoint:"}),u.jsxs("select",{className:"border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",value:$??"",onChange:J=>{const de=J.target.value||null;$e(de)},children:[u.jsx("option",{value:"",children:"Latest"}),ft.map(J=>{const de=ht.get(J.checkpointId??"")??null;return u.jsx("option",{value:J.checkpointId??void 0,children:Gt(de)},J.checkpointId)})]})]}),u.jsxs("div",{className:`relative ${pt}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Ga,{className:"h-full",style:{height:"100%"},messages:b,isStreaming:V,streamingAssistantId:oe,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:lr,enableMessageEditing:c,editingMessageId:D,onStartReached:()=>{Tt&&Pr()},onScrollAway:J=>{if(!zt.current){zt.current=!0;return}J&&Vt(!0)},onEdit:ue,onRegenerate:ke,onCancelEdit:q,emptyMessage:tt??void 0,isNavigatingCheckpoint:X,activeInterrupt:we,disableInterruptActions:Ne,onInterruptActionStart:ie,onInterruptActionEnd:Te,showToolMessages:d,checkpointMetaById:ht,checkpointIndexByKey:Be,activeCheckpointId:$,onSelectCheckpoint:jt}),(H==="reconnecting"||H==="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(pe.Loader2,{className:"h-3 w-3 animate-spin"}),H==="reconnecting"?"Reconnecting…":"Connecting…"]})}),H==="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"}),k&&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(pe.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]})]}),u.jsxs("div",{className:qt,children:[D&&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(pe.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:q,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(pe.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:Ft,type:"file",multiple:!0,onChange:J=>Xe(J),className:"hidden"},Ve),ve.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:ve.map((J,de)=>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(pe.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:J.name}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:()=>at(de),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 ${J.name}`,children:u.jsx(pe.X,{size:12})})]},de))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Oe,type:"file",accept:".xls,.xlsx,.xlsm",onChange:Ke,className:"hidden"},et),nt&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),It&&!nt&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:It}),rt&&!nt&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:rt})]})]}),Q&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:Q}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(OC,{children:[u.jsx(MC,{asChild:!0,children:u.jsx(lt,{type:"button",size:"icon",variant:"outline",disabled:V||ee,title:"More input actions",className:f.moreButton||"",children:u.jsx(pe.Plus,{size:16})})}),u.jsxs(rp,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(vl,{onClick:()=>{var J;return(J=Ft.current)==null?void 0:J.click()},className:"cursor-pointer",children:[u.jsx(pe.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(vl,{onClick:()=>{var J;nt||(J=Oe.current)==null||J.click()},className:`cursor-pointer ${nt?"opacity-60 pointer-events-none":""}`,children:[u.jsx(pe.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(dy,{initialValue:ae,editingMessageId:D,value:Kt,onValueChange:ar,placeholder:D?"Edit your message...":t,isStreaming:V,disabled:ee,maxLength:Ys,onSend:Qr,onCancelEdit:q,onStop:W,allowEmptySend:ve.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${D?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${Q?"border-red-400":""} ${f.textarea||""}`})})]})]})]})}const mi=v.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}));mi.displayName="Input";function wl(e,[t,n]){return Math.min(n,Math.max(t,e))}function HC(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var bl="ScrollArea",[sp,PT]=Hn(bl),[UC,yn]=sp(bl),ip=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,g]=v.useState(null),[x,y]=v.useState(null),[m,b]=v.useState(0),[S,T]=v.useState(0),[k,C]=v.useState(!1),[E,R]=v.useState(!1),_=Ze(t,L=>l(L)),j=Js(o);return u.jsx(UC,{scope:n,type:r,dir:j,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:g,scrollbarXEnabled:k,onScrollbarXEnabledChange:C,scrollbarY:x,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:R,onCornerWidthChange:b,onCornerHeightChange:T,children:u.jsx(De.div,{dir:j,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});ip.displayName=bl;var ap="ScrollAreaViewport",lp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=yn(ap,n),a=v.useRef(null),l=Ze(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(De.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})})]})});lp.displayName=ap;var $n="ScrollAreaScrollbar",Sl=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=yn($n,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(WC,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(VC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(cp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Cl,{...r,ref:t}):null});Sl.displayName=$n;var WC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=yn($n,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(gn,{present:n||s,children:u.jsx(cp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),VC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=yn($n,e.__scopeScrollArea),s=e.orientation==="horizontal",i=vi(()=>l("SCROLL_END"),100),[a,l]=HC("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(gn,{present:n||a!=="hidden",children:u.jsx(Cl,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:ye(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:ye(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),cp=v.forwardRef((e,t)=>{const n=yn($n,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=vi(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Yr(n.viewport,l),Yr(n.content,l),u.jsx(gn,{present:r||s,children:u.jsx(Cl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Cl=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=yn($n,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=pp(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 JC(h,i.current,a,p)}return n==="horizontal"?u.jsx(KC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=mp(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(qC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=mp(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}),KC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=yn($n,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(dp,{"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":yi(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),xp(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:xi(i.paddingLeft),paddingEnd:xi(i.paddingRight)}})}})}),qC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=yn($n,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(dp,{"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":yi(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),xp(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:xi(i.paddingTop),paddingEnd:xi(i.paddingBottom)}})}})}),[GC,up]=sp($n),dp=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=yn($n,n),[g,x]=v.useState(null),y=Ze(t,_=>x(_)),m=v.useRef(null),b=v.useRef(""),S=p.viewport,T=r.content-r.viewport,k=Wt(d),C=Wt(l),E=vi(f,10);function R(_){if(m.current){const j=_.clientX-m.current.left,L=_.clientY-m.current.top;c({x:j,y:L})}}return v.useEffect(()=>{const _=j=>{const L=j.target;(g==null?void 0:g.contains(L))&&k(j,T)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,g,T,k]),v.useEffect(C,[r,C]),Yr(g,E),Yr(p.content,E),u.jsx(GC,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:Wt(s),onThumbPointerUp:Wt(i),onThumbPositionChange:C,onThumbPointerDown:Wt(a),children:u.jsx(De.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:ye(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),m.current=g.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),R(_))}),onPointerMove:ye(e.onPointerMove,R),onPointerUp:ye(e.onPointerUp,_=>{const j=_.target;j.hasPointerCapture(_.pointerId)&&j.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),m.current=null})})})}),gi="ScrollAreaThumb",fp=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=up(gi,e.__scopeScrollArea);return u.jsx(gn,{present:n||o.hasThumb,children:u.jsx(XC,{ref:t,...r})})}),XC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=yn(gi,n),i=up(gi,n),{onThumbPositionChange:a}=i,l=Ze(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=vi(()=>{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=ZC(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(De.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:ye(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),g=f.clientX-p.left,x=f.clientY-p.top;i.onThumbPointerDown({x:g,y:x})}),onPointerUp:ye(e.onPointerUp,i.onThumbPointerUp)})});fp.displayName=gi;var kl="ScrollAreaCorner",hp=v.forwardRef((e,t)=>{const n=yn(kl,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(YC,{...e,ref:t}):null});hp.displayName=kl;var YC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=yn(kl,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return Yr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Yr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(De.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 xi(e){return e?parseInt(e,10):0}function pp(e,t){const n=e/t;return isNaN(n)?0:n}function yi(e){const t=pp(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function JC(e,t,n,r="ltr"){const o=yi(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 mp(e,t,n="ltr"){const r=yi(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=wl(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 xp(e,t){return e>0&&e<t}var ZC=(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 vi(e,t){const n=Wt(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 Yr(e,t){const n=Wt(t);Ut(()=>{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 yp=ip,QC=lp,ek=hp;const vp=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(yp,{ref:r,className:se("relative overflow-hidden",e),...n,children:[u.jsx(QC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(wp,{}),u.jsx(ek,{})]}));vp.displayName=yp.displayName;const wp=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Sl,{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(fp,{className:"relative flex-1 rounded-full bg-border"})}));wp.displayName=Sl.displayName;const bp=25;function Tl({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,currentThreadId:h,isLoading:p,actions:g}=cs(),{loadThread:x}=us(),{createThread:y,deleteThread:m,renameThread:b}=g,[S,T]=w.useState(Array.isArray(f)?f:[]),k=w.useRef(S.length>0),C=w.useRef(null),E=w.useRef(0),[R,_]=w.useState(null),[j,L]=w.useState(""),[z,V]=w.useState(!1);w.useEffect(()=>{const Z=Array.isArray(f)?f:[];if(Z.length>0){k.current=!0,T(Z);return}p||(k.current=!1,T(Z))},[f,p]),w.useEffect(()=>{if(!C.current)return;const Z=C.current.querySelector("[data-radix-scroll-area-viewport]");if(!Z)return;let ie=null,Te=null;return ie=requestAnimationFrame(()=>{Te=requestAnimationFrame(()=>{Z.scrollTop=E.current})}),()=>{ie!==null&&cancelAnimationFrame(ie),Te!==null&&cancelAnimationFrame(Te)}},[S]);const O=async Z=>{try{await x(Z),a==null||a(Z),l==null||l(Z)}catch(ie){console.error("Failed to select thread:",ie)}},H=async()=>{try{V(!0);const Z=await y();c==null||c(Z),a==null||a(Z)}catch(Z){console.error("Failed to create thread:",Z)}finally{V(!1)}},P=async(Z,ie)=>{if(ie.stopPropagation(),!!confirm("Delete this thread?")){if(C.current){const Te=C.current.querySelector("[data-radix-scroll-area-viewport]");Te&&(E.current=Te.scrollTop)}try{await m(Z),d==null||d(Z)}catch(Te){console.error("Failed to delete thread:",Te)}}},W=(Z,ie)=>{ie.stopPropagation(),_(Z.threadId),L(Z.title||`Thread ${Z.threadId.slice(0,8)}`)},F=async Z=>{if(j.trim())try{await b(Z,j.trim()),_(null),L("")}catch(ie){console.error("Failed to update title:",ie)}},$=()=>{_(null),L("")},ne=(Z,ie)=>{Z.key==="Enter"?F(ie):Z.key==="Escape"&&$()},oe=Z=>{if(!Z)return"";try{const ie=new Date(Z),ee=new Date().getTime()-ie.getTime(),D=Math.floor(ee/(1e3*60*60*24));return D===0?ie.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):D===1?"Yesterday":D<7?`${D} days ago`:ie.toLocaleDateString()}catch{return""}},we=Z=>Z.title||`Thread ${Z.threadId.slice(0,8)}`,Ne=Z=>{const ie=we(Z);return ie.length<=bp?ie:`${ie.slice(0,bp)}...`};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(lt,{onClick:H,disabled:z||p,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:z?"Creating...":"New Chat",children:u.jsx(pe.MessageSquarePlus,{size:20})})}),u.jsx(vp,{ref:C,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:p?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(pe.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):S.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(pe.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"})]}):S.slice().sort((Z,ie)=>new Date(ie.updatedAt||ie.createdAt||"").getTime()-new Date(Z.updatedAt||Z.createdAt||"").getTime()).map(Z=>u.jsxs("div",{onClick:()=>O(Z.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??h)===Z.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:R===Z.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:ie=>ie.stopPropagation(),children:[u.jsx(mi,{value:j,onChange:ie=>L(ie.target.value),onKeyDown:ie=>ne(ie,Z.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:()=>F(Z.threadId),className:"h-6 w-6 p-0",children:u.jsx(pe.Check,{size:12})}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:$,className:"h-6 w-6 p-0",children:u.jsx(pe.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:Ne(Z)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(pe.Calendar,{size:10}),u.jsx("span",{children:oe(Z.updatedAt||Z.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&R!==Z.threadId&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:ie=>W(Z,ie),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(pe.Edit3,{size:12})}),n&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:ie=>P(Z.threadId,ie),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(pe.Trash2,{size:12})})]})]}),i===Z.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},Z.threadId))})})]})}function Jr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function tk(e){if(typeof e!="string")return;const t=e.trim();if(t)return zn(t)}function Sp(){const e=[Jr("__API_BASE_URL__"),Jr("__CHAT_API_BASE_URL__"),Jr("__CHAT_API_URL__")];for(const t of e){const n=tk(t);if(n)return n}}function Cp(){const e=[Jr("__API_AUTH_TOKEN__"),Jr("__CHAT_API_KEY__"),Jr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function kp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return zn(t);return zn()}function Tp(){const e={},t=Sp(),n=Cp();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Ep(){const e=Tp(),t=Gn.getAuthToken(),n=Sp();return{apiBaseUrl:kp(e.baseUrl,Gn.baseUrl,n),apiKey:t||e.apiKey||Cp()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Ip="chat-settings";function nk(){try{const e=localStorage.getItem(Ip);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function rk(e){try{const t={...e,apiBaseUrl:zn(e.apiBaseUrl)};localStorage.setItem(Ip,JSON.stringify(t)),t.apiKey&&Gn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function ok(){const e=Ep(),t=nk(),n=Gn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:kp(Gn.baseUrl,r,e.apiBaseUrl)}}function sk(e){Gn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),rk(e)}var ik="Label",Np=v.forwardRef((e,t)=>u.jsx(De.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())}}));Np.displayName=ik;var Ap=Np;const ak=Uo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),vn=v.forwardRef(({className:e,...t},n)=>u.jsx(Ap,{ref:n,className:se(ak(),e),...t}));vn.displayName=Ap.displayName;function _p(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 wi="Switch",[lk,OT]=Hn(wi),[ck,uk]=lk(wi),jp=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),g=Ze(t,S=>p(S)),x=v.useRef(!1),y=h?d||!!h.closest("form"):!0,[m,b]=Br({prop:o,defaultProp:s??!1,onChange:c,caller:wi});return u.jsxs(ck,{scope:n,checked:m,disabled:a,children:[u.jsx(De.button,{type:"button",role:"switch","aria-checked":m,"aria-required":i,"data-state":Mp(m),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:g,onClick:ye(e.onClick,S=>{b(T=>!T),y&&(x.current=S.isPropagationStopped(),x.current||S.stopPropagation())})}),y&&u.jsx(Op,{control:h,bubbles:!x.current,name:r,value:l,checked:m,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});jp.displayName=wi;var Rp="SwitchThumb",Pp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=uk(Rp,n);return u.jsx(De.span,{"data-state":Mp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Pp.displayName=Rp;var dk="SwitchBubbleInput",Op=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=Ze(i,s),l=_p(n),c=Uf(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 g=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(g)}},[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}})});Op.displayName=dk;function Mp(e){return e?"checked":"unchecked"}var Dp=jp,fk=Pp;const or=v.forwardRef(({className:e,...t},n)=>u.jsx(Dp,{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(fk,{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")})}));or.displayName=Dp.displayName;var Lp=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"}),hk="VisuallyHidden",pk=v.forwardRef((e,t)=>u.jsx(De.span,{...e,ref:t,style:{...Lp,...e.style}}));pk.displayName=hk;var mk=[" ","Enter","ArrowUp","ArrowDown"],gk=[" ","Enter"],Nr="Select",[bi,Si,xk]=Xa(Nr),[Zr,MT]=Hn(Nr,[xk,li]),Ci=li(),[yk,sr]=Zr(Nr),[vk,wk]=Zr(Nr),$p=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:g}=e,x=Ci(t),[y,m]=v.useState(null),[b,S]=v.useState(null),[T,k]=v.useState(!1),C=Js(c),[E,R]=Br({prop:r,defaultProp:o??!1,onChange:s,caller:Nr}),[_,j]=Br({prop:i,defaultProp:a,onChange:l,caller:Nr}),L=v.useRef(null),z=y?g||!!y.closest("form"):!0,[V,O]=v.useState(new Set),H=Array.from(V).map(P=>P.props.value).join(";");return u.jsx(Qf,{...x,children:u.jsxs(yk,{required:p,scope:t,trigger:y,onTriggerChange:m,valueNode:b,onValueNodeChange:S,valueNodeHasChildren:T,onValueNodeHasChildrenChange:k,contentId:Un(),value:_,onValueChange:j,open:E,onOpenChange:R,dir:C,triggerPointerDownPosRef:L,disabled:h,children:[u.jsx(bi.Provider,{scope:t,children:u.jsx(vk,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(P=>{O(W=>new Set(W).add(P))},[]),onNativeOptionRemove:v.useCallback(P=>{O(W=>{const F=new Set(W);return F.delete(P),F})},[]),children:n})}),z?u.jsxs(lm,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:P=>j(P.target.value),disabled:h,form:g,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(V)]},H):null]})})};$p.displayName=Nr;var Fp="SelectTrigger",zp=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Ci(n),i=sr(Fp,n),a=i.disabled||r,l=Ze(t,i.onTriggerChange),c=Si(n),d=v.useRef("touch"),[f,h,p]=um(x=>{const y=c().filter(S=>!S.disabled),m=y.find(S=>S.value===i.value),b=dm(y,x,m);b!==void 0&&i.onValueChange(b.value)}),g=x=>{a||(i.onOpenChange(!0),p()),x&&(i.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return u.jsx(eh,{asChild:!0,...s,children:u.jsx(De.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":cm(i.value)?"":void 0,...o,ref:l,onClick:ye(o.onClick,x=>{x.currentTarget.focus(),d.current!=="mouse"&&g(x)}),onPointerDown:ye(o.onPointerDown,x=>{d.current=x.pointerType;const y=x.target;y.hasPointerCapture(x.pointerId)&&y.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(g(x),x.preventDefault())}),onKeyDown:ye(o.onKeyDown,x=>{const y=f.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&h(x.key),!(y&&x.key===" ")&&mk.includes(x.key)&&(g(),x.preventDefault())})})})});zp.displayName=Fp;var Bp="SelectValue",Hp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=sr(Bp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ze(t,l.onValueNodeChange);return Ut(()=>{c(d)},[c,d]),u.jsx(De.span,{...a,ref:f,style:{pointerEvents:"none"},children:cm(l.value)?u.jsx(u.Fragment,{children:i}):s})});Hp.displayName=Bp;var bk="SelectIcon",Up=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(De.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Up.displayName=bk;var Sk="SelectPortal",Wp=e=>u.jsx(_s,{asChild:!0,...e});Wp.displayName=Sk;var Ar="SelectContent",Vp=v.forwardRef((e,t)=>{const n=sr(Ar,e.__scopeSelect),[r,o]=v.useState();if(Ut(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Wo.createPortal(u.jsx(Kp,{scope:e.__scopeSelect,children:u.jsx(bi.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(qp,{...e,ref:t})});Vp.displayName=Ar;var Nn=10,[Kp,ir]=Zr(Ar),Ck="SelectContentImpl",kk=hr.createSlot("SelectContent.RemoveScroll"),qp=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:g,hideWhenDetached:x,avoidCollisions:y,...m}=e,b=sr(Ar,n),[S,T]=v.useState(null),[k,C]=v.useState(null),E=Ze(t,ee=>T(ee)),[R,_]=v.useState(null),[j,L]=v.useState(null),z=Si(n),[V,O]=v.useState(!1),H=v.useRef(!1);v.useEffect(()=>{if(S)return Ba(S)},[S]),Ma();const P=v.useCallback(ee=>{const[D,...G]=z().map(B=>B.ref.current),[ae]=G.slice(-1),fe=document.activeElement;for(const B of ee)if(B===fe||(B==null||B.scrollIntoView({block:"nearest"}),B===D&&k&&(k.scrollTop=0),B===ae&&k&&(k.scrollTop=k.scrollHeight),B==null||B.focus(),document.activeElement!==fe))return},[z,k]),W=v.useCallback(()=>P([R,S]),[P,R,S]);v.useEffect(()=>{V&&W()},[V,W]);const{onOpenChange:F,triggerPointerDownPosRef:$}=b;v.useEffect(()=>{if(S){let ee={x:0,y:0};const D=ae=>{var fe,B;ee={x:Math.abs(Math.round(ae.pageX)-(((fe=$.current)==null?void 0:fe.x)??0)),y:Math.abs(Math.round(ae.pageY)-(((B=$.current)==null?void 0:B.y)??0))}},G=ae=>{ee.x<=10&&ee.y<=10?ae.preventDefault():S.contains(ae.target)||F(!1),document.removeEventListener("pointermove",D),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",D),document.addEventListener("pointerup",G,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",G,{capture:!0})}}},[S,F,$]),v.useEffect(()=>{const ee=()=>F(!1);return window.addEventListener("blur",ee),window.addEventListener("resize",ee),()=>{window.removeEventListener("blur",ee),window.removeEventListener("resize",ee)}},[F]);const[ne,oe]=um(ee=>{const D=z().filter(fe=>!fe.disabled),G=D.find(fe=>fe.ref.current===document.activeElement),ae=dm(D,ee,G);ae&&setTimeout(()=>ae.ref.current.focus())}),we=v.useCallback((ee,D,G)=>{const ae=!H.current&&!G;(b.value!==void 0&&b.value===D||ae)&&(_(ee),ae&&(H.current=!0))},[b.value]),Ne=v.useCallback(()=>S==null?void 0:S.focus(),[S]),Z=v.useCallback((ee,D,G)=>{const ae=!H.current&&!G;(b.value!==void 0&&b.value===D||ae)&&L(ee)},[b.value]),ie=r==="popper"?El:Gp,Te=ie===El?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:g,hideWhenDetached:x,avoidCollisions:y}:{};return u.jsx(Kp,{scope:n,content:S,viewport:k,onViewportChange:C,itemRefCallback:we,selectedItem:R,onItemLeave:Ne,itemTextRefCallback:Z,focusSelectedItem:W,selectedItemText:j,position:r,isPositioned:V,searchRef:ne,children:u.jsx(Ls,{as:kk,allowPinchZoom:!0,children:u.jsx(As,{asChild:!0,trapped:b.open,onMountAutoFocus:ee=>{ee.preventDefault()},onUnmountAutoFocus:ye(o,ee=>{var D;(D=b.trigger)==null||D.focus({preventScroll:!0}),ee.preventDefault()}),children:u.jsx(Ns,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:ee=>ee.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(ie,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:ee=>ee.preventDefault(),...m,...Te,onPlaced:()=>O(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...m.style},onKeyDown:ye(m.onKeyDown,ee=>{const D=ee.ctrlKey||ee.altKey||ee.metaKey;if(ee.key==="Tab"&&ee.preventDefault(),!D&&ee.key.length===1&&oe(ee.key),["ArrowUp","ArrowDown","Home","End"].includes(ee.key)){let ae=z().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);if(["ArrowUp","End"].includes(ee.key)&&(ae=ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(ee.key)){const fe=ee.target,B=ae.indexOf(fe);ae=ae.slice(B+1)}setTimeout(()=>P(ae)),ee.preventDefault()}})})})})})})});qp.displayName=Ck;var Tk="SelectItemAlignedPosition",Gp=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=sr(Ar,n),i=ir(Ar,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=Ze(t,E=>d(E)),h=Si(n),p=v.useRef(!1),g=v.useRef(!0),{viewport:x,selectedItem:y,selectedItemText:m,focusSelectedItem:b}=i,S=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&x&&y&&m){const E=s.trigger.getBoundingClientRect(),R=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),j=m.getBoundingClientRect();if(s.dir!=="rtl"){const fe=j.left-R.left,B=_.left-fe,le=E.left-B,Q=E.width+le,Ae=Math.max(Q,R.width),ve=window.innerWidth-Nn,Re=wl(B,[Nn,Math.max(Nn,ve-Ae)]);a.style.minWidth=Q+"px",a.style.left=Re+"px"}else{const fe=R.right-j.right,B=window.innerWidth-_.right-fe,le=window.innerWidth-E.right-B,Q=E.width+le,Ae=Math.max(Q,R.width),ve=window.innerWidth-Nn,Re=wl(B,[Nn,Math.max(Nn,ve-Ae)]);a.style.minWidth=Q+"px",a.style.right=Re+"px"}const L=h(),z=window.innerHeight-Nn*2,V=x.scrollHeight,O=window.getComputedStyle(c),H=parseInt(O.borderTopWidth,10),P=parseInt(O.paddingTop,10),W=parseInt(O.borderBottomWidth,10),F=parseInt(O.paddingBottom,10),$=H+P+V+F+W,ne=Math.min(y.offsetHeight*5,$),oe=window.getComputedStyle(x),we=parseInt(oe.paddingTop,10),Ne=parseInt(oe.paddingBottom,10),Z=E.top+E.height/2-Nn,ie=z-Z,Te=y.offsetHeight/2,ee=y.offsetTop+Te,D=H+P+ee,G=$-D;if(D<=Z){const fe=L.length>0&&y===L[L.length-1].ref.current;a.style.bottom="0px";const B=c.clientHeight-x.offsetTop-x.offsetHeight,le=Math.max(ie,Te+(fe?Ne:0)+B+W),Q=D+le;a.style.height=Q+"px"}else{const fe=L.length>0&&y===L[0].ref.current;a.style.top="0px";const le=Math.max(Z,H+x.offsetTop+(fe?we:0)+Te)+G;a.style.height=le+"px",x.scrollTop=D-Z+x.offsetTop}a.style.margin=`${Nn}px 0`,a.style.minHeight=ne+"px",a.style.maxHeight=z+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,x,y,m,s.dir,r]);Ut(()=>S(),[S]);const[T,k]=v.useState();Ut(()=>{c&&k(window.getComputedStyle(c).zIndex)},[c]);const C=v.useCallback(E=>{E&&g.current===!0&&(S(),b==null||b(),g.current=!1)},[S,b]);return u.jsx(Ik,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:C,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:u.jsx(De.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});Gp.displayName=Tk;var Ek="SelectPopperPosition",El=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=Nn,...s}=e,i=Ci(n);return u.jsx(th,{...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)"}})});El.displayName=Ek;var[Ik,Il]=Zr(Ar,{}),Nl="SelectViewport",Xp=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=ir(Nl,n),i=Il(Nl,n),a=Ze(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(bi.Slot,{scope:n,children:u.jsx(De.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:ye(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 g=window.innerHeight-Nn*2,x=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),m=Math.max(x,y);if(m<g){const b=m+p,S=Math.min(g,b),T=b-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=T>0?T:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});Xp.displayName=Nl;var Yp="SelectGroup",[Nk,Ak]=Zr(Yp),_k=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Un();return u.jsx(Nk,{scope:n,id:o,children:u.jsx(De.div,{role:"group","aria-labelledby":o,...r,ref:t})})});_k.displayName=Yp;var Jp="SelectLabel",Zp=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ak(Jp,n);return u.jsx(De.div,{id:o.id,...r,ref:t})});Zp.displayName=Jp;var ki="SelectItem",[jk,Qp]=Zr(ki),em=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=sr(ki,n),l=ir(ki,n),c=a.value===r,[d,f]=v.useState(s??""),[h,p]=v.useState(!1),g=Ze(t,b=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,b,r,o)}),x=Un(),y=v.useRef("touch"),m=()=>{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(jk,{scope:n,value:r,disabled:o,textId:x,isSelected:c,onItemTextChange:v.useCallback(b=>{f(S=>S||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(bi.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(De.div,{role:"option","aria-labelledby":x,"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:g,onFocus:ye(i.onFocus,()=>p(!0)),onBlur:ye(i.onBlur,()=>p(!1)),onClick:ye(i.onClick,()=>{y.current!=="mouse"&&m()}),onPointerUp:ye(i.onPointerUp,()=>{y.current==="mouse"&&m()}),onPointerDown:ye(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:ye(i.onPointerMove,b=>{var S;y.current=b.pointerType,o?(S=l.onItemLeave)==null||S.call(l):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ye(i.onPointerLeave,b=>{var S;b.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:ye(i.onKeyDown,b=>{var T;((T=l.searchRef)==null?void 0:T.current)!==""&&b.key===" "||(gk.includes(b.key)&&m(),b.key===" "&&b.preventDefault())})})})})});em.displayName=ki;var $o="SelectItemText",tm=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=sr($o,n),a=ir($o,n),l=Qp($o,n),c=wk($o,n),[d,f]=v.useState(null),h=Ze(t,m=>f(m),l.onItemTextChange,m=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,m,l.value,l.disabled)}),p=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:y}=c;return Ut(()=>(x(g),()=>y(g)),[x,y,g]),u.jsxs(u.Fragment,{children:[u.jsx(De.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Wo.createPortal(s.children,i.valueNode):null]})});tm.displayName=$o;var nm="SelectItemIndicator",rm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Qp(nm,n).isSelected?u.jsx(De.span,{"aria-hidden":!0,...r,ref:t}):null});rm.displayName=nm;var Al="SelectScrollUpButton",om=v.forwardRef((e,t)=>{const n=ir(Al,e.__scopeSelect),r=Il(Al,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Ut(()=>{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(im,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});om.displayName=Al;var _l="SelectScrollDownButton",sm=v.forwardRef((e,t)=>{const n=ir(_l,e.__scopeSelect),r=Il(_l,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Ut(()=>{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(im,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});sm.displayName=_l;var im=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=ir("SelectScrollButton",n),i=v.useRef(null),a=Si(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),Ut(()=>{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(De.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:ye(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ye(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ye(o.onPointerLeave,()=>{l()})})}),Rk="SelectSeparator",am=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(De.div,{"aria-hidden":!0,...r,ref:t})});am.displayName=Rk;var jl="SelectArrow",Pk=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ci(n),s=sr(jl,n),i=ir(jl,n);return s.open&&i.position==="popper"?u.jsx(nh,{...o,...r,ref:t}):null});Pk.displayName=jl;var Ok="SelectBubbleInput",lm=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=Ze(r,o),i=_p(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(De.select,{...n,style:{...Lp,...n.style},ref:s,defaultValue:t})});lm.displayName=Ok;function cm(e){return e===""||e===void 0}function um(e){const t=Wt(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 dm(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=Mk(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 Mk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Dk=$p,fm=zp,Lk=Hp,$k=Up,Fk=Wp,hm=Vp,zk=Xp,pm=Zp,mm=em,Bk=tm,Hk=rm,gm=om,xm=sm,ym=am;const vm=Dk,wm=Lk,Rl=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(fm,{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($k,{asChild:!0,children:u.jsx(pe.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Rl.displayName=fm.displayName;const bm=v.forwardRef(({className:e,...t},n)=>u.jsx(gm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(pe.ChevronUp,{className:"h-4 w-4"})}));bm.displayName=gm.displayName;const Sm=v.forwardRef(({className:e,...t},n)=>u.jsx(xm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(pe.ChevronDown,{className:"h-4 w-4"})}));Sm.displayName=xm.displayName;const Pl=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(Fk,{children:u.jsxs(hm,{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(bm,{}),u.jsx(zk,{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(Sm,{})]})}));Pl.displayName=hm.displayName;const Uk=v.forwardRef(({className:e,...t},n)=>u.jsx(pm,{ref:n,className:se("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Uk.displayName=pm.displayName;const _r=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(mm,{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(Hk,{children:u.jsx(pe.Check,{className:"h-4 w-4"})})}),u.jsx(Bk,{children:t})]}));_r.displayName=mm.displayName;const Wk=v.forwardRef(({className:e,...t},n)=>u.jsx(ym,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));Wk.displayName=ym.displayName;var Vk="Separator",Cm="horizontal",Kk=["horizontal","vertical"],km=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Cm,...o}=e,s=qk(r)?r:Cm,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(De.div,{"data-orientation":s,...a,...o,ref:t})});km.displayName=Vk;function qk(e){return Kk.includes(e)}var Tm=km;const Em=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Tm,{ref:o,decorative:n,orientation:t,className:se("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Em.displayName=Tm.displayName;const Gk=Xd,Xk=hb,Yk=Yd,Im=v.forwardRef(({className:e,...t},n)=>u.jsx(Hs,{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}));Im.displayName=Hs.displayName;const Jk=Uo.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"}}),Nm=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(Yk,{children:[u.jsx(Im,{}),u.jsxs(Us,{ref:o,className:se(Jk({side:e}),t),...r,children:[n,u.jsxs(Jd,{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(pe.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Nm.displayName=Us.displayName;const Am=({className:e,...t})=>u.jsx("div",{className:se("flex flex-col space-y-2 text-center sm:text-left",e),...t});Am.displayName="SheetHeader";const _m=v.forwardRef(({className:e,...t},n)=>u.jsx(Cr,{ref:n,className:se("text-lg font-semibold text-foreground",e),...t}));_m.displayName=Cr.displayName;const jm=v.forwardRef(({className:e,...t},n)=>u.jsx(Ws,{ref:n,className:se("text-sm text-muted-foreground",e),...t}));jm.displayName=Ws.displayName;const Zk={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 Qk({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}=Na();w.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),w.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(Zk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},g=()=>{l(e),d(!1),o(!1)},x=async()=>{try{const m=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${m.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(Gk,{open:r,onOpenChange:o,children:[u.jsx(Xk,{asChild:!0,children:u.jsxs(lt,{variant:"outline",size:"sm",className:n,children:[u.jsx(pe.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(td,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Nm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(Am,{children:[u.jsx(_m,{children:"Chat Settings"}),u.jsx(jm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(bo,{children:[u.jsx(So,{className:"pb-3",children:u.jsxs(Co,{className:"text-lg flex items-center gap-2",children:[u.jsx(pe.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(ko,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(mi,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(m=>({...m,api:{...m.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(lt,{variant:"outline",onClick:x,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(or,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(m=>({...m,api:{...m.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(mi,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(m=>({...m,api:{...m.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(lt,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(pe.EyeOff,{className:"h-4 w-4"}):u.jsx(pe.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(bo,{children:[u.jsx(So,{className:"pb-3",children:u.jsxs(Co,{className:"text-lg flex items-center gap-2",children:[u.jsx(pe.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(ko,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(vm,{value:a.ui.layout,onValueChange:y=>l(m=>({...m,ui:{...m.ui,layout:y}})),children:[u.jsx(Rl,{children:u.jsx(wm,{})}),u.jsxs(Pl,{children:[u.jsx(_r,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(_r,{value:"fullscreen",children:"Fullscreen"}),u.jsx(_r,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"theme",children:"Theme"}),u.jsxs(vm,{value:a.ui.theme,onValueChange:y=>l(m=>({...m,ui:{...m.ui,theme:y}})),children:[u.jsx(Rl,{children:u.jsx(wm,{})}),u.jsxs(Pl,{children:[u.jsx(_r,{value:"light",children:"Light"}),u.jsx(_r,{value:"dark",children:"Dark"}),u.jsx(_r,{value:"system",children:"System"})]})]})]}),u.jsx(Em,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(or,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(m=>({...m,ui:{...m.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(or,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(m=>({...m,ui:{...m.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(or,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(m=>({...m,ui:{...m.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(bo,{children:[u.jsx(So,{className:"pb-3",children:u.jsxs(Co,{className:"text-lg flex items-center gap-2",children:[u.jsx(pe.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(ko,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(vn,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(or,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(m=>({...m,behavior:{...m.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(vn,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(or,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(m=>({...m,behavior:{...m.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(vn,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(or,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(m=>({...m,behavior:{...m.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(lt,{variant:"outline",onClick:p,children:[u.jsx(pe.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(lt,{variant:"outline",onClick:g,children:"Cancel"}),u.jsxs(lt,{onClick:h,disabled:!c,children:[u.jsx(pe.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function eT({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(ds,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(pi,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(ds,{...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(Tl,{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(pi,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(ds,{...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(Tl,{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(pi,{onError:s.onError,enableFileUpload:!0})})]})})}Pe.ChatApi=_c,Pe.ChatInterface=pi,Pe.ChatProviders=ds,Pe.ChatSettings=Qk,Pe.MarkdownContent=No,Pe.MessageComponent=qa,Pe.MessageList=Ga,Pe.ThreadManager=Tl,Pe.applySettings=sk,Pe.chatApiClient=Gn,Pe.default=eT,Pe.del=Ac,Pe.get=bn,Pe.getChatToken=Ec,Pe.getCurrentSettings=ok,Pe.getDefaultApiConfig=Tp,Pe.getDefaultChatSettings=Ep,Pe.onChatTokenChanged=Ic,Pe.post=zi,Pe.put=Nc,Pe.setChatToken=Fi,Pe.useApi=Bi,Pe.useChatStream=Vc,Pe.useMessagesReducer=Lc,Pe.useStream=tu,Pe.useThreadState=us,Pe.useThreads=cs,Object.defineProperties(Pe,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
137
+ `).trim():n.replace(/</g,"&lt;").replace(/>/g,"&gt;").trim()}function Kb(e,t=Ys){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 qb(e){let t;return typeof e=="string"?t=e:typeof e=="object"&&e!==null?t=JSON.stringify(e):t=String(e),Kb(t),Vb(t)}function Xa(e){const t=e+"CollectionProvider",[n,r]=Hn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:y,children:m}=x,b=w.useRef(null),S=w.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:b,children:m})};i.displayName=t;const a=e+"CollectionSlot",l=hr.createSlot(a),c=w.forwardRef((x,y)=>{const{scope:m,children:b}=x,S=s(a,m),T=Ze(y,S.collectionRef);return u.jsx(l,{ref:T,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=hr.createSlot(d),p=w.forwardRef((x,y)=>{const{scope:m,children:b,...S}=x,T=w.useRef(null),k=Ze(y,T),C=s(d,m);return w.useEffect(()=>(C.itemMap.set(T,{ref:T,...S}),()=>void C.itemMap.delete(T))),u.jsx(h,{[f]:"",ref:k,children:b})});p.displayName=d;function g(x){const y=s(e+"CollectionConsumer",x);return w.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const S=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((C,E)=>S.indexOf(C.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},g,r]}var Gb=v.createContext(void 0);function Js(e){const t=v.useContext(Gb);return e||t||"ltr"}const Xb=["top","right","bottom","left"],nr=Math.min,un=Math.max,Zs=Math.round,Qs=Math.floor,On=e=>({x:e,y:e}),Yb={left:"right",right:"left",bottom:"top",top:"bottom"},Jb={start:"end",end:"start"};function Ya(e,t,n){return un(e,nr(t,n))}function Wn(e,t){return typeof e=="function"?e(t):e}function Vn(e){return e.split("-")[0]}function Kr(e){return e.split("-")[1]}function Ja(e){return e==="x"?"y":"x"}function Za(e){return e==="y"?"height":"width"}const Zb=new Set(["top","bottom"]);function Mn(e){return Zb.has(Vn(e))?"y":"x"}function Qa(e){return Ja(Mn(e))}function Qb(e,t,n){n===void 0&&(n=!1);const r=Kr(e),o=Qa(e),s=Za(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=ei(i)),[i,ei(i)]}function e0(e){const t=ei(e);return[el(e),t,el(t)]}function el(e){return e.replace(/start|end/g,t=>Jb[t])}const wf=["left","right"],bf=["right","left"],t0=["top","bottom"],n0=["bottom","top"];function r0(e,t,n){switch(e){case"top":case"bottom":return n?t?bf:wf:t?wf:bf;case"left":case"right":return t?t0:n0;default:return[]}}function o0(e,t,n,r){const o=Kr(e);let s=r0(Vn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(el)))),s}function ei(e){return e.replace(/left|right|bottom|top/g,t=>Yb[t])}function s0(e){return{top:0,right:0,bottom:0,left:0,...e}}function Sf(e){return typeof e!="number"?s0(e):{top:e,right:e,bottom:e,left:e}}function ti(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 Cf(e,t,n){let{reference:r,floating:o}=e;const s=Mn(t),i=Qa(t),a=Za(i),l=Vn(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(Kr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const i0=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}=Cf(c,r,l),h=r,p={},g=0;for(let x=0;x<a.length;x++){const{name:y,fn:m}=a[x],{x:b,y:S,data:T,reset:k}=await m({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=S??f,p={...p,[y]:{...p[y],...T}},k&&g<=50&&(g++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(c=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=Cf(c,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Ao(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}=Wn(t,e),g=Sf(p),y=a[h?f==="floating"?"reference":"floating":f],m=ti(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,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),T=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},k=ti(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:S,strategy:l}):b);return{top:(m.top-k.top+g.top)/T.y,bottom:(k.bottom-m.bottom+g.bottom)/T.y,left:(m.left-k.left+g.left)/T.x,right:(k.right-m.right+g.right)/T.x}}const a0=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}=Wn(e,t)||{};if(c==null)return{};const f=Sf(d),h={x:n,y:r},p=Qa(o),g=Za(p),x=await i.getDimensions(c),y=p==="y",m=y?"top":"left",b=y?"bottom":"right",S=y?"clientHeight":"clientWidth",T=s.reference[g]+s.reference[p]-h[p]-s.floating[g],k=h[p]-s.reference[p],C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=C?C[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(C)))&&(E=a.floating[S]||s.floating[g]);const R=T/2-k/2,_=E/2-x[g]/2-1,j=nr(f[m],_),L=nr(f[b],_),z=j,V=E-x[g]-L,O=E/2-x[g]/2+R,H=Ya(z,O,V),P=!l.arrow&&Kr(o)!=null&&O!==H&&s.reference[g]/2-(O<z?j:L)-x[g]/2<0,W=P?O<z?O-z:O-V:0;return{[p]:h[p]+W,data:{[p]:H,centerOffset:O-H-W,...P&&{alignmentOffset:W}},reset:P}}}),l0=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:g="none",flipAlignment:x=!0,...y}=Wn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const m=Vn(o),b=Mn(a),S=Vn(a)===a,T=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(S||!x?[ei(a)]:e0(a)),C=g!=="none";!h&&C&&k.push(...o0(a,x,g,T));const E=[a,...k],R=await Ao(t,y),_=[];let j=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(R[m]),f){const O=Qb(o,i,T);_.push(R[O[0]],R[O[1]])}if(j=[...j,{placement:o,overflows:_}],!_.every(O=>O<=0)){var L,z;const O=(((L=s.flip)==null?void 0:L.index)||0)+1,H=E[O];if(H&&(!(f==="alignment"?b!==Mn(H):!1)||j.every(F=>Mn(F.placement)===b?F.overflows[0]>0:!0)))return{data:{index:O,overflows:j},reset:{placement:H}};let P=(z=j.filter(W=>W.overflows[0]<=0).sort((W,F)=>W.overflows[1]-F.overflows[1])[0])==null?void 0:z.placement;if(!P)switch(p){case"bestFit":{var V;const W=(V=j.filter(F=>{if(C){const $=Mn(F.placement);return $===b||$==="y"}return!0}).map(F=>[F.placement,F.overflows.filter($=>$>0).reduce(($,ne)=>$+ne,0)]).sort((F,$)=>F[1]-$[1])[0])==null?void 0:V[0];W&&(P=W);break}case"initialPlacement":P=a;break}if(o!==P)return{reset:{placement:P}}}return{}}}};function kf(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Tf(e){return Xb.some(t=>e[t]>=0)}const c0=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Wn(e,t);switch(r){case"referenceHidden":{const s=await Ao(t,{...o,elementContext:"reference"}),i=kf(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Tf(i)}}}case"escaped":{const s=await Ao(t,{...o,altBoundary:!0}),i=kf(s,n.floating);return{data:{escapedOffsets:i,escaped:Tf(i)}}}default:return{}}}}},Ef=new Set(["left","top"]);async function u0(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Vn(n),a=Kr(n),l=Mn(n)==="y",c=Ef.has(i)?-1:1,d=s&&l?-1:1,f=Wn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(p=a==="end"?g*-1:g),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const d0=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 u0(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}}}}},f0=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:m,y:b}=y;return{x:m,y:b}}},...l}=Wn(e,t),c={x:n,y:r},d=await Ao(t,l),f=Mn(Vn(o)),h=Ja(f);let p=c[h],g=c[f];if(s){const y=h==="y"?"top":"left",m=h==="y"?"bottom":"right",b=p+d[y],S=p-d[m];p=Ya(b,p,S)}if(i){const y=f==="y"?"top":"left",m=f==="y"?"bottom":"right",b=g+d[y],S=g-d[m];g=Ya(b,g,S)}const x=a.fn({...t,[h]:p,[f]:g});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},h0=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}=Wn(e,t),d={x:n,y:r},f=Mn(o),h=Ja(f);let p=d[h],g=d[f];const x=Wn(a,t),y=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const S=h==="y"?"height":"width",T=s.reference[h]-s.floating[S]+y.mainAxis,k=s.reference[h]+s.reference[S]-y.mainAxis;p<T?p=T:p>k&&(p=k)}if(c){var m,b;const S=h==="y"?"width":"height",T=Ef.has(Vn(o)),k=s.reference[f]-s.floating[S]+(T&&((m=i.offset)==null?void 0:m[f])||0)+(T?0:y.crossAxis),C=s.reference[f]+s.reference[S]+(T?0:((b=i.offset)==null?void 0:b[f])||0)-(T?y.crossAxis:0);g<k?g=k:g>C&&(g=C)}return{[h]:p,[f]:g}}}},p0=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}=Wn(e,t),d=await Ao(t,c),f=Vn(o),h=Kr(o),p=Mn(o)==="y",{width:g,height:x}=s.floating;let y,m;f==="top"||f==="bottom"?(y=f,m=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(m=f,y=h==="end"?"top":"bottom");const b=x-d.top-d.bottom,S=g-d.left-d.right,T=nr(x-d[y],b),k=nr(g-d[m],S),C=!t.middlewareData.shift;let E=T,R=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=b),C&&!h){const j=un(d.left,0),L=un(d.right,0),z=un(d.top,0),V=un(d.bottom,0);p?R=g-2*(j!==0||L!==0?j+L:un(d.left,d.right)):E=x-2*(z!==0||V!==0?z+V:un(d.top,d.bottom))}await l({...t,availableWidth:R,availableHeight:E});const _=await i.getDimensions(a.floating);return g!==_.width||x!==_.height?{reset:{rects:!0}}:{}}}};function ni(){return typeof window<"u"}function qr(e){return If(e)?(e.nodeName||"").toLowerCase():"#document"}function dn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dn(e){var t;return(t=(If(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function If(e){return ni()?e instanceof Node||e instanceof dn(e).Node:!1}function En(e){return ni()?e instanceof Element||e instanceof dn(e).Element:!1}function Ln(e){return ni()?e instanceof HTMLElement||e instanceof dn(e).HTMLElement:!1}function Nf(e){return!ni()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof dn(e).ShadowRoot}const m0=new Set(["inline","contents"]);function _o(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=In(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!m0.has(o)}const g0=new Set(["table","td","th"]);function x0(e){return g0.has(qr(e))}const y0=[":popover-open",":modal"];function ri(e){return y0.some(t=>{try{return e.matches(t)}catch{return!1}})}const v0=["transform","translate","scale","rotate","perspective"],w0=["transform","translate","scale","rotate","perspective","filter"],b0=["paint","layout","strict","content"];function tl(e){const t=nl(),n=En(e)?In(e):e;return v0.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)||w0.some(r=>(n.willChange||"").includes(r))||b0.some(r=>(n.contain||"").includes(r))}function S0(e){let t=rr(e);for(;Ln(t)&&!Gr(t);){if(tl(t))return t;if(ri(t))return null;t=rr(t)}return null}function nl(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const C0=new Set(["html","body","#document"]);function Gr(e){return C0.has(qr(e))}function In(e){return dn(e).getComputedStyle(e)}function oi(e){return En(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function rr(e){if(qr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Nf(e)&&e.host||Dn(e);return Nf(t)?t.host:t}function Af(e){const t=rr(e);return Gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ln(t)&&_o(t)?t:Af(t)}function jo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Af(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=dn(o);if(s){const a=rl(i);return t.concat(i,i.visualViewport||[],_o(o)?o:[],a&&n?jo(a):[])}return t.concat(o,jo(o,[],n))}function rl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _f(e){const t=In(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ln(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Zs(n)!==s||Zs(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ol(e){return En(e)?e:e.contextElement}function Xr(e){const t=ol(e);if(!Ln(t))return On(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=_f(t);let i=(s?Zs(n.width):n.width)/r,a=(s?Zs(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const k0=On(0);function jf(e){const t=dn(e);return!nl()||!t.visualViewport?k0:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function T0(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==dn(e)?!1:t}function Tr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ol(e);let i=On(1);t&&(r?En(r)&&(i=Xr(r)):i=Xr(e));const a=T0(s,n,r)?jf(s):On(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=dn(s),p=r&&En(r)?dn(r):r;let g=h,x=rl(g);for(;x&&r&&p!==g;){const y=Xr(x),m=x.getBoundingClientRect(),b=In(x),S=m.left+(x.clientLeft+parseFloat(b.paddingLeft))*y.x,T=m.top+(x.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=T,g=dn(x),x=rl(g)}}return ti({width:d,height:f,x:l,y:c})}function si(e,t){const n=oi(e).scrollLeft;return t?t.left+n:Tr(Dn(e)).left+n}function Rf(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-si(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function E0(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Dn(r),a=t?ri(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=On(1);const d=On(0),f=Ln(r);if((f||!f&&!s)&&((qr(r)!=="body"||_o(i))&&(l=oi(r)),Ln(r))){const p=Tr(r);c=Xr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Rf(i,l):On(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 I0(e){return Array.from(e.getClientRects())}function N0(e){const t=Dn(e),n=oi(e),r=e.ownerDocument.body,o=un(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=un(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+si(e);const a=-n.scrollTop;return In(r).direction==="rtl"&&(i+=un(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Pf=25;function A0(e,t){const n=dn(e),r=Dn(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=nl();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=si(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,g=Math.abs(r.clientWidth-f.clientWidth-p);g<=Pf&&(s-=g)}else c<=Pf&&(s+=c);return{width:s,height:i,x:a,y:l}}const _0=new Set(["absolute","fixed"]);function j0(e,t){const n=Tr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Ln(e)?Xr(e):On(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 Of(e,t,n){let r;if(t==="viewport")r=A0(e,n);else if(t==="document")r=N0(Dn(e));else if(En(t))r=j0(t,n);else{const o=jf(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ti(r)}function Mf(e,t){const n=rr(e);return n===t||!En(n)||Gr(n)?!1:In(n).position==="fixed"||Mf(n,t)}function R0(e,t){const n=t.get(e);if(n)return n;let r=jo(e,[],!1).filter(a=>En(a)&&qr(a)!=="body"),o=null;const s=In(e).position==="fixed";let i=s?rr(e):e;for(;En(i)&&!Gr(i);){const a=In(i),l=tl(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&_0.has(o.position)||_o(i)&&!l&&Mf(e,i))?r=r.filter(d=>d!==i):o=a,i=rr(i)}return t.set(e,r),r}function P0(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?ri(t)?[]:R0(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Of(t,d,o);return c.top=un(f.top,c.top),c.right=nr(f.right,c.right),c.bottom=nr(f.bottom,c.bottom),c.left=un(f.left,c.left),c},Of(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function O0(e){const{width:t,height:n}=_f(e);return{width:t,height:n}}function M0(e,t,n){const r=Ln(t),o=Dn(t),s=n==="fixed",i=Tr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=On(0);function c(){l.x=si(o)}if(r||!r&&!s)if((qr(t)!=="body"||_o(o))&&(a=oi(t)),r){const p=Tr(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?Rf(o,a):On(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 sl(e){return In(e).position==="static"}function Df(e,t){if(!Ln(e)||In(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dn(e)===n&&(n=n.ownerDocument.body),n}function Lf(e,t){const n=dn(e);if(ri(e))return n;if(!Ln(e)){let o=rr(e);for(;o&&!Gr(o);){if(En(o)&&!sl(o))return o;o=rr(o)}return n}let r=Df(e,t);for(;r&&x0(r)&&sl(r);)r=Df(r,t);return r&&Gr(r)&&sl(r)&&!tl(r)?n:r||S0(e)||n}const D0=async function(e){const t=this.getOffsetParent||Lf,n=this.getDimensions,r=await n(e.floating);return{reference:M0(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function L0(e){return In(e).direction==="rtl"}const $0={convertOffsetParentRelativeRectToViewportRelativeRect:E0,getDocumentElement:Dn,getClippingRect:P0,getOffsetParent:Lf,getElementRects:D0,getClientRects:I0,getDimensions:O0,getScale:Xr,isElement:En,isRTL:L0};function $f(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function F0(e,t){let n=null,r;const o=Dn(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 g=Qs(f),x=Qs(o.clientWidth-(d+h)),y=Qs(o.clientHeight-(f+p)),m=Qs(d),S={rootMargin:-g+"px "+-x+"px "+-y+"px "+-m+"px",threshold:un(0,nr(1,l))||1};let T=!0;function k(C){const E=C[0].intersectionRatio;if(E!==l){if(!T)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!$f(c,e.getBoundingClientRect())&&i(),T=!1}try{n=new IntersectionObserver(k,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,S)}n.observe(e)}return i(!0),s}function z0(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=ol(e),d=o||s?[...c?jo(c):[],...jo(t)]:[];d.forEach(m=>{o&&m.addEventListener("scroll",n,{passive:!0}),s&&m.addEventListener("resize",n)});const f=c&&a?F0(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(m=>{let[b]=m;b&&b.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 g,x=l?Tr(e):null;l&&y();function y(){const m=Tr(e);x&&!$f(x,m)&&n(),x=m,g=requestAnimationFrame(y)}return n(),()=>{var m;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(m=p)==null||m.disconnect(),p=null,l&&cancelAnimationFrame(g)}}const B0=d0,H0=f0,U0=l0,W0=p0,V0=c0,Ff=a0,K0=h0,q0=(e,t,n)=>{const r=new Map,o={platform:$0,...n},s={...o.platform,_c:r};return i0(e,t,{...o,platform:s})};var G0=typeof document<"u",X0=function(){},ii=G0?w.useLayoutEffect:X0;function ai(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(!ai(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)&&!ai(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function zf(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Bf(e,t){const n=zf(e);return Math.round(t*n)/n}function il(e){const t=v.useRef(e);return ii(()=>{t.current=e}),t}function Y0(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);ai(h,r)||p(r);const[g,x]=v.useState(null),[y,m]=v.useState(null),b=v.useCallback(F=>{F!==C.current&&(C.current=F,x(F))},[]),S=v.useCallback(F=>{F!==E.current&&(E.current=F,m(F))},[]),T=s||g,k=i||y,C=v.useRef(null),E=v.useRef(null),R=v.useRef(d),_=l!=null,j=il(l),L=il(o),z=il(c),V=v.useCallback(()=>{if(!C.current||!E.current)return;const F={placement:t,strategy:n,middleware:h};L.current&&(F.platform=L.current),q0(C.current,E.current,F).then($=>{const ne={...$,isPositioned:z.current!==!1};O.current&&!ai(R.current,ne)&&(R.current=ne,Wo.flushSync(()=>{f(ne)}))})},[h,t,n,L,z]);ii(()=>{c===!1&&R.current.isPositioned&&(R.current.isPositioned=!1,f(F=>({...F,isPositioned:!1})))},[c]);const O=v.useRef(!1);ii(()=>(O.current=!0,()=>{O.current=!1}),[]),ii(()=>{if(T&&(C.current=T),k&&(E.current=k),T&&k){if(j.current)return j.current(T,k,V);V()}},[T,k,V,j,_]);const H=v.useMemo(()=>({reference:C,floating:E,setReference:b,setFloating:S}),[b,S]),P=v.useMemo(()=>({reference:T,floating:k}),[T,k]),W=v.useMemo(()=>{const F={position:n,left:0,top:0};if(!P.floating)return F;const $=Bf(P.floating,d.x),ne=Bf(P.floating,d.y);return a?{...F,transform:"translate("+$+"px, "+ne+"px)",...zf(P.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:$,top:ne}},[n,a,P.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:H,elements:P,floatingStyles:W}),[d,V,H,P,W])}const J0=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?Ff({element:r.current,padding:o}).fn(n):{}:r?Ff({element:r,padding:o}).fn(n):{}}}},Z0=(e,t)=>({...B0(e),options:[e,t]}),Q0=(e,t)=>({...H0(e),options:[e,t]}),eS=(e,t)=>({...K0(e),options:[e,t]}),tS=(e,t)=>({...U0(e),options:[e,t]}),nS=(e,t)=>({...W0(e),options:[e,t]}),rS=(e,t)=>({...V0(e),options:[e,t]}),oS=(e,t)=>({...J0(e),options:[e,t]});var sS="Arrow",Hf=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(De.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"})})});Hf.displayName=sS;var iS=Hf;function Uf(e){const[t,n]=v.useState(void 0);return Ut(()=>{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 al="Popper",[Wf,li]=Hn(al),[aS,Vf]=Wf(al),Kf=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(aS,{scope:t,anchor:r,onAnchorChange:o,children:n})};Kf.displayName=al;var qf="PopperAnchor",Gf=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Vf(qf,n),i=v.useRef(null),a=Ze(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(De.div,{...o,ref:a})});Gf.displayName=qf;var ll="PopperContent",[lS,cS]=Wf(ll),Xf=v.forwardRef((e,t)=>{var ee,D,X,ae,fe,B;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:g,...x}=e,y=Vf(ll,n),[m,b]=v.useState(null),S=Ze(t,le=>b(le)),[T,k]=v.useState(null),C=Uf(T),E=(C==null?void 0:C.width)??0,R=(C==null?void 0:C.height)??0,_=r+(s!=="center"?"-"+s:""),j=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},L=Array.isArray(c)?c:[c],z=L.length>0,V={padding:j,boundary:L.filter(dS),altBoundary:z},{refs:O,floatingStyles:H,placement:P,isPositioned:W,middlewareData:F}=Y0({strategy:"fixed",placement:_,whileElementsMounted:(...le)=>z0(...le,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Z0({mainAxis:o+R,alignmentAxis:i}),l&&Q0({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?eS():void 0,...V}),l&&tS({...V}),nS({...V,apply:({elements:le,rects:Q,availableWidth:Ae,availableHeight:ve})=>{const{width:Re,height:Ve}=Q.reference,Qe=le.floating.style;Qe.setProperty("--radix-popper-available-width",`${Ae}px`),Qe.setProperty("--radix-popper-available-height",`${ve}px`),Qe.setProperty("--radix-popper-anchor-width",`${Re}px`),Qe.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),T&&oS({element:T,padding:a}),fS({arrowWidth:E,arrowHeight:R}),h&&rS({strategy:"referenceHidden",...V})]}),[$,ne]=Zf(P),oe=Wt(g);Ut(()=>{W&&(oe==null||oe())},[W,oe]);const we=(ee=F.arrow)==null?void 0:ee.x,Ne=(D=F.arrow)==null?void 0:D.y,Z=((X=F.arrow)==null?void 0:X.centerOffset)!==0,[ie,Te]=v.useState();return Ut(()=>{m&&Te(window.getComputedStyle(m).zIndex)},[m]),u.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:W?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ie,"--radix-popper-transform-origin":[(ae=F.transformOrigin)==null?void 0:ae.x,(fe=F.transformOrigin)==null?void 0:fe.y].join(" "),...((B=F.hide)==null?void 0:B.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(lS,{scope:n,placedSide:$,onArrowChange:k,arrowX:we,arrowY:Ne,shouldHideArrow:Z,children:u.jsx(De.div,{"data-side":$,"data-align":ne,...x,ref:S,style:{...x.style,animation:W?void 0:"none"}})})})});Xf.displayName=ll;var Yf="PopperArrow",uS={top:"bottom",right:"left",bottom:"top",left:"right"},Jf=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=cS(Yf,r),i=uS[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(iS,{...o,ref:n,style:{...o.style,display:"block"}})})});Jf.displayName=Yf;function dS(e){return e!==null}var fS=e=>({name:"transformOrigin",options:e,fn(t){var y,m,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]=Zf(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((m=o.arrow)==null?void 0:m.x)??0)+a/2,p=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let g="",x="";return c==="bottom"?(g=i?f:`${h}px`,x=`${-l}px`):c==="top"?(g=i?f:`${h}px`,x=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,x=i?f:`${p}px`):c==="left"&&(g=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:g,y:x}}}});function Zf(e){const[t,n="center"]=e.split("-");return[t,n]}var Qf=Kf,eh=Gf,th=Xf,nh=Jf,cl="rovingFocusGroup.onEntryFocus",hS={bubbles:!1,cancelable:!0},Ro="RovingFocusGroup",[ul,rh,pS]=Xa(Ro),[mS,oh]=Hn(Ro,[pS]),[gS,xS]=mS(Ro),sh=v.forwardRef((e,t)=>u.jsx(ul.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(ul.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(yS,{...e,ref:t})})}));sh.displayName=Ro;var yS=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=Ze(t,h),g=Js(s),[x,y]=Br({prop:i,defaultProp:a??null,onChange:l,caller:Ro}),[m,b]=v.useState(!1),S=Wt(c),T=rh(n),k=v.useRef(!1),[C,E]=v.useState(0);return v.useEffect(()=>{const R=h.current;if(R)return R.addEventListener(cl,S),()=>R.removeEventListener(cl,S)},[S]),u.jsx(gS,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:x,onItemFocus:v.useCallback(R=>y(R),[y]),onItemShiftTab:v.useCallback(()=>b(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(R=>R+1),[]),onFocusableItemRemove:v.useCallback(()=>E(R=>R-1),[]),children:u.jsx(De.div,{tabIndex:m||C===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:ye(e.onMouseDown,()=>{k.current=!0}),onFocus:ye(e.onFocus,R=>{const _=!k.current;if(R.target===R.currentTarget&&_&&!m){const j=new CustomEvent(cl,hS);if(R.currentTarget.dispatchEvent(j),!j.defaultPrevented){const L=T().filter(P=>P.focusable),z=L.find(P=>P.active),V=L.find(P=>P.id===x),H=[z,V,...L].filter(Boolean).map(P=>P.ref.current);lh(H,d)}}k.current=!1}),onBlur:ye(e.onBlur,()=>b(!1))})})}),ih="RovingFocusGroupItem",ah=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=Un(),c=s||l,d=xS(ih,n),f=d.currentTabStopId===c,h=rh(n),{onFocusableItemAdd:p,onFocusableItemRemove:g,currentTabStopId:x}=d;return v.useEffect(()=>{if(r)return p(),()=>g()},[r,p,g]),u.jsx(ul.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(De.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:ye(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:ye(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ye(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const m=bS(y,d.orientation,d.dir);if(m!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=h().filter(T=>T.focusable).map(T=>T.ref.current);if(m==="last")S.reverse();else if(m==="prev"||m==="next"){m==="prev"&&S.reverse();const T=S.indexOf(y.currentTarget);S=d.loop?SS(S,T+1):S.slice(T+1)}setTimeout(()=>lh(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});ah.displayName=ih;var vS={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function wS(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function bS(e,t,n){const r=wS(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return vS[r]}function lh(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function SS(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var CS=sh,kS=ah,dl=["Enter"," "],TS=["ArrowDown","PageUp","Home"],ch=["ArrowUp","PageDown","End"],ES=[...TS,...ch],IS={ltr:[...dl,"ArrowRight"],rtl:[...dl,"ArrowLeft"]},NS={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Po="Menu",[Oo,AS,_S]=Xa(Po),[Er,uh]=Hn(Po,[_S,li,oh]),ci=li(),dh=oh(),[jS,Ir]=Er(Po),[RS,Mo]=Er(Po),fh=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:s,modal:i=!0}=e,a=ci(t),[l,c]=v.useState(null),d=v.useRef(!1),f=Wt(s),h=Js(o);return v.useEffect(()=>{const p=()=>{d.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>d.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),u.jsx(Qf,{...a,children:u.jsx(jS,{scope:t,open:n,onOpenChange:f,content:l,onContentChange:c,children:u.jsx(RS,{scope:t,onClose:v.useCallback(()=>f(!1),[f]),isUsingKeyboardRef:d,dir:h,modal:i,children:r})})})};fh.displayName=Po;var PS="MenuAnchor",fl=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ci(n);return u.jsx(eh,{...o,...r,ref:t})});fl.displayName=PS;var hl="MenuPortal",[OS,hh]=Er(hl,{forceMount:void 0}),ph=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Ir(hl,t);return u.jsx(OS,{scope:t,forceMount:n,children:u.jsx(gn,{present:n||s.open,children:u.jsx(_s,{asChild:!0,container:o,children:r})})})};ph.displayName=hl;var xn="MenuContent",[MS,pl]=Er(xn),mh=v.forwardRef((e,t)=>{const n=hh(xn,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Ir(xn,e.__scopeMenu),i=Mo(xn,e.__scopeMenu);return u.jsx(Oo.Provider,{scope:e.__scopeMenu,children:u.jsx(gn,{present:r||s.open,children:u.jsx(Oo.Slot,{scope:e.__scopeMenu,children:i.modal?u.jsx(DS,{...o,ref:t}):u.jsx(LS,{...o,ref:t})})})})}),DS=v.forwardRef((e,t)=>{const n=Ir(xn,e.__scopeMenu),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return Ba(s)},[]),u.jsx(ml,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ye(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),LS=v.forwardRef((e,t)=>{const n=Ir(xn,e.__scopeMenu);return u.jsx(ml,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),$S=hr.createSlot("MenuContent.ScrollLock"),ml=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:g,...x}=e,y=Ir(xn,n),m=Mo(xn,n),b=ci(n),S=dh(n),T=AS(n),[k,C]=v.useState(null),E=v.useRef(null),R=Ze(t,E,y.onContentChange),_=v.useRef(0),j=v.useRef(""),L=v.useRef(0),z=v.useRef(null),V=v.useRef("right"),O=v.useRef(0),H=g?Ls:v.Fragment,P=g?{as:$S,allowPinchZoom:!0}:void 0,W=$=>{var ee,D;const ne=j.current+$,oe=T().filter(X=>!X.disabled),we=document.activeElement,Ne=(ee=oe.find(X=>X.ref.current===we))==null?void 0:ee.textValue,Z=oe.map(X=>X.textValue),ie=YS(Z,ne,Ne),Te=(D=oe.find(X=>X.textValue===ie))==null?void 0:D.ref.current;(function X(ae){j.current=ae,window.clearTimeout(_.current),ae!==""&&(_.current=window.setTimeout(()=>X(""),1e3))})(ne),Te&&setTimeout(()=>Te.focus())};v.useEffect(()=>()=>window.clearTimeout(_.current),[]),Ma();const F=v.useCallback($=>{var oe,we;return V.current===((oe=z.current)==null?void 0:oe.side)&&ZS($,(we=z.current)==null?void 0:we.area)},[]);return u.jsx(MS,{scope:n,searchRef:j,onItemEnter:v.useCallback($=>{F($)&&$.preventDefault()},[F]),onItemLeave:v.useCallback($=>{var ne;F($)||((ne=E.current)==null||ne.focus(),C(null))},[F]),onTriggerLeave:v.useCallback($=>{F($)&&$.preventDefault()},[F]),pointerGraceTimerRef:L,onPointerGraceIntentChange:v.useCallback($=>{z.current=$},[]),children:u.jsx(H,{...P,children:u.jsx(As,{asChild:!0,trapped:o,onMountAutoFocus:ye(s,$=>{var ne;$.preventDefault(),(ne=E.current)==null||ne.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:u.jsx(Ns,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:f,onInteractOutside:h,onDismiss:p,children:u.jsx(CS,{asChild:!0,...S,dir:m.dir,orientation:"vertical",loop:r,currentTabStopId:k,onCurrentTabStopIdChange:C,onEntryFocus:ye(l,$=>{m.isUsingKeyboardRef.current||$.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(th,{role:"menu","aria-orientation":"vertical","data-state":Rh(y.open),"data-radix-menu-content":"",dir:m.dir,...b,...x,ref:R,style:{outline:"none",...x.style},onKeyDown:ye(x.onKeyDown,$=>{const oe=$.target.closest("[data-radix-menu-content]")===$.currentTarget,we=$.ctrlKey||$.altKey||$.metaKey,Ne=$.key.length===1;oe&&($.key==="Tab"&&$.preventDefault(),!we&&Ne&&W($.key));const Z=E.current;if($.target!==Z||!ES.includes($.key))return;$.preventDefault();const Te=T().filter(ee=>!ee.disabled).map(ee=>ee.ref.current);ch.includes($.key)&&Te.reverse(),GS(Te)}),onBlur:ye(e.onBlur,$=>{$.currentTarget.contains($.target)||(window.clearTimeout(_.current),j.current="")}),onPointerMove:ye(e.onPointerMove,Lo($=>{const ne=$.target,oe=O.current!==$.clientX;if($.currentTarget.contains(ne)&&oe){const we=$.clientX>O.current?"right":"left";V.current=we,O.current=$.clientX}}))})})})})})})});mh.displayName=xn;var FS="MenuGroup",gl=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(De.div,{role:"group",...r,ref:t})});gl.displayName=FS;var zS="MenuLabel",gh=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(De.div,{...r,ref:t})});gh.displayName=zS;var ui="MenuItem",xh="menu.itemSelect",di=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=v.useRef(null),i=Mo(ui,e.__scopeMenu),a=pl(ui,e.__scopeMenu),l=Ze(t,s),c=v.useRef(!1),d=()=>{const f=s.current;if(!n&&f){const h=new CustomEvent(xh,{bubbles:!0,cancelable:!0});f.addEventListener(xh,p=>r==null?void 0:r(p),{once:!0}),cd(f,h),h.defaultPrevented?c.current=!1:i.onClose()}};return u.jsx(yh,{...o,ref:l,disabled:n,onClick:ye(e.onClick,d),onPointerDown:f=>{var h;(h=e.onPointerDown)==null||h.call(e,f),c.current=!0},onPointerUp:ye(e.onPointerUp,f=>{var h;c.current||(h=f.currentTarget)==null||h.click()}),onKeyDown:ye(e.onKeyDown,f=>{const h=a.searchRef.current!=="";n||h&&f.key===" "||dl.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})});di.displayName=ui;var yh=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=pl(ui,n),a=dh(n),l=v.useRef(null),c=Ze(t,l),[d,f]=v.useState(!1),[h,p]=v.useState("");return v.useEffect(()=>{const g=l.current;g&&p((g.textContent??"").trim())},[s.children]),u.jsx(Oo.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:u.jsx(kS,{asChild:!0,...a,focusable:!r,children:u.jsx(De.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:ye(e.onPointerMove,Lo(g=>{r?i.onItemLeave(g):(i.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ye(e.onPointerLeave,Lo(g=>i.onItemLeave(g))),onFocus:ye(e.onFocus,()=>f(!0)),onBlur:ye(e.onBlur,()=>f(!1))})})})}),BS="MenuCheckboxItem",vh=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return u.jsx(kh,{scope:e.__scopeMenu,checked:n,children:u.jsx(di,{role:"menuitemcheckbox","aria-checked":fi(n)?"mixed":n,...o,ref:t,"data-state":yl(n),onSelect:ye(o.onSelect,()=>r==null?void 0:r(fi(n)?!0:!n),{checkForDefaultPrevented:!1})})})});vh.displayName=BS;var wh="MenuRadioGroup",[HS,US]=Er(wh,{value:void 0,onValueChange:()=>{}}),bh=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=Wt(r);return u.jsx(HS,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(gl,{...o,ref:t})})});bh.displayName=wh;var Sh="MenuRadioItem",Ch=v.forwardRef((e,t)=>{const{value:n,...r}=e,o=US(Sh,e.__scopeMenu),s=n===o.value;return u.jsx(kh,{scope:e.__scopeMenu,checked:s,children:u.jsx(di,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":yl(s),onSelect:ye(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});Ch.displayName=Sh;var xl="MenuItemIndicator",[kh,WS]=Er(xl,{checked:!1}),Th=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=WS(xl,n);return u.jsx(gn,{present:r||fi(s.checked)||s.checked===!0,children:u.jsx(De.span,{...o,ref:t,"data-state":yl(s.checked)})})});Th.displayName=xl;var VS="MenuSeparator",Eh=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(De.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Eh.displayName=VS;var KS="MenuArrow",Ih=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ci(n);return u.jsx(nh,{...o,...r,ref:t})});Ih.displayName=KS;var qS="MenuSub",[jT,Nh]=Er(qS),Do="MenuSubTrigger",Ah=v.forwardRef((e,t)=>{const n=Ir(Do,e.__scopeMenu),r=Mo(Do,e.__scopeMenu),o=Nh(Do,e.__scopeMenu),s=pl(Do,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(fl,{asChild:!0,...c,children:u.jsx(yh,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Rh(n.open),...e,ref:_a(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:ye(e.onPointerMove,Lo(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:ye(e.onPointerLeave,Lo(f=>{var p,g;d();const h=(p=n.content)==null?void 0:p.getBoundingClientRect();if(h){const x=(g=n.content)==null?void 0:g.dataset.side,y=x==="right",m=y?-5:5,b=h[y?"left":"right"],S=h[y?"right":"left"];s.onPointerGraceIntentChange({area:[{x:f.clientX+m,y:f.clientY},{x:b,y:h.top},{x:S,y:h.top},{x:S,y:h.bottom},{x:b,y:h.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(f),f.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:ye(e.onKeyDown,f=>{var p;const h=s.searchRef.current!=="";e.disabled||h&&f.key===" "||IS[r.dir].includes(f.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),f.preventDefault())})})})});Ah.displayName=Do;var _h="MenuSubContent",jh=v.forwardRef((e,t)=>{const n=hh(xn,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Ir(xn,e.__scopeMenu),i=Mo(xn,e.__scopeMenu),a=Nh(_h,e.__scopeMenu),l=v.useRef(null),c=Ze(t,l);return u.jsx(Oo.Provider,{scope:e.__scopeMenu,children:u.jsx(gn,{present:r||s.open,children:u.jsx(Oo.Slot,{scope:e.__scopeMenu,children:u.jsx(ml,{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:ye(e.onFocusOutside,d=>{d.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:ye(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:ye(e.onKeyDown,d=>{var p;const f=d.currentTarget.contains(d.target),h=NS[i.dir].includes(d.key);f&&h&&(s.onOpenChange(!1),(p=a.trigger)==null||p.focus(),d.preventDefault())})})})})})});jh.displayName=_h;function Rh(e){return e?"open":"closed"}function fi(e){return e==="indeterminate"}function yl(e){return fi(e)?"indeterminate":e?"checked":"unchecked"}function GS(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function XS(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function YS(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=XS(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 JS(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 ZS(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return JS(n,t)}function Lo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var QS=fh,eC=fl,tC=ph,nC=mh,rC=gl,oC=gh,sC=di,iC=vh,aC=bh,lC=Ch,cC=Th,uC=Eh,dC=Ih,fC=Ah,hC=jh,hi="DropdownMenu",[pC,RT]=Hn(hi,[uh]),tn=uh(),[mC,Ph]=pC(hi),Oh=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:s,onOpenChange:i,modal:a=!0}=e,l=tn(t),c=v.useRef(null),[d,f]=Br({prop:o,defaultProp:s??!1,onChange:i,caller:hi});return u.jsx(mC,{scope:t,triggerId:Un(),triggerRef:c,contentId:Un(),open:d,onOpenChange:f,onOpenToggle:v.useCallback(()=>f(h=>!h),[f]),modal:a,children:u.jsx(QS,{...l,open:d,onOpenChange:f,dir:r,modal:a,children:n})})};Oh.displayName=hi;var Mh="DropdownMenuTrigger",Dh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=Ph(Mh,n),i=tn(n);return u.jsx(eC,{asChild:!0,...i,children:u.jsx(De.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:_a(t,s.triggerRef),onPointerDown:ye(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(s.onOpenToggle(),s.open||a.preventDefault())}),onKeyDown:ye(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&s.onOpenToggle(),a.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Dh.displayName=Mh;var gC="DropdownMenuPortal",Lh=e=>{const{__scopeDropdownMenu:t,...n}=e,r=tn(t);return u.jsx(tC,{...r,...n})};Lh.displayName=gC;var $h="DropdownMenuContent",Fh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ph($h,n),s=tn(n),i=v.useRef(!1);return u.jsx(nC,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:ye(e.onCloseAutoFocus,a=>{var l;i.current||(l=o.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:ye(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)"}})});Fh.displayName=$h;var xC="DropdownMenuGroup",yC=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(rC,{...o,...r,ref:t})});yC.displayName=xC;var vC="DropdownMenuLabel",zh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(oC,{...o,...r,ref:t})});zh.displayName=vC;var wC="DropdownMenuItem",Bh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(sC,{...o,...r,ref:t})});Bh.displayName=wC;var bC="DropdownMenuCheckboxItem",Hh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(iC,{...o,...r,ref:t})});Hh.displayName=bC;var SC="DropdownMenuRadioGroup",CC=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(aC,{...o,...r,ref:t})});CC.displayName=SC;var kC="DropdownMenuRadioItem",Uh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(lC,{...o,...r,ref:t})});Uh.displayName=kC;var TC="DropdownMenuItemIndicator",Wh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(cC,{...o,...r,ref:t})});Wh.displayName=TC;var EC="DropdownMenuSeparator",Vh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(uC,{...o,...r,ref:t})});Vh.displayName=EC;var IC="DropdownMenuArrow",NC=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(dC,{...o,...r,ref:t})});NC.displayName=IC;var AC="DropdownMenuSubTrigger",Kh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(fC,{...o,...r,ref:t})});Kh.displayName=AC;var _C="DropdownMenuSubContent",qh=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=tn(n);return u.jsx(hC,{...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)"}})});qh.displayName=_C;var jC=Oh,RC=Dh,PC=Lh,Gh=Fh,Xh=zh,Yh=Bh,Jh=Hh,Zh=Uh,Qh=Wh,ep=Vh,tp=Kh,np=qh;const OC=jC,MC=RC,DC=v.forwardRef(({className:e,inset:t,children:n,...r},o)=>u.jsxs(tp,{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(pe.ChevronRight,{className:"ml-auto h-4 w-4"})]}));DC.displayName=tp.displayName;const LC=v.forwardRef(({className:e,...t},n)=>u.jsx(np,{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}));LC.displayName=np.displayName;const rp=v.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(PC,{children:u.jsx(Gh,{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})}));rp.displayName=Gh.displayName;const vl=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(Yh,{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}));vl.displayName=Yh.displayName;const $C=v.forwardRef(({className:e,children:t,checked:n,...r},o)=>u.jsxs(Jh,{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(Qh,{children:u.jsx(pe.Check,{className:"h-4 w-4"})})}),t]}));$C.displayName=Jh.displayName;const FC=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Zh,{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(Qh,{children:u.jsx(pe.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));FC.displayName=Zh.displayName;const zC=v.forwardRef(({className:e,inset:t,...n},r)=>u.jsx(Xh,{ref:r,className:se("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));zC.displayName=Xh.displayName;const BC=v.forwardRef(({className:e,...t},n)=>u.jsx(ep,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));BC.displayName=ep.displayName;const op={value:""};function pi({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,customStyles:f={},onMessageSent:h,onExcelUploadSuccess:p,onError:g}){const{api:x}=Bi(),{currentThreadId:y}=cs(),{threadId:m,messages:b,hasMore:S,isHistoryLoading:T,isLoading:k,loadOlder:C,navigateToCheckpoint:E,returnToLatest:R,checkpoint:_,checkpoints:j,interrupt:L,metadata:z}=us(),{isStreaming:V,error:O,connectionState:H,submit:P,stop:W}=tu(),F=m??y??null,$=(_==null?void 0:_.id)??null,ne=(_==null?void 0:_.namespace)??null,oe=(z==null?void 0:z.assemblingMessageId)??null,we=L,[Ne,Z]=w.useState(!1);w.useEffect(()=>{we||Z(!1)},[we]);const ie=w.useCallback(()=>{Z(!0)},[]),Te=w.useCallback(()=>{Z(!1)},[]),ee=!!we||Ne,[D,X]=w.useState(null),[ae,fe]=w.useState(""),[B,le]=w.useState(null),[Q,Ae]=w.useState(null),[ve,Re]=w.useState([]),[Ve,Qe]=w.useState(0),[et,Se]=w.useState(0),[nt,ut]=w.useState(!1),[rt,Ye]=w.useState(null),[It,dt]=w.useState(null),[kt,Nt]=w.useState(!1),[tt,He]=w.useState(null),[Tt,Vt]=w.useState(!1),zt=w.useRef(!1),[Kt,st]=w.useState(()=>op.value),Le=w.useRef(Kt),_t=w.useRef(null),yt=w.useCallback(J=>{op.value=J,st(J)},[]),[G,Ce]=w.useState(!1),ge=w.useCallback((J,de)=>{if(!J||typeof J!="object")return null;const he=J[de];return typeof he=="number"?he:null},[]),xt=w.useCallback((J,de)=>{if(!J||typeof J!="object")return null;const he=J[de];return typeof he=="string"&&he.trim()?he:null},[]),ft=w.useMemo(()=>{const J=Array.isArray(j)?[...j]:[];return J.some(he=>ge(he.metadata,"step")!==null)&&J.sort((he,wt)=>{const Ot=ge(he.metadata,"step"),an=ge(wt.metadata,"step");if(Ot!==null||an!==null)return(an??Number.NEGATIVE_INFINITY)-(Ot??Number.NEGATIVE_INFINITY);const qn=Date.parse(he.createdAt??""),cr=Date.parse(wt.createdAt??"");return Number.isNaN(qn)||Number.isNaN(cr)?0:cr-qn}),J},[j,ge]),{checkpointMetaById:ht,checkpointIndexByKey:Be}=w.useMemo(()=>{const J=new Map,de=new Map;for(const he of ft){const wt=he.checkpointId??null;if(!wt)continue;const Ot=ge(he.metadata,"step"),an=xt(he.metadata,"source"),qn={id:wt,step:Ot,source:an,createdAt:he.createdAt??null,namespace:he.checkpointNs??null,parentId:he.parentId??null};if(J.set(wt,qn),Ot!==null&&an){const cr=`${Ot}:${an}`,Fo=de.get(cr)??[];Fo.push(qn),de.set(cr,Fo)}}for(const he of de.values())he.sort((wt,Ot)=>{const an=wt.createdAt??"";return(Ot.createdAt??"").localeCompare(an)});return{checkpointMetaById:J,checkpointIndexByKey:de}},[ft,ge,xt]),Ft=w.useRef(null),Oe=w.useRef(null),it=w.useCallback(()=>{Ft.current&&(Ft.current.value=""),Oe.current&&(Oe.current.value=""),Qe(J=>J+1),Se(J=>J+1)},[]),ar=w.useCallback(J=>{yt(J)},[yt]),jr=w.useRef(!1);w.useEffect(()=>{jr.current&&!V&&(Re([]),it()),jr.current=V},[V,it]);const[lr,Rr]=w.useState("desktop");w.useEffect(()=>{const J=()=>{const de=window.innerWidth;Rr(de<640?"phone":de<1024?"tablet":"desktop")};return J(),window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),w.useEffect(()=>{Vt(!1),zt.current=!1},[F]),w.useEffect(()=>{Le.current=Kt},[Kt]),w.useEffect(()=>{if(!D){_t.current=null;return}_t.current===null&&(_t.current=Le.current),yt(ae??"")},[ae,D,yt]);const Pr=w.useCallback(async()=>{if(!(!S||T||!Tt))try{await C()}catch(J){console.warn("loadOlder failed",J)}},[S,Tt,T,C]);w.useEffect(()=>{(async()=>{if(!x.baseUrl){He(null);return}try{const he=(await x.getAgent("default")).uiDefaultMessage||"";He(he||null)}catch(de){console.warn("Failed to fetch default message:",de),He(null)}})()},[x.baseUrl]),w.useEffect(()=>{O&&!kt&&(g==null||g(O))},[O,kt,g]);const Kn=J=>{if(J.length>Ys)return`Message too long (${J.length}/${Ys} characters)`;try{return qb(J),null}catch(de){return(de==null?void 0:de.message)||"Invalid message"}},Qr=async J=>{const de=J.trim();if(!(!de&&ve.length===0)){if(de){const he=Kn(de);if(he){Ae(he);return}}try{const he=$??void 0,wt=ne??void 0,Ot=D?{edit:!0,originalMessageId:D,...B!=null&&B.checkpointId?{originalCheckpointId:B.checkpointId}:{},...B!=null&&B.checkpointNs?{originalCheckpointNs:B.checkpointNs}:{}}:void 0;await P({text:de||"",attachments:ve,messageAdditionalKwargs:Ot},{checkpointId:he,checkpointNs:wt}),h==null||h(de),yt(""),Ae(null),Re([]),it(),X(null),fe(""),le(null)}catch(he){const wt=(he==null?void 0:he.message)||"Failed to send message";Ae(wt),g==null||g(wt)}}},I=w.useCallback((J,de,he)=>{c&&(_t.current=Kt,X(J),fe(de),yt(de),Ae(null),le({checkpointId:(he==null?void 0:he.checkpointId)??null,checkpointNs:(he==null?void 0:he.checkpointNs)??null}))},[Kt,c,yt]),q=w.useCallback(()=>{X(null),fe(""),le(null),Ae(null),yt(_t.current??Kt),_t.current=null},[Kt,yt]),ue=w.useCallback((J,de,he)=>{I(J,de,he)},[I]),ke=w.useCallback(J=>{for(let de=J-1;de>=0;de--)if(b[de].role==="user"){const he=b[de].content||[],Ot=he.filter(an=>an.type==="text").map(an=>an.text).join("")||(()=>{try{return JSON.stringify(he,null,2)}catch{return String(he)}})();Ot&&P({text:Ot},{checkpointId:$??void 0,checkpointNs:ne??void 0});break}},[b,P,$,ne]),Xe=J=>{const de=Array.from(J.target.files||[]);Re(he=>[...he,...de]),J.target.value=""},at=J=>{Re(de=>{const he=de.filter((wt,Ot)=>J!==Ot);return he.length===0&&it(),he})},Ke=async J=>{const de=(J.target.files||[])[0];if(de){Ye(null),dt(null),ut(!0);try{await P({attachments:[de]},{checkpointId:$??void 0,checkpointNs:ne??void 0});const he=`Uploaded ${de.name} - processing through chat stream`;dt(he)}catch(he){const wt=he instanceof Error?he.message:"Failed to upload Excel file";console.error("Excel upload failed",he),Ye(wt),g==null||g(wt)}finally{ut(!1),J.target.value="",it()}}},$e=async J=>{if(y){Ce(!0);try{if(!J){await R();return}const de=ft.find(wt=>wt.checkpointId===J),he=(de==null?void 0:de.checkpointNs)??null;await E(J,he)}finally{Ce(!1)}}},jt=w.useCallback(async J=>{await $e(J)},[$e]),vt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${f.container||""}`,pt=`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 ${f.messagesArea||""}`,qt=`flex-shrink-0 w-full border-t p-4 bg-transparent ${f.inputArea||""}`,Gt=w.useCallback(J=>{if(!J)return"Latest";const de=[];J.step!==null&&de.push(`Step ${J.step}`),J.source&&de.push(J.source);const he=J.createdAt?new Date(J.createdAt):null,wt=he&&!Number.isNaN(he.getTime())?he.toLocaleString():J.createdAt??J.id,Ot=de.length?` — ${de.join(" • ")}`:"";return`${wt}${Ot}`},[]);return u.jsxs("div",{className:vt,children:[!!O&&!kt&&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:O}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:()=>Nt(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(pe.X,{size:16})})]}),y&&ft.length>0&&u.jsxs("div",{className:"flex-shrink-0 flex items-center gap-2 px-4 py-2 border-b border-border bg-muted/60 text-xs dark:bg-muted/50",children:[u.jsx("span",{className:"opacity-70",children:"Checkpoint:"}),u.jsxs("select",{className:"border border-border rounded px-2 py-1 text-xs bg-card text-foreground focus:outline-none focus:ring-1 focus:ring-ring dark:bg-secondary",value:$??"",onChange:J=>{const de=J.target.value||null;$e(de)},children:[u.jsx("option",{value:"",children:"Latest"}),ft.map(J=>{const de=ht.get(J.checkpointId??"")??null;return u.jsx("option",{value:J.checkpointId??void 0,children:Gt(de)},J.checkpointId)})]})]}),u.jsxs("div",{className:`relative ${pt}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Ga,{className:"h-full",style:{height:"100%"},messages:b,isStreaming:V,streamingAssistantId:oe,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:lr,enableMessageEditing:c,editingMessageId:D,onStartReached:()=>{Tt&&Pr()},onScrollAway:J=>{if(!zt.current){zt.current=!0;return}J&&Vt(!0)},onEdit:ue,onRegenerate:ke,onCancelEdit:q,emptyMessage:tt??void 0,isNavigatingCheckpoint:G,activeInterrupt:we,disableInterruptActions:Ne,onInterruptActionStart:ie,onInterruptActionEnd:Te,showToolMessages:d,checkpointMetaById:ht,checkpointIndexByKey:Be,activeCheckpointId:$,onSelectCheckpoint:jt}),(H==="reconnecting"||H==="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(pe.Loader2,{className:"h-3 w-3 animate-spin"}),H==="reconnecting"?"Reconnecting…":"Connecting…"]})}),H==="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"}),k&&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(pe.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]})]}),u.jsxs("div",{className:qt,children:[D&&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(pe.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:q,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(pe.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:Ft,type:"file",multiple:!0,onChange:J=>Xe(J),className:"hidden"},Ve),ve.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:ve.map((J,de)=>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(pe.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:J.name}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:()=>at(de),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 ${J.name}`,children:u.jsx(pe.X,{size:12})})]},de))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Oe,type:"file",accept:".xls,.xlsx,.xlsm",onChange:Ke,className:"hidden"},et),nt&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(pe.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),It&&!nt&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:It}),rt&&!nt&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:rt})]})]}),Q&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:Q}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(OC,{children:[u.jsx(MC,{asChild:!0,children:u.jsx(lt,{type:"button",size:"icon",variant:"outline",disabled:V||ee,title:"More input actions",className:f.moreButton||"",children:u.jsx(pe.Plus,{size:16})})}),u.jsxs(rp,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(vl,{onClick:()=>{var J;return(J=Ft.current)==null?void 0:J.click()},className:"cursor-pointer",children:[u.jsx(pe.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(vl,{onClick:()=>{var J;nt||(J=Oe.current)==null||J.click()},className:`cursor-pointer ${nt?"opacity-60 pointer-events-none":""}`,children:[u.jsx(pe.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(dy,{initialValue:ae,editingMessageId:D,value:Kt,onValueChange:ar,placeholder:D?"Edit your message...":t,isStreaming:V,disabled:ee,maxLength:Ys,onSend:Qr,onCancelEdit:q,onStop:W,allowEmptySend:ve.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${D?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${Q?"border-red-400":""} ${f.textarea||""}`})})]})]})]})}const mi=v.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}));mi.displayName="Input";function wl(e,[t,n]){return Math.min(n,Math.max(t,e))}function HC(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var bl="ScrollArea",[sp,PT]=Hn(bl),[UC,yn]=sp(bl),ip=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,g]=v.useState(null),[x,y]=v.useState(null),[m,b]=v.useState(0),[S,T]=v.useState(0),[k,C]=v.useState(!1),[E,R]=v.useState(!1),_=Ze(t,L=>l(L)),j=Js(o);return u.jsx(UC,{scope:n,type:r,dir:j,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:g,scrollbarXEnabled:k,onScrollbarXEnabledChange:C,scrollbarY:x,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:R,onCornerWidthChange:b,onCornerHeightChange:T,children:u.jsx(De.div,{dir:j,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});ip.displayName=bl;var ap="ScrollAreaViewport",lp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=yn(ap,n),a=v.useRef(null),l=Ze(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(De.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})})]})});lp.displayName=ap;var $n="ScrollAreaScrollbar",Sl=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=yn($n,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(WC,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(VC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(cp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Cl,{...r,ref:t}):null});Sl.displayName=$n;var WC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=yn($n,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(gn,{present:n||s,children:u.jsx(cp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),VC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=yn($n,e.__scopeScrollArea),s=e.orientation==="horizontal",i=vi(()=>l("SCROLL_END"),100),[a,l]=HC("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(gn,{present:n||a!=="hidden",children:u.jsx(Cl,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:ye(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:ye(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),cp=v.forwardRef((e,t)=>{const n=yn($n,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=vi(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Yr(n.viewport,l),Yr(n.content,l),u.jsx(gn,{present:r||s,children:u.jsx(Cl,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Cl=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=yn($n,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=pp(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 JC(h,i.current,a,p)}return n==="horizontal"?u.jsx(KC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=mp(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(qC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=mp(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}),KC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=yn($n,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(dp,{"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":yi(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),xp(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:xi(i.paddingLeft),paddingEnd:xi(i.paddingRight)}})}})}),qC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=yn($n,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=Ze(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(dp,{"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":yi(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),xp(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:xi(i.paddingTop),paddingEnd:xi(i.paddingBottom)}})}})}),[GC,up]=sp($n),dp=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=yn($n,n),[g,x]=v.useState(null),y=Ze(t,_=>x(_)),m=v.useRef(null),b=v.useRef(""),S=p.viewport,T=r.content-r.viewport,k=Wt(d),C=Wt(l),E=vi(f,10);function R(_){if(m.current){const j=_.clientX-m.current.left,L=_.clientY-m.current.top;c({x:j,y:L})}}return v.useEffect(()=>{const _=j=>{const L=j.target;(g==null?void 0:g.contains(L))&&k(j,T)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,g,T,k]),v.useEffect(C,[r,C]),Yr(g,E),Yr(p.content,E),u.jsx(GC,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:Wt(s),onThumbPointerUp:Wt(i),onThumbPositionChange:C,onThumbPointerDown:Wt(a),children:u.jsx(De.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:ye(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),m.current=g.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),R(_))}),onPointerMove:ye(e.onPointerMove,R),onPointerUp:ye(e.onPointerUp,_=>{const j=_.target;j.hasPointerCapture(_.pointerId)&&j.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),m.current=null})})})}),gi="ScrollAreaThumb",fp=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=up(gi,e.__scopeScrollArea);return u.jsx(gn,{present:n||o.hasThumb,children:u.jsx(XC,{ref:t,...r})})}),XC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=yn(gi,n),i=up(gi,n),{onThumbPositionChange:a}=i,l=Ze(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=vi(()=>{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=ZC(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(De.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:ye(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),g=f.clientX-p.left,x=f.clientY-p.top;i.onThumbPointerDown({x:g,y:x})}),onPointerUp:ye(e.onPointerUp,i.onThumbPointerUp)})});fp.displayName=gi;var kl="ScrollAreaCorner",hp=v.forwardRef((e,t)=>{const n=yn(kl,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(YC,{...e,ref:t}):null});hp.displayName=kl;var YC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=yn(kl,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return Yr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Yr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(De.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 xi(e){return e?parseInt(e,10):0}function pp(e,t){const n=e/t;return isNaN(n)?0:n}function yi(e){const t=pp(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function JC(e,t,n,r="ltr"){const o=yi(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 mp(e,t,n="ltr"){const r=yi(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=wl(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 xp(e,t){return e>0&&e<t}var ZC=(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 vi(e,t){const n=Wt(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 Yr(e,t){const n=Wt(t);Ut(()=>{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 yp=ip,QC=lp,ek=hp;const vp=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(yp,{ref:r,className:se("relative overflow-hidden",e),...n,children:[u.jsx(QC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(wp,{}),u.jsx(ek,{})]}));vp.displayName=yp.displayName;const wp=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Sl,{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(fp,{className:"relative flex-1 rounded-full bg-border"})}));wp.displayName=Sl.displayName;const bp=25;function Tl({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,currentThreadId:h,isLoading:p,actions:g}=cs(),{loadThread:x}=us(),{createThread:y,deleteThread:m,renameThread:b}=g,[S,T]=w.useState(Array.isArray(f)?f:[]),k=w.useRef(S.length>0),C=w.useRef(null),E=w.useRef(0),[R,_]=w.useState(null),[j,L]=w.useState(""),[z,V]=w.useState(!1);w.useEffect(()=>{const Z=Array.isArray(f)?f:[];if(Z.length>0){k.current=!0,T(Z);return}p||(k.current=!1,T(Z))},[f,p]),w.useEffect(()=>{if(!C.current)return;const Z=C.current.querySelector("[data-radix-scroll-area-viewport]");if(!Z)return;let ie=null,Te=null;return ie=requestAnimationFrame(()=>{Te=requestAnimationFrame(()=>{Z.scrollTop=E.current})}),()=>{ie!==null&&cancelAnimationFrame(ie),Te!==null&&cancelAnimationFrame(Te)}},[S]);const O=async Z=>{try{await x(Z),a==null||a(Z),l==null||l(Z)}catch(ie){console.error("Failed to select thread:",ie)}},H=async()=>{try{V(!0);const Z=await y();c==null||c(Z),a==null||a(Z)}catch(Z){console.error("Failed to create thread:",Z)}finally{V(!1)}},P=async(Z,ie)=>{if(ie.stopPropagation(),!!confirm("Delete this thread?")){if(C.current){const Te=C.current.querySelector("[data-radix-scroll-area-viewport]");Te&&(E.current=Te.scrollTop)}try{await m(Z),d==null||d(Z)}catch(Te){console.error("Failed to delete thread:",Te)}}},W=(Z,ie)=>{ie.stopPropagation(),_(Z.threadId),L(Z.title||`Thread ${Z.threadId.slice(0,8)}`)},F=async Z=>{if(j.trim())try{await b(Z,j.trim()),_(null),L("")}catch(ie){console.error("Failed to update title:",ie)}},$=()=>{_(null),L("")},ne=(Z,ie)=>{Z.key==="Enter"?F(ie):Z.key==="Escape"&&$()},oe=Z=>{if(!Z)return"";try{const ie=new Date(Z),ee=new Date().getTime()-ie.getTime(),D=Math.floor(ee/(1e3*60*60*24));return D===0?ie.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):D===1?"Yesterday":D<7?`${D} days ago`:ie.toLocaleDateString()}catch{return""}},we=Z=>Z.title||`Thread ${Z.threadId.slice(0,8)}`,Ne=Z=>{const ie=we(Z);return ie.length<=bp?ie:`${ie.slice(0,bp)}...`};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(lt,{onClick:H,disabled:z||p,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:z?"Creating...":"New Chat",children:u.jsx(pe.MessageSquarePlus,{size:20})})}),u.jsx(vp,{ref:C,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:p?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(pe.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):S.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(pe.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"})]}):S.slice().sort((Z,ie)=>new Date(ie.updatedAt||ie.createdAt||"").getTime()-new Date(Z.updatedAt||Z.createdAt||"").getTime()).map(Z=>u.jsxs("div",{onClick:()=>O(Z.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??h)===Z.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:R===Z.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:ie=>ie.stopPropagation(),children:[u.jsx(mi,{value:j,onChange:ie=>L(ie.target.value),onKeyDown:ie=>ne(ie,Z.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:()=>F(Z.threadId),className:"h-6 w-6 p-0",children:u.jsx(pe.Check,{size:12})}),u.jsx(lt,{variant:"ghost",size:"sm",onClick:$,className:"h-6 w-6 p-0",children:u.jsx(pe.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:Ne(Z)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(pe.Calendar,{size:10}),u.jsx("span",{children:oe(Z.updatedAt||Z.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&R!==Z.threadId&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:ie=>W(Z,ie),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(pe.Edit3,{size:12})}),n&&u.jsx(lt,{variant:"ghost",size:"sm",onClick:ie=>P(Z.threadId,ie),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(pe.Trash2,{size:12})})]})]}),i===Z.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},Z.threadId))})})]})}function Jr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function tk(e){if(typeof e!="string")return;const t=e.trim();if(t)return zn(t)}function Sp(){const e=[Jr("__API_BASE_URL__"),Jr("__CHAT_API_BASE_URL__"),Jr("__CHAT_API_URL__")];for(const t of e){const n=tk(t);if(n)return n}}function Cp(){const e=[Jr("__API_AUTH_TOKEN__"),Jr("__CHAT_API_KEY__"),Jr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function kp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return zn(t);return zn()}function Tp(){const e={},t=Sp(),n=Cp();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Ep(){const e=Tp(),t=Gn.getAuthToken(),n=Sp();return{apiBaseUrl:kp(e.baseUrl,Gn.baseUrl,n),apiKey:t||e.apiKey||Cp()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Ip="chat-settings";function nk(){try{const e=localStorage.getItem(Ip);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function rk(e){try{const t={...e,apiBaseUrl:zn(e.apiBaseUrl)};localStorage.setItem(Ip,JSON.stringify(t)),t.apiKey&&Gn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function ok(){const e=Ep(),t=nk(),n=Gn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:kp(Gn.baseUrl,r,e.apiBaseUrl)}}function sk(e){Gn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),rk(e)}var ik="Label",Np=v.forwardRef((e,t)=>u.jsx(De.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())}}));Np.displayName=ik;var Ap=Np;const ak=Uo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),vn=v.forwardRef(({className:e,...t},n)=>u.jsx(Ap,{ref:n,className:se(ak(),e),...t}));vn.displayName=Ap.displayName;function _p(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 wi="Switch",[lk,OT]=Hn(wi),[ck,uk]=lk(wi),jp=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),g=Ze(t,S=>p(S)),x=v.useRef(!1),y=h?d||!!h.closest("form"):!0,[m,b]=Br({prop:o,defaultProp:s??!1,onChange:c,caller:wi});return u.jsxs(ck,{scope:n,checked:m,disabled:a,children:[u.jsx(De.button,{type:"button",role:"switch","aria-checked":m,"aria-required":i,"data-state":Mp(m),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:g,onClick:ye(e.onClick,S=>{b(T=>!T),y&&(x.current=S.isPropagationStopped(),x.current||S.stopPropagation())})}),y&&u.jsx(Op,{control:h,bubbles:!x.current,name:r,value:l,checked:m,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});jp.displayName=wi;var Rp="SwitchThumb",Pp=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=uk(Rp,n);return u.jsx(De.span,{"data-state":Mp(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Pp.displayName=Rp;var dk="SwitchBubbleInput",Op=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=Ze(i,s),l=_p(n),c=Uf(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 g=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(g)}},[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}})});Op.displayName=dk;function Mp(e){return e?"checked":"unchecked"}var Dp=jp,fk=Pp;const or=v.forwardRef(({className:e,...t},n)=>u.jsx(Dp,{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(fk,{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")})}));or.displayName=Dp.displayName;var Lp=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"}),hk="VisuallyHidden",pk=v.forwardRef((e,t)=>u.jsx(De.span,{...e,ref:t,style:{...Lp,...e.style}}));pk.displayName=hk;var mk=[" ","Enter","ArrowUp","ArrowDown"],gk=[" ","Enter"],Nr="Select",[bi,Si,xk]=Xa(Nr),[Zr,MT]=Hn(Nr,[xk,li]),Ci=li(),[yk,sr]=Zr(Nr),[vk,wk]=Zr(Nr),$p=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:g}=e,x=Ci(t),[y,m]=v.useState(null),[b,S]=v.useState(null),[T,k]=v.useState(!1),C=Js(c),[E,R]=Br({prop:r,defaultProp:o??!1,onChange:s,caller:Nr}),[_,j]=Br({prop:i,defaultProp:a,onChange:l,caller:Nr}),L=v.useRef(null),z=y?g||!!y.closest("form"):!0,[V,O]=v.useState(new Set),H=Array.from(V).map(P=>P.props.value).join(";");return u.jsx(Qf,{...x,children:u.jsxs(yk,{required:p,scope:t,trigger:y,onTriggerChange:m,valueNode:b,onValueNodeChange:S,valueNodeHasChildren:T,onValueNodeHasChildrenChange:k,contentId:Un(),value:_,onValueChange:j,open:E,onOpenChange:R,dir:C,triggerPointerDownPosRef:L,disabled:h,children:[u.jsx(bi.Provider,{scope:t,children:u.jsx(vk,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(P=>{O(W=>new Set(W).add(P))},[]),onNativeOptionRemove:v.useCallback(P=>{O(W=>{const F=new Set(W);return F.delete(P),F})},[]),children:n})}),z?u.jsxs(lm,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:P=>j(P.target.value),disabled:h,form:g,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(V)]},H):null]})})};$p.displayName=Nr;var Fp="SelectTrigger",zp=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Ci(n),i=sr(Fp,n),a=i.disabled||r,l=Ze(t,i.onTriggerChange),c=Si(n),d=v.useRef("touch"),[f,h,p]=um(x=>{const y=c().filter(S=>!S.disabled),m=y.find(S=>S.value===i.value),b=dm(y,x,m);b!==void 0&&i.onValueChange(b.value)}),g=x=>{a||(i.onOpenChange(!0),p()),x&&(i.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return u.jsx(eh,{asChild:!0,...s,children:u.jsx(De.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":cm(i.value)?"":void 0,...o,ref:l,onClick:ye(o.onClick,x=>{x.currentTarget.focus(),d.current!=="mouse"&&g(x)}),onPointerDown:ye(o.onPointerDown,x=>{d.current=x.pointerType;const y=x.target;y.hasPointerCapture(x.pointerId)&&y.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(g(x),x.preventDefault())}),onKeyDown:ye(o.onKeyDown,x=>{const y=f.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&h(x.key),!(y&&x.key===" ")&&mk.includes(x.key)&&(g(),x.preventDefault())})})})});zp.displayName=Fp;var Bp="SelectValue",Hp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=sr(Bp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=Ze(t,l.onValueNodeChange);return Ut(()=>{c(d)},[c,d]),u.jsx(De.span,{...a,ref:f,style:{pointerEvents:"none"},children:cm(l.value)?u.jsx(u.Fragment,{children:i}):s})});Hp.displayName=Bp;var bk="SelectIcon",Up=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(De.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Up.displayName=bk;var Sk="SelectPortal",Wp=e=>u.jsx(_s,{asChild:!0,...e});Wp.displayName=Sk;var Ar="SelectContent",Vp=v.forwardRef((e,t)=>{const n=sr(Ar,e.__scopeSelect),[r,o]=v.useState();if(Ut(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Wo.createPortal(u.jsx(Kp,{scope:e.__scopeSelect,children:u.jsx(bi.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(qp,{...e,ref:t})});Vp.displayName=Ar;var Nn=10,[Kp,ir]=Zr(Ar),Ck="SelectContentImpl",kk=hr.createSlot("SelectContent.RemoveScroll"),qp=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:g,hideWhenDetached:x,avoidCollisions:y,...m}=e,b=sr(Ar,n),[S,T]=v.useState(null),[k,C]=v.useState(null),E=Ze(t,ee=>T(ee)),[R,_]=v.useState(null),[j,L]=v.useState(null),z=Si(n),[V,O]=v.useState(!1),H=v.useRef(!1);v.useEffect(()=>{if(S)return Ba(S)},[S]),Ma();const P=v.useCallback(ee=>{const[D,...X]=z().map(B=>B.ref.current),[ae]=X.slice(-1),fe=document.activeElement;for(const B of ee)if(B===fe||(B==null||B.scrollIntoView({block:"nearest"}),B===D&&k&&(k.scrollTop=0),B===ae&&k&&(k.scrollTop=k.scrollHeight),B==null||B.focus(),document.activeElement!==fe))return},[z,k]),W=v.useCallback(()=>P([R,S]),[P,R,S]);v.useEffect(()=>{V&&W()},[V,W]);const{onOpenChange:F,triggerPointerDownPosRef:$}=b;v.useEffect(()=>{if(S){let ee={x:0,y:0};const D=ae=>{var fe,B;ee={x:Math.abs(Math.round(ae.pageX)-(((fe=$.current)==null?void 0:fe.x)??0)),y:Math.abs(Math.round(ae.pageY)-(((B=$.current)==null?void 0:B.y)??0))}},X=ae=>{ee.x<=10&&ee.y<=10?ae.preventDefault():S.contains(ae.target)||F(!1),document.removeEventListener("pointermove",D),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",D),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",X,{capture:!0})}}},[S,F,$]),v.useEffect(()=>{const ee=()=>F(!1);return window.addEventListener("blur",ee),window.addEventListener("resize",ee),()=>{window.removeEventListener("blur",ee),window.removeEventListener("resize",ee)}},[F]);const[ne,oe]=um(ee=>{const D=z().filter(fe=>!fe.disabled),X=D.find(fe=>fe.ref.current===document.activeElement),ae=dm(D,ee,X);ae&&setTimeout(()=>ae.ref.current.focus())}),we=v.useCallback((ee,D,X)=>{const ae=!H.current&&!X;(b.value!==void 0&&b.value===D||ae)&&(_(ee),ae&&(H.current=!0))},[b.value]),Ne=v.useCallback(()=>S==null?void 0:S.focus(),[S]),Z=v.useCallback((ee,D,X)=>{const ae=!H.current&&!X;(b.value!==void 0&&b.value===D||ae)&&L(ee)},[b.value]),ie=r==="popper"?El:Gp,Te=ie===El?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:g,hideWhenDetached:x,avoidCollisions:y}:{};return u.jsx(Kp,{scope:n,content:S,viewport:k,onViewportChange:C,itemRefCallback:we,selectedItem:R,onItemLeave:Ne,itemTextRefCallback:Z,focusSelectedItem:W,selectedItemText:j,position:r,isPositioned:V,searchRef:ne,children:u.jsx(Ls,{as:kk,allowPinchZoom:!0,children:u.jsx(As,{asChild:!0,trapped:b.open,onMountAutoFocus:ee=>{ee.preventDefault()},onUnmountAutoFocus:ye(o,ee=>{var D;(D=b.trigger)==null||D.focus({preventScroll:!0}),ee.preventDefault()}),children:u.jsx(Ns,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:ee=>ee.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(ie,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:ee=>ee.preventDefault(),...m,...Te,onPlaced:()=>O(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...m.style},onKeyDown:ye(m.onKeyDown,ee=>{const D=ee.ctrlKey||ee.altKey||ee.metaKey;if(ee.key==="Tab"&&ee.preventDefault(),!D&&ee.key.length===1&&oe(ee.key),["ArrowUp","ArrowDown","Home","End"].includes(ee.key)){let ae=z().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);if(["ArrowUp","End"].includes(ee.key)&&(ae=ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(ee.key)){const fe=ee.target,B=ae.indexOf(fe);ae=ae.slice(B+1)}setTimeout(()=>P(ae)),ee.preventDefault()}})})})})})})});qp.displayName=Ck;var Tk="SelectItemAlignedPosition",Gp=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=sr(Ar,n),i=ir(Ar,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=Ze(t,E=>d(E)),h=Si(n),p=v.useRef(!1),g=v.useRef(!0),{viewport:x,selectedItem:y,selectedItemText:m,focusSelectedItem:b}=i,S=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&x&&y&&m){const E=s.trigger.getBoundingClientRect(),R=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),j=m.getBoundingClientRect();if(s.dir!=="rtl"){const fe=j.left-R.left,B=_.left-fe,le=E.left-B,Q=E.width+le,Ae=Math.max(Q,R.width),ve=window.innerWidth-Nn,Re=wl(B,[Nn,Math.max(Nn,ve-Ae)]);a.style.minWidth=Q+"px",a.style.left=Re+"px"}else{const fe=R.right-j.right,B=window.innerWidth-_.right-fe,le=window.innerWidth-E.right-B,Q=E.width+le,Ae=Math.max(Q,R.width),ve=window.innerWidth-Nn,Re=wl(B,[Nn,Math.max(Nn,ve-Ae)]);a.style.minWidth=Q+"px",a.style.right=Re+"px"}const L=h(),z=window.innerHeight-Nn*2,V=x.scrollHeight,O=window.getComputedStyle(c),H=parseInt(O.borderTopWidth,10),P=parseInt(O.paddingTop,10),W=parseInt(O.borderBottomWidth,10),F=parseInt(O.paddingBottom,10),$=H+P+V+F+W,ne=Math.min(y.offsetHeight*5,$),oe=window.getComputedStyle(x),we=parseInt(oe.paddingTop,10),Ne=parseInt(oe.paddingBottom,10),Z=E.top+E.height/2-Nn,ie=z-Z,Te=y.offsetHeight/2,ee=y.offsetTop+Te,D=H+P+ee,X=$-D;if(D<=Z){const fe=L.length>0&&y===L[L.length-1].ref.current;a.style.bottom="0px";const B=c.clientHeight-x.offsetTop-x.offsetHeight,le=Math.max(ie,Te+(fe?Ne:0)+B+W),Q=D+le;a.style.height=Q+"px"}else{const fe=L.length>0&&y===L[0].ref.current;a.style.top="0px";const le=Math.max(Z,H+x.offsetTop+(fe?we:0)+Te)+X;a.style.height=le+"px",x.scrollTop=D-Z+x.offsetTop}a.style.margin=`${Nn}px 0`,a.style.minHeight=ne+"px",a.style.maxHeight=z+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,x,y,m,s.dir,r]);Ut(()=>S(),[S]);const[T,k]=v.useState();Ut(()=>{c&&k(window.getComputedStyle(c).zIndex)},[c]);const C=v.useCallback(E=>{E&&g.current===!0&&(S(),b==null||b(),g.current=!1)},[S,b]);return u.jsx(Ik,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:C,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:T},children:u.jsx(De.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});Gp.displayName=Tk;var Ek="SelectPopperPosition",El=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=Nn,...s}=e,i=Ci(n);return u.jsx(th,{...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)"}})});El.displayName=Ek;var[Ik,Il]=Zr(Ar,{}),Nl="SelectViewport",Xp=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=ir(Nl,n),i=Il(Nl,n),a=Ze(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(bi.Slot,{scope:n,children:u.jsx(De.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:ye(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 g=window.innerHeight-Nn*2,x=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),m=Math.max(x,y);if(m<g){const b=m+p,S=Math.min(g,b),T=b-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=T>0?T:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});Xp.displayName=Nl;var Yp="SelectGroup",[Nk,Ak]=Zr(Yp),_k=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Un();return u.jsx(Nk,{scope:n,id:o,children:u.jsx(De.div,{role:"group","aria-labelledby":o,...r,ref:t})})});_k.displayName=Yp;var Jp="SelectLabel",Zp=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ak(Jp,n);return u.jsx(De.div,{id:o.id,...r,ref:t})});Zp.displayName=Jp;var ki="SelectItem",[jk,Qp]=Zr(ki),em=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=sr(ki,n),l=ir(ki,n),c=a.value===r,[d,f]=v.useState(s??""),[h,p]=v.useState(!1),g=Ze(t,b=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,b,r,o)}),x=Un(),y=v.useRef("touch"),m=()=>{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(jk,{scope:n,value:r,disabled:o,textId:x,isSelected:c,onItemTextChange:v.useCallback(b=>{f(S=>S||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(bi.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(De.div,{role:"option","aria-labelledby":x,"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:g,onFocus:ye(i.onFocus,()=>p(!0)),onBlur:ye(i.onBlur,()=>p(!1)),onClick:ye(i.onClick,()=>{y.current!=="mouse"&&m()}),onPointerUp:ye(i.onPointerUp,()=>{y.current==="mouse"&&m()}),onPointerDown:ye(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:ye(i.onPointerMove,b=>{var S;y.current=b.pointerType,o?(S=l.onItemLeave)==null||S.call(l):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ye(i.onPointerLeave,b=>{var S;b.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:ye(i.onKeyDown,b=>{var T;((T=l.searchRef)==null?void 0:T.current)!==""&&b.key===" "||(gk.includes(b.key)&&m(),b.key===" "&&b.preventDefault())})})})})});em.displayName=ki;var $o="SelectItemText",tm=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=sr($o,n),a=ir($o,n),l=Qp($o,n),c=wk($o,n),[d,f]=v.useState(null),h=Ze(t,m=>f(m),l.onItemTextChange,m=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,m,l.value,l.disabled)}),p=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:y}=c;return Ut(()=>(x(g),()=>y(g)),[x,y,g]),u.jsxs(u.Fragment,{children:[u.jsx(De.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Wo.createPortal(s.children,i.valueNode):null]})});tm.displayName=$o;var nm="SelectItemIndicator",rm=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Qp(nm,n).isSelected?u.jsx(De.span,{"aria-hidden":!0,...r,ref:t}):null});rm.displayName=nm;var Al="SelectScrollUpButton",om=v.forwardRef((e,t)=>{const n=ir(Al,e.__scopeSelect),r=Il(Al,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Ut(()=>{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(im,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});om.displayName=Al;var _l="SelectScrollDownButton",sm=v.forwardRef((e,t)=>{const n=ir(_l,e.__scopeSelect),r=Il(_l,e.__scopeSelect),[o,s]=v.useState(!1),i=Ze(t,r.onScrollButtonChange);return Ut(()=>{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(im,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});sm.displayName=_l;var im=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=ir("SelectScrollButton",n),i=v.useRef(null),a=Si(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),Ut(()=>{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(De.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:ye(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ye(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ye(o.onPointerLeave,()=>{l()})})}),Rk="SelectSeparator",am=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(De.div,{"aria-hidden":!0,...r,ref:t})});am.displayName=Rk;var jl="SelectArrow",Pk=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ci(n),s=sr(jl,n),i=ir(jl,n);return s.open&&i.position==="popper"?u.jsx(nh,{...o,...r,ref:t}):null});Pk.displayName=jl;var Ok="SelectBubbleInput",lm=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=Ze(r,o),i=_p(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(De.select,{...n,style:{...Lp,...n.style},ref:s,defaultValue:t})});lm.displayName=Ok;function cm(e){return e===""||e===void 0}function um(e){const t=Wt(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 dm(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=Mk(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 Mk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Dk=$p,fm=zp,Lk=Hp,$k=Up,Fk=Wp,hm=Vp,zk=Xp,pm=Zp,mm=em,Bk=tm,Hk=rm,gm=om,xm=sm,ym=am;const vm=Dk,wm=Lk,Rl=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(fm,{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($k,{asChild:!0,children:u.jsx(pe.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Rl.displayName=fm.displayName;const bm=v.forwardRef(({className:e,...t},n)=>u.jsx(gm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(pe.ChevronUp,{className:"h-4 w-4"})}));bm.displayName=gm.displayName;const Sm=v.forwardRef(({className:e,...t},n)=>u.jsx(xm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(pe.ChevronDown,{className:"h-4 w-4"})}));Sm.displayName=xm.displayName;const Pl=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(Fk,{children:u.jsxs(hm,{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(bm,{}),u.jsx(zk,{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(Sm,{})]})}));Pl.displayName=hm.displayName;const Uk=v.forwardRef(({className:e,...t},n)=>u.jsx(pm,{ref:n,className:se("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Uk.displayName=pm.displayName;const _r=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(mm,{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(Hk,{children:u.jsx(pe.Check,{className:"h-4 w-4"})})}),u.jsx(Bk,{children:t})]}));_r.displayName=mm.displayName;const Wk=v.forwardRef(({className:e,...t},n)=>u.jsx(ym,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));Wk.displayName=ym.displayName;var Vk="Separator",Cm="horizontal",Kk=["horizontal","vertical"],km=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Cm,...o}=e,s=qk(r)?r:Cm,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(De.div,{"data-orientation":s,...a,...o,ref:t})});km.displayName=Vk;function qk(e){return Kk.includes(e)}var Tm=km;const Em=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Tm,{ref:o,decorative:n,orientation:t,className:se("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Em.displayName=Tm.displayName;const Gk=Xd,Xk=hb,Yk=Yd,Im=v.forwardRef(({className:e,...t},n)=>u.jsx(Hs,{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}));Im.displayName=Hs.displayName;const Jk=Uo.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"}}),Nm=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(Yk,{children:[u.jsx(Im,{}),u.jsxs(Us,{ref:o,className:se(Jk({side:e}),t),...r,children:[n,u.jsxs(Jd,{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(pe.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Nm.displayName=Us.displayName;const Am=({className:e,...t})=>u.jsx("div",{className:se("flex flex-col space-y-2 text-center sm:text-left",e),...t});Am.displayName="SheetHeader";const _m=v.forwardRef(({className:e,...t},n)=>u.jsx(Cr,{ref:n,className:se("text-lg font-semibold text-foreground",e),...t}));_m.displayName=Cr.displayName;const jm=v.forwardRef(({className:e,...t},n)=>u.jsx(Ws,{ref:n,className:se("text-sm text-muted-foreground",e),...t}));jm.displayName=Ws.displayName;const Zk={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 Qk({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}=Na();w.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),w.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(Zk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},g=()=>{l(e),d(!1),o(!1)},x=async()=>{try{const m=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${m.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(Gk,{open:r,onOpenChange:o,children:[u.jsx(Xk,{asChild:!0,children:u.jsxs(lt,{variant:"outline",size:"sm",className:n,children:[u.jsx(pe.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(td,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Nm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(Am,{children:[u.jsx(_m,{children:"Chat Settings"}),u.jsx(jm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(bo,{children:[u.jsx(So,{className:"pb-3",children:u.jsxs(Co,{className:"text-lg flex items-center gap-2",children:[u.jsx(pe.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(ko,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(mi,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(m=>({...m,api:{...m.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(lt,{variant:"outline",onClick:x,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(or,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(m=>({...m,api:{...m.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(mi,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(m=>({...m,api:{...m.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(lt,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(pe.EyeOff,{className:"h-4 w-4"}):u.jsx(pe.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(bo,{children:[u.jsx(So,{className:"pb-3",children:u.jsxs(Co,{className:"text-lg flex items-center gap-2",children:[u.jsx(pe.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(ko,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(vm,{value:a.ui.layout,onValueChange:y=>l(m=>({...m,ui:{...m.ui,layout:y}})),children:[u.jsx(Rl,{children:u.jsx(wm,{})}),u.jsxs(Pl,{children:[u.jsx(_r,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(_r,{value:"fullscreen",children:"Fullscreen"}),u.jsx(_r,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(vn,{htmlFor:"theme",children:"Theme"}),u.jsxs(vm,{value:a.ui.theme,onValueChange:y=>l(m=>({...m,ui:{...m.ui,theme:y}})),children:[u.jsx(Rl,{children:u.jsx(wm,{})}),u.jsxs(Pl,{children:[u.jsx(_r,{value:"light",children:"Light"}),u.jsx(_r,{value:"dark",children:"Dark"}),u.jsx(_r,{value:"system",children:"System"})]})]})]}),u.jsx(Em,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(or,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(m=>({...m,ui:{...m.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(or,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(m=>({...m,ui:{...m.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(vn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(or,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(m=>({...m,ui:{...m.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(bo,{children:[u.jsx(So,{className:"pb-3",children:u.jsxs(Co,{className:"text-lg flex items-center gap-2",children:[u.jsx(pe.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(ko,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(vn,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(or,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(m=>({...m,behavior:{...m.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(vn,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(or,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(m=>({...m,behavior:{...m.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(vn,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(or,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(m=>({...m,behavior:{...m.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(lt,{variant:"outline",onClick:p,children:[u.jsx(pe.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(lt,{variant:"outline",onClick:g,children:"Cancel"}),u.jsxs(lt,{onClick:h,disabled:!c,children:[u.jsx(pe.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function eT({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(ds,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(pi,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(ds,{...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(Tl,{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(pi,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(ds,{...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(Tl,{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(pi,{onError:s.onError,enableFileUpload:!0})})]})})}Pe.ChatApi=_c,Pe.ChatInterface=pi,Pe.ChatProviders=ds,Pe.ChatSettings=Qk,Pe.MarkdownContent=No,Pe.MessageComponent=qa,Pe.MessageList=Ga,Pe.ThreadManager=Tl,Pe.applySettings=sk,Pe.chatApiClient=Gn,Pe.default=eT,Pe.del=Ac,Pe.get=bn,Pe.getChatToken=Ec,Pe.getCurrentSettings=ok,Pe.getDefaultApiConfig=Tp,Pe.getDefaultChatSettings=Ep,Pe.onChatTokenChanged=Ic,Pe.post=zi,Pe.put=Nc,Pe.setChatToken=Fi,Pe.useApi=Bi,Pe.useChatStream=Vc,Pe.useMessagesReducer=Lc,Pe.useStream=tu,Pe.useThreadState=us,Pe.useThreads=cs,Object.defineProperties(Pe,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});